Switch to json web tokens.

This commit is contained in:
Mike Cao 2020-07-22 20:45:09 -07:00
parent 5219582803
commit cb0c912c5b
10 changed files with 202 additions and 86 deletions

View file

@ -1,18 +1,21 @@
import { serialize } from 'cookie';
import { hash, random, encrypt } from 'lib/crypto';
import { checkPassword, createToken, secret } from 'lib/crypto';
import { getAccount } from 'lib/db';
export default (req, res) => {
const { password } = req.body;
export default async (req, res) => {
const { username, password } = req.body;
if (password === process.env.PASSWORD) {
const account = await getAccount(username);
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 id = random();
const value = encrypt(`${id}:${hash(id)}`);
const cookie = serialize('umami.auth', value, { expires, httpOnly: true });
const cookie = serialize('umami.auth', token, { expires, httpOnly: true });
res.setHeader('Set-Cookie', [cookie]);
res.status(200).send('');
res.status(200).send({ token });
} else {
res.status(401).send('');
}

View file

@ -1,14 +1,14 @@
import { parseSession } from 'lib/utils';
import { savePageView, saveEvent } from 'lib/db';
import { allowPost } from 'lib/middleware';
import checkSession from 'lib/session';
import { createToken } from 'lib/crypto';
export default async (req, res) => {
await allowPost(req, res);
const session = await checkSession(req);
const { website_id, session_id } = parseSession(session);
const { website_id, session_id } = session;
const { type, payload } = req.body;
let ok = 1;
@ -26,5 +26,7 @@ export default async (req, res) => {
});
}
res.status(200).json({ ok, session });
const token = await createToken(session);
res.status(200).json({ ok, session: token });
};