64 lines
2.4 KiB
JavaScript
64 lines
2.4 KiB
JavaScript
import assert from 'node:assert';
|
|
import BoxError from './boxerror.js';
|
|
import database from './database.js';
|
|
import safe from 'safetydance';
|
|
|
|
const MAIL_PASSWORD_FIELDS = [ 'appId', 'userId', 'password', 'creationTime' ].join(',');
|
|
|
|
async function get(appId, userId) {
|
|
assert.strictEqual(typeof appId, 'string');
|
|
assert.strictEqual(typeof userId, 'string');
|
|
|
|
const result = await database.query('SELECT ' + MAIL_PASSWORD_FIELDS + ' FROM mailPasswords WHERE appId = ? AND userId = ?', [ appId, userId ]);
|
|
if (result.length === 0) return null;
|
|
return result[0];
|
|
}
|
|
|
|
async function getByUserId(userId) {
|
|
assert.strictEqual(typeof userId, 'string');
|
|
|
|
return await database.query('SELECT ' + MAIL_PASSWORD_FIELDS + ' FROM mailPasswords WHERE userId = ?', [ userId ]);
|
|
}
|
|
|
|
async function add(appId, userId, password) {
|
|
assert.strictEqual(typeof appId, 'string');
|
|
assert.strictEqual(typeof userId, 'string');
|
|
assert.strictEqual(typeof password, 'string');
|
|
|
|
if (appId.length < 1) throw new BoxError(BoxError.BAD_FIELD, 'appId must be at least 1 char');
|
|
if (userId.length < 1) throw new BoxError(BoxError.BAD_FIELD, 'userId must be at least 1 char');
|
|
if (password.length < 1) throw new BoxError(BoxError.BAD_FIELD, 'password must be at least 1 char');
|
|
|
|
const query = 'INSERT INTO mailPasswords (appId, userId, password) VALUES (?, ?, ?)';
|
|
const args = [ appId, userId, password ];
|
|
|
|
const [error] = await safe(database.query(query, args));
|
|
if (error && error.sqlCode === 'ER_DUP_ENTRY') throw new BoxError(BoxError.ALREADY_EXISTS, 'mail password for this app and user already exists');
|
|
if (error && error.sqlCode === 'ER_NO_REFERENCED_ROW_2') throw new BoxError(BoxError.NOT_FOUND, 'app or user not found');
|
|
if (error) throw error;
|
|
|
|
return { appId, userId };
|
|
}
|
|
|
|
async function list(userId) {
|
|
assert.strictEqual(typeof userId, 'string');
|
|
|
|
return await database.query('SELECT ' + MAIL_PASSWORD_FIELDS + ' FROM mailPasswords WHERE userId = ? ORDER BY appId', [ userId ]);
|
|
}
|
|
|
|
async function del(appId, userId) {
|
|
assert.strictEqual(typeof appId, 'string');
|
|
assert.strictEqual(typeof userId, 'string');
|
|
|
|
const result = await database.query('DELETE FROM mailPasswords WHERE appId = ? AND userId = ?', [ appId, userId ]);
|
|
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'mail password not found');
|
|
}
|
|
|
|
export default {
|
|
get,
|
|
getByUserId,
|
|
add,
|
|
list,
|
|
del
|
|
};
|