我想编写一个在数据库中创建组织者的 Register 方法。为此,我使用以下代码。我对这个仍然不满意,因为它仍然不安全。我应该在代码中更改什么以使其安全?我使用
express-async-errors
作为中间件。
const getConnection = async (): Promise<mariadb.PoolConnection> => {
const pool = mariadb.createPool({
host: 'localhost',
user: process.env.MARIADB_USER,
password: process.env.MARIADB_USERPASSWORD,
connectionLimit: 5,
database: 'TicketingDB'
});
return pool.getConnection();
};
public Register = async (req: Request, res: Response) => {
const { email, password } = req.body;
if (!email || !password) throw new MissingFieldsError('email and password are required.');
let connection;
try {
connection = await getConnection();
} catch (error) {
if (connection) connection.end();
throw new DbError('Error while establishing a database connection."');
}
// what happens if the connection to the database is interrupted here?
let salt;
let saltedPasswordHash;
try {
salt = await bcrypt.genSalt(10);
saltedPasswordHash = await bcrypt.hash(password, salt);
} catch (error) {
throw new InternalServerError('bcrypt error');
} finally {
if (connection) connection.end();
}
try {
await connection.query('INSERT INTO Organizer (ID, Email, SaltedPasswordHash) VALUES (UUID(), ?, ?);', [email, saltedPasswordHash]);
} catch (error) {
// It would still be interesting to know where exactly there is a duplicate. For example, the email or username is duplicated.
if (error instanceof SqlError && error.code == 'ER_DUP_ENTRY') throw new DbDuplicateEntryError('email already registered.');
throw new DbError('Error at execution of connection.query()');
} finally {
if (connection) connection.end();
}
return res.json({ registered: true });
};