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

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

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

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

29
             const token = await userService.createToken({
29
             const token = await userService.createToken({
30
                 ...res,
30
                 ...res,
31
                 // NOTE: Set Expiration Time for Access Token Here
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
             try {
36
             try {
35
                 const response = h.response({
37
                 const response = h.response({

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

29
             const token = await userService.createToken({
29
             const token = await userService.createToken({
30
                 ...res,
30
                 ...res,
31
                 // NOTE: Set Expiration Time for Session Token Here
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
             try {
34
             try {
35
                 const response = h.response({
35
                 const response = h.response({

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

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

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

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

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

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

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

71
         accessToken = this.grabStoredCookie('siimee_access')
71
         accessToken = this.grabStoredCookie('siimee_access')
72
         // TODO: More graceful way of throwing exceptions if sessionData is not defined??
72
         // TODO: More graceful way of throwing exceptions if sessionData is not defined??
73
         try {
73
         try {
74
-            const sessionData = await this.verifyBothTokens(
75
-                sessionToken,
76
-                accessToken,
77
-            )
74
+            const sessionData = await this.verifyBothTokens()
78
             await this.isEmailInRegistry(sessionData.payload.email)
75
             await this.isEmailInRegistry(sessionData.payload.email)
79
             // TODO: Validate All routes hit by these methods using tokens in headers
76
             // TODO: Validate All routes hit by these methods using tokens in headers
80
             const userId = await this.grabUserIdByEmail(
77
             const userId = await this.grabUserIdByEmail(
110
                 cookieKey in cookies ? cookies[`${cookieKey}`] : undefined
107
                 cookieKey in cookies ? cookies[`${cookieKey}`] : undefined
111
             return cookieVal
108
             return cookieVal
112
         },
109
         },
113
-        async verifyBothTokens(sessionToken, accessToken) {
110
+        async verifyBothTokens() {
114
             const sessionTokenIsValid = await this.verifySessionToken(
111
             const sessionTokenIsValid = await this.verifySessionToken(
115
                 sessionToken,
112
                 sessionToken,
116
             )
113
             )
122
                 console.warn(
119
                 console.warn(
123
                     'WARNING :=> Access Token Expired, but Session Token Is Still Valid, reissuing Access Token...',
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
                 const newAccessToken = await this.authenticator.getAccessToken(
123
                 const newAccessToken = await this.authenticator.getAccessToken(
132
                     sessionTokenIsValid.payload,
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
                 const newAccessTokenIsValid = await this.verifyAccessToken(
126
                 const newAccessTokenIsValid = await this.verifyAccessToken(
139
                     newAccessToken,
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
                 return newAccessTokenIsValid
139
                 return newAccessTokenIsValid
142
             } else if (
140
             } else if (
143
                 accessTokenIsValid.status === 401 &&
141
                 accessTokenIsValid.status === 401 &&
184
         },
182
         },
185
         async grabProfileIdByUserId(userId) {
183
         async grabProfileIdByUserId(userId) {
186
             const profilesFromUserId = await fetchProfilesByUserId(userId)
184
             const profilesFromUserId = await fetchProfilesByUserId(userId)
187
-            if (profilesFromUserId.length === 1) {
185
+            if (
186
+                profilesFromUserId.length === 1 &&
187
+                profilesFromUserId.status !== 401
188
+            ) {
188
                 return profilesFromUserId[0].profile_id
189
                 return profilesFromUserId[0].profile_id
189
-            } else {
190
+            } else if (profilesFromUserId.length > 1) {
190
                 // TODO: Refactor once more is known on users with multiple profiles
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
                 throw new Error('Multiple Profiles for this User ID')
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
         async grabProfileByProfileId(profileId) {
197
         async grabProfileByProfileId(profileId) {
199
             const profile = await fetchProfileByProfileId(profileId)
198
             const profile = await fetchProfileByProfileId(profileId)
200
-            if (!profile) {
199
+            if (!profile || profile.status === 401) {
201
                 throw new Error(`No Profile Found for profileId ${profileId}`)
200
                 throw new Error(`No Profile Found for profileId ${profileId}`)
202
             } else {
201
             } else {
203
                 return profile
202
                 return profile
206
         async grabResponsesByProfileId(profileId) {
205
         async grabResponsesByProfileId(profileId) {
207
             const responses = []
206
             const responses = []
208
             const profile = await this.grabProfileByProfileId(profileId)
207
             const profile = await this.grabProfileByProfileId(profileId)
209
-            if (!profile.responses.length) {
208
+            if (!profile.responses.length || profile.responses.status === 401) {
210
                 throw new Error(`No Responses Found for profileId ${profileId}`)
209
                 throw new Error(`No Responses Found for profileId ${profileId}`)
211
             } else {
210
             } else {
212
                 profile.responses.forEach(response => {
211
                 profile.responses.forEach(response => {
234
                 response.response_key_id = payload.question.response_key_id
233
                 response.response_key_id = payload.question.response_key_id
235
                 response.val = payload.input
234
                 response.val = payload.input
236
                 this.responses.push(response)
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
                 if (k === 'aspects') return
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
             if (this.currentStep > this.survey.steps.length) {
253
             if (this.currentStep > this.survey.steps.length) {
257
                 this.onSubmit(this.answered)
254
                 this.onSubmit(this.answered)
258
             } else {
255
             } else {

Ładowanie…
Anuluj
Zapisz