Accounts and login.

This commit is contained in:
Mike Cao 2020-07-23 19:56:55 -07:00
parent f3f0ad15f2
commit 49a55b40b4
22 changed files with 347 additions and 172 deletions

View file

@ -1,8 +1,11 @@
import { serialize } from 'cookie';
import { checkPassword, createSecureToken } from 'lib/crypto';
import { getAccount } from 'lib/db';
import { allowPost } from 'lib/middleware';
export default async (req, res) => {
await allowPost(req, res);
const { username, password } = req.body;
const account = await getAccount(username);
@ -10,13 +13,16 @@ export default async (req, res) => {
if (account && (await checkPassword(password, account.password))) {
const { user_id, username, is_admin } = account;
const token = await createSecureToken({ user_id, username, is_admin });
const expires = new Date(Date.now() + 31536000000);
const cookie = serialize('umami.auth', token, { expires, httpOnly: true });
const cookie = serialize('umami.auth', token, {
path: '/',
httpOnly: true,
maxAge: 60 * 60 * 24 * 365,
});
res.setHeader('Set-Cookie', [cookie]);
res.status(200).send({ token });
} else {
res.status(401).send('');
res.status(401).end();
}
};