2023-04-05 06:29:54 +00:00
|
|
|
import { NextApiResponse } from 'next';
|
2022-11-09 06:58:52 +00:00
|
|
|
import {
|
|
|
|
|
ok,
|
|
|
|
|
unauthorized,
|
|
|
|
|
badRequest,
|
|
|
|
|
checkPassword,
|
|
|
|
|
createSecureToken,
|
|
|
|
|
methodNotAllowed,
|
|
|
|
|
} from 'next-basics';
|
2022-12-27 05:51:16 +00:00
|
|
|
import redis from '@umami/redis-client';
|
2023-02-28 04:03:04 +00:00
|
|
|
import { getUser } from 'queries';
|
2022-08-29 03:20:54 +00:00
|
|
|
import { secret } from 'lib/crypto';
|
2023-02-28 04:03:04 +00:00
|
|
|
import { NextApiRequestQueryBody, User } from 'lib/types';
|
2023-04-05 06:29:54 +00:00
|
|
|
import { setAuthKey } from 'lib/auth';
|
2022-11-15 21:21:14 +00: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 06:58:52 +00:00
|
|
|
if (req.method === 'POST') {
|
|
|
|
|
const { username, password } = req.body;
|
2020-07-22 22:46:05 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
if (!username || !password) {
|
|
|
|
|
return badRequest(res);
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-09 07:43:43 +00:00
|
|
|
const user = await getUser({ username }, { includePassword: true });
|
2021-10-04 03:44:02 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
if (user && checkPassword(password, user.password)) {
|
|
|
|
|
if (redis.enabled) {
|
2023-04-05 06:29:54 +00:00
|
|
|
const token = await setAuthKey(user);
|
2022-11-09 06:58:52 +00:00
|
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
|
}
|
|
|
|
|
|
2023-03-03 20:30:12 +00:00
|
|
|
const token = createSecureToken({ userId: user.id }, secret());
|
2022-11-08 00:22:49 +00:00
|
|
|
|
|
|
|
|
return ok(res, { token, user });
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-08 20:14:22 +00:00
|
|
|
return unauthorized(res, 'message.incorrect-username-password');
|
2020-07-22 22:46:05 +00:00
|
|
|
}
|
2020-07-29 02:04:45 +00:00
|
|
|
|
2022-11-09 06:58:52 +00:00
|
|
|
return methodNotAllowed(res);
|
2020-07-22 22:46:05 +00:00
|
|
|
};
|