Merge pull request #32 from chirag3003/feature/auth-backend
Feature/auth backend
This commit is contained in:
commit
4476e782db
|
@ -1,2 +1,3 @@
|
|||
MONGO_DB=mongo-uri
|
||||
SECRET=secret
|
||||
SECRET=secret
|
||||
AUTH_SECRET=secret
|
|
@ -0,0 +1,53 @@
|
|||
const jwt = require("jsonwebtoken");
|
||||
const User = require("../models/user");
|
||||
|
||||
|
||||
module.exports.register = async ({ body: { email, password } }, res) => {
|
||||
try{
|
||||
if(!email || !password) return res.sendStatus(400)
|
||||
let oldUser = await User.findOne({ email }).catch((err) => {
|
||||
console.error(err);
|
||||
});
|
||||
if (oldUser) return res.status(400).send('Already Exists');
|
||||
let user = new User({ email });
|
||||
user.setPassword(password);
|
||||
let validationError = false;
|
||||
await user.save().catch((err) => {
|
||||
validationError = true;
|
||||
return res.sendStatus(400);
|
||||
});
|
||||
if (!validationError) return res.send(user.generateJWT());
|
||||
|
||||
}catch(e){
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
}
|
||||
module.exports.login = async ({ body: { email, password } }, res) => {
|
||||
try{
|
||||
if (!email || !password) return res.sendStatus(400)
|
||||
let user = await User.findOne({email}).catch((err) => console.error(err));
|
||||
|
||||
if (user && user.validatePassword(password))
|
||||
return res.send(user.generateJWT());
|
||||
return res.status(401).send(null);
|
||||
}catch(err) {
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
}
|
||||
module.exports.me= async (req, res) => {
|
||||
try{
|
||||
if (!req.user.isAuthenticated) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
}
|
||||
let user = req.user.data;
|
||||
res.send({
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
phone: user.phone,
|
||||
});
|
||||
}catch (e){
|
||||
console.log(e)
|
||||
return res.sendStatus(500)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
const jwt = require("jsonwebtoken");
|
||||
const User = require("../models/user")
|
||||
|
||||
|
||||
module.exports.auth = async (req, res, next) => {
|
||||
let user = {isAuthenticated:false};
|
||||
if (req.headers.authorization && req.headers.authorization !== null) {
|
||||
try {
|
||||
let jwtData = jwt.verify(
|
||||
req.headers.authorization.replace("Bearer ", ""),
|
||||
process.env.AUTH_SECRET
|
||||
);
|
||||
let userData = await User.findOne({
|
||||
email: jwtData.email,
|
||||
hash: jwtData.hash,
|
||||
}).catch((err) => console.error(err));
|
||||
user.isAuthenticated = userData ? true : false;
|
||||
user.data = userData;
|
||||
} catch (err) {
|
||||
user.isAuthenticated = false;
|
||||
user.data = null;
|
||||
}
|
||||
}
|
||||
req.user = user;
|
||||
next();
|
||||
}
|
|
@ -0,0 +1,63 @@
|
|||
const mongoose = require("mongoose");
|
||||
const crypto = require("crypto");
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const { Schema } = mongoose;
|
||||
|
||||
const UsersSchema = new Schema(
|
||||
{
|
||||
email: {
|
||||
type: String,
|
||||
unique: true,
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
// required: true,
|
||||
},
|
||||
hash: String,
|
||||
salt: String,
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
UsersSchema.methods.setPassword = function (password) {
|
||||
this.salt = crypto.randomBytes(16).toString("hex");
|
||||
this.hash = crypto
|
||||
.pbkdf2Sync(password, this.salt, 10000, 512, "sha512")
|
||||
.toString("hex");
|
||||
};
|
||||
|
||||
UsersSchema.methods.validatePassword = function (password) {
|
||||
const hash = crypto
|
||||
.pbkdf2Sync(password, this.salt, 10000, 512, "sha512")
|
||||
.toString("hex");
|
||||
return this.hash === hash;
|
||||
};
|
||||
|
||||
UsersSchema.methods.generateJWT = function () {
|
||||
const today = new Date();
|
||||
const expirationDate = new Date(today);
|
||||
expirationDate.setDate(today.getDate() + 60);
|
||||
|
||||
return jwt.sign(
|
||||
{
|
||||
email: this.email,
|
||||
hash: this.hash,
|
||||
id: this._id,
|
||||
exp: parseInt(String(expirationDate.getTime() / 1000), 10),
|
||||
},
|
||||
process.env.AUTH_SECRET
|
||||
);
|
||||
};
|
||||
|
||||
UsersSchema.methods.toAuthJSON = function () {
|
||||
return {
|
||||
id: this._id,
|
||||
email: this.email,
|
||||
token: this.generateJWT(),
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = mongoose.model("users", UsersSchema);
|
|
@ -34,6 +34,7 @@
|
|||
"express": "^4.17.2",
|
||||
"express-session": "^1.17.2",
|
||||
"helmet": "^5.0.2",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mongoose": "^6.1.8",
|
||||
"morgan": "^1.10.0",
|
||||
"nanoid": "^3.2.0"
|
||||
|
|
|
@ -4,6 +4,7 @@ const router = express.Router()
|
|||
const homeController = require('../controllers/home_controller')
|
||||
|
||||
router.get('/', homeController.home)
|
||||
router.use("/minify",require("./minify"))
|
||||
router.use("/minify", require("./minify"))
|
||||
router.use('/user', require("./user"))
|
||||
|
||||
module.exports = router
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
const {Router} = require("express")
|
||||
const controller = require("../controllers/user")
|
||||
const {auth} = require("../middlewares/auth")
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post('/login',controller.login )
|
||||
router.post('/register', controller.register)
|
||||
router.get('/me',auth, controller.me)
|
||||
|
||||
module.exports = router
|
2391
backend/yarn.lock
2391
backend/yarn.lock
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue