From 58ae32178ad6321c13997715c69be2d23bba2312 Mon Sep 17 00:00:00 2001 From: Bradley Shellnut Date: Tue, 27 Apr 2021 10:20:42 -0700 Subject: [PATCH] Setup form to submit 2FA after login and logging them in if correct. --- api/src/accounts/authorize.js | 24 ++++++++++++++++++------ api/src/index.js | 35 ++++++++++++++++++++++++++++++++--- 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/api/src/accounts/authorize.js b/api/src/accounts/authorize.js index 73e2219..0270b28 100644 --- a/api/src/accounts/authorize.js +++ b/api/src/accounts/authorize.js @@ -8,10 +8,22 @@ export async function authorizeUser(email, password) { const userData = await user.findOne({ 'email.address': email, }) - // Get user password - const savedPassword = userData.password - // Compare password with one in database - const isAuthorized = await compare(password, savedPassword) - // Return boolean of if password is correct - return { isAuthorized, userId: userData._id } + + if (userData) { + // Get user password + const savedPassword = userData.password + // Compare password with one in database + const isAuthorized = await compare(password, savedPassword) + // Return boolean of if password is correct + return { + isAuthorized, + userId: userData._id, + authenticatorSecret: userData.authenticator, + } + } + return { + isAuthorized: false, + userId: null, + authenticatorSecret: null, + } } \ No newline at end of file diff --git a/api/src/index.js b/api/src/index.js index fe56bb8..d34af0c 100644 --- a/api/src/index.js +++ b/api/src/index.js @@ -70,6 +70,29 @@ async function startApp() { } }); + app.post('/api/verify-2fa', {}, async (request, reply) => { + try { + // Verify user login + const { token, email, password } = request.body + const { + isAuthorized, + userId, + authenticatorSecret + } = await authorizeUser(email, password) + + const isValid = authenticator.verify({ token, secret: authenticatorSecret }) + + if (userId && isValid && isAuthorized) { + await logUserIn(userId, request, reply) + reply.send("success") + } + reply.code(401).send() + } catch (e) { + console.log('e', e) + return reply.code(401).send({}) + } + }); + app.post('/api/register', {}, async (request, reply) => { try { const userId = await registerUser( @@ -208,12 +231,11 @@ async function startApp() { app.post('/api/authorize', {}, async (request, reply) => { try { - console.log(request.body.email, request.body.password) - const { isAuthorized, userId } = await authorizeUser( + const { isAuthorized, userId, authenticatorSecret } = await authorizeUser( request.body.email, request.body.password ) - if (isAuthorized) { + if (isAuthorized && !authenticatorSecret) { await logUserIn(userId, request, reply) reply.send({ data: { @@ -221,7 +243,14 @@ async function startApp() { userId, }, }) + } else if (isAuthorized && authenticatorSecret) { + reply.send({ + data: { + status: "2FA", + }, + }) } + reply.code(401).send() } catch (e) { console.error('e', e); reply.send({