Преглед изворни кода

:truck: Renamed variables/functions as a refactor

tags/0.0.3^2
tomit4 пре 3 година
родитељ
комит
ab73fb4039

+ 6
- 6
backend/lib/plugins/user.js Прегледај датотеку

14
 const UserSignupRoute = require('../routes/user/signup')
14
 const UserSignupRoute = require('../routes/user/signup')
15
 const UserEmailRoute = require('../routes/user/email.js')
15
 const UserEmailRoute = require('../routes/user/email.js')
16
 const UserVerifyEmailRoute = require('../routes/user/verifyemail.js')
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
 const UserByEmail = require('../routes/user/user-by-email.js')
20
 const UserByEmail = require('../routes/user/user-by-email.js')
21
 const UserPassword = require('../routes/user/authentication')
21
 const UserPassword = require('../routes/user/authentication')
22
 
22
 
57
         await server.route(UserProfilesListRoute)
57
         await server.route(UserProfilesListRoute)
58
         await server.route(UserEmailRoute)
58
         await server.route(UserEmailRoute)
59
         await server.route(UserVerifyEmailRoute)
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
         await server.route(UserByEmail)
63
         await server.route(UserByEmail)
64
         await server.route(UserPassword)
64
         await server.route(UserPassword)
65
     },
65
     },

backend/lib/routes/user/check-cache.js → backend/lib/routes/user/check-email-registry.js Прегледај датотеку

6
     handlerType: 'email',
6
     handlerType: 'email',
7
     docs: {
7
     docs: {
8
         get: {
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
 module.exports = {
15
 module.exports = {
16
     method: 'POST',
16
     method: 'POST',
17
-    path: '/checkcache/',
17
+    path: '/checkemailregistry/',
18
     options: {
18
     options: {
19
         ...pluginConfig.docs.get,
19
         ...pluginConfig.docs.get,
20
         tags: ['api'],
20
         tags: ['api'],
24
             const { userService } = request.server.services()
24
             const { userService } = request.server.services()
25
             const userEmail = request.payload
25
             const userEmail = request.payload
26
             try {
26
             try {
27
-                const emailIsInCache = await userService.checkEmailCache(
27
+                const emailIsRegistered = await userService.checkEmailRegistry(
28
                     userEmail,
28
                     userEmail,
29
                 )
29
                 )
30
                 return {
30
                 return {
31
                     ok: true,
31
                     ok: true,
32
                     handler: pluginConfig.handlerType,
32
                     handler: pluginConfig.handlerType,
33
-                    data: { emailIsInCache: emailIsInCache },
33
+                    data: emailIsRegistered,
34
                 }
34
                 }
35
             } catch (err) {
35
             } catch (err) {
36
                 return {
36
                 return {
49
             schema: Joi.object({
49
             schema: Joi.object({
50
                 ok: Joi.bool(),
50
                 ok: Joi.bool(),
51
                 handler: Joi.string(),
51
                 handler: Joi.string(),
52
-                data: Joi.object(),
53
-            }).label('email_res'),
52
+                data: Joi.bool(),
53
+            }).label('email_registry_res'),
54
             failAction: 'log',
54
             failAction: 'log',
55
         },
55
         },
56
     },
56
     },

backend/lib/routes/user/generatejwt.js → backend/lib/routes/user/getjwt.js Прегледај датотеку

6
     handlerType: 'email',
6
     handlerType: 'email',
7
     docs: {
7
     docs: {
8
         get: {
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
 module.exports = {
15
 module.exports = {
16
     method: 'POST',
16
     method: 'POST',
17
-    path: '/generatejwt',
17
+    path: '/getjwt',
18
     options: {
18
     options: {
19
         ...pluginConfig.docs.get,
19
         ...pluginConfig.docs.get,
20
         tags: ['api'],
20
         tags: ['api'],
30
                 return {
30
                 return {
31
                     ok: true,
31
                     ok: true,
32
                     handler: pluginConfig.handlerType,
32
                     handler: pluginConfig.handlerType,
33
-                    data: { jwt: token },
33
+                    data: token,
34
                 }
34
                 }
35
             } catch (err) {
35
             } catch (err) {
36
                 return {
36
                 return {
49
             schema: Joi.object({
49
             schema: Joi.object({
50
                 ok: Joi.bool(),
50
                 ok: Joi.bool(),
51
                 handler: Joi.string(),
51
                 handler: Joi.string(),
52
-                data: Joi.object(),
53
-            }).label('generate_jwt_res'),
52
+                data: Joi.string(),
53
+            }).label('get_jwt_res'),
54
             failAction: 'log',
54
             failAction: 'log',
55
         },
55
         },
56
     },
56
     },

backend/lib/routes/user/validatejwt.js → backend/lib/routes/user/validatesession.js Прегледај датотеку

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

+ 4
- 4
backend/lib/services/user.js Прегледај датотеку

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

+ 1
- 2
frontend/src/components/onboarding/Auth.vue Прегледај датотеку

51
             })
51
             })
52
             const newUserId = newUser.user_id
52
             const newUserId = newUser.user_id
53
             await createProfileForUserId(newUserId, this.responses)
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
                 ...this.answered,
55
                 ...this.answered,
57
                 expiration: 60 * 10,
56
                 expiration: 60 * 10,
58
             })
57
             })

+ 14
- 11
frontend/src/services/auth.service.js Прегледај датотеку

8
         const emailWasSent = await db.post('/user/sendemail/', answered)
8
         const emailWasSent = await db.post('/user/sendemail/', answered)
9
         return emailWasSent
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
     async verifyAuthEmail(hashedEmail) {
18
     async verifyAuthEmail(hashedEmail) {
16
         const isVerified = await db.get(`/user/verify/${hashedEmail}`)
19
         const isVerified = await db.get(`/user/verify/${hashedEmail}`)
17
         return isVerified.hashesMatch
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
         // TODO: Move token into repsonse.headers
24
         // TODO: Move token into repsonse.headers
23
         // return response.headers ?
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
         survey: null,
62
         survey: null,
63
         invalidResponse: false,
63
         invalidResponse: false,
64
         userEmail: null,
64
         userEmail: null,
65
-        emailIsInCache: false,
65
+        emailIsRegistered: false,
66
         authenticator: {},
66
         authenticator: {},
67
     }),
67
     }),
68
     async created() {
68
     async created() {
69
         this.survey = await surveyFactory.createSurvey()
69
         this.survey = await surveyFactory.createSurvey()
70
         this.authenticator = new Authenticator()
70
         this.authenticator = new Authenticator()
71
         // TODO: Consider switch/case() depending on what tokens exist/are valid...
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
         // if (!sessionToken) {
74
         // if (!sessionToken) {
74
         //     //
75
         //     //
75
         // }
76
         // }
76
-        accessToken = this.grabCookie('siimee_access_onboarding')
77
+        // accessToken = this.grabStoredCookie('siimee_access_onboarding')
77
         // if (!accessToken) {
78
         // if (!accessToken) {
78
         //     // blow up
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
             this.userEmail = sessionData.payload.email
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
         // TODO: EVERY ROUTE WE HIT AFTER THIS HAS TO BE AUTHENTICATED
93
         // TODO: EVERY ROUTE WE HIT AFTER THIS HAS TO BE AUTHENTICATED
90
         // ACCESS TOKEN WORKS
94
         // ACCESS TOKEN WORKS
91
-        if (this.emailIsInCache) {
95
+        if (this.emailIsRegistered) {
92
             const user = await fetchUserByEmail(this.userEmail)
96
             const user = await fetchUserByEmail(this.userEmail)
93
             const userId = user.user_id
97
             const userId = user.user_id
94
             const profilesFromUserId = await fetchProfilesByUserId(userId)
98
             const profilesFromUserId = await fetchProfilesByUserId(userId)
97
                 profileId = profilesFromUserId[0].profile_id
101
                 profileId = profilesFromUserId[0].profile_id
98
                 this.currentProfileId = profileId
102
                 this.currentProfileId = profileId
99
             }
103
             }
104
+            // if (!profileId) {
105
+            // throw new Error
106
+            // }
100
             const profile = await fetchProfileByProfileId(profileId)
107
             const profile = await fetchProfileByProfileId(profileId)
101
             profile.responses.forEach(response => {
108
             profile.responses.forEach(response => {
102
                 this.responses.push({
109
                 this.responses.push({
117
         async goToStep(num) {
124
         async goToStep(num) {
118
             this.currentStep = num
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
             const cookies = document.cookie
128
             const cookies = document.cookie
124
                 .split('; ')
129
                 .split('; ')
125
                 .reduce((prev, current) => {
130
                 .reduce((prev, current) => {

+ 3
- 5
frontend/src/views/VerifyView.vue Прегледај датотеку

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

Loading…
Откажи
Сачувај