umami/pages/api/auth.js

23 lines
726 B
JavaScript
Raw Normal View History

2020-07-23 00:46:05 +02:00
import { serialize } from 'cookie';
2020-07-23 05:45:09 +02:00
import { checkPassword, createToken, secret } from 'lib/crypto';
import { getAccount } from 'lib/db';
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
2020-07-23 05:45:09 +02:00
const account = await getAccount(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;
const token = await createToken({ user_id, username, is_admin });
const expires = new Date(Date.now() + 31536000000);
const cookie = serialize('umami.auth', token, { expires, httpOnly: true });
2020-07-23 00:46:05 +02:00
res.setHeader('Set-Cookie', [cookie]);
2020-07-23 05:45:09 +02:00
res.status(200).send({ token });
2020-07-23 00:46:05 +02:00
} else {
res.status(401).send('');
}
};