Created the auth.ts controller

This commit is contained in:
Mathias Wagner 2023-01-15 19:42:12 +01:00
parent a083935704
commit 379bbbcd9f
Signed by: Mathias
GPG Key ID: B8DC354B0A1F5B44

35
src/controller/auth.ts Normal file
View File

@ -0,0 +1,35 @@
import { Account } from "../models/Account";
import { decryptField, encryptClearField } from "@utils/decryption";
import { compare } from "bcrypt";
import { Session } from "../models/Session";
export const login = async (configuration: { username: string, password: string }, user: { ip: string, userAgent: string }) => {
const account = await Account.findOne({ username: encryptClearField(configuration.username) });
// Check if account exists
if (account === null) return { code: 2001, message: "Username or password incorrect" };
// Check if password is correct
if (!await compare(configuration.password, account.password)) return {
code: 2001,
message: "Username or password incorrect",
};
// TODO: Integrate TOTP Verification
// Create Session
const session = await Session.create({
userId: account._id, ip: user.ip, userAgent: user.userAgent,
verified: true,
});
return { token: decryptField(session.token) };
};
export const logout = async (token: string) => {
const session = await Session.findOne({ token: encryptClearField(token) });
if (session === null) return { code: 2002, message: "Your session token is invalid" };
await session.delete();
};