File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ import jwt from 'jsonwebtoken' ;
2
+ import httpStatus from 'http-status' ;
3
+ import APIError from '../helpers/APIError' ;
4
+ import config from '../../config/config' ;
5
+
6
+ // sample user, used for authentication
7
+ const user = {
8
+ username : 'react' ,
9
+ password : 'express' ,
10
+ } ;
11
+
12
+ /**
13
+ * Returns jwt token if valid username and password is provided
14
+ * @param req
15
+ * @param res
16
+ * @param next
17
+ * @returns {* }
18
+ */
19
+ function login ( req , res , next ) {
20
+ // Ideally you'll fetch this from the db
21
+ // Idea here was to show how jwt works with simplicity
22
+ if ( req . body . username === user . username && req . body . password === user . password ) {
23
+ const token = jwt . sign ( {
24
+ username : user . username ,
25
+ expiresIn : 3600 ,
26
+ } , config . jwtSecret ) ;
27
+ return res . json ( {
28
+ token,
29
+ username : user . username ,
30
+ } ) ;
31
+ }
32
+
33
+ const err = new APIError ( 'Authentication error' , httpStatus . UNAUTHORIZED , true ) ;
34
+ return next ( err ) ;
35
+ }
36
+
37
+ /**
38
+ * This is a protected route. Will return random number only if jwt token is provided in header.
39
+ * @param req
40
+ * @param res
41
+ * @returns {* }
42
+ */
43
+ function getRandomNumber ( req , res ) {
44
+ // req.user is assigned by jwt middleware if valid token is provided
45
+ return res . json ( {
46
+ user : req . user ,
47
+ num : Math . random ( ) * 100 ,
48
+ } ) ;
49
+ }
50
+
51
+ export default { login, getRandomNumber } ;
You can’t perform that action at this time.
0 commit comments