diff --git a/src/controller/auth.ts b/src/controller/auth.ts new file mode 100644 index 0000000..2b7e39c --- /dev/null +++ b/src/controller/auth.ts @@ -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(); +}; \ No newline at end of file