umami/pages/api/auth/login.js

24 lines
710 B
JavaScript
Raw Normal View History

2022-08-29 05:20:54 +02:00
import { ok, unauthorized, badRequest, checkPassword, createSecureToken } from 'next-basics';
2022-07-12 23:14:36 +02:00
import { getAccountByUsername } from 'queries/admin/account/getAccountByUsername';
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);
}
2020-08-12 07:24:41 +02:00
const account = await getAccountByUsername(username);
2020-07-23 00:46:05 +02:00
2022-08-29 05:20:54 +02:00
if (account && checkPassword(password, account.password)) {
2020-07-23 05:45:09 +02:00
const { user_id, username, is_admin } = account;
const user = { user_id, username, is_admin };
2022-08-29 05:20:54 +02:00
const token = createSecureToken(user, secret());
2020-07-23 05:45:09 +02:00
return ok(res, { token, user });
2020-07-23 00:46:05 +02:00
}
return unauthorized(res);
2020-07-23 00:46:05 +02:00
};