91 lines
2.3 KiB
TypeScript
91 lines
2.3 KiB
TypeScript
import { type FastifyReply, type FastifyRequest } from "fastify";
|
|
import type {
|
|
IPostLoginRequest,
|
|
IPostRegisterResponseError,
|
|
IPostRegisterResponseSuccess,
|
|
IPostRegisterRequest,
|
|
IPostLoginResponseError,
|
|
IPostLoginResponseSuccess,
|
|
IGetRefreshResponseError,
|
|
IGetRefreshResponseSuccess,
|
|
} from "./types.js";
|
|
import {
|
|
loginUser,
|
|
refreshSession,
|
|
registerUser,
|
|
} from "../../services/auth/auth.js";
|
|
import { API_ERROR } from "../errors.js";
|
|
|
|
const postRegister = async (request: FastifyRequest, reply: FastifyReply) => {
|
|
const { username, password, email } = request.body as IPostRegisterRequest;
|
|
|
|
const newUser = await registerUser({
|
|
username: username,
|
|
password: password,
|
|
email: email,
|
|
});
|
|
|
|
if (!newUser) {
|
|
reply.status(409);
|
|
return {
|
|
error: API_ERROR.USER_ALREADY_EXISTS,
|
|
} as IPostRegisterResponseError;
|
|
}
|
|
|
|
return {
|
|
id: newUser.id,
|
|
username: newUser.username,
|
|
registerDate: newUser.registerDate?.getTime(),
|
|
} as IPostRegisterResponseSuccess;
|
|
};
|
|
|
|
const postLogin = async (request: FastifyRequest, reply: FastifyReply) => {
|
|
const { username, password } = request.body as IPostLoginRequest;
|
|
|
|
const session = await loginUser({
|
|
username: username,
|
|
password: password,
|
|
});
|
|
|
|
if (!session) {
|
|
reply.status(403);
|
|
return {
|
|
username: username,
|
|
error: API_ERROR.ACCESS_DENIED,
|
|
} as IPostLoginResponseError;
|
|
}
|
|
|
|
reply.setCookie("token", session.cookie, {
|
|
path: "/",
|
|
httpOnly: true,
|
|
sameSite: "none",
|
|
secure: true,
|
|
maxAge: 60 * 60 * 24 * 365 * 100,
|
|
});
|
|
|
|
return {
|
|
id: session.id,
|
|
ownerId: session.userId,
|
|
} as IPostLoginResponseSuccess;
|
|
};
|
|
|
|
const getRefresh = async (request: FastifyRequest, reply: FastifyReply) => {
|
|
const cookie = request.cookies["token"];
|
|
|
|
const refresh = await refreshSession(cookie);
|
|
|
|
if (!refresh) {
|
|
reply.status(403);
|
|
return {
|
|
error: API_ERROR.ACCESS_DENIED,
|
|
} as IGetRefreshResponseError;
|
|
}
|
|
|
|
return {
|
|
id: refresh[0].id,
|
|
ownerId: refresh[0].userId,
|
|
token: refresh[1],
|
|
} as IGetRefreshResponseSuccess;
|
|
};
|
|
|
|
export { postRegister, postLogin, getRefresh };
|