1+ const bcrypt = require ( 'bcryptjs' ) ;
2+
3+ const register = async ( req , res ) => {
4+ // get db instance
5+ const db = req . app . get ( 'db' ) ;
6+ // get email and password from body
7+ const { email, password} = req . body ;
8+ // find an existing email
9+ const foundUser = await db . get_user ( [ email ] ) ;
10+ // check to see if user is found
11+ if ( foundUser [ 0 ] ) return res . status ( 409 ) . send ( 'Sorry, email already exists.' ) ;
12+ // If user is not found, create a new hash and salt
13+ const salt = bcrypt . genSaltSync ( 15 ) ;
14+ const hash = bcrypt . hashSync ( password , salt ) ;
15+ // Add user to database
16+ const newUser = await db . register_user ( [ email , hash ] ) ;
17+ // Add user to the session
18+ req . session . user = newUser [ 0 ] ;
19+ // Send user back
20+ res . status ( 200 ) . send ( req . session . user ) ;
21+ } ;
22+
23+ const login = async ( req , res ) => {
24+ // get db instance
25+ const db = req . app . get ( 'db' ) ;
26+ // get email and password from body
27+ const { email, password} = req . body ;
28+ // find an existing email
29+ const foundUser = await db . get_user ( [ email ] ) ;
30+ // check to see if user is found
31+ if ( ! foundUser [ 0 ] ) return res . status ( 409 ) . send ( 'Sorry, email already exists.' ) ;
32+ // else use will be found so compare password to the hashed password stored in db
33+ const authenticated = bcrypt . compareSync ( password , foundUser [ 0 ] . password ) ;
34+ // check to see if authenticated is true or false
35+ if ( authenticated ) {
36+ // remove user password
37+ delete foundUser [ 0 ] . password ;
38+ // if authed set user to session and make a response
39+ req . session . user = foundUser [ 0 ] ;
40+ // send response
41+ res . status ( 200 ) . send ( req . session . user ) ;
42+ } else {
43+ // if failure send error message
44+ return res . status ( 401 ) . send ( 'Inccorect username or password' ) ;
45+ } ;
46+ } ;
47+
48+ module . exports = {
49+ register,
50+ login
51+ } ;
0 commit comments