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();
}
};

View file

@ -8,25 +8,24 @@ export default async (req, res) => {
const session = await checkSession(req);
const token = await createToken(session);
const { website_id, session_id } = session;
const { type, payload } = req.body;
let ok = 1;
let ok = false;
if (type === 'pageview') {
const { url, referrer } = payload;
await savePageView(website_id, session_id, url, referrer).catch(e => {
ok = 0;
throw e;
});
await savePageView(website_id, session_id, url, referrer);
ok = true;
} else if (type === 'event') {
const { url, event_type, event_value } = payload;
await saveEvent(website_id, session_id, url, event_type, event_value).catch(() => {
ok = 0;
throw e;
});
}
const token = await createToken(session);
await saveEvent(website_id, session_id, url, event_type, event_value);
ok = true;
}
res.status(200).json({ ok, session: token });
};

View file

@ -7,6 +7,6 @@ export default async (req, res) => {
const payload = await verifySecureToken(token);
res.status(200).send(payload);
} catch {
res.status(400).send('');
res.status(400).end();
}
};