2020-07-23 00:46:05 +02:00
|
|
|
import { serialize } from 'cookie';
|
2020-07-23 06:33:17 +02:00
|
|
|
import { checkPassword, createSecureToken } from 'lib/crypto';
|
2020-07-23 05:45:09 +02:00
|
|
|
import { getAccount } from 'lib/db';
|
2020-07-24 04:56:55 +02:00
|
|
|
import { allowPost } from 'lib/middleware';
|
2020-07-23 00:46:05 +02:00
|
|
|
|
2020-07-23 05:45:09 +02:00
|
|
|
export default async (req, res) => {
|
2020-07-24 04:56:55 +02:00
|
|
|
await allowPost(req, res);
|
|
|
|
|
2020-07-23 05:45:09 +02:00
|
|
|
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;
|
2020-07-23 06:33:17 +02:00
|
|
|
const token = await createSecureToken({ user_id, username, is_admin });
|
2020-07-24 04:56:55 +02:00
|
|
|
const cookie = serialize('umami.auth', token, {
|
|
|
|
path: '/',
|
|
|
|
httpOnly: true,
|
|
|
|
maxAge: 60 * 60 * 24 * 365,
|
|
|
|
});
|
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 {
|
2020-07-24 04:56:55 +02:00
|
|
|
res.status(401).end();
|
2020-07-23 00:46:05 +02:00
|
|
|
}
|
|
|
|
};
|