diff --git a/client/src/App.js b/client/src/App.js
index a62279e..d7b381f 100644
--- a/client/src/App.js
+++ b/client/src/App.js
@@ -1,27 +1,24 @@
-import React, { createContext, useReducer } from "react";
+import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
-import StudentSigin from "./components/Screens/Signin/StudentSignin";
+import StudentSignin from "./components/Screens/Signin/StudentSignin";
import AdminSignin from "./components/Screens/Signin/AdminSigin";
import StudentSignup from "./components/Screens/Signup/StudentSignup";
import AdminSignup from "./components/Screens/Signup/AdminSignup";
+import AdminOTP from "./components/Screens/AdminOTP/AdminOtp";
import Footer from "../src/components/footer";
import Header from "../src/components/header";
-import HomePage from "../src/components/Screens/HomeScreen/HomePage";
+import HomePage from "../src/components/Screens/HomeScreen/HomePage";
+import StudentOTP from "./components/Screens/StudentOTP/StudentOTP";
import home from "./components/home";
import about from "./components/about";
import contact from "./components/contact";
import myshelf from "./components/myshelf";
-import { initialState, reducer } from "./reducer/UseReducer";
-
-// crete context
-export const userContext = createContext();
-
const sections = [
{ title: "Technology", url: "#" },
{ title: "Design", url: "#" },
@@ -36,24 +33,24 @@ const sections = [
];
function App() {
- const [state, dispatch] = useReducer(reducer, initialState);
return (
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
);
}
diff --git a/client/src/components/Screens/AdminOTP/AdminOtp.js b/client/src/components/Screens/AdminOTP/AdminOtp.js
new file mode 100644
index 0000000..3b82e40
--- /dev/null
+++ b/client/src/components/Screens/AdminOTP/AdminOtp.js
@@ -0,0 +1,222 @@
+import React, { useState, useEffect } from "react";
+import { useHistory } from "react-router-dom";
+import Avatar from "@material-ui/core/Avatar";
+import Button from "@material-ui/core/Button";
+import CssBaseline from "@material-ui/core/CssBaseline";
+import TextField from "@material-ui/core/TextField";
+import Link from "@material-ui/core/Link";
+import Paper from "@material-ui/core/Paper";
+import Box from "@material-ui/core/Box";
+import Grid from "@material-ui/core/Grid";
+import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
+import Typography from "@material-ui/core/Typography";
+import { makeStyles } from "@material-ui/core/styles";
+import { toast } from "react-toastify";
+import "react-toastify/dist/ReactToastify.css";
+require('dotenv').config()
+
+
+const jwt = require("jsonwebtoken");
+// import LoadingScreen from "../LoadingScreen/LoadingScreen";
+toast.configure();
+
+function sleep(time) {
+ return new Promise((resolve) => setTimeout(resolve, time));
+}
+function Copyright() {
+ return (
+
+ {"Copyright © "}
+
+ Library
+ {" "}
+ {new Date().getFullYear()}
+ {"."}
+
+ );
+}
+
+const useStyles = makeStyles((theme) => ({
+ root: {
+ height: "100vh",
+ },
+ image: {
+ backgroundImage: "url(/images/img.jpg)",
+ backgroundRepeat: "no-repeat",
+ backgroundColor:
+ theme.palette.type === "light"
+ ? theme.palette.grey[50]
+ : theme.palette.grey[900],
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ },
+ paper: {
+ margin: theme.spacing(8, 4),
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ },
+ avatar: {
+ margin: theme.spacing(1),
+ backgroundColor: theme.palette.secondary.main,
+ },
+ form: {
+ width: "100%", // Fix IE 11 issue.
+ marginTop: theme.spacing(1),
+ },
+ submit: {
+ margin: theme.spacing(3, 0, 2),
+ },
+}));
+
+export default function AdminOTP() {
+ const classes = useStyles();
+ const [otp, setOtp] = useState("");
+ const [id, setid] = useState("");
+ const history = useHistory();
+
+ const [loading, setLoading] = useState(true);
+ useEffect(() => {
+ try {
+ setLoading(true);
+ // toast.success("uieuri");
+ // const token=localStorage.getItem("Studenttoken");
+ // toast.success(token);
+ const decoded_token = jwt.verify(
+ localStorage.getItem("Admintoken"),
+ process.env.REACT_APP_JWT_SECRET
+ );
+ toast.error(decoded_token._id);
+ setid(decoded_token._id);
+ // toast.success(id);
+ fetch("http://localhost:3001/api/admin/verifyadmin", {
+ method: "post",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ id: decoded_token._id,
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ setLoading(false);
+ if (result.isverified) {
+
+ history.push("/");
+ }
+ });
+ } catch (err) {
+ toast.error("error");
+ setLoading(false);
+ // history.push("/signin");
+ }
+ }, []);
+
+ const submitHandler = () => {
+
+ if (otp === "") {
+ console.log("Please enter otp");
+ } else {
+ fetch("http://localhost:3001/api/admin/adminotp", {
+ method: "post",
+ headers: {
+ "Content-Type": "application/json",
+ authorization: "Bearer " + localStorage.getItem("jwt"),
+ },
+ body: JSON.stringify({
+ otp: otp,
+ timestamp: Date.now(),
+ id: id,
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+
+ if (result.message === "Valid OTP...Admin Authenticated") {
+ toast.success("Sweet !", {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 1500,
+ });
+ sleep(2000).then(() => {
+ history.push("/");
+ window.location.reload(false);
+ });
+ } else {
+ toast.warning(result.message, {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 2000,
+ });
+ }
+ });
+ }
+ };
+ return (
+ <>
+ {}
+
+ { (
+
+
+
+
+
+
+
+
+
+ Student OTP
+
+
+
+
+
+ )}
+ >
+ );
+}
\ No newline at end of file
diff --git a/client/src/components/Screens/AdminOTP/readme.md b/client/src/components/Screens/AdminOTP/readme.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/client/src/components/Screens/AdminOTP/readme.md
@@ -0,0 +1 @@
+
diff --git a/client/src/components/Screens/Signin/AdminSigin.js b/client/src/components/Screens/Signin/AdminSigin.js
index 4504fd3..1fd7bf8 100644
--- a/client/src/components/Screens/Signin/AdminSigin.js
+++ b/client/src/components/Screens/Signin/AdminSigin.js
@@ -108,10 +108,31 @@ export default function AdminSigin() {
// console.log(result);
if (result.message === "Success") {
- toast.success("Sweet !", {
+
+ localStorage.setItem("Admintoken",result.token);
+
+ if (result.isAuthenticated) {
+ toast.success("Sweet !", {
position: toast.POSITION.TOP_CENTER,
autoClose: 1500,
- })
+ });
+ sleep(2000).then(() => {
+ history.push("/");
+ window.location.reload(false);
+ });
+ } else {
+ console.log("Admin unauthorised");
+ toast.warning("Please Authorize yourself", {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 2000,
+ });
+ sleep(2300).then(() => {
+ history.push("/adminotp");
+ // window.location.reload(false);
+ });
+ }
+
+
} else {
toast.error(`${result.message}`, {
position: toast.POSITION.TOP_CENTER,
diff --git a/client/src/components/Screens/Signin/StudentSignin.js b/client/src/components/Screens/Signin/StudentSignin.js
index ef17835..eef4a41 100644
--- a/client/src/components/Screens/Signin/StudentSignin.js
+++ b/client/src/components/Screens/Signin/StudentSignin.js
@@ -1,6 +1,5 @@
-import { useContext,React, useState } from "react";
+import { React, useState } from "react";
import { useHistory } from "react-router-dom";
-// import { jwt } from "jsonwebtoken";
import Avatar from "@material-ui/core/Avatar";
import Button from "@material-ui/core/Button";
import CssBaseline from "@material-ui/core/CssBaseline";
@@ -17,9 +16,6 @@ import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
// import LoadingScreen from "../LoadingScreen/LoadingScreen";
-import {userContext} from "../../../App";
-
-
toast.configure();
function sleep(time) {
@@ -72,11 +68,7 @@ const useStyles = makeStyles((theme) => ({
},
}));
-export default function StudentSigin() {
-
- const {state, dispatch} = useContext(userContext);
-
-
+export default function StudentSignin() {
const [Loading, setLoading] = useState(false);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
@@ -110,14 +102,32 @@ export default function StudentSigin() {
// setLoading(false);
// toast.success("ueuririr");
- // console.log(result);
+ // toast.success(result.message);
if (result.message === "Success") {
- dispatch({type:"USER", payload:true});
- toast.success("Sweet !", {
- position: toast.POSITION.TOP_CENTER,
- autoClose: 1500,
- });
- history.push("/");
+
+
+ localStorage.setItem("Studenttoken",result.token);
+
+ if (result.isAuthenticated) {
+ toast.success("Sweet !", {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 1500,
+ });
+ sleep(2000).then(() => {
+ history.push("/");
+ window.location.reload(false);
+ });
+ } else {
+ console.log("customer unauthorised");
+ toast.warning("Please Authorize yourself", {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 2000,
+ });
+ sleep(2300).then(() => {
+ history.push("/studentotp");
+ // window.location.reload(false);
+ });
+ }
} else {
toast.error(`${result.message}`, {
position: toast.POSITION.TOP_CENTER,
diff --git a/client/src/components/Screens/StudentOTP/StudentOTP.js b/client/src/components/Screens/StudentOTP/StudentOTP.js
new file mode 100644
index 0000000..8b0a8e2
--- /dev/null
+++ b/client/src/components/Screens/StudentOTP/StudentOTP.js
@@ -0,0 +1,222 @@
+import React, { useState, useEffect } from "react";
+import { useHistory } from "react-router-dom";
+import Avatar from "@material-ui/core/Avatar";
+import Button from "@material-ui/core/Button";
+import CssBaseline from "@material-ui/core/CssBaseline";
+import TextField from "@material-ui/core/TextField";
+import Link from "@material-ui/core/Link";
+import Paper from "@material-ui/core/Paper";
+import Box from "@material-ui/core/Box";
+import Grid from "@material-ui/core/Grid";
+import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
+import Typography from "@material-ui/core/Typography";
+import { makeStyles } from "@material-ui/core/styles";
+import { toast } from "react-toastify";
+import "react-toastify/dist/ReactToastify.css";
+require('dotenv').config()
+
+
+const jwt = require("jsonwebtoken");
+// import LoadingScreen from "../LoadingScreen/LoadingScreen";
+toast.configure();
+
+function sleep(time) {
+ return new Promise((resolve) => setTimeout(resolve, time));
+}
+function Copyright() {
+ return (
+
+ {"Copyright © "}
+
+ Library
+ {" "}
+ {new Date().getFullYear()}
+ {"."}
+
+ );
+}
+
+const useStyles = makeStyles((theme) => ({
+ root: {
+ height: "100vh",
+ },
+ image: {
+ backgroundImage: "url(/images/img.jpg)",
+ backgroundRepeat: "no-repeat",
+ backgroundColor:
+ theme.palette.type === "light"
+ ? theme.palette.grey[50]
+ : theme.palette.grey[900],
+ backgroundSize: "cover",
+ backgroundPosition: "center",
+ },
+ paper: {
+ margin: theme.spacing(8, 4),
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ },
+ avatar: {
+ margin: theme.spacing(1),
+ backgroundColor: theme.palette.secondary.main,
+ },
+ form: {
+ width: "100%", // Fix IE 11 issue.
+ marginTop: theme.spacing(1),
+ },
+ submit: {
+ margin: theme.spacing(3, 0, 2),
+ },
+}));
+
+export default function StudentOTP() {
+ const classes = useStyles();
+ const [otp, setOtp] = useState("");
+ const [id, setid] = useState("");
+ const history = useHistory();
+
+ const [loading, setLoading] = useState(true);
+ useEffect(() => {
+ try {
+ setLoading(true);
+ // toast.success("uieuri");
+ // const token=localStorage.getItem("Studenttoken");
+ // toast.success(token);
+ const decoded_token = jwt.verify(
+ localStorage.getItem("Studenttoken"),
+ process.env.REACT_APP_JWT_SECRET
+ );
+ toast.error(decoded_token._id);
+ setid(decoded_token._id);
+ // toast.success(id);
+ fetch("http://localhost:3001/api/student/verifystudent", {
+ method: "post",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ id: decoded_token._id,
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+ setLoading(false);
+ if (result.isverified) {
+
+ history.push("/homepage");
+ }
+ });
+ } catch (err) {
+ toast.error("error");
+ setLoading(false);
+ // history.push("/signin");
+ }
+ }, []);
+
+ const submitHandler = () => {
+
+ if (otp === "") {
+ console.log("Please enter otp");
+ } else {
+ fetch("http://localhost:3001/api/student/studentotp", {
+ method: "post",
+ headers: {
+ "Content-Type": "application/json",
+ authorization: "Bearer " + localStorage.getItem("jwt"),
+ },
+ body: JSON.stringify({
+ otp: otp,
+ timestamp: Date.now(),
+ id: id,
+ }),
+ })
+ .then((res) => res.json())
+ .then((result) => {
+
+ if (result.message === "Valid OTP...User Authenticated") {
+ toast.success("Sweet !", {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 1500,
+ });
+ sleep(2000).then(() => {
+ history.push("/");
+ window.location.reload(false);
+ });
+ } else {
+ toast.warning(result.message, {
+ position: toast.POSITION.TOP_CENTER,
+ autoClose: 2000,
+ });
+ }
+ });
+ }
+ };
+ return (
+ <>
+ {}
+
+ { (
+
+
+
+
+
+
+
+
+
+ Student OTP
+
+
+
+
+
+ )}
+ >
+ );
+}
\ No newline at end of file
diff --git a/client/src/components/Screens/StudentOTP/readme.md b/client/src/components/Screens/StudentOTP/readme.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/client/src/components/Screens/StudentOTP/readme.md
@@ -0,0 +1 @@
+
diff --git a/server/index.js b/server/index.js
index 5b7890e..5183b91 100644
--- a/server/index.js
+++ b/server/index.js
@@ -18,6 +18,7 @@ require("dotenv").config();
const app = express();
+app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride("_method"));
app.set("view engine", "ejs");
@@ -31,6 +32,7 @@ const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
+ useCreateIndex: true,
});
const connection = mongoose.connection;
@@ -183,5 +185,5 @@ app.delete("/files/:id", (req, res) => {
});
app.listen(3001, function () {
- console.log("Server started on port 3001");
+ console.log("Server started on port 7000");
});
diff --git a/server/middleware/middleware.js b/server/middleware/middleware.js
new file mode 100644
index 0000000..1edb9a3
--- /dev/null
+++ b/server/middleware/middleware.js
@@ -0,0 +1,47 @@
+const jwt=require("jsonwebtoken");
+const Student = require('../model/database/Student');
+const Admin = require('../model/database/Admin');
+const expressAsyncHandler = require("express-async-handler");
+
+exports.requireSignin = (req, res, next) => {
+ if (req.headers.authorization) {
+ const token = req.headers.authorization.split(" ")[1];
+ const user = jwt.verify(token, process.env.JWT_SECRET);
+ req.user = user;
+ } else {
+ return res.status(400).json({ error: "Authorization required" });
+ }
+ next();
+};
+
+exports.isUnAuthenticated = expressAsyncHandler(async(req,res,next)=>{
+ {
+ if(!req.headers.authorization){
+ return res.status(401).json({ error: "Authorization required" });
+ }else {
+ const token = req.headers.authorization.split(" ")[1];
+ const user = jwt.verify(token, process.env.JWT_SECRET);
+ const student = await Student.findById(user._id);
+ if(student.isAuthenticated){
+ return res.status(401).json({ error: "Already authenticated" });
+ }
+ }
+ next();
+ }
+})
+
+exports.isUnAuthenticatedAdmin = expressAsyncHandler(async(req,res,next)=>{
+ {
+ if(!req.headers.authorization){
+ return res.status(401).json({ error: "Authorization required" });
+ }else {
+ const token = req.headers.authorization.split(" ")[1];
+ const user = jwt.verify(token, process.env.JWT_SECRET);
+ const admin = await Admin.findById(user._id);
+ if(admin.isAuthenticated){
+ return res.status(401).json({ error: "Already authenticated" });
+ }
+ }
+ next();
+ }
+})
\ No newline at end of file
diff --git a/server/middleware/readme.md b/server/middleware/readme.md
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/server/middleware/readme.md
@@ -0,0 +1 @@
+
diff --git a/server/model/database/Admin.js b/server/model/database/Admin.js
index d672615..b1ce238 100644
--- a/server/model/database/Admin.js
+++ b/server/model/database/Admin.js
@@ -1,6 +1,16 @@
const mongoose = require("mongoose");
const adminSchema = new mongoose.Schema(
- { firstName: { type: String, required: true }, lastName: { type: String }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, contactNo: { type: String, required: true}, bookingtime: { type: Date, default: Date.now }})
+ { firstName: { type: String, required: true }, lastName: { type: String }, email: { type: String, required: true, unique: true },otp:{type: {
+ otpCode:{
+ type:String,
+ required:true
+ },
+ timeStamp:{
+ type: Date,
+ default: Date.now
+ }
+ }},
+ isAuthenticated: {type:Boolean, default:false}, password: { type: String, required: true }, contactNo: { type: String, required: true}})
- module.exports = mongoose.model("Admin", adminSchema);
\ No newline at end of file
+ module.exports = mongoose.model("Admin", adminSchema);
diff --git a/server/model/database/Student.js b/server/model/database/Student.js
index f879d79..c2ae4d7 100644
--- a/server/model/database/Student.js
+++ b/server/model/database/Student.js
@@ -1,28 +1,16 @@
const mongoose = require("mongoose");
-const jwt = require("jsonwebtoken");
-
const studentSchema = new mongoose.Schema({
firstName: { type: String, required: true },
- lastName: { type: String }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, contactNo: { type: String, required: true }, timestamp: { type: Date, default: Date.now },tokens : [
- {
- token:{
- type : String,
- require:true
- }
+ lastName: { type: String }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, contactNo: { type: String, required: true },otp:{type: {
+ otpCode:{
+ type:String,
+ required:true
+ },
+ timeStamp:{
+ type: Date,
+ default: Date.now
}
- ] });
-
- // GENERATING TOKEN
-
-studentSchema.methods.generateAuthToken = async function (){
- try{
- let token = jwt.sign({_id: this._id}, process.env.SECRET_KEY);
- this.tokens = this.tokens.concat({token:token});
- await this.save();
- return token;
- }catch(err){
- console.log(err);
- }
-}
-module.exports = mongoose.model("Student", studentSchema);
\ No newline at end of file
+ }},
+ isAuthenticated: {type:Boolean, default:false}});
+module.exports = mongoose.model("Student", studentSchema);
diff --git a/server/router/AdminRoute.js b/server/router/AdminRoute.js
index b7b8321..e445a2e 100644
--- a/server/router/AdminRoute.js
+++ b/server/router/AdminRoute.js
@@ -1,110 +1,221 @@
-const express = require('express');
-const expressAsynchandler = require('express-async-handler');
-
-const bcrypt = require('bcryptjs');
-const Admin = require('../model/database/Admin');
-
+const express = require("express");
+const expressAsynchandler = require("express-async-handler");
+const jwt = require("jsonwebtoken");
+const nodemailer = require("nodemailer");
+const sendgridTransport = require("nodemailer-sendgrid-transport");
+const bcrypt = require("bcryptjs");
+const Admin = require("../model/database/Admin");
+const middleware = require("../middleware/middleware");
const adminRoute = express.Router();
-adminRoute.post("/signin",
-expressAsynchandler(async(req, res) => {
-
+
+adminRoute.post(
+ "/signin",
+ expressAsynchandler(async (req, res) => {
console.log(req.body.email);
if (!req.body.email) {
- return (res.send({ message: "Please Enter email id" }))
+ return res.send({ message: "Please Enter email id" });
} else if (!req.body.password) {
- return res.send({ message: "Please enter password" });
+ return res.send({ message: "Please enter password" });
}
// console.log("Request");
const admin = await Admin.findOne({ email: req.body.email });
- console.log(req.body.email + " admin wants to sign in ");
+ console.log(req.body.email + " wants to sign in ");
if (admin) {
- console.log(req.body.email + " admin signin found in database");
-
- if(bcrypt.compareSync(req.body.password,admin.password))
- {
- return res.send({
- firstName:admin.firstName,
- lastName:admin.lastName,
- email:admin.email,
- message:"Success"
- });
+ console.log(req.body.email + " signin found in database");
+
+ if (bcrypt.compareSync(req.body.password, admin.password)) {
+
+ if (!admin.isAuthenticated) {
+ console.log(req.body.email + " password valid");
+
+
+ var digits = "0123456789";
+ let OTP = "";
+ for (let i = 0; i <6; i++) {
+ OTP += digits[Math.floor(Math.random() * 10)];
+ }
+
+ const transporter = nodemailer.createTransport(
+ sendgridTransport({
+ auth: {
+ api_key: process.env.SEND_GRID,
+ },
+ })
+ );
+
+ transporter.sendMail({
+ to: req.body.email,
+ from: process.env.COMPANY_EMAIL,
+ subject: "VERIFY ONLINE LIBRARY OTP",
+ html: `Welcome to Online Library...
+ You are just one step away from verifying your email.
+ Your OTP is: ${OTP}
.
Just Enter this OTP on the email verification screen`,
+ });
+
+ const updateOtp = await Admin.findOneAndUpdate(
+ { _id: admin._id },
+ { otp: { otpCode: OTP, timeStamp: Date.now() } },
+ function (err, res) {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(
+ req.body.email + " OTP updation success with OTP: " + OTP
+ );
+ }
+ }
+ );
}
- else
- {
- console.log("Invalid Password");
- res.send({
- message: "Invalid email or password",
-
- });
- // window.location.reload();
- }
- } else {
- console.log("Invalid Email");
+ const token = jwt.sign({ _id: admin._id }, process.env.JWT_SECRET, {
+ expiresIn: "28d",
+ });
+ return res.send({
+ _id: admin._id,
+ firstName: admin.firstName,
+ lastName: admin.lastName,
+ email:admin.email,
+ message: "Success",
+ isAuthenticated:admin.isAuthenticated,
+ token: token,
+ });
+ } else {
+ console.log("Invalid Password");
res.send({
- message: "Invalid email or password",
+ message: "Invalid email or password",
});
// window.location.reload();
+ }
+ } else {
+ console.log("Invalid Email");
+ res.send({
+ message: "Invalid email or password",
+ });
+ // window.location.reload();
}
+ })
+);
-}));
+adminRoute.post("/alladmins", (req, res) => {
+ Admin.find({}).exec((err, admins) => {
+ if (err) {
+ return res.status(422).json({ error: err });
+ }
+ return res.json({ admins });
+ });
+});
-adminRoute.post("/signup",
-expressAsynchandler(async(req,res)=>{
- console.log(req.body.email + " admin requested to register");
+adminRoute.post(
+ "/signup",
+ expressAsynchandler(async (req, res) => {
+ console.log(req.body.email + " requested to register");
const admin = await Admin.findOne({ email: req.body.email });
- if(admin)
- {
- console.log(req.body.email+" admin already registered ");
- res.send({
- message:"Email Already Registered"
- });
+ if (admin) {
+ console.log(req.body.email + " already registered ");
+ res.send({
+ message: "Email Already Registered",
+ });
+ } else {
+ var digits = "0123456789";
+ let OTP = "";
+ for (let i = 0; i < 6; i++) {
+ OTP += digits[Math.floor(Math.random() * 10)];
+ }
+
+ const transporter = nodemailer.createTransport(
+ sendgridTransport({
+ auth: {
+ api_key: process.env.SEND_GRID,
+ },
+ })
+ );
+
+ transporter.sendMail({
+ to: req.body.email,
+ from: process.env.COMPANY_EMAIL,
+ subject: "VERIFY OTP",
+ html: `Welcome to Online Library...
You are just one step away from verifying your email.
+ // Your OTP is ${OTP}. Just Enter this OTP on the email verification screen`,
+ });
+ // var digits = "0123456789";
+ // let OTP = "";
+ // for (let i = 0; i < 6; i++) {
+ // OTP += digits[Math.floor(Math.random() * 10)];
+ // }
+
+ // const transporter=nodemailer.createTransport(
+ // sendgridTransport({
+ // auth:
+ // })
+ // )
+
+ const user = new Admin({
+ firstName: req.body.firstName,
+ lastName: req.body.lastName,
+ email: req.body.email,
+ password: bcrypt.hashSync(req.body.password, 8),
+ contactNo: req.body.contactNo,
+ otp: { otpCode: OTP, timeStamp: Date.now() },
+ isAuthenticated: false,
+ });
+
+ console.log(user.firstName);
+ console.log(user.email);
+ console.log(user.lastName);
+ console.log(user.password);
+ console.log(user.contactNo);
+ console.log(user.otp.OTP);
+
+ const creatstudent = await user.save();
+
+ console.log(req.body.email + " admin created");
+
+ res.status(200).send({
+ firstName: user.firstName,
+ lastName: user.lastName,
+ email: user.email,
+ contactNo: user.contactNo,
+ message: "Success",
+ });
}
- else{
-
- // var digits = "0123456789";
- // let OTP = "";
- // for (let i = 0; i < 6; i++) {
- // OTP += digits[Math.floor(Math.random() * 10)];
- // }
-
- // const transporter=nodemailer.createTransport(
- // sendgridTransport({
- // auth:
- // })
- // )
-
-
- const user=new Admin({
- firstName:req.body.firstName,
- lastName:req.body.lastName,
- email:req.body.email,
- password: bcrypt.hashSync(req.body.password, 8),
- contactNo:req.body.contactNo
+ })
+);
+
+adminRoute.post(
+ "/verifyadmin",
+ expressAsynchandler(async (req, res) => {
+
+ console.log(req.body.id);
+ const admin = await Admin.findById(req.body.id);
+ return res.status(200).send({ isverified:admin.isAuthenticated});
+ })
+);
+
+adminRoute.post(
+ "/adminotp",
+ expressAsynchandler(async (req, res) => {
+ console.log(req.body.otp);
+ const admin = await Admin.findById(req.body.id);
+ if ((req.body.timestamp - admin.otp.timeStamp) / (1000 * 60) > 5) {
+ res.status(401).send({ message: "OTP Expired" });
+ } else {
+ if (req.body.otp === admin.otp.otpCode) {
+ await Admin.findByIdAndUpdate(req.body.id, {
+ isAuthenticated: true,
});
-
- console.log(user.firstName);
- console.log(user.email);
- console.log(user.lastName);
- console.log(user.password);
- console.log(user.contactNo);
-
- const creatstudent=await user.save();
-
- console.log(req.body.email + " admin created");
-
res.status(200).send({
- firstName:user.firstName,
- lastName:user.lastName,
- email:user.email,
- contactNo:user.contactNo,
- message:"Success"
+ message: "Valid OTP...User Authenticated",
+ token: admin.token,
});
+ } else {
+ res.status(401).send({ message: "Invalid OTP" });
+ }
}
-}));
+ })
+);
-module.exports = adminRoute;
\ No newline at end of file
+module.exports = adminRoute;
diff --git a/server/router/StudentRoute.js b/server/router/StudentRoute.js
index 4d592a1..7bdf3e6 100644
--- a/server/router/StudentRoute.js
+++ b/server/router/StudentRoute.js
@@ -1,16 +1,15 @@
const express = require("express");
const expressAsynchandler = require("express-async-handler");
+const jwt = require("jsonwebtoken");
+const nodemailer = require("nodemailer");
+const sendgridTransport = require("nodemailer-sendgrid-transport");
const bcrypt = require("bcryptjs");
const Student = require("../model/database/Student");
-const jwt = require("jsonwebtoken");
+const middleware = require("../middleware/middleware");
const studentRoute = express.Router();
-
-
-
studentRoute.post(
"/signin",
expressAsynchandler(async (req, res) => {
- let token;
console.log(req.body.email);
if (!req.body.email) {
return res.send({ message: "Please Enter email id" });
@@ -26,17 +25,58 @@ studentRoute.post(
console.log(req.body.email + " signin found in database");
if (bcrypt.compareSync(req.body.password, student.password)) {
- // generating token for student
- token = await student.generateAuthToken();
- res.cookie("jwtoken", token, {
- expires:new Date(Date.now() + 25892000000),
- httpOnly:true
- });
+
+ if (!student.isAuthenticated) {
+ console.log(req.body.email + " password valid");
+ //GENERATING A 6 DIGIT OTP
+ var digits = "0123456789";
+ let OTP = "";
+ for (let i = 0; i <6; i++) {
+ OTP += digits[Math.floor(Math.random() * 10)];
+ }
+
+ const transporter = nodemailer.createTransport(
+ sendgridTransport({
+ auth: {
+ api_key: process.env.SEND_GRID,
+ },
+ })
+ );
+
+ transporter.sendMail({
+ to: req.body.email,
+ from: process.env.COMPANY_EMAIL,
+ subject: "VERIFY ONLINE LIBRARY OTP",
+ html: `Welcome to Online Library...
+ You are just one step away from verifying your email.
+ Your OTP is: ${OTP}
.
Just Enter this OTP on the email verification screen`,
+ });
+
+ const updateOtp = await Student.findOneAndUpdate(
+ { _id: student._id },
+ { otp: { otpCode: OTP, timeStamp: Date.now() } },
+ function (err, res) {
+ if (err) {
+ console.log(err);
+ } else {
+ console.log(
+ req.body.email + " OTP updation success with OTP: " + OTP
+ );
+ }
+ }
+ );
+ }
+ const token = jwt.sign({ _id: student._id }, process.env.JWT_SECRET, {
+ expiresIn: "28d",
+ });
return res.send({
+ _id: student._id,
firstName: student.firstName,
lastName: student.lastName,
email: student.email,
message: "Success",
+ isAuthenticated: student.isAuthenticated,
+ token: token,
});
} else {
console.log("Invalid Password");
@@ -55,6 +95,15 @@ studentRoute.post(
})
);
+studentRoute.post("/allstudents", (req, res) => {
+ Student.find({}).exec((err, students) => {
+ if (err) {
+ return res.status(422).json({ error: err });
+ }
+ return res.json({ students });
+ });
+});
+
studentRoute.post(
"/signup",
@@ -69,6 +118,27 @@ studentRoute.post(
message: "Email Already Registered",
});
} else {
+ var digits = "0123456789";
+ let OTP = "";
+ for (let i = 0; i < 6; i++) {
+ OTP += digits[Math.floor(Math.random() * 10)];
+ }
+
+ const transporter = nodemailer.createTransport(
+ sendgridTransport({
+ auth: {
+ api_key: process.env.SEND_GRID,
+ },
+ })
+ );
+
+ transporter.sendMail({
+ to: req.body.email,
+ from: process.env.COMPANY_EMAIL,
+ subject: "VERIFY OTP",
+ html: `Welcome to Online Library...
You are just one step away from verifying your email.
+ // Your OTP is ${OTP}. Just Enter this OTP on the email verification screen`,
+ });
// var digits = "0123456789";
// let OTP = "";
// for (let i = 0; i < 6; i++) {
@@ -87,6 +157,8 @@ studentRoute.post(
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
contactNo: req.body.contactNo,
+ otp: { otpCode: OTP, timeStamp: Date.now() },
+ isAuthenticated: false,
});
console.log(user.firstName);
@@ -94,6 +166,7 @@ studentRoute.post(
console.log(user.lastName);
console.log(user.password);
console.log(user.contactNo);
+ console.log(user.otp.OTP);
const creatstudent = await user.save();
@@ -110,10 +183,37 @@ studentRoute.post(
})
);
-studentRoute.get('/logout',(req, res)=>{
+studentRoute.post(
+ "/verifystudent",
+ expressAsynchandler(async (req, res) => {
+
+ console.log(req.body.id);
+ const student = await Student.findById(req.body.id);
+ return res.status(200).send({ isverified:student.isAuthenticated});
+ })
+);
- res.clearCookie('jwtoken', { path : "/"});
- res.status(200).send("user logout");
-})
+studentRoute.post(
+ "/studentotp",
+ expressAsynchandler(async (req, res) => {
+ console.log(req.body.otp);
+ const student = await Student.findById(req.body.id);
+ if ((req.body.timestamp - student.otp.timeStamp) / (1000 * 60) > 5) {
+ res.status(401).send({ message: "OTP Expired" });
+ } else {
+ if (req.body.otp === student.otp.otpCode) {
+ await Student.findByIdAndUpdate(req.body.id, {
+ isAuthenticated: true,
+ });
+ res.status(200).send({
+ message: "Valid OTP...User Authenticated",
+ token: student.token,
+ });
+ } else {
+ res.status(401).send({ message: "Invalid OTP" });
+ }
+ }
+ })
+);
module.exports = studentRoute;