From 6526c1696b82c87be2511efed8cbd376fc075961 Mon Sep 17 00:00:00 2001 From: gurpinder2023 Date: Thu, 14 Nov 2024 11:07:03 -0800 Subject: [PATCH 1/2] completed cognito authentication --- server/server.js | 108 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/server/server.js b/server/server.js index 4e3160d..97d640c 100644 --- a/server/server.js +++ b/server/server.js @@ -6,6 +6,9 @@ import express from "express"; import cors from 'cors' import bodyParser from "body-parser" import coursesRouter from './api/courses.js'; +import AWS from "aws-sdk"; // Use import for aws-sdk + + // CONSTANTS @@ -13,6 +16,21 @@ const PORT = process.env.PORT || 5000; const app = express(); +// AWS CONFIG +let awsConfig = { + "region": "us-west-2", + "accessKeyId": process.env.AWS_ACCESS_KEY, + "secretAccessKey": process.env.AWS_SECRET_KEY +}; + +AWS.config.update(awsConfig); + +// Create a new SES object +const ses = new AWS.SES({ apiVersion: "2010-12-01" }); + +// Create a new CognitoIdentityServiceProvider object +const cognito = new AWS.CognitoIdentityServiceProvider(); + // MIDDLEWARE app.use(cors()) app.use(bodyParser.json()) @@ -30,6 +48,96 @@ app.get('/', async (req, res) => { }); +// signup route +app.post('/signup', async (req, res) => { + const { password, email, dob, firstName, lastName, phoneNo } = req.body; + + // Generate a unique student ID starting with 'A' followed by random digits + const studentId = 'A' + Math.floor(Math.random() * 100000000).toString(); // 'A' followed by an 8-digit random number + + + const params = { + ClientId: process.env.COGNITO_CLIENT_ID, // Your Cognito app client ID + Username: email, + Password: password, + UserAttributes: [ + { Name: 'email', Value: email }, + { Name: 'custom:DOB', Value: dob }, + { Name: 'custom:FirstName', Value: firstName }, + { Name: 'custom:LastName', Value: lastName }, + { Name: 'custom:PhoneNo', Value: phoneNo }, + { Name: 'custom:StudentId', Value: studentId }, + { Name: 'custom:UserType', Value: '0' } // Setting default userType to '0' + ] + }; + + try { + // Sign up the user + const data = await cognito.signUp(params).promise(); + + console.log('User signed up successfully:', data); + + res.status(200).json({ success: true, message: 'User signed up successfully', studentId }); + } catch (error) { + console.error('Error signing up user:', error); + res.status(500).json({ success: false, error: 'Error signing up user: ' + error.message }); + } + }); + +// verification of email route + +app.post('/verify', async (req, res) => { + const { email, verificationCode } = req.body; + + const params = { + ClientId: process.env.COGNITO_CLIENT_ID, // Your Cognito app client ID + Username: email, + ConfirmationCode: verificationCode + }; + + try { + // Confirm user's email address + await cognito.confirmSignUp(params).promise(); + + console.log('User email confirmed successfully'); + + res.status(200).json({ success: true, message: 'Email confirmed successfully. You can now log in.' }); + + + } catch (error) { + console.error('Error confirming email:', error); + res.status(500).json({ success: false, error: 'Internal Server Error' }); + } +}); + + +app.post('/login', async (req, res) => { + const { email, password } = req.body; + + const params = { + AuthFlow: 'USER_PASSWORD_AUTH', + ClientId: process.env.COGNITO_CLIENT_ID, + AuthParameters: { + USERNAME: email, + PASSWORD: password, + }, + }; + + try { + const data = await cognito.initiateAuth(params).promise(); + console.log("Login successful:", data); + res.status(200).json({ + success: true, + message: "Login successful", + // token: data.AuthenticationResult.IdToken, // If successful, send the ID token + }); + } catch (error) { + console.error("Error during login:", error); + res.status(400).json({ success: false, message: error.message }); + } +}); + + // LISTEN app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); From b4027e9b57b9303bd2ab9ef4d81605ddd073475a Mon Sep 17 00:00:00 2001 From: gurpinder2023 Date: Fri, 15 Nov 2024 21:48:09 -0800 Subject: [PATCH 2/2] changed the userpool to have less attributes --- server/server.js | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/server/server.js b/server/server.js index 97d640c..0aeae58 100644 --- a/server/server.js +++ b/server/server.js @@ -50,24 +50,17 @@ app.get('/', async (req, res) => { // signup route app.post('/signup', async (req, res) => { - const { password, email, dob, firstName, lastName, phoneNo } = req.body; + const { password, email } = req.body; - // Generate a unique student ID starting with 'A' followed by random digits - const studentId = 'A' + Math.floor(Math.random() * 100000000).toString(); // 'A' followed by an 8-digit random number - + const params = { ClientId: process.env.COGNITO_CLIENT_ID, // Your Cognito app client ID Username: email, Password: password, UserAttributes: [ - { Name: 'email', Value: email }, - { Name: 'custom:DOB', Value: dob }, - { Name: 'custom:FirstName', Value: firstName }, - { Name: 'custom:LastName', Value: lastName }, - { Name: 'custom:PhoneNo', Value: phoneNo }, - { Name: 'custom:StudentId', Value: studentId }, - { Name: 'custom:UserType', Value: '0' } // Setting default userType to '0' + { Name: 'email', Value: email } + ] }; @@ -76,8 +69,9 @@ app.post('/signup', async (req, res) => { const data = await cognito.signUp(params).promise(); console.log('User signed up successfully:', data); + const userId = data.UserSub; - res.status(200).json({ success: true, message: 'User signed up successfully', studentId }); + res.status(200).json({ success: true, message: 'User signed up successfully', userId}); } catch (error) { console.error('Error signing up user:', error); res.status(500).json({ success: false, error: 'Error signing up user: ' + error.message }); @@ -126,10 +120,14 @@ app.post('/login', async (req, res) => { try { const data = await cognito.initiateAuth(params).promise(); console.log("Login successful:", data); + // Extract the user ID from the ID token + const token = data.AuthenticationResult.IdToken; + const decodedToken = JSON.parse(Buffer.from(token.split('.')[1], 'base64').toString()); + const userId = decodedToken.sub; res.status(200).json({ success: true, message: "Login successful", - // token: data.AuthenticationResult.IdToken, // If successful, send the ID token + userId, // Return the unique user ID }); } catch (error) { console.error("Error during login:", error);