99 lines
2.5 KiB
JavaScript
99 lines
2.5 KiB
JavaScript
const bcrypt = require('bcryptjs') ;
|
|
const User = require('../models/User') ;
|
|
const Student = require('../models/Student') ;
|
|
const jwt = require('jsonwebtoken');
|
|
const JWT_secret = "Cantileverlabs";
|
|
|
|
module.exports.Protected = async (req,res,next)=>{
|
|
res.send("Hello User")
|
|
}
|
|
module.exports.postSignup = async (req , res , next) => {
|
|
try
|
|
{
|
|
let firstName = req.body.firstName || " " ;
|
|
let lastName = req.body.lastName || " " ;
|
|
let email = req.body.email ;
|
|
let password = req.body.password ;
|
|
let user = await User.findOne({email:email}) ;
|
|
if(user)
|
|
{
|
|
res.json({
|
|
message:"User already exist" ,
|
|
type:"error"
|
|
})
|
|
}
|
|
else
|
|
{
|
|
const hashedPass = await bcrypt.hash(password , 12) ;
|
|
user = new User({
|
|
firstName : firstName ,
|
|
lastName : lastName ,
|
|
email : email ,
|
|
password : hashedPass
|
|
}) ;
|
|
user = await user.save() ;
|
|
await Student.deleteOne({user:user._id}) ;
|
|
let student = new Student({
|
|
user:user._id
|
|
})
|
|
await student.save() ;
|
|
res.json({
|
|
message:"Successfully signed Up" ,
|
|
type:"success"
|
|
})
|
|
}
|
|
}
|
|
catch(err)
|
|
{
|
|
console.log(err);
|
|
}
|
|
} ;
|
|
|
|
|
|
module.exports.postSignin = async (req , res , next) => {
|
|
try
|
|
{
|
|
let email = req.body.email ;
|
|
let password = req.body.password ;
|
|
let user = await User.findOne({email : email}) ;
|
|
if(user)
|
|
{
|
|
const isMatched = await bcrypt.compare(password , user.password) ;
|
|
if(isMatched)
|
|
{
|
|
const token = jwt.sign({_id:user._id},JWT_secret)
|
|
res.json(
|
|
{
|
|
token:token
|
|
}
|
|
)
|
|
}
|
|
else
|
|
{
|
|
res.json({
|
|
message:"email and password doesn't match" ,
|
|
type:"error"
|
|
})
|
|
}
|
|
}
|
|
else
|
|
{
|
|
res.json({
|
|
message:"No user with this email exists" ,
|
|
type : "error"
|
|
})
|
|
}
|
|
}
|
|
catch(err)
|
|
{
|
|
console.log(err);
|
|
}
|
|
}
|
|
|
|
module.exports.checkProtected = (req , res , next) => {
|
|
console.log(req.user);
|
|
res.json({
|
|
message:"Protected" ,
|
|
user : req.user
|
|
})
|
|
} |