1
+ const { AsyncRouter } = require ( "express-async-router" ) ;
2
+ const jwt = require ( "jsonwebtoken" ) ;
3
+ const { check, validationResult } = require ( "express-validator" ) ;
4
+
5
+ const User = require ( "../models/User" ) ;
6
+ const handleValidationErrors = require ( "../helpers/handleValidationErrors" ) ;
7
+ const jwtMiddleware = require ( "../helpers/jwtMiddleware" ) ;
8
+
9
+ const router = AsyncRouter ( ) ;
10
+
11
+ const signUpValidators = [
12
+ check ( "email" ) . isEmail ( ) ,
13
+ check ( "password" ) . exists ( ) ,
14
+ check ( "passwordConfirm" ) . exists ( )
15
+ ] ;
16
+
17
+ const loginValidators = [
18
+ check ( "email" ) . isEmail ( ) ,
19
+ check ( "password" ) . exists ( )
20
+ ] ;
21
+
22
+ router . post (
23
+ "/sign-up" ,
24
+ [ ...signUpValidators , handleValidationErrors ] ,
25
+ async ( req , res ) => {
26
+ const userExists = await User . findOne ( { email : req . body . email } ) ;
27
+
28
+ if ( userExists )
29
+ return res . status ( 400 ) . send ( "E-mail already exists" ) ;
30
+ if ( req . body . password !== req . body . passwordConfirm )
31
+ return res . status ( 400 ) . send ( "Passwords do not match" ) ;
32
+
33
+ const user = await User . signUp ( req . body . email , req . body . password ) ;
34
+ res . status ( 201 ) . send ( user . sanitize ( ) ) ;
35
+ }
36
+ ) ;
37
+
38
+ router . post (
39
+ "/login" ,
40
+ [ ...loginValidators , handleValidationErrors ] ,
41
+ async ( req , res ) => {
42
+ const user = await User . findOne ( { email : req . body . email } ) ;
43
+
44
+ if ( ! user || ! user . comparePassword ( req . body . password ) )
45
+ return res . status ( 400 ) . send ( "Invalid login information" ) ;
46
+
47
+ const token = jwt . sign ( {
48
+ _id : user . _id ,
49
+ } , "CHANGEME!" ) ;
50
+
51
+ res . send ( { token} ) ;
52
+ }
53
+ ) ;
54
+
55
+ router . get ( "/profile" , [ jwtMiddleware ] , async ( req , res ) => {
56
+ const user = await User . findOne ( { _id : req . user . _id } ) . populate ( "chrips" ) ;
57
+
58
+ res . send ( user ) ;
59
+ } ) ;
60
+
61
+ module . exports = router ;
0 commit comments