瀏覽代碼

:white_check_mark: Started testing

tags/0.0.4
tomit4 2 年之前
父節點
當前提交
7ad445c373

+ 8
- 21
backend/lib/routes/user/login.js 查看文件

@@ -33,9 +33,8 @@ module.exports = {
33 33
         auth: false,
34 34
         handler: async function (request, h) {
35 35
             try {
36
-                const { userService, profileService } =
37
-                    request.server.services()
38
-
36
+                const { userService } = request.server.services()
37
+                console.log('testing from here login.js :=>')
39 38
                 const res = request.payload
40 39
 
41 40
                 // Callback to use as transaction
@@ -50,32 +49,20 @@ module.exports = {
50 49
                 }
51 50
 
52 51
                 // Bound context from your plugin server declaration
53
-                const user = await h.context.transaction(login)
54
-                const rawUser = await userService.findByUserEmail(
55
-                    res.user_email,
56
-                )
52
+                await h.context.transaction(login)
53
+
57 54
                 // Uses Same Logic Behind Initial Sign Up,
58 55
                 // passing expected credentials to be used for logging in
59
-                const userCredentials = {
60
-                    email: rawUser.user_email,
61
-                    name: rawUser.user_name,
62
-                    seeking: rawUser.is_poster === 1 ? 'poster' : 'seeker',
63
-                }
64
-                const token = userService.createToken({
65
-                    payload: userCredentials,
66
-                })
56
+                const { userCredentials, token } =
57
+                    await userService.makeUserCredentials(res.user_email)
67 58
 
68 59
                 return {
69 60
                     ok: true,
70 61
                     handler: pluginConfig.handlerType,
71 62
                     data: {
72
-                        user_email: user.user_email,
63
+                        user_email: userCredentials.email,
73 64
                         jwt: token,
74
-                        answered: {
75
-                            email: userCredentials.email,
76
-                            name: userCredentials.name,
77
-                            seeking: userCredentials.seeking,
78
-                        },
65
+                        answered: userCredentials,
79 66
                     },
80 67
                 }
81 68
             } catch (err) {

+ 2
- 0
backend/lib/routes/user/verifyactivesession.js 查看文件

@@ -45,6 +45,8 @@ module.exports = {
45 45
                 if (!hashToMatch) {
46 46
                     throw new Error('no record of email in cache')
47 47
                 }
48
+                // NOTE: When user responds to email,
49
+                // boolean value is set to true, allowing user back into the survey
48 50
                 userService.activeSessions[
49 51
                     hashToMatch
50 52
                 ].emailWasRespondedTo = true

+ 17
- 0
backend/lib/services/user.js 查看文件

@@ -212,6 +212,7 @@ module.exports = class UserService extends Schmervice.Service {
212 212
 
213 213
         /** Uncomment to run password check using SecurePassword */
214 214
         const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
215
+
215 216
         if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
216 217
             await this.changePassword(user.user_email, password, txn)
217 218
         } else if (passwordCheck !== SecurePassword.VALID) {
@@ -233,6 +234,22 @@ module.exports = class UserService extends Schmervice.Service {
233 234
         return JWT.sign(obj, key, { expiresIn: expiration })
234 235
     }
235 236
 
237
+    async makeUserCredentials(email) {
238
+        const user = await this.findByUserEmail(email)
239
+        const userCredentials = {
240
+            email: user.user_email,
241
+            name: user.user_name,
242
+            seeking: user.is_poster === 1 ? 'poster' : 'seeker',
243
+        }
244
+        const token = this.createToken({
245
+            payload: userCredentials,
246
+        })
247
+        return {
248
+            userCredentials,
249
+            token,
250
+        }
251
+    }
252
+
236 253
     /**
237 254
      * Validates whether a token has expired or not
238 255
      * @param {User} user

+ 1
- 1
backend/package.json 查看文件

@@ -12,7 +12,7 @@
12 12
         "reseed": "knex migrate:rollback --all && knex migrate:latest && knex seed:run",
13 13
         "generate": "node ./db/data-generator/index.js",
14 14
         "seed": "knex seed:run",
15
-        "test": "nyc ava --timeout=100000"
15
+        "test": "nyc ava --timeout=100000 --verbose"
16 16
     },
17 17
     "author": "TOJ",
18 18
     "license": "UNLICENSED",

+ 112
- 0
backend/tests/usercredential.spec.js 查看文件

@@ -0,0 +1,112 @@
1
+'use strict'
2
+
3
+const test = require('ava')
4
+const { stub } = require('sinon')
5
+const Hapi = require('@hapi/hapi')
6
+const Objection = require('objection')
7
+const UserService = require('../lib/services/user.js')
8
+
9
+const plugin = require('../lib/plugins/user.js')
10
+
11
+const Auth = require('../lib/models/authentication.js')
12
+const User = require('../lib/models/user.js')
13
+
14
+/**
15
+ * Route parameters
16
+ */
17
+const payload = {
18
+    user_email: 'test@testemail.com',
19
+    password: 'abcd123',
20
+}
21
+
22
+const mockReturn = {
23
+    user_id: 1234,
24
+    user_name: 'brian',
25
+    user_email: 'test@testemail.com',
26
+    is_poster: 1,
27
+    is_admin: 0,
28
+    is_verified: 1,
29
+}
30
+
31
+const pathToTest = {
32
+    method: 'POST',
33
+    url: `/login`,
34
+    payload: JSON.stringify(payload),
35
+}
36
+
37
+// NOTE: how does hapi/ava expect payload from 'POST' request??
38
+test('path /login should return ok', async t => {
39
+    /**
40
+     * Create a new server and register services,
41
+     * models and routes for testing
42
+     * -
43
+     * NOTE: We use a mocked registerModel() and register
44
+     * models manually. Normally this is handled by
45
+     * Schwifty at runtime.
46
+     */
47
+    const server = Hapi.server()
48
+    /**
49
+     * Overload so we don't register any models
50
+     * using the plugin call (see plugins/profile.js)
51
+     * and Manually load the model we need for the test
52
+     */
53
+    server.registerModel = () => {}
54
+
55
+    server.models = () => ({ User, Auth })
56
+    server.registrations = {
57
+        'main-app-plugin': {
58
+            options: {},
59
+        },
60
+    }
61
+    server.registrations['main-app-plugin'].options.jwtKey = {
62
+        $filter: 'NODE_ENV',
63
+        $default: {
64
+            $param: 'APP_SECRET',
65
+            $default: 'app-secret',
66
+        },
67
+        // Use .env file in production
68
+        production: {
69
+            $param: 'APP_SECRET',
70
+        },
71
+    }
72
+    stub(Objection, 'transaction').returns({})
73
+    /**
74
+     * Register Routes and Services as usual
75
+     */
76
+    await plugin.register(server)
77
+    server.services()['userService'] = new UserService(server)
78
+    server.services()['userService'].createToken = () =>
79
+        'a;slkdf;asdfa;sdfkja;lsdfj;askdfj;laskdjf;laskjdf'
80
+
81
+    /**
82
+     * Replace Objection model methods with our own mock functions
83
+     * !: Janky - might be better to temp knex sqlite instance
84
+     */
85
+
86
+    stub(server.models()['Auth'], 'query').returns({
87
+        throwIfNotFound: () => ({
88
+            first: () => ({
89
+                where: () => ({ ...mockReturn }),
90
+            }),
91
+        }),
92
+    })
93
+    stub(server.models()['User'], 'createNotFoundError').returns({})
94
+    stub(server.models()['User'], 'query').returns({
95
+        throwIfNotFound: () => ({
96
+            first: () => ({
97
+                where: () => ({ ...mockReturn }),
98
+            }),
99
+        }),
100
+    })
101
+
102
+    /**
103
+     * Test the server with registered models and services
104
+     */
105
+    const { payload } = await server.inject(pathToTest)
106
+    const res = JSON.parse(payload)
107
+
108
+    t.deepEqual(res.ok, true)
109
+    t.deepEqual(res.data.answered.email, mockReturn.user_email)
110
+    t.deepEqual(res.data.answered.name, mockReturn.user_name)
111
+    t.deepEqual(res.data.answered.seeking, 'poster')
112
+})

+ 27
- 0
frontend/src/utils/index.js 查看文件

@@ -2,6 +2,7 @@ import Joi from 'joi'
2 2
 import { SurveyFactory } from './survey.js'
3 3
 import { possible } from './lang.js'
4 4
 import { pidMixin, profileMixin } from './mixins.js'
5
+import { authenticator } from '../services/auth.service.js'
5 6
 
6 7
 // This will NOT work until ES2022 gets assert in browsers
7 8
 // import config from '../../../backend/db/data-generator/config.json' assert { type: 'json' }
@@ -129,6 +130,30 @@ const randomSurveyResponses = count => {
129 130
     return surveyResponses
130 131
 }
131 132
 
133
+const grabStoredCookie = cookieKey => {
134
+    const cookies = document.cookie.split('; ').reduce((prev, current) => {
135
+        const [name, ...value] = current.split('=')
136
+        prev[name] = value.join('=')
137
+        return prev
138
+    }, {})
139
+    const cookieVal = cookieKey in cookies ? cookies[`${cookieKey}`] : undefined
140
+    return cookieVal
141
+}
142
+
143
+const verifySession = async () => {
144
+    const hashedAccessToken = grabStoredCookie('siimee_access')
145
+    if (!hashedAccessToken)
146
+        return console.warn('WARNING :=> accessToken is not defined')
147
+    const validatedToken = await authenticator.validateSession(
148
+        hashedAccessToken,
149
+    )
150
+    if (validatedToken.error) {
151
+        console.error('ERROR :=>', validatedToken.error)
152
+    } else {
153
+        return validatedToken
154
+    }
155
+}
156
+
132 157
 export {
133 158
     validatorMapping,
134 159
     surveyFactory,
@@ -140,4 +165,6 @@ export {
140 165
     randomMedia,
141 166
     randomName,
142 167
     randomEmail,
168
+    grabStoredCookie,
169
+    verifySession,
143 170
 }

Loading…
取消
儲存