From fb1e2af67b0592e0c0759e7de8e9b4dff2fabc4a Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Sat, 21 Jan 2023 14:01:06 +0100 Subject: [PATCH] Created the verifySession method in the auth.ts controller --- src/controller/auth.ts | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/controller/auth.ts b/src/controller/auth.ts index 2b7e39c..be3d492 100644 --- a/src/controller/auth.ts +++ b/src/controller/auth.ts @@ -1,7 +1,8 @@ -import { Account } from "../models/Account"; +import { Account } from "@models/Account"; import { decryptField, encryptClearField } from "@utils/decryption"; import { compare } from "bcrypt"; -import { Session } from "../models/Session"; +import { Session } from "@models/Session"; +import speakeasy from "speakeasy"; export const login = async (configuration: { username: string, password: string }, user: { ip: string, userAgent: string }) => { const account = await Account.findOne({ username: encryptClearField(configuration.username) }); @@ -15,15 +16,32 @@ export const login = async (configuration: { username: string, password: string 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, + verified: !account.totpEnabled, }); - return { token: decryptField(session.token) }; + return { token: decryptField(session.token), totpRequired: account.totpEnabled }; +}; + +export const verifySession = async (configuration: { token: string, code: string }) => { + const session = await Session.findOne({ token: encryptClearField(configuration.token) }); + if (session === null) return { code: 2002, message: "Your session token is invalid" }; + + if (session.verified) return { code: 2012, message: "Your session already got verified" }; + + const account = await Account.findById(session.userId); + if (account === null) return { code: 2001, message: "Username or password incorrect" }; + + const tokenCorrect = speakeasy.totp.verify({ + secret: account.totpSecret || "", encoding: "base32", + token: configuration.code, + }); + + if (!tokenCorrect) return { code: 2011, message: "Your provided code is invalid or has expired." }; + + await Session.findByIdAndUpdate(session._id, { verified: true }); }; export const logout = async (token: string) => {