Skip to content

Instantly share code, notes, and snippets.

@ShwetaRPawar
Created August 8, 2020 10:59
Show Gist options
  • Save ShwetaRPawar/87d0854db8ff57e40f58d403c4046f03 to your computer and use it in GitHub Desktop.
Save ShwetaRPawar/87d0854db8ff57e40f58d403c4046f03 to your computer and use it in GitHub Desktop.
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const SECRET = 'asbadbbdbbh7788888887hb113h3hbb';
const { prisma } = require('../generated/prisma-client')
//add new user
async function allUser(req, res){
const allUsers = await prisma.users()
res.send(JSON.stringify({"status": 200, "error": null, 'response': allUsers}));
}
async function register(req, res){
try
{
const user = await prisma.users({
where: {email: req.body.email}
})
console.log('user: ', user);
if(user.length != 0)
{
res.send(JSON.stringify({"status": 302, "error": 'User is found with that email'}));
return;
}
req.body.password = await bcrypt.hash(req.body.password, 12);
try
{
console.log('password: ', req.body.password);
const user = await prisma.createUser({
username: req.body.username,
email: req.body.email,
password: req.body.password
})
res.send(JSON.stringify({"status": 200, "error": null, "response": user.id}));
}
catch(e)
{
res.send(JSON.stringify({"status": 500, "error": 'In create user '+e, "response": null}));
}
}
catch(e)
{
res.send(JSON.stringify({"status": 500, "error": 'In user '+e, "response": null}));
}
}
//login
async function login(req, res){
const user = await prisma.users({
where: {email: req.body.email}
})
console.log('user: ', user);
if (user.length === 0)
{
res.send(JSON.stringify({"status": 404, "error": 'Not user with that email', "token": null}));
return;
}
const valid = await bcrypt.compare(req.body.password, user[0].password);
if (!valid){
res.send(JSON.stringify({"status": 404, "error": 'Incorrect password', "token": null}));
return;
}
// verify: needs SECRET | use for authentication
// decode: no secret | use for client side
const token = jwt.sign({
user: _.pick(user[0], ['id', 'email']),
},
SECRET,
{
expiresIn: '5m',
});
res.send(JSON.stringify({"status": 200, "error": null, "token": token}));
}
//Delete user
async function deleteUser(req, res){
try
{
const user = await prisma.deleteUser({
id: req.params.id
})
res.send(JSON.stringify({"status": 200, "error": null, "response": user.id}));
}
catch(e)
{
res.send(JSON.stringify({"status": 500, "error": e, "response": null}));
}
}
module.exports = {
register,
login,
deleteUser,
allUser
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment