2022-08-29 03:20:54 +00:00
|
|
|
import { ok, unauthorized, badRequest, checkPassword, createSecureToken } 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';
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2020-07-23 03:45:09 +00:00
|
|
|
export default async (req, res) => {
|
|
|
|
|
const { username, password } = req.body;
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2021-10-04 03:44:02 +00:00
|
|
|
if (!username || !password) {
|
|
|
|
|
return badRequest(res);
|
|
|
|
|
}
|
|
|
|
|
|
2022-11-01 06:42:37 +00:00
|
|
|
const user = await getUser({ username });
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2022-11-01 06:42:37 +00:00
|
|
|
if (user && checkPassword(password, user.password)) {
|
|
|
|
|
const { id: userId, username, isAdmin } = user;
|
|
|
|
|
const token = createSecureToken({ userId, username, isAdmin }, secret());
|
2020-07-23 03:45:09 +00:00
|
|
|
|
2022-02-23 06:47:59 +00:00
|
|
|
return ok(res, { token, user });
|
2020-07-22 22:46:05 +00:00
|
|
|
}
|
2020-07-29 02:04:45 +00:00
|
|
|
|
2020-08-08 00:19:42 +00:00
|
|
|
return unauthorized(res);
|
2020-07-22 22:46:05 +00:00
|
|
|
};
|