Add services and auth
This commit is contained in:
parent
9b0b5dc040
commit
5dec454afb
46 changed files with 900 additions and 31 deletions
56
src/controllers/auth/auth.ts
Normal file
56
src/controllers/auth/auth.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import { type FastifyReply, type FastifyRequest } from "fastify";
|
||||
import type {
|
||||
ILoginRequest,
|
||||
IRegisterResponseError,
|
||||
IRegisterResponseSuccess,
|
||||
IRegisterRequest,
|
||||
ILoginResponseError,
|
||||
ILoginResponseSuccess,
|
||||
} from "./types.js";
|
||||
import { loginUser, registerUser } from "../../services/auth/auth.js";
|
||||
|
||||
const postRegister = async (request: FastifyRequest, _reply: FastifyReply) => {
|
||||
const { username, password, email } = request.body as IRegisterRequest;
|
||||
|
||||
const newUser = await registerUser({
|
||||
username: username,
|
||||
password: password,
|
||||
email: email,
|
||||
});
|
||||
|
||||
if (!newUser) {
|
||||
return {
|
||||
error: "user already exists",
|
||||
} as IRegisterResponseError;
|
||||
}
|
||||
|
||||
return {
|
||||
id: newUser.id,
|
||||
username: newUser.username,
|
||||
registerDate: newUser.registerDate?.getTime(),
|
||||
} as IRegisterResponseSuccess;
|
||||
};
|
||||
|
||||
const postLogin = async (request: FastifyRequest, _reply: FastifyReply) => {
|
||||
const { username, password } = request.body as ILoginRequest;
|
||||
|
||||
const session = await loginUser({
|
||||
username: username,
|
||||
password: password,
|
||||
});
|
||||
|
||||
if (!session) {
|
||||
return {
|
||||
ownerId: "",
|
||||
error: "incorrect credentials",
|
||||
} as ILoginResponseError;
|
||||
}
|
||||
|
||||
return {
|
||||
id: session.id,
|
||||
ownerId: session.userId,
|
||||
token: session.token,
|
||||
} as ILoginResponseSuccess;
|
||||
};
|
||||
|
||||
export { postRegister, postLogin };
|
||||
Loading…
Add table
Add a link
Reference in a new issue