Created
June 27, 2019 13:17
-
-
Save newbenhd/da8f37478e93250236aa1d2d3a5010a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import config from '../config' | |
import { User } from '../resources/user/user.model' | |
import jwt from 'jsonwebtoken' | |
export const newToken = user => { | |
return jwt.sign({ id: user.id }, config.secrets.jwt, { | |
expiresIn: config.secrets.jwtExp | |
}) | |
} | |
export const verifyToken = token => new Promise((resolve, reject) => { | |
jwt.verify(token, config.secrets.jwt, (err, payload) => { | |
if (err) return reject(err) | |
resolve(payload) | |
}) | |
}) | |
export const signup = async (req, res) => { | |
const data = req.body | |
if(!data.password || !data.email) | |
return res.status(400).send({message: 'requires email and password!!'}) | |
try { | |
const user = await User.create(data) | |
const token = newToken({id: user._id}) | |
return res.status(201).send({token}) | |
} | |
catch(e) { | |
res.status(400).send({message: 'Error with creating user'}) | |
} | |
} | |
export const signin = async (req, res) => { | |
if(!req.body.email || !req.body.password) | |
return res.status(400).send({message: 'requires email and password!'}) | |
const user = await User.findOne({email: req.body.email}).lean(true).exec() | |
if (!user) | |
return res.status(401).send({message: 'user must be real'}) | |
try { | |
const match = await user.checkPassword(req.body.password) | |
if (!match) { | |
return res.status(401).send({message: 'password must match'}) | |
} | |
const token = newToken(user) | |
return res.status(201).send(token) | |
} | |
catch(e) { | |
console.log(`I'm in error 401`) | |
return res.status(401).send({message: 'error'}) | |
} | |
} | |
export const protect = async (req, res, next) => { | |
next() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment