ソースを参照

rework login complete

tags/0.0.1^2
diaseu 3年前
コミット
7cd9af964f

+ 1
- 1
backend/db/migrations/20220901171733_user_authentication.js ファイルの表示

3
         table.string('user_email', 90).primary().unique()
3
         table.string('user_email', 90).primary().unique()
4
         table.date('created_at').notNullable()
4
         table.date('created_at').notNullable()
5
         // table.char('token').notNullable()
5
         // table.char('token').notNullable()
6
-        table.binary('token').notNullable()
6
+        table.binary('token')
7
     })
7
     })
8
 }
8
 }
9
 
9
 

+ 2
- 5
backend/lib/models/authentication.js ファイルの表示

1
 const Schwifty = require('@hapipal/schwifty')
1
 const Schwifty = require('@hapipal/schwifty')
2
 const Joi = require('joi')
2
 const Joi = require('joi')
3
+const { userAuth } = require('../schemas/authentication')
3
 
4
 
4
 module.exports = class Auth extends Schwifty.Model {
5
 module.exports = class Auth extends Schwifty.Model {
5
     static get tableName() {
6
     static get tableName() {
6
         return 'authentication'
7
         return 'authentication'
7
     }
8
     }
8
     static get joiSchema() {
9
     static get joiSchema() {
9
-        return Joi.object({
10
-            user_email: Joi.string().required(),
11
-            created_at: Joi.date().required(),
12
-            token: Joi.binary()
13
-        })
10
+        return userAuth
14
     }
11
     }
15
 }
12
 }

+ 24
- 15
backend/lib/routes/user/login.js ファイルの表示

16
 const validators = {
16
 const validators = {
17
     post: {
17
     post: {
18
         payload: Joi.object({
18
         payload: Joi.object({
19
-            user: userSchema.single,
20
-            error: errorSchema.single,
21
-        })
22
-            .append()
23
-            .label('login_payload'),
19
+            user_email: Joi.string(),
20
+            password: Joi.string(),
21
+        }),
22
+        
24
     },
23
     },
25
     user: userSchema.single,
24
     user: userSchema.single,
25
+    error: errorSchema.single,
26
 }
26
 }
27
 
27
 
28
 module.exports = {
28
 module.exports = {
34
         auth: false,
34
         auth: false,
35
         handler: async function (request, h) {
35
         handler: async function (request, h) {
36
             try {
36
             try {
37
-                const { userService, displayService } = request.services()
37
+                const { userService } = request.services()
38
 
38
 
39
                 const res = request.payload
39
                 const res = request.payload
40
 
40
 
42
                 const login = async txn => {
42
                 const login = async txn => {
43
                     return await userService.login(
43
                     return await userService.login(
44
                         {
44
                         {
45
-                            email: res.user.email,
46
-                            password: res.user.password,
45
+                            email: res.user_email,
46
+                            password: res.password,
47
                         },
47
                         },
48
                         txn,
48
                         txn,
49
                     )
49
                     )
56
                 return {
56
                 return {
57
                     ok: true,
57
                     ok: true,
58
                     handler: pluginConfig.handlerType,
58
                     handler: pluginConfig.handlerType,
59
-                    data: displayService.user(user, token),
59
+                    data: { user_email: user.user_email, jwtToken: token },
60
                 }
60
                 }
61
             } catch (err) {
61
             } catch (err) {
62
                 console.error(err)
62
                 console.error(err)
69
         },
69
         },
70
         validate: validators.post,
70
         validate: validators.post,
71
         response: {
71
         response: {
72
-            schema: Joi.object({
73
-                ok: Joi.bool(),
74
-                handler: Joi.string(),
75
-                data: validators.user,
76
-            }).label('login_res'),
77
-            failAction: 'log',
72
+            status: {
73
+                201: Joi.object({
74
+                    ok: Joi.bool(),
75
+                    handler: Joi.string(),
76
+                    data: Joi.object({
77
+                        user_email: Joi.string(),
78
+                        jwtToken: Joi.string(),
79
+                    }),
80
+                }).label('login_res'),
81
+                409: Joi.object({
82
+                    ok: Joi.bool(),
83
+                    handler: Joi.string(),
84
+                    data: validators.error,
85
+                }).label('login_error'),
86
+            },
78
         },
87
         },
79
     },
88
     },
80
 }
89
 }

+ 1
- 1
backend/lib/routes/user/signup.js ファイルの表示

26
         is_poster: Joi.number(),
26
         is_poster: Joi.number(),
27
         is_admin: Joi.number(),
27
         is_admin: Joi.number(),
28
         is_verified: Joi.number(),
28
         is_verified: Joi.number(),
29
-        user_pass: Joi.string()
30
     }).label('created_user'),
29
     }).label('created_user'),
31
     error: errorSchema.single,
30
     error: errorSchema.single,
32
 }
31
 }
57
                         is_admin: 0,
56
                         is_admin: 0,
58
                         is_verified: 0,
57
                         is_verified: 0,
59
                     },
58
                     },
59
+                    created_at: Date.now()
60
                 })
60
                 })
61
                 return h
61
                 return h
62
                     .response({
62
                     .response({

+ 1
- 1
backend/lib/schemas/authentication.js ファイルの表示

5
 const userAuth = Joi.object({
5
 const userAuth = Joi.object({
6
     user_email: Joi.string(),
6
     user_email: Joi.string(),
7
     created_at: Joi.date(),
7
     created_at: Joi.date(),
8
-    token: Joi.binary()
8
+    token: Joi.binary().allow(null)
9
 }).label('user_auth')
9
 }).label('user_auth')
10
 
10
 
11
 module.exports = {
11
 module.exports = {

+ 40
- 55
backend/lib/services/user.js ファイルの表示

86
      * @param {*} txn
86
      * @param {*} txn
87
      * @returns
87
      * @returns
88
      */
88
      */
89
-    async signup({ password, userInfo }, txn) {
89
+    async signup({ password, userInfo, created_at }, txn) {
90
         const { User, Auth } = this.server.models()
90
         const { User, Auth } = this.server.models()
91
         const matchingEmails = await User.query().where(
91
         const matchingEmails = await User.query().where(
92
             'user_email',
92
             'user_email',
95
         if (matchingEmails.length > 0) {
95
         if (matchingEmails.length > 0) {
96
             throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
96
             throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
97
         }
97
         }
98
-        // const todayTest = new Date.now()
99
-        console.log("password passed to .signup()", password)
100
-        console.log("steak", steak)
101
-        console.log("user_email", userInfo.user_email)
102
-
103
-        const { email } = await Auth.query(txn).insert({
104
-            user_email: userInfo.user_email,
105
-            created_at: new Date.now(),
106
-            token: this.changePassword(
107
-                userInfo.user_email,
108
-                password,
109
-                txn,
110
-            ),
98
+        // Insert User Info to User table
99
+        const insertUser = await User.query().insert(userInfo)
100
+        // insert a row with blank password to be updated by changePassword()
101
+        await Auth.query().insert({
102
+            user_email: insertUser.user_email,
103
+            created_at: created_at,
104
+            token: null,
111
         })
105
         })
112
-
113
-        return userInfo.user_email
114
-        console.log("signup return finished")
115
-        // Library: Secure-Password
116
-        // console.log('data type of create_at', )
117
-        // add pepper to pw and convert to buffer to prep for hash bytes
118
-        // const steak = Buffer.from(password + pepper, 'utf-8')
119
-        // console.log("steak", steak)
120
-        // send peppered pw to (argon algorithm) library for salted hash
121
-        // hashed is actually for logging in
122
-        // const hashed = await hasher(this.pwd, steak)
123
-        // console.log("hashed", hashed)
124
-        // console.log ("user_email", userInfo.user_email)
125
-        // const newAuth = await Auth.query(txn).insert({
126
-        //     user_email: userInfo.user_email,
127
-        //     created_at: new Date.now(),
128
-        //     token: steak,
129
-        // })
130
-        // console.log("newAuth", newAuth)
131
-        // return newAuth
132
-
133
-        // const user = await User.query(txn).insert(userInfo)
134
-        // user.user_id = user.id
135
-        // delete user.id
136
-        // await this.changePassword(id, password, txn)
137
-        // return user
106
+        // update null token with hashed password
107
+        await this.changePassword(insertUser.user_email, password, txn)
108
+        return {
109
+            user_id: insertUser.id,
110
+            user_name: insertUser.user_name,
111
+            user_email: insertUser.user_email,
112
+            is_poster: insertUser.is_poster,
113
+            is_admin: insertUser.is_admin,
114
+            is_verified: insertUser.is_verified,
115
+        }
138
     }
116
     }
139
 
117
 
140
     /**
118
     /**
168
      * @returns
146
      * @returns
169
      */
147
      */
170
     async login({ email, password }, txn) {
148
     async login({ email, password }, txn) {
171
-        const { User } = this.server.models()
149
+        const { User, Auth } = this.server.models()
172
 
150
 
173
-        const user = await User.query(txn)
151
+        
152
+        
153
+        const user = await Auth.query(txn)
174
             .throwIfNotFound()
154
             .throwIfNotFound()
175
             .first()
155
             .first()
176
             .where({ user_email: email })
156
             .where({ user_email: email })
177
 
157
 
158
+        const bufferPepper = Buffer.from(process.env.PEPPER + password)
159
+
178
         /** Uncomment to run password check using SecurePassword */
160
         /** Uncomment to run password check using SecurePassword */
179
-        // const passwordCheck = await this.pwd.verify(Buffer.from(password), user.password)
180
-        // if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
181
-        //     await this.changePassword(user.id, password, txn)
182
-        // }
183
-        // else if (passwordCheck !== SecurePassword.VALID) {
184
-        //     throw User.createNotFoundError()
185
-        // }
161
+        const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
162
+        console.log("passwordCheck", passwordCheck)
163
+        if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
164
+            await this.changePassword(user.user_email, password, txn)
165
+        }
166
+        else if (passwordCheck !== SecurePassword.VALID) {
167
+            throw User.createNotFoundError()
168
+        }
186
 
169
 
187
         return user
170
         return user
188
     }
171
     }
221
     async changePassword(email, password, txn) {
204
     async changePassword(email, password, txn) {
222
         const { User, Auth } = this.server.models()
205
         const { User, Auth } = this.server.models()
223
 
206
 
207
+        console.log('email passed to changePassword', email)
208
+
209
+        const hashed = await this.pwd.hash(Buffer.from(process.env.PEPPER + password))
210
+        console.log('hashed', hashed)
211
+
224
         await Auth.query(txn)
212
         await Auth.query(txn)
225
             .throwIfNotFound()
213
             .throwIfNotFound()
226
-            .where({ email })
214
+            .where({ user_email: email })
227
             .patch({
215
             .patch({
228
                 // user_email: email,
216
                 // user_email: email,
229
-                token: await this.pwd.hash(
230
-                    Buffer.from(process.env.PEPPER + password),
231
-                ),
217
+                token: hashed
232
             })
218
             })
233
-        console.log("changed pw return", email)
234
-        console.log("token created in changePassword", this.pwd.hash(Buffer.from(password)))
219
+        console.log('changePassword query completed')
235
         return email
220
         return email
236
 
221
 
237
         // await User.query(txn)
222
         // await User.query(txn)

読み込み中…
キャンセル
保存