1+ const _ = require ( 'lodash' )
2+ const jwt = require ( 'jsonwebtoken' )
3+ const bcrypt = require ( 'bcrypt' )
4+ const User = require ( './user' )
5+ const env = require ( '../../.env' )
6+
7+ const emailRegex = / \S + @ \S + \. \S + /
8+ const passwordRegex = / ( (? = .* \d ) (? = .* [ a - z ] ) (? = .* [ A - Z ] ) (? = .* [ @ # $ % ] ) .{ 6 , 20 } ) /
9+
10+ const sendErrorsFromDB = ( res , dbErrors ) => {
11+ const errors = [ ]
12+ _ . forIn ( dbErrors . errors , error => errors . push ( error . message ) )
13+ return res . status ( 400 ) . json ( { errors } )
14+ }
15+
16+ const login = ( req , res , next ) => {
17+ const email = req . body . email || ''
18+ const password = req . body . password || ''
19+
20+ User . findOne ( { email } , ( err , user ) => {
21+ if ( err ) {
22+ return sendErrorsFromDB ( res , err )
23+ } else if ( user && bcrypt . compareSync ( password , user . password ) ) {
24+ const token = jwt . sign ( user , env . authSecret , {
25+ expiresIn : "1 day"
26+ } )
27+ const { name, email } = user
28+ res . json ( { name, email, token } )
29+ } else {
30+ return res . status ( 400 ) . send ( { errors : [ 'Usuário/Senha inválidos' ] } )
31+ }
32+ } )
33+ }
34+
35+ const validateToken = ( req , res , next ) => {
36+ const token = req . body . token || ''
37+
38+ jwt . verify ( token , env . authSecret , function ( err , decoded ) {
39+ return res . status ( 200 ) . send ( { valid : ! err } )
40+ } )
41+ }
42+
43+ const signup = ( req , res , next ) => {
44+ const name = req . body . name || ''
45+ const email = req . body . email || ''
46+ const password = req . body . password || ''
47+ const confirmPassword = req . body . confirm_password || ''
48+
49+ if ( ! email . match ( emailRegex ) ) {
50+ return res . status ( 400 ) . send ( { errors : [ 'O e-mail informado está inválido' ] } )
51+ }
52+
53+ if ( ! password . match ( passwordRegex ) ) {
54+ return res . status ( 400 ) . send ( {
55+ errors : [
56+ "Senha precisar ter: uma letra maiúscula, uma letra minúscula, um número, uma caractere especial(@#$ %) e tamanho entre 6-20."
57+ ]
58+ } )
59+ }
60+
61+ const salt = bcrypt . genSaltSync ( )
62+ const passwordHash = bcrypt . hashSync ( password , salt )
63+ if ( ! bcrypt . compareSync ( confirmPassword , passwordHash ) ) {
64+ return res . status ( 400 ) . send ( { errors : [ 'Senhas não conferem.' ] } )
65+ }
66+
67+ User . findOne ( { email } , ( err , user ) => {
68+ if ( err ) {
69+ return sendErrorsFromDB ( res , err )
70+ } else if ( user ) {
71+ return res . status ( 400 ) . send ( { errors : [ 'Usuário já cadastrado.' ] } )
72+ } else {
73+ const newUser = new User ( { name, email, password : passwordHash } )
74+ newUser . save ( err => {
75+ if ( err ) {
76+ return sendErrorsFromDB ( res , err )
77+ } else {
78+ login ( req , res , next )
79+ }
80+ } )
81+ }
82+ } )
83+ }
84+
85+ module . exports = { login, signup, validateToken }
0 commit comments