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

Meeting Application | Pradyuman Agrawal #25

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
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
Prev Previous commit
Next Next commit
Added Login endpoint, Password encryption, json web tokens and auth m…
…iddleware
PradyumanAgrawal committed Jan 9, 2022
commit f3746187d534809d6c1997c402843880124f59fd
61 changes: 61 additions & 0 deletions Pradyuman_Agrawal/teams_app/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const User = require("../models/users.js");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken")

//get all user
const login =(req,res) => {
try{
//get user input
const {email,password}=req.body;
//validate input
if(!(email&&password)){
return res.status(400).send("all inputs for login required");
}
//check if user exists with same emailId
User.findUserByEmailId(email, async (err, data) => {
console.log(data)
if (err){
res.status(500).send({
message: "internal error"
});
}
else if(data.user.length==0){
res.status(400).send(`Sorry user with email ${email} doesnt exists, Trying registering instead`);
}
else{
//check if the password matchs with user input
const user = data.user;
if(await bcrypt.compare(password,user.password)){
//create token
const token = jwt.sign(
{userId:user.userId,email:email},
process.env.TOKEN_KEY,
{
expiresIn:"24h"
}
)
console.log("User successfully logged in")
user.token=token;
return res.status(200).json(user);
}
res.status(400).send("Invalid credentials");
}
})
}catch(err){
console.error(err)
}
}

//find user by userId
const logout = (req,res) => {
res.status(404).send("Endpoint yet to be implemented");
}

module.exports = {
login,
logout
};




11 changes: 7 additions & 4 deletions Pradyuman_Agrawal/teams_app/controllers/users.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const User = require("../models/users.js")
const bcrypt = require("bcryptjs")

//signup user
const create = async (req,res) => {
@@ -12,20 +13,22 @@ const create = async (req,res) => {
}

//check if user exists with same emailId
User.findUserByEmailId(email, (err, data) => {
User.findUserByEmailId(email, async (err, data) => {
if (err){
res.status(500).send({
message: "internal error"
});
}
else if(data.user.length){
res.status(400).send(`Sorry user with email ${email} already exists, Trying logging instead`);

}
else{
else{
//encrpyt user password
encryptedPassword =await bcrypt.hash(password,10)

const user = new User({
email:req.body.email,
password:req.body.password,
password:encryptedPassword,
name:req.body.name
})
User.create(user,(err,data) =>{
20 changes: 20 additions & 0 deletions Pradyuman_Agrawal/teams_app/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const jwt = require("jsonwebtoken")

const verifyToken=(req,res,next)=>{
try{
const token=req.headers["x-access-token"];
if(!token)
return res.status(403).send("Auth token is missing, restricted access");

const decoded=jwt.verify(token,process.env.TOKEN_KEY);
req.userId=decoded.userId
req.email=decoded.email

}catch(err){
return res.status(403).json(err);
}

return next();
}

module.exports = verifyToken
14 changes: 9 additions & 5 deletions Pradyuman_Agrawal/teams_app/models/users.js
Original file line number Diff line number Diff line change
@@ -26,7 +26,7 @@ User.getAllUser = (cb) => {
return;
}
console.log("All users info sent");
cb(null,{user:res});
cb(null,{users:res});
});
};

@@ -38,20 +38,24 @@ User.findUserById = (userId,cb) => {
return;
}
console.log("User found with userId",userId);
cb(null,{user:res});
cb(null,{user:res[0]});
});
};

User.findUserByEmailId = async (email,cb) => {
User.findUserByEmailId = (email,cb) => {
pool.query("Select * from users where email = ?",email,(err,res) => {
if(err){
console.log("error: ",err);
cb(err,null);
return;
}
if(res.length)
if(res.length){
console.log("user found with email",email);
cb(null,{user:res});
cb(null,{user:res[0]});
}
else{
cb(null,{user:[]});
}
});
};

2 changes: 2 additions & 0 deletions Pradyuman_Agrawal/teams_app/package.json
Original file line number Diff line number Diff line change
@@ -9,9 +9,11 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.18.1"
},
"devDependencies": {
9 changes: 9 additions & 0 deletions Pradyuman_Agrawal/teams_app/routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = app => {
const auth = require("../controllers/auth.js");
var router = require("express").Router();

router.post("/login",auth.login);
router.get("/logout",auth.logout);

app.use("/auth",router)
}
5 changes: 4 additions & 1 deletion Pradyuman_Agrawal/teams_app/server.js
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@ const express = require("express");
require("dotenv").config();
const cors = require("cors");
const middleware_utils = require('./middleware/utils');
const auth =require("./middleware/auth")

const app = express();

@@ -18,11 +19,13 @@ require("./routes/users")(app);
//path /auth
require("./routes/auth")(app);

app.get("/profile",auth,(req,res)=>{
res.status(200).send(`Welcome to user profile page ${req.userId} ${req.email}`)
})

app.use(middleware_utils.unknownEndpoint);
app.use(middleware_utils.errorHandler);


const PORT = process.env.PORT||3000
app.listen(PORT,() => {
console.log(`server running on port: ${PORT}`);