2022-08-29 05:20:54 +02:00
|
|
|
import { ok, unauthorized, badRequest, checkPassword, createSecureToken } from 'next-basics';
|
2022-10-26 01:50:12 +02:00
|
|
|
import { getAccount } from 'queries';
|
2022-08-29 05:20:54 +02:00
|
|
|
import { secret } from 'lib/crypto';
|
2020-07-23 00:46:05 +02:00
|
|
|
|
2020-07-23 05:45:09 +02:00
|
|
|
export default async (req, res) => {
|
|
|
|
const { username, password } = req.body;
|
2020-07-23 00:46:05 +02:00
|
|
|
|
2021-10-04 05:44:02 +02:00
|
|
|
if (!username || !password) {
|
|
|
|
return badRequest(res);
|
|
|
|
}
|
|
|
|
|
2022-10-26 01:50:12 +02:00
|
|
|
const account = await getAccount({ username });
|
2020-07-23 00:46:05 +02:00
|
|
|
|
2022-08-29 05:20:54 +02:00
|
|
|
if (account && checkPassword(password, account.password)) {
|
2022-10-10 22:42:18 +02:00
|
|
|
const { id, username, isAdmin, accountUuid } = account;
|
|
|
|
const user = { userId: id, username, isAdmin, accountUuid };
|
2022-08-29 05:20:54 +02:00
|
|
|
const token = createSecureToken(user, secret());
|
2020-07-23 05:45:09 +02:00
|
|
|
|
2022-02-23 07:47:59 +01:00
|
|
|
return ok(res, { token, user });
|
2020-07-23 00:46:05 +02:00
|
|
|
}
|
2020-07-29 04:04:45 +02:00
|
|
|
|
2020-08-08 02:19:42 +02:00
|
|
|
return unauthorized(res);
|
2020-07-23 00:46:05 +02:00
|
|
|
};
|