2022-11-09 07:58:52 +01:00
|
|
|
import {
|
|
|
|
ok,
|
|
|
|
unauthorized,
|
|
|
|
badRequest,
|
|
|
|
checkPassword,
|
|
|
|
createSecureToken,
|
|
|
|
methodNotAllowed,
|
|
|
|
getRandomChars,
|
|
|
|
} from 'next-basics';
|
2022-12-27 06:51:16 +01:00
|
|
|
import redis from '@umami/redis-client';
|
2023-02-28 05:03:04 +01:00
|
|
|
import { getUser } from 'queries';
|
2022-08-29 05:20:54 +02:00
|
|
|
import { secret } from 'lib/crypto';
|
2023-02-28 05:03:04 +01:00
|
|
|
import { NextApiRequestQueryBody, User } from 'lib/types';
|
2022-11-15 22:21:14 +01:00
|
|
|
import { NextApiResponse } from 'next';
|
|
|
|
|
|
|
|
export interface LoginRequestBody {
|
|
|
|
username: string;
|
|
|
|
password: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface LoginResponse {
|
|
|
|
token: string;
|
|
|
|
user: User;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async (
|
|
|
|
req: NextApiRequestQueryBody<any, LoginRequestBody>,
|
|
|
|
res: NextApiResponse<LoginResponse>,
|
|
|
|
) => {
|
2022-11-09 07:58:52 +01:00
|
|
|
if (req.method === 'POST') {
|
|
|
|
const { username, password } = req.body;
|
2020-07-23 00:46:05 +02:00
|
|
|
|
2022-11-09 07:58:52 +01:00
|
|
|
if (!username || !password) {
|
|
|
|
return badRequest(res);
|
|
|
|
}
|
|
|
|
|
2022-12-09 08:43:43 +01:00
|
|
|
const user = await getUser({ username }, { includePassword: true });
|
2021-10-04 05:44:02 +02:00
|
|
|
|
2022-11-09 07:58:52 +01:00
|
|
|
if (user && checkPassword(password, user.password)) {
|
|
|
|
if (redis.enabled) {
|
2023-02-02 03:39:54 +01:00
|
|
|
const authKey = `auth:${getRandomChars(32)}`;
|
2020-07-23 00:46:05 +02:00
|
|
|
|
2023-02-02 03:39:54 +01:00
|
|
|
await redis.set(authKey, user);
|
2022-11-08 21:28:45 +01:00
|
|
|
|
2023-02-02 03:39:54 +01:00
|
|
|
const token = createSecureToken({ authKey }, secret());
|
2022-11-09 07:58:52 +01:00
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
}
|
|
|
|
|
|
|
|
const token = createSecureToken(user.id, secret());
|
2022-11-08 01:22:49 +01:00
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
}
|
|
|
|
|
2022-11-09 07:58:52 +01:00
|
|
|
return unauthorized(res, 'Incorrect username and/or password.');
|
2020-07-23 00:46:05 +02:00
|
|
|
}
|
2020-07-29 04:04:45 +02:00
|
|
|
|
2022-11-09 07:58:52 +01:00
|
|
|
return methodNotAllowed(res);
|
2020-07-23 00:46:05 +02:00
|
|
|
};
|