forked from Wroclaw/WorkshopTasker
Initial commit
This commit is contained in:
commit
1e63e008af
48 changed files with 12715 additions and 0 deletions
40
server/api/login.post.ts
Normal file
40
server/api/login.post.ts
Normal file
|
@ -0,0 +1,40 @@
|
|||
/* global defineEventHandler, getCookie, setCookie, readBody, createError */
|
||||
import crypto from "crypto";
|
||||
|
||||
import { database, data } from "../utils/database";
|
||||
import { isString } from "../utils/isString";
|
||||
import Snowflake from "../utils/snowflake";
|
||||
import { cookieSettings } from "../utils/rootUtils";
|
||||
|
||||
export default defineEventHandler(async (e) => {
|
||||
if (getCookie(e, "token"))
|
||||
throw createError({ statusCode: 501, message: "Case not implemented: logging in while cookie is set" });
|
||||
await new Promise(resolve => setTimeout(resolve, 420));
|
||||
const data = await readBody(e);
|
||||
|
||||
const login = data.login;
|
||||
const password = data.password;
|
||||
|
||||
if (!isString(login)) throw createError({ statusCode: 400, message: "Login is not string." });
|
||||
if (!isString(password)) throw createError({ statusCode: 400, message: "Password is not string." });
|
||||
|
||||
const hashedPassword = crypto.createHmac("sha512", "42")
|
||||
.update(password)
|
||||
.digest("hex");
|
||||
|
||||
const [account] = await database.query(
|
||||
"SELECT CONVERT(`id`, CHAR(32)) AS `id` from `users` WHERE `username` = ? AND LOWER(HEX(`password`)) = ? LIMIT 1",
|
||||
[login, hashedPassword],
|
||||
)as unknown as data<{id: string}>;
|
||||
|
||||
if (account.length === 0) throw createError({ statusCode: 400, message: "Invalid username or password." });
|
||||
|
||||
const sessionId = new Snowflake().toString();
|
||||
|
||||
await database.query(
|
||||
"INSERT INTO `sessions` (`id`, `user`) VALUES ( ? , ? )",
|
||||
[sessionId, account[0].id],
|
||||
);
|
||||
setCookie(e, "token", sessionId, cookieSettings);
|
||||
return { message: "Login successful", token: sessionId };
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue