2022-11-09 06:58:52 +00:00
|
|
|
import {
|
|
|
|
|
ok,
|
|
|
|
|
unauthorized,
|
|
|
|
|
badRequest,
|
|
|
|
|
checkPassword,
|
|
|
|
|
createSecureToken,
|
|
|
|
|
methodNotAllowed,
|
|
|
|
|
getRandomChars,
|
|
|
|
|
} from 'next-basics';
|
2022-11-01 06:42:37 +00:00
|
|
|
import { getUser } from 'queries';
|
2022-08-29 03:20:54 +00:00
|
|
|
import { secret } from 'lib/crypto';
|
2022-11-08 00:22:49 +00:00
|
|
|
import redis from 'lib/redis';
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2020-07-23 03:45:09 +00:00
|
|
|
export default async (req, res) => {
|
2022-11-09 06:58:52 +00:00
|
|
|
if (req.method === 'POST') {
|
|
|
|
|
const { username, password } = req.body;
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
if (!username || !password) {
|
|
|
|
|
return badRequest(res);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const user = await getUser({ username });
|
2021-10-04 03:44:02 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
if (user && checkPassword(password, user.password)) {
|
|
|
|
|
if (redis.enabled) {
|
|
|
|
|
const key = `auth:${getRandomChars(32)}`;
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
await redis.set(key, user);
|
2022-11-08 20:28:45 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
const token = createSecureToken(key, secret());
|
|
|
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const token = createSecureToken(user.id, secret());
|
2022-11-08 00:22:49 +00:00
|
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
return unauthorized(res, 'Incorrect username and/or password.');
|
2020-07-22 22:46:05 +00:00
|
|
|
}
|
2020-07-29 02:04:45 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
return methodNotAllowed(res);
|
2020-07-22 22:46:05 +00:00
|
|
|
};
|