I'm creating some kind of SignIn request/response in Express. When user give valid username & password, then server will return valid authorization code.
This is code.
export const getAuthKey = async (req, res, next) => {
// Query parameter : :username, :hash(SHA256 encoded pasword)
// Return : { authKey: authKey }
if (req.query.username === undefined) { res.status(400).send('`username` query paramter missing.'); }
if (req.query.hash === undefined) { res.status(400).send('`hash` query paramter missing.'); }
getConnection()
.then(conn => new Promise((resolve, reject) => {
const escapeUserName = conn.escape(req.query.username);
const escapeSHA256 = conn.escape(req.query.hash);
return conn.query(`SELECT HEX(AuthorizationKey) AS authKey FROM UserInfo WHERE UserName = ${escapeUserName} AND UserPassword = UNHEX(${escapeSHA256});`)
.then(result => resolve(result))
.catch(err => reject(err))
.finally(() => { conn.end(); });
}))
.then(auth => {
if (auth.length < 1) { res.status(401).send('No such user found'); }
else {
log(`User ${req.query.username} requests valid authorization.`, `AUTH`)
res.json(auth[0]);
}
})
.catch(err => {
log('Unable to get authKey', 'AUTH', 'ERROR', err);
res.status(500).send(`Unable to logging-in`);
});
}
The steps are simple,
1. User send request with parameterusername
and hash
(password)
1-1. If parameter is not fulfilled, it returns status 400.
2. Check Database and find if user is valid, if so, return it's authorization code.
3-2 If there are some unexpected error, returns status 500.
This code works. But I always see
(node:11580) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I think I miss something about http request. Can you tell me what is wrong? Also would you provide me a code pattern for this kind of process?
p.s please ignore async on function definition.