chore: Move API source code to API folder.
This commit is contained in:
parent
8015b0af74
commit
d3a664fea4
59 changed files with 43 additions and 38 deletions
66
api/src/routes/user/login.ts
Normal file
66
api/src/routes/user/login.ts
Normal file
|
@ -0,0 +1,66 @@
|
|||
import { compare } from "bcrypt";
|
||||
|
||||
import { generateToken } from "../../libs/generateToken.js";
|
||||
import type { RouteOptions } from "../../libs/types.js";
|
||||
|
||||
export function route(routeOptions: RouteOptions) {
|
||||
const {
|
||||
fastify,
|
||||
prisma,
|
||||
tokens
|
||||
} = routeOptions;
|
||||
|
||||
/**
|
||||
* Logs in to a user account.
|
||||
*/
|
||||
fastify.post("/api/v1/users/login", {
|
||||
schema: {
|
||||
body: {
|
||||
type: "object",
|
||||
required: ["email", "password"],
|
||||
|
||||
properties: {
|
||||
email: { type: "string" },
|
||||
password: { type: "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}, async(req, res) => {
|
||||
// @ts-ignore
|
||||
const body: {
|
||||
email: string,
|
||||
password: string
|
||||
} = req.body;
|
||||
|
||||
const userSearch = await prisma.user.findFirst({
|
||||
where: {
|
||||
email: body.email
|
||||
}
|
||||
});
|
||||
|
||||
if (!userSearch) return res.status(403).send({
|
||||
error: "Email or password is incorrect"
|
||||
});
|
||||
|
||||
const passwordIsValid = await compare(body.password, userSearch.password);
|
||||
|
||||
if (!passwordIsValid) return res.status(403).send({
|
||||
error: "Email or password is incorrect"
|
||||
});
|
||||
|
||||
const token = generateToken();
|
||||
if (!tokens[userSearch.id]) tokens[userSearch.id] = [];
|
||||
|
||||
tokens[userSearch.id].push({
|
||||
createdAt: Date.now(),
|
||||
expiresAt: Date.now() + (30 * 60_000),
|
||||
|
||||
token
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
token
|
||||
}
|
||||
});
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue