Przeglądaj źródła

:bug: Fixed bug with access token expiration

tags/0.0.3^2
tomit4 2 lat temu
rodzic
commit
e7c13686bc

+ 1
- 1
backend/lib/auth/strategies/jwt.js Wyświetl plik

@@ -13,7 +13,7 @@ module.exports = options => {
13 13
                 const validatedJwt = JWT.verify(token, process.env.APP_SECRET)
14 14
                 return {
15 15
                     isValid: true,
16
-                    credentials: validatedJwt.payload.email,
16
+                    credentials: validatedJwt.email,
17 17
                 }
18 18
             } catch (err) {
19 19
                 console.error('ERROR :=>', err)

+ 2
- 1
backend/lib/routes/profile/get.js Wyświetl plik

@@ -29,7 +29,8 @@ module.exports = {
29 29
         ...pluginConfig.docs,
30 30
         tags: ['api'],
31 31
         /** Protect this route with authentication? */
32
-        auth: false,
32
+        // auth: false,
33
+        auth: 'default_jwt',
33 34
         cors: true,
34 35
         handler: async function (request, h) {
35 36
             const { profile_id } = request.params

+ 3
- 1
backend/lib/routes/user/getaccess.js Wyświetl plik

@@ -29,7 +29,9 @@ module.exports = {
29 29
             const token = await userService.createToken({
30 30
                 ...res,
31 31
                 // NOTE: Set Expiration Time for Access Token Here
32
-                expires: Math.floor(Date.now() / 1000) + 60 * 2,
32
+                // expires: 60 * 2,
33
+                // TESTING:
34
+                expires: 30,
33 35
             })
34 36
             try {
35 37
                 const response = h.response({

+ 1
- 1
backend/lib/routes/user/getsession.js Wyświetl plik

@@ -29,7 +29,7 @@ module.exports = {
29 29
             const token = await userService.createToken({
30 30
                 ...res,
31 31
                 // NOTE: Set Expiration Time for Session Token Here
32
-                expires: Math.floor(Date.now() / 1000) + 60 * 10,
32
+                expires: 60 * 10,
33 33
             })
34 34
             try {
35 35
                 const response = h.response({

+ 2
- 1
backend/lib/routes/user/list-profiles.js Wyświetl plik

@@ -38,7 +38,8 @@ module.exports = {
38 38
         ...pluginConfig.docs,
39 39
         tags: ['api'],
40 40
         /** Protect this route with authentication? */
41
-        auth: false,
41
+        // auth: false,
42
+        auth: 'default_jwt',
42 43
         cors: true,
43 44
         handler: async function (request, h) {
44 45
             const { userService, profileService } = request.server.services()

+ 2
- 1
backend/lib/routes/user/user-by-email.js Wyświetl plik

@@ -18,7 +18,8 @@ module.exports = {
18 18
     options: {
19 19
         ...pluginConfig.docs.get,
20 20
         tags: ['api'],
21
-        auth: false,
21
+        // auth: false,
22
+        auth: 'default_jwt',
22 23
         cors: true,
23 24
         handler: async function (request, h) {
24 25
             const email = request.params.email

+ 2
- 1
frontend/src/utils/db.js Wyświetl plik

@@ -45,7 +45,7 @@ class Connector {
45 45
             if (!res.ok) {
46 46
                 // NOTE: Somewhat hacky workaround here to get auth working
47 47
                 if (res.status === 401) {
48
-                    return { ...jsonRes.data, status: res.status }
48
+                    return { status: jsonRes.statusCode }
49 49
                 } else {
50 50
                     throw Error(res.statusText)
51 51
                 }
@@ -75,6 +75,7 @@ class Connector {
75 75
             })
76 76
         }
77 77
     }
78
+    // TODO: probably needs authHeader param for insertSurveyResponses
78 79
     async post(endpoint, payload = {}, returnHeaders = false) {
79 80
         return await this._tryFetch({
80 81
             endpoint,

+ 37
- 40
frontend/src/views/OnboardingView.vue Wyświetl plik

@@ -71,10 +71,7 @@ export default {
71 71
         accessToken = this.grabStoredCookie('siimee_access')
72 72
         // TODO: More graceful way of throwing exceptions if sessionData is not defined??
73 73
         try {
74
-            const sessionData = await this.verifyBothTokens(
75
-                sessionToken,
76
-                accessToken,
77
-            )
74
+            const sessionData = await this.verifyBothTokens()
78 75
             await this.isEmailInRegistry(sessionData.payload.email)
79 76
             // TODO: Validate All routes hit by these methods using tokens in headers
80 77
             const userId = await this.grabUserIdByEmail(
@@ -110,7 +107,7 @@ export default {
110 107
                 cookieKey in cookies ? cookies[`${cookieKey}`] : undefined
111 108
             return cookieVal
112 109
         },
113
-        async verifyBothTokens(sessionToken, accessToken) {
110
+        async verifyBothTokens() {
114 111
             const sessionTokenIsValid = await this.verifySessionToken(
115 112
                 sessionToken,
116 113
             )
@@ -122,22 +119,23 @@ export default {
122 119
                 console.warn(
123 120
                     'WARNING :=> Access Token Expired, but Session Token Is Still Valid, reissuing Access Token...',
124 121
                 )
125
-                // NOTE: Whether to implement newSessionToken is unclear in notes,
126
-                // but without this, user session will expire in 10 minutes no matter what...
127
-                const newSessionToken =
128
-                    await this.authenticator.getSessionToken(
129
-                        sessionTokenIsValid.payload,
130
-                    )
122
+                // TODO: break out reissuing new tokens into separate _function
131 123
                 const newAccessToken = await this.authenticator.getAccessToken(
132 124
                     sessionTokenIsValid.payload,
133 125
                 )
134
-                sessionToken = newSessionToken
135
-                accessToken = newAccessToken
136
-                document.cookie = `siimee_access=${newSessionToken}; max-age=600; path=/; secure`
137
-                document.cookie = `siimee_access=${newAccessToken}; max-age=600; path=/; secure`
138 126
                 const newAccessTokenIsValid = await this.verifyAccessToken(
139 127
                     newAccessToken,
140 128
                 )
129
+                accessToken = newAccessToken
130
+                document.cookie = `siimee_access=${newAccessToken}; max-age=600; path=/; secure`
131
+                // NOTE: Resetting Session Token otherwise session
132
+                // token will always expire after 10 minutes...???
133
+                const newSessionToken =
134
+                    await this.authenticator.getSessionToken(
135
+                        sessionTokenIsValid.payload,
136
+                    )
137
+                sessionToken = newSessionToken
138
+                document.cookie = `siimee_session=${newSessionToken}; max-age=600; path=/; secure`
141 139
                 return newAccessTokenIsValid
142 140
             } else if (
143 141
                 accessTokenIsValid.status === 401 &&
@@ -184,20 +182,21 @@ export default {
184 182
         },
185 183
         async grabProfileIdByUserId(userId) {
186 184
             const profilesFromUserId = await fetchProfilesByUserId(userId)
187
-            if (profilesFromUserId.length === 1) {
185
+            if (
186
+                profilesFromUserId.length === 1 &&
187
+                profilesFromUserId.status !== 401
188
+            ) {
188 189
                 return profilesFromUserId[0].profile_id
189
-            } else {
190
+            } else if (profilesFromUserId.length > 1) {
190 191
                 // TODO: Refactor once more is known on users with multiple profiles
191
-                console.error(
192
-                    'ERROR :=> Multiple Profiles for this User ID',
193
-                    profilesFromUserId,
194
-                )
195 192
                 throw new Error('Multiple Profiles for this User ID')
193
+            } else {
194
+                throw new Error('No Profile for User ID found')
196 195
             }
197 196
         },
198 197
         async grabProfileByProfileId(profileId) {
199 198
             const profile = await fetchProfileByProfileId(profileId)
200
-            if (!profile) {
199
+            if (!profile || profile.status === 401) {
201 200
                 throw new Error(`No Profile Found for profileId ${profileId}`)
202 201
             } else {
203 202
                 return profile
@@ -206,7 +205,7 @@ export default {
206 205
         async grabResponsesByProfileId(profileId) {
207 206
             const responses = []
208 207
             const profile = await this.grabProfileByProfileId(profileId)
209
-            if (!profile.responses.length) {
208
+            if (!profile.responses.length || profile.responses.status === 401) {
210 209
                 throw new Error(`No Responses Found for profileId ${profileId}`)
211 210
             } else {
212 211
                 profile.responses.forEach(response => {
@@ -234,25 +233,23 @@ export default {
234 233
                 response.response_key_id = payload.question.response_key_id
235 234
                 response.val = payload.input
236 235
                 this.responses.push(response)
237
-
238
-                // TODO: Validate this route using tokens in headers
239
-                // TODO: Set check via methods to see if tokens are still valid,
240
-                // if BOTH tokens are NOT valid,
241
-                // currentProfileId = null and this.currentStep = 0
242
-                if (currentProfileId) {
243
-                    await surveyFactory.addNewSurveyAnswer(
244
-                        this.responses[this.responses.length - 1],
245
-                        currentProfileId,
246
-                    )
247
-                    try {
248
-                        this.verifyBothTokens(sessionToken, accessToken)
249
-                    } catch (err) {
250
-                        console.error('ERROR :=>', err)
251
-                        this.goToStep(0)
252
-                    }
253
-                }
254 236
                 if (k === 'aspects') return
255 237
             }
238
+            if (currentProfileId) {
239
+                // TODO: Still have to authenticate this route
240
+                await surveyFactory.addNewSurveyAnswer(
241
+                    this.responses[this.responses.length - 1],
242
+                    currentProfileId,
243
+                    accessToken,
244
+                )
245
+                try {
246
+                    await this.verifyBothTokens(sessionToken, accessToken)
247
+                } catch (err) {
248
+                    this.currentStep = 0
249
+                    this.goToStep(this.currentStep)
250
+                    throw new Error(err)
251
+                }
252
+            }
256 253
             if (this.currentStep > this.survey.steps.length) {
257 254
                 this.onSubmit(this.answered)
258 255
             } else {

Ładowanie…
Anuluj
Zapisz