umami/pages/api/auth/login.js

23 lines
647 B
JavaScript
Raw Normal View History

2020-07-23 06:33:17 +02:00
import { checkPassword, createSecureToken } from 'lib/crypto';
2020-08-12 07:24:41 +02:00
import { getAccountByUsername } from 'lib/queries';
2021-10-04 05:44:02 +02:00
import { ok, unauthorized, badRequest } from 'lib/response';
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
2020-07-23 05:45:09 +02:00
if (account && (await checkPassword(password, account.password))) {
const { user_id, username, is_admin } = account;
2020-07-23 06:33:17 +02:00
const token = await createSecureToken({ user_id, username, is_admin });
2020-07-23 05:45:09 +02:00
return ok(res, { token });
2020-07-23 00:46:05 +02:00
}
return unauthorized(res);
2020-07-23 00:46:05 +02:00
};