Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OTP Authentication #14

Merged
merged 102 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 99 commits
Commits
Show all changes
102 commits
Select commit Hold shift + click to select a range
5b0ace4
added google fonts, calendar date picker, search choices packages
Nailsonseat Jan 19, 2024
1d10082
added placeholder image
Nailsonseat Jan 19, 2024
89420db
added android flex fonts
Nailsonseat Jan 19, 2024
ce355e3
routed admin pages as root
Nailsonseat Jan 19, 2024
1b35d4b
routed collapsing app bar component
Nailsonseat Jan 19, 2024
517ba4e
routed menu tile component
Nailsonseat Jan 19, 2024
b7e016b
routed text divider component
Nailsonseat Jan 19, 2024
0d0f626
implemented a tile based admin menu
Nailsonseat Jan 19, 2024
e4dddce
add students page layout with input fields
Nailsonseat Jan 19, 2024
3d03d80
add courses page layout with input fields
Nailsonseat Jan 19, 2024
1bb562e
add faculty page layout (barebone)
Nailsonseat Jan 19, 2024
c3bca4e
initial view courses page with search bar
Nailsonseat Jan 19, 2024
730b1cc
initial view faculty page with search bar
Nailsonseat Jan 19, 2024
493cd8c
initial view students page with search bar
Nailsonseat Jan 19, 2024
582f2a6
removed dead code
Nailsonseat Jan 19, 2024
f88924d
added mess menu tiles
Nailsonseat Jan 19, 2024
3619b3a
added year picker component
Nailsonseat Jan 20, 2024
fca1df8
added logger package
Nailsonseat Jan 20, 2024
71d28bc
added flutter type head package
Nailsonseat Jan 20, 2024
e237017
added rounded chip component
Nailsonseat Jan 20, 2024
01be33b
added json serializable component
Nailsonseat Jan 21, 2024
2c6ab5a
added file picker, grouped list and slide switcher package
Nailsonseat Jan 21, 2024
5fd9e7e
menu provider initial commit
Nailsonseat Jan 21, 2024
7d7062f
add menu initial commit
Nailsonseat Jan 21, 2024
f5d1f78
added validators
Nailsonseat Jan 21, 2024
4e7aa89
added choice selector component
Nailsonseat Jan 21, 2024
ca87cc5
fined course model
Nailsonseat Jan 21, 2024
29d11ef
fined student model
Nailsonseat Jan 21, 2024
3b649f9
added email validator and awesome snack bar package
Nailsonseat Jan 21, 2024
fdcedf4
implemented student provider
Nailsonseat Jan 21, 2024
5344aa7
changed choice selector to not have a null value
Nailsonseat Jan 21, 2024
bfe1ac4
display snack bar on student addition
Nailsonseat Jan 21, 2024
088c146
added validators
Nailsonseat Jan 21, 2024
f2b069e
tile default splash color to grey[200]
Nailsonseat Jan 21, 2024
608d12b
defined admin provider with menu tile builder
Nailsonseat Jan 21, 2024
87761e2
added a search bar for menu tiles and a popup menu
Nailsonseat Jan 21, 2024
9a883f6
dynamic menu tile builder connected to search bar
Nailsonseat Jan 21, 2024
41d78a1
courses provider initial commit
Nailsonseat Jan 21, 2024
5f1b4a9
defined providers at root
Nailsonseat Jan 21, 2024
7b7498c
defined faculty model
Nailsonseat Jan 21, 2024
e46f427
added admin routes
Nailsonseat Jan 21, 2024
47ac3ec
added branches list
Nailsonseat Jan 21, 2024
641a9a0
added special role list
Nailsonseat Jan 21, 2024
7a02af1
formatted validators
Nailsonseat Jan 21, 2024
d976b52
added bottom parameter to collapsing appbar
Nailsonseat Jan 21, 2024
5570f4d
initial commit search course by code
Nailsonseat Jan 21, 2024
d89bde0
replaced chip adder with suggestion text field
Nailsonseat Jan 21, 2024
2e33e03
search student by roll number
Nailsonseat Jan 21, 2024
2aa7342
add mess menu initial commit
Nailsonseat Jan 21, 2024
c4fb4e1
added delightful toast package
Nailsonseat Jan 23, 2024
01a486d
added dummy entries for variety of schemas
Nailsonseat Jan 23, 2024
eb8f272
Add BorderlessButton component
Nailsonseat Jan 23, 2024
020a3be
Refactor CollapsingAppBar constructor and update SliverAppBar properties
Nailsonseat Jan 23, 2024
d08faad
Add MaterialTextFormField component
Nailsonseat Jan 23, 2024
ee16b7b
Add MultipleChoiceSelector component
Nailsonseat Jan 23, 2024
7c4b227
Add SuggestionTextField component
Nailsonseat Jan 23, 2024
1c1cf0c
Add MessMenu model class
Nailsonseat Jan 23, 2024
57a9609
Add new routes for managing rooms and viewing menu
Nailsonseat Jan 23, 2024
9e92824
Add Room model class
Nailsonseat Jan 23, 2024
c2fca2c
Add file picker functionality and search by student name
Nailsonseat Jan 23, 2024
aee98b4
Add file picker functionality and menu initialization
Nailsonseat Jan 23, 2024
15615ea
Add menu functionality and remove menu item
Nailsonseat Jan 23, 2024
ac5db9b
Added a menu tile for managing rooms
Nailsonseat Jan 23, 2024
84396c7
Add RoomProvider class with methods for picking spreadsheet and addin…
Nailsonseat Jan 23, 2024
b79dc85
Add search functionality to RoomProvider
Nailsonseat Jan 23, 2024
2a8e0a7
Refactor courses_provider to search students by name
Nailsonseat Jan 23, 2024
1ecc5a7
Add FacultyProvider class with methods for adding, searching, and rem…
Nailsonseat Jan 23, 2024
1f5e611
Add FacultyProvider and RoomProvider to root
Nailsonseat Jan 23, 2024
c8d44f2
Add ChoiceSelector component and import necessary files
Nailsonseat Jan 23, 2024
5d5054c
impleemented input fields for single faculty entry
Nailsonseat Jan 23, 2024
24bce73
Update add_students.dart with new button to pick spreadsheet
Nailsonseat Jan 23, 2024
93255e8
Add ManageRooms screen
Nailsonseat Jan 23, 2024
b5688e7
implemented row and column sliders for adding menu
Nailsonseat Jan 23, 2024
54d84a0
Added about and logout dialog pop ups
Nailsonseat Jan 23, 2024
9885766
Update course search functionality and add course editing dialog
Nailsonseat Jan 23, 2024
99edc90
Add faculty search functionality and display faculty list
Nailsonseat Jan 23, 2024
c5deaf4
Add ViewMessMenu screen
Nailsonseat Jan 23, 2024
8453de0
Update search bar hint text and add dialog for student editing
Nailsonseat Jan 23, 2024
b27ced2
Finalized validators
Nailsonseat Jan 23, 2024
9f59c3a
Merge branch 'main' into admin-role
Nailsonseat Jan 23, 2024
39b866b
Merge branch 'pr/13' into loginPage
ArinNigam Jan 28, 2024
60f5c2e
Merge branch 'OpenLake:main' into admin-role
Nailsonseat Jan 28, 2024
43b7daf
Removed dummy test files
Nailsonseat Jan 28, 2024
d245bca
Added flutter_riverpod package
Nailsonseat Jan 28, 2024
134ff7f
Defined provider scope at root
Nailsonseat Jan 28, 2024
0ce6268
Migrate Room provider to riverpod
Nailsonseat Jan 28, 2024
e41fb85
Migrate Student provider to riverpod
Nailsonseat Jan 28, 2024
d5a3c7a
Migrate Course provider to riverpod
Nailsonseat Jan 28, 2024
e68f3ea
Migrate Faculty provider to riverpod
Nailsonseat Jan 28, 2024
56e05c6
Migrate Menu provider to riverpod
Nailsonseat Jan 28, 2024
4bc702a
Migrate Admin provider to riverpod
Nailsonseat Jan 28, 2024
f8d75af
Formatting and minor bug fixes
Nailsonseat Jan 28, 2024
5480372
added login page
ArinNigam Jan 28, 2024
28467b5
fixed otp for gmail
ArinNigam Jan 29, 2024
05c305a
added login page
ArinNigam Jan 28, 2024
c3025dc
fixed otp for gmail
ArinNigam Jan 29, 2024
8602a68
Merge branch 'loginPage' of https://github.com/ArinNigam/Smart-Insti-…
ArinNigam Jan 30, 2024
c965921
Revert "Merge branch 'loginPage' of https://github.com/ArinNigam/Smar…
ArinNigam Jan 31, 2024
dd7363b
Deleted backend/package-lock.json
ArinNigam Jan 31, 2024
96204f4
Delete .vscode/easycode.ignore
ArinNigam Feb 1, 2024
0969b01
Update .gitignore
ArinNigam Feb 1, 2024
f053624
sender email is env variable
ArinNigam Feb 1, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .vscode/easycode.ignore
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add it to .gitignore.

Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
node_modules/
dist/
vendor/
cache/
.*/
*.min.*
*.test.*
*.spec.*
*.bundle.*
*.bundle-min.*
*.*.js
*.*.ts
*.log
8 changes: 4 additions & 4 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ import authResource from "./resources/authResource.js";
import otpResource from "./resources/otpResource.js";
import Connection from "./database/db.js";
import bodyParser from "body-parser";

import cors from "cors";
const PORT =`${process.env.PORT || 3000}`;
const app = express();

app.use(logger("dev"));
app.use(express.json())
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors());

// Get Database connection
Connection();

app.use(authResource);
app.use("/signup",otpResource);
app.use("/signin",otpResource);
app.use(otpResource);
app.use("/", testResource);

export default app;
4 changes: 2 additions & 2 deletions backend/bin/www
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const server = http.createServer(app);
* Listen on provided port, on all network interfaces.
*/

server.listen(port);
server.listen(port,"0.0.0.0");
server.on("error", onError);
server.on("listening", onListening);

Expand Down Expand Up @@ -82,7 +82,7 @@ function onError(error) {
function onListening() {
const addr = server.address();
let address = addr.address;
if (address === "::" || address === "127.0.0.1" || address === "::1") {
if (address === "::" || address === "127.0.0.1" || address === "::1" || address==="0.0.0.0") {
address = "localhost";
}
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
Expand Down
8 changes: 6 additions & 2 deletions backend/constants/errorMessages.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ export const databaseConnectionError = "Error while connecting with the database

// OTP
export const emailIsRequired = 'Email is required';
export const failedToSendOTPEmail = 'Failed to send OTP email';
export const failedToSendOTPEmail = 'Failed to send OTP to email';
export const emailAndOTPRequired = 'Email and OTP are required';
export const noOTPFoundForEmail = 'No OTP found for the email';
export const incorrectOTP = 'Incorrect OTP';
export const otpVerfied = 'OTP verified successfully';
export const otpSent = 'OTP sent successfully';
export const otpSent = 'OTP sent successfully';

// Auth Middleware
export const noAuthToken = 'No auth token, access denied';
export const tokenVerificationFailed = 'Token verification failed, authorization denied.';
2 changes: 1 addition & 1 deletion backend/constants/mailOption.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export const senderEmail = 'college@gmail.com';
export const senderEmail = 'arin.nigam@gmail.com';
export const subjectOTPLogin = 'OTP for Login';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please take email as an env variable.


export function createOTPEmailBody(otp) {
Expand Down
7 changes: 4 additions & 3 deletions backend/middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import jwt from "jsonwebtoken";
const passwordKey = proccess.env.PASSWORD_KEY;
import * as errorMessages from "../constants/errorMessages.js";
const passwordKey = process.env.PASSWORD_KEY;

const auth = async (req, res, next) => {
try {
const token = req.header("x-auth-token");
if (!token)
return res.status(401).json({ msg: "No auth token, access denied" });
return res.status(401).json({ msg: errorMessages.noAuthToken });

const verified = jwt.verify(token, passwordKey);
if (!verified)
return res
.status(401)
.json({ msg: "Token verification failed, authorization denied." });
.json({ msg: errorMessages.tokenVerificationFailed });

req.user = verified.id;
req.token = token;
Expand Down
5 changes: 4 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "^4.3.4",
"dotenv": "^16.3.2",
"express": "~4.16.1",
Expand All @@ -22,6 +23,8 @@
"multer": "^1.4.5-lts.1",
"nodemailer": "^6.9.8",
"nodemon": "^3.0.3",
"pug": "2.0.0-beta11"
"pug": "2.0.0-beta11",
"xoauth2": "^1.2.0",
"yarn": "^1.22.21"
}
}
81 changes: 35 additions & 46 deletions backend/resources/otpResource.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,32 @@
import express from 'express'
import nodemailer from 'nodemailer'
import dotenv from 'dotenv'
import { MongoClient } from 'mongodb';
import jwt from 'jsonwebtoken';
import * as errorConstants from '../constants/errorMessages.js';
import * as mailOption from '../constants/mailOption.js';
const otpRouter = express.Router();

const otpRouter = express.Router();
dotenv.config();

// Nodemailer configuration using Ethereal
async function getTestAccount() {
return nodemailer.createTestAccount();
}

// Generate a random 4-digit OTP
function generateOTP() {
return Math.floor(1000 + Math.random() * 9000).toString();
}

// Nodemailer configuration
const transporter = nodemailer.createTransport({
// Create an ethereal account and replace it in .env file
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
service: "Gmail",
host: "smtp.gmail.com",
port: 465,
secure: false,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
pass: process.env.SMTP_PASSWORD,
},
});

import { MongoClient } from 'mongodb';

// Connection URI for your MongoDB database
const uri = process.env.MONGODB_URI; // Change this to your actual MongoDB connection URI
const uri = process.env.MONGODB_URI;

// Create a new MongoClient
const client = new MongoClient(uri);
Expand All @@ -45,36 +40,14 @@ const otpStorage = new Map();

otpRouter.post('/send-otp', async (req, res) => {
const { email } = req.body;

if (!email) {
return res.status(400).json({ error: errorConstants.emailIsRequired });
}

// Generate OTP
const otp = generateOTP();
console.log(otp);

// Store OTP with the associated email
otpStorage.set(email, otp);

try {
// Connect to the MongoDB server
await client.connect();

// Use a specific database
const database = client.db(dbName);

// Use a specific collection
const collection = database.collection(collectionName);
await collection.deleteMany({
email:email,
});
await collection.insertOne({ email, otp});
console.log('OTP data stored in MongoDB');
} finally {
// Close the connection when done
await client.close();
}
// Nodemailer options
const mailOptions = {
from: mailOption.senderEmail,
to: email,
Expand All @@ -85,10 +58,30 @@ otpRouter.post('/send-otp', async (req, res) => {
// Send mail
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
return res.status(500).json({ error: errorConstants.failedToSendOTPEmail });
}
res.json({ message: errorConstants.otpSent, email });
else{
console.log('Message sent: %s', info.response);
res.json({ message: errorConstants.otpSent, email });
}
});

// Connect to the MongoDB server
try {
await client.connect();
const database = client.db(dbName);
const collection = database.collection(collectionName);
await collection.deleteMany({
email:email,
});

await collection.insertOne({ email, otp});
console.log('OTP data stored in MongoDB');

} finally {
await client.close();
}
});

otpRouter.post('/verify-otp', async (req, res) => {
Expand All @@ -100,11 +93,9 @@ otpRouter.post('/verify-otp', async (req, res) => {

try {
await client.connect();

const database = client.db(dbName);
const collection = database.collection(collectionName);

// Retrieve stored OTP and timestamp for the email from the database
const result = await collection.findOne({ email });

if (!result || !result.otp) {
Expand All @@ -115,15 +106,13 @@ otpRouter.post('/verify-otp', async (req, res) => {

// Compare the provided OTP with the stored OTP
if (otp === storedOTP) {
// Clear OTP from storage after successful verification (for demo purposes)
await collection.deleteOne({ email });
return res.json({ message: errorConstants.otpVerfied });
const token = jwt.sign({ email }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1h' });
return res.json({ message: errorConstants.otpVerfied, token });
}

res.status(401).json({ error: errorConstants.incorrectOTP });
} catch (err) {
console.error('Error:', err.message);
res.status(500).json({ error: 'Internal Server Error' });
res.status(500).json({ error: errorConstants.internalServerError });
} finally {
await client.close();
}
Expand Down
Loading
Loading