@@ -16,15 +16,45 @@ function createToken(user) {
1616 return jwt . sign ( _ . omit ( user , 'password' ) , config . secret , { expiresInMinutes : 60 * 5 } ) ;
1717}
1818
19+ function getUserScheme ( req ) {
20+
21+ var username ;
22+ var type ;
23+ var userSearch = { } ;
24+
25+ // The POST contains a username and not an email
26+ if ( req . body . username ) {
27+ username = req . body . username ;
28+ type = 'username' ;
29+ userSearch = { username : username } ;
30+ }
31+ // The POST contains an email and not an username
32+ else if ( req . body . email ) {
33+ username = req . body . email ;
34+ type = 'email' ;
35+ userSearch = { email : username } ;
36+ }
37+
38+ return {
39+ username : username ,
40+ type : type ,
41+ userSearch : userSearch
42+ }
43+ }
44+
1945app . post ( '/users' , function ( req , res ) {
20- if ( ! req . body . username || ! req . body . password ) {
46+
47+ var userScheme = getUserScheme ( req ) ;
48+
49+ if ( ! userScheme . username || ! req . body . password ) {
2150 return res . status ( 400 ) . send ( "You must send the username and the password" ) ;
2251 }
23- if ( _ . find ( users , { username : req . body . username } ) ) {
52+
53+ if ( _ . find ( users , userScheme . userSearch ) ) {
2454 return res . status ( 400 ) . send ( "A user with that username already exists" ) ;
2555 }
2656
27- var profile = _ . pick ( req . body , 'username' , 'password' , 'extra' ) ;
57+ var profile = _ . pick ( req . body , userScheme . type , 'password' , 'extra' ) ;
2858 profile . id = _ . max ( users , 'id' ) . id + 1 ;
2959
3060 users . push ( profile ) ;
@@ -35,13 +65,17 @@ app.post('/users', function(req, res) {
3565} ) ;
3666
3767app . post ( '/sessions/create' , function ( req , res ) {
38- if ( ! req . body . username || ! req . body . password ) {
68+
69+ var userScheme = getUserScheme ( req ) ;
70+
71+ if ( ! userScheme . username || ! req . body . password ) {
3972 return res . status ( 400 ) . send ( "You must send the username and the password" ) ;
4073 }
4174
42- var user = _ . find ( users , { username : req . body . username } ) ;
75+ var user = _ . find ( users , userScheme . userSearch ) ;
76+
4377 if ( ! user ) {
44- return res . status ( 401 ) . send ( "The username or password don't match" ) ;
78+ return res . status ( 401 ) . send ( { message : "The username or password don't match" , user : user } ) ;
4579 }
4680
4781 if ( user . password !== req . body . password ) {
@@ -51,4 +85,4 @@ app.post('/sessions/create', function(req, res) {
5185 res . status ( 201 ) . send ( {
5286 id_token : createToken ( user )
5387 } ) ;
54- } ) ;
88+ } ) ;
0 commit comments