Просмотр исходного кода

:truck: Renamed variables/functions as a refactor

juan_spike
tomit4 3 лет назад
Родитель
Сommit
4ae52ce18b

+ 6
- 6
backend/lib/plugins/user.js Просмотреть файл

@@ -14,9 +14,9 @@ const UserLoginRoute = require('../routes/user/login')
14 14
 const UserSignupRoute = require('../routes/user/signup')
15 15
 const UserEmailRoute = require('../routes/user/email.js')
16 16
 const UserVerifyEmailRoute = require('../routes/user/verifyemail.js')
17
-const UserGenerateJWTRoute = require('../routes/user/generatejwt.js')
18
-const UserValidateJWTRoute = require('../routes/user/validatejwt.js')
19
-const UserCheckCache = require('../routes/user/check-cache.js')
17
+const UserGetJWTRoute = require('../routes/user/getjwt.js')
18
+const UserValidateSessionRoute = require('../routes/user/validatesession.js')
19
+const UserCheckEmailRegistry = require('../routes/user/check-email-registry.js')
20 20
 const UserByEmail = require('../routes/user/user-by-email.js')
21 21
 const UserPassword = require('../routes/user/authentication')
22 22
 
@@ -57,9 +57,9 @@ module.exports = {
57 57
         await server.route(UserProfilesListRoute)
58 58
         await server.route(UserEmailRoute)
59 59
         await server.route(UserVerifyEmailRoute)
60
-        await server.route(UserGenerateJWTRoute)
61
-        await server.route(UserValidateJWTRoute)
62
-        await server.route(UserCheckCache)
60
+        await server.route(UserGetJWTRoute)
61
+        await server.route(UserValidateSessionRoute)
62
+        await server.route(UserCheckEmailRegistry)
63 63
         await server.route(UserByEmail)
64 64
         await server.route(UserPassword)
65 65
     },

backend/lib/routes/user/check-cache.js → backend/lib/routes/user/check-email-registry.js Просмотреть файл

@@ -6,15 +6,15 @@ const pluginConfig = {
6 6
     handlerType: 'email',
7 7
     docs: {
8 8
         get: {
9
-            description: 'checks if user email is in cache',
10
-            notes: 'Checks if user email is in email cache and returns boolean',
9
+            description: 'checks if user email is registered in memory',
10
+            notes: 'Checks if user email is in application state and returns boolean',
11 11
         },
12 12
     },
13 13
 }
14 14
 
15 15
 module.exports = {
16 16
     method: 'POST',
17
-    path: '/checkcache/',
17
+    path: '/checkemailregistry/',
18 18
     options: {
19 19
         ...pluginConfig.docs.get,
20 20
         tags: ['api'],
@@ -24,13 +24,13 @@ module.exports = {
24 24
             const { userService } = request.server.services()
25 25
             const userEmail = request.payload
26 26
             try {
27
-                const emailIsInCache = await userService.checkEmailCache(
27
+                const emailIsRegistered = await userService.checkEmailRegistry(
28 28
                     userEmail,
29 29
                 )
30 30
                 return {
31 31
                     ok: true,
32 32
                     handler: pluginConfig.handlerType,
33
-                    data: { emailIsInCache: emailIsInCache },
33
+                    data: emailIsRegistered,
34 34
                 }
35 35
             } catch (err) {
36 36
                 return {
@@ -49,8 +49,8 @@ module.exports = {
49 49
             schema: Joi.object({
50 50
                 ok: Joi.bool(),
51 51
                 handler: Joi.string(),
52
-                data: Joi.object(),
53
-            }).label('email_res'),
52
+                data: Joi.bool(),
53
+            }).label('email_registry_res'),
54 54
             failAction: 'log',
55 55
         },
56 56
     },

backend/lib/routes/user/generatejwt.js → backend/lib/routes/user/getjwt.js Просмотреть файл

@@ -6,15 +6,15 @@ const pluginConfig = {
6 6
     handlerType: 'email',
7 7
     docs: {
8 8
         get: {
9
-            description: 'generates jwt after verifying email',
10
-            notes: 'Generates jwt after validating email',
9
+            description: 'gets jwt after verifying email',
10
+            notes: 'Gets jwt after validating email',
11 11
         },
12 12
     },
13 13
 }
14 14
 
15 15
 module.exports = {
16 16
     method: 'POST',
17
-    path: '/generatejwt',
17
+    path: '/getjwt',
18 18
     options: {
19 19
         ...pluginConfig.docs.get,
20 20
         tags: ['api'],
@@ -30,7 +30,7 @@ module.exports = {
30 30
                 return {
31 31
                     ok: true,
32 32
                     handler: pluginConfig.handlerType,
33
-                    data: { jwt: token },
33
+                    data: token,
34 34
                 }
35 35
             } catch (err) {
36 36
                 return {
@@ -49,8 +49,8 @@ module.exports = {
49 49
             schema: Joi.object({
50 50
                 ok: Joi.bool(),
51 51
                 handler: Joi.string(),
52
-                data: Joi.object(),
53
-            }).label('generate_jwt_res'),
52
+                data: Joi.string(),
53
+            }).label('get_jwt_res'),
54 54
             failAction: 'log',
55 55
         },
56 56
     },

backend/lib/routes/user/validatejwt.js → backend/lib/routes/user/validatesession.js Просмотреть файл

@@ -6,33 +6,32 @@ const pluginConfig = {
6 6
     handlerType: 'jwt',
7 7
     docs: {
8 8
         get: {
9
-            description: 'validates jwt for each step of survey',
10
-            notes: 'validates jwt for each step of survey',
9
+            description: 'validates session token for each step of survey',
10
+            notes: 'validates session token for each step of survey',
11 11
         },
12 12
     },
13 13
 }
14 14
 
15 15
 module.exports = {
16 16
     method: 'GET',
17
-    path: '/validatejwt/{jwt}',
17
+    path: '/validatesession/{sessionToken}',
18 18
     // method: 'GET' sessionToken in header ?
19
-    // path: '/validatesession/{sessionToken}'
20 19
     options: {
21 20
         ...pluginConfig.docs.get,
22 21
         tags: ['api'],
23 22
         auth: false,
24 23
         cors: true,
25 24
         handler: async function (request, h) {
26
-            const jwt = request.params.jwt
25
+            const sessionToken = request.params.sessionToken
27 26
             const { userService } = request.server.services()
28
-            const jwtIsValid = userService.validateToken(jwt)
27
+            const sessionTokenIsValid = userService.validateToken(sessionToken)
29 28
             try {
30 29
                 return {
31 30
                     ok: true,
32 31
                     handler: pluginConfig.handlerType,
33 32
                     data: {
34
-                        isValid: jwtIsValid.isValid,
35
-                        payload: jwtIsValid.payload,
33
+                        isValid: sessionTokenIsValid.isValid,
34
+                        payload: sessionTokenIsValid.payload,
36 35
                     },
37 36
                 }
38 37
             } catch (err) {
@@ -53,7 +52,7 @@ module.exports = {
53 52
                 ok: Joi.bool(),
54 53
                 handler: Joi.string(),
55 54
                 data: Joi.object(),
56
-            }).label('validate_jwt_res'),
55
+            }).label('validate_session_res'),
57 56
             failAction: 'log',
58 57
         },
59 58
     },

+ 4
- 4
backend/lib/services/user.js Просмотреть файл

@@ -383,19 +383,19 @@ module.exports = class UserService extends Schmervice.Service {
383 383
         return passwordRow ? passwordRow.token : null
384 384
     }
385 385
 
386
-    async checkEmailCache(userEmail) {
386
+    async checkEmailRegistry(userEmail) {
387 387
         const hashedEmail = await hashEmail(userEmail)
388 388
         const now = Date.now()
389 389
         // hashedEmail needs to be derived by email, salt
390 390
         const expiration = this.hashedEmails[hashedEmail]
391 391
         console.log('this.hashedEmails :=>', this.hashedEmails)
392
-        const emailIsInCache = Object.keys(this.hashedEmails).includes(
392
+        const emailIsRegistered = Object.keys(this.hashedEmails).includes(
393 393
             hashedEmail,
394 394
         )
395 395
         const emailIsExpired = now > expiration ? true : false
396
-        console.log('emailIsInCache :=>', emailIsInCache)
396
+        console.log('emailIsRegistered :=>', emailIsRegistered)
397 397
         console.log('emailIsExpired :=>', emailIsExpired)
398
-        if (emailIsInCache && !emailIsExpired) {
398
+        if (emailIsRegistered && !emailIsExpired) {
399 399
             return true
400 400
         } else {
401 401
             // try {

+ 1
- 2
frontend/src/components/onboarding/Auth.vue Просмотреть файл

@@ -51,8 +51,7 @@ export default {
51 51
             })
52 52
             const newUserId = newUser.user_id
53 53
             await createProfileForUserId(newUserId, this.responses)
54
-            // TODO: rename getJwt
55
-            const jwt = await this.authenticator.generateJwt({
54
+            const jwt = await this.authenticator.getJwt({
56 55
                 ...this.answered,
57 56
                 expiration: 60 * 10,
58 57
             })

+ 14
- 11
frontend/src/services/auth.service.js Просмотреть файл

@@ -8,26 +8,29 @@ class Authenticator {
8 8
         const emailWasSent = await db.post('/user/sendemail/', answered)
9 9
         return emailWasSent
10 10
     }
11
-    async checkEmailCache(email) {
12
-        const emailIsInCache = await db.post('/user/checkcache/', email)
13
-        return emailIsInCache.emailIsInCache
11
+    async checkIfEmailIsRegistered(email) {
12
+        const emailIsRegistered = await db.post(
13
+            '/user/checkemailregistry/',
14
+            email,
15
+        )
16
+        return emailIsRegistered
14 17
     }
15 18
     async verifyAuthEmail(hashedEmail) {
16 19
         const isVerified = await db.get(`/user/verify/${hashedEmail}`)
17 20
         return isVerified.hashesMatch
18 21
     }
19
-    // TODO: rename getJwt()
20
-    async generateJwt(req) {
21
-        const response = await db.post('/user/generatejwt', req)
22
+    async getJwt(req) {
23
+        const jwt = await db.post('/user/getjwt', req)
22 24
         // TODO: Move token into repsonse.headers
23 25
         // return response.headers ?
24
-        return response.jwt
26
+        return jwt
25 27
     }
26 28
 
27
-    // validateSession(sessionToken)
28
-    async validateJwt(jwt) {
29
-        const validateJwt = await db.get(`/user/validatejwt/${jwt}`)
30
-        return validateJwt
29
+    async validateSession(sessionToken) {
30
+        const validateSession = await db.get(
31
+            `/user/validatesession/${sessionToken}`,
32
+        )
33
+        return validateSession
31 34
     }
32 35
 }
33 36
 

+ 19
- 14
frontend/src/views/OnboardingView.vue Просмотреть файл

@@ -62,33 +62,37 @@ export default {
62 62
         survey: null,
63 63
         invalidResponse: false,
64 64
         userEmail: null,
65
-        emailIsInCache: false,
65
+        emailIsRegistered: false,
66 66
         authenticator: {},
67 67
     }),
68 68
     async created() {
69 69
         this.survey = await surveyFactory.createSurvey()
70 70
         this.authenticator = new Authenticator()
71 71
         // TODO: Consider switch/case() depending on what tokens exist/are valid...
72
-        sessionToken = this.grabCookie('siimee_session_onboarding')
72
+        sessionToken = this.grabStoredCookie('siimee_session')
73
+        console.log('sessionToken :=>', sessionToken)
73 74
         // if (!sessionToken) {
74 75
         //     //
75 76
         // }
76
-        accessToken = this.grabCookie('siimee_access_onboarding')
77
+        // accessToken = this.grabStoredCookie('siimee_access_onboarding')
77 78
         // if (!accessToken) {
78 79
         //     // blow up
79 80
         // }
80
-        const sessionData = await this.authenticator.validateJwt(sessionToken)
81
-        // NOTE: Left off here, INCOMPLETE, no ACCESS TOKEN yet, crazy amount of logic here...
82
-        if (sessionData.isValid && !accessToken) {
81
+        const sessionData = await this.authenticator.validateSession(
82
+            sessionToken,
83
+        )
84
+        console.log('sessionData :=>', sessionData)
85
+        // if (sessionData.isValid && !accessToken) {
86
+        if (sessionData.isValid) {
83 87
             this.userEmail = sessionData.payload.email
84
-            // this.emailIsRegistered
85
-            this.emailIsInCache = await this.authenticator.checkEmailCache(
86
-                this.userEmail,
87
-            )
88
+            this.emailIsRegistered =
89
+                await this.authenticator.checkIfEmailIsRegistered(
90
+                    this.userEmail,
91
+                )
88 92
         }
89 93
         // TODO: EVERY ROUTE WE HIT AFTER THIS HAS TO BE AUTHENTICATED
90 94
         // ACCESS TOKEN WORKS
91
-        if (this.emailIsInCache) {
95
+        if (this.emailIsRegistered) {
92 96
             const user = await fetchUserByEmail(this.userEmail)
93 97
             const userId = user.user_id
94 98
             const profilesFromUserId = await fetchProfilesByUserId(userId)
@@ -97,6 +101,9 @@ export default {
97 101
                 profileId = profilesFromUserId[0].profile_id
98 102
                 this.currentProfileId = profileId
99 103
             }
104
+            // if (!profileId) {
105
+            // throw new Error
106
+            // }
100 107
             const profile = await fetchProfileByProfileId(profileId)
101 108
             profile.responses.forEach(response => {
102 109
                 this.responses.push({
@@ -117,9 +124,7 @@ export default {
117 124
         async goToStep(num) {
118 125
             this.currentStep = num
119 126
         },
120
-        // TODO: Rename this method, grab cookie from where?
121
-        // grabStoredCookie(cookieKey)
122
-        grabCookie(cookieKey) {
127
+        grabStoredCookie(cookieKey) {
123 128
             const cookies = document.cookie
124 129
                 .split('; ')
125 130
                 .reduce((prev, current) => {

+ 3
- 5
frontend/src/views/VerifyView.vue Просмотреть файл

@@ -32,11 +32,9 @@ export default {
32 32
 
33 33
         // TODO: Refactor to not nest, use try/catch/throw
34 34
         if (sessionToken) {
35
-            // TODO: rename
36
-            // const accessToken = await this.authenticator.validateSession(sessionToken)
37
-            // hits backend route and the backend route has to be /validateSession/
35
+            // NOTE: hits backend route and the backend route has to be /validateSession/
38 36
             // if backend route succeeds, gives you access token
39
-            const accessToken = await this.authenticator.validateJwt(
37
+            const accessToken = await this.authenticator.validateSession(
40 38
                 sessionToken,
41 39
             )
42 40
             // TODO: isValid logic needs to live on back end
@@ -64,7 +62,7 @@ export default {
64 62
                 : undefined
65 63
         },
66 64
         async generateAccessToken() {
67
-            const accessJwt = await this.authenticator.generateJwt({
65
+            const accessJwt = await this.authenticator.getJwt({
68 66
                 ...this.answers,
69 67
                 expiration: 60 * 3, // testing for now... extend to 1 hour?
70 68
             })

Загрузка…
Отмена
Сохранить