Skip to content

Instantly share code, notes, and snippets.

@andersonFaro9
Created May 7, 2024 12:10
Show Gist options
  • Save andersonFaro9/db68a5562dff08b5663fadf9bd51e5b4 to your computer and use it in GitHub Desktop.
Save andersonFaro9/db68a5562dff08b5663fadf9bd51e5b4 to your computer and use it in GitHub Desktop.
const bcrypt = require("bcrypt");
const db = require("../models");
const jwt = require("jsonwebtoken");
const User = db.users;
const signup = async (req, res)=> {
try {
const {userName, password, email} = req.body;
const data = {
userName,email, password:await bcrypt.hash(password,10),
};
const user = await User.create(data);
if (user) {
let token = jwt.sign({ id: user.id }, process.env.SECRET, {
expiresIn: 1 * 24 * 60 * 60 * 1000,
})
res.cookie('jwt', token, { maxAge: 1 * 24 * 60 * 60, httpOnly: true })
console.log('user', JSON.stringify(user, null, 2))
console.log(token)
return res.status(201).send(user)
} else {
return res.status(409).send('Details are not correct')
}
} catch(error) {
console.log("Error", error)
}
}
const login = async (req,res)=> {
try{
const {email, password} = req.body;
const user = await User.findOne({
where: {
email:email
}
})
if(user) {
const isSame = await bcrypt.compare(password, user.password)
if(isSame) {
let token = jwt.sign({ id: user.id }, 'secret_key', {
expiresIn: 1 * 24 * 60 * 60 * 1000,
})
res.cookie ("jwt", token, {
maXAge: 1 * 24 * 60 * 60 , httpOnly: true
});
console.log("user", JSON.stringify(user, null, 2));
console.log(token);
return res.status(201).send(user);
} else {
return res.status(401).send("Authentication failed");
}
}
}catch(error) {
console.log("error")
}
}
module.exports = {
signup,
login
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment