2023-04-05 08:29:54 +02:00
|
|
|
import { NextApiResponse } from 'next';
|
2022-11-09 07:58:52 +01:00
|
|
|
import {
|
|
|
|
ok,
|
|
|
|
unauthorized,
|
|
|
|
badRequest,
|
|
|
|
checkPassword,
|
|
|
|
createSecureToken,
|
|
|
|
methodNotAllowed,
|
|
|
|
} 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';
|
2023-04-05 08:29:54 +02:00
|
|
|
import { setAuthKey } from 'lib/auth';
|
2022-11-15 22:21:14 +01:00
|
|
|
|
|
|
|
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-04-05 08:29:54 +02:00
|
|
|
const token = await setAuthKey(user);
|
2022-11-09 07:58:52 +01:00
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
}
|
|
|
|
|
2023-03-03 21:30:12 +01:00
|
|
|
const token = createSecureToken({ userId: user.id }, secret());
|
2022-11-08 01:22:49 +01:00
|
|
|
|
2023-04-13 21:08:53 +02:00
|
|
|
return ok(res, {
|
|
|
|
token,
|
|
|
|
user: { id: user.id, username: user.username, createdAt: user.createdAt },
|
|
|
|
});
|
2022-11-08 01:22:49 +01:00
|
|
|
}
|
|
|
|
|
2023-04-08 22:14:22 +02:00
|
|
|
return unauthorized(res, 'message.incorrect-username-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
|
|
|
};
|