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

:construction: Achieved basic login upon verification from email

brian_dev_survey_complete
tomit4 2 лет назад
Родитель
Сommit
73d8d80fb5

+ 0
- 8
backend/lib/routes/user/validatesession.js Просмотреть файл

40
                 )
40
                 )
41
                 // TODO: handle user with multiple profiles...
41
                 // TODO: handle user with multiple profiles...
42
                 const profileId = profiles[0].profile_id
42
                 const profileId = profiles[0].profile_id
43
-                const responses = []
44
-                profiles[0].responses.forEach(response => {
45
-                    responses.push({
46
-                        response_key_id: response.response_key_id,
47
-                        val: response.val,
48
-                    })
49
-                })
50
                 return {
43
                 return {
51
                     ok: true,
44
                     ok: true,
52
                     handler: pluginConfig.handlerType,
45
                     handler: pluginConfig.handlerType,
53
                     data: {
46
                     data: {
54
                         ...validatedSessionToken,
47
                         ...validatedSessionToken,
55
                         profileId: profileId,
48
                         profileId: profileId,
56
-                        responses: responses,
57
                     },
49
                     },
58
                 }
50
                 }
59
             } catch (err) {
51
             } catch (err) {

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

9
      * @param {number} profileId
9
      * @param {number} profileId
10
      * @returns {array} MatchQueue
10
      * @returns {array} MatchQueue
11
      */
11
      */
12
-    async getQueue(profileId, limit, offset=0) {
12
+    async getQueue(profileId, limit, offset = 0) {
13
         const { MatchQueue } = this.server.models()
13
         const { MatchQueue } = this.server.models()
14
-        if(typeof limit==='undefined') {
14
+        if (typeof limit === 'undefined') {
15
             return await MatchQueue.query()
15
             return await MatchQueue.query()
16
                 .where('profile_id', profileId)
16
                 .where('profile_id', profileId)
17
                 .where('is_deleted', 0)
17
                 .where('is_deleted', 0)

+ 0
- 2
frontend/src/App.vue Просмотреть файл

58
             if (currentProfile.isLoggedIn) {
58
             if (currentProfile.isLoggedIn) {
59
                 currentProfile.logout()
59
                 currentProfile.logout()
60
             }
60
             }
61
-            // TODO: grab JWT from cookie and add JWT as third argument here
62
-            // (see views/OnboardingView.vue)
63
             await currentProfile.login(profileId, this.$waveui.notify)
61
             await currentProfile.login(profileId, this.$waveui.notify)
64
             console.log('---')
62
             console.log('---')
65
 
63
 

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

5
 </template>
5
 </template>
6
 
6
 
7
 <script>
7
 <script>
8
-import { Authenticator } from '../../services/auth.service.js'
8
+import { authenticator } from '../../services/auth.service.js'
9
 import { createProfileForUserId } from '../../services/profile.service'
9
 import { createProfileForUserId } from '../../services/profile.service'
10
 import { signupUser } from '../../services/user.service.js'
10
 import { signupUser } from '../../services/user.service.js'
11
 
11
 
32
         },
32
         },
33
     },
33
     },
34
     emits: ['update-answers'],
34
     emits: ['update-answers'],
35
-    data: () => ({
36
-        authenticator: {},
37
-    }),
38
     async created() {
35
     async created() {
39
         // Establishes New User And Sends Auth Email
36
         // Establishes New User And Sends Auth Email
40
-        this.authenticator = new Authenticator()
41
         try {
37
         try {
42
             this.doesUserHaveMinResponses(this.responses)
38
             this.doesUserHaveMinResponses(this.responses)
43
             const userPass = this.responses.find(
39
             const userPass = this.responses.find(
52
                 ...this.answered,
48
                 ...this.answered,
53
             })
49
             })
54
             console.log('accessToken :=>', accessToken)
50
             console.log('accessToken :=>', accessToken)
55
-            const sessionInfo = await this.authenticator.sendAuthEmail({
51
+            const sessionInfo = await authenticator.sendAuthEmail({
56
                 ...this.answered,
52
                 ...this.answered,
57
                 accessToken: accessToken,
53
                 accessToken: accessToken,
58
             })
54
             })
71
                 )
67
                 )
72
         },
68
         },
73
         async getAccessToken(payload) {
69
         async getAccessToken(payload) {
74
-            return await this.authenticator.getAccessToken({
70
+            return await authenticator.getAccessToken({
75
                 payload,
71
                 payload,
76
             })
72
             })
77
         },
73
         },

+ 43
- 3
frontend/src/router/guards.js Просмотреть файл

1
-import { currentProfile } from '../services'
2
-
1
+import { currentProfile, authenticator } from '../services'
2
+import WaveUI from '../../node_modules/wave-ui/src/wave-ui/core'
3
 const DEV_MODE = import.meta.env.VITE_DEV == 'true'
3
 const DEV_MODE = import.meta.env.VITE_DEV == 'true'
4
 
4
 
5
 async function log(to) {
5
 async function log(to) {
13
     }
13
     }
14
 }
14
 }
15
 
15
 
16
-const checkLoginStatus = (destination, nextCb) => {
16
+const grabStoredCookie = cookieKey => {
17
+    const cookies = document.cookie.split('; ').reduce((prev, current) => {
18
+        const [name, ...value] = current.split('=')
19
+        prev[name] = value.join('=')
20
+        return prev
21
+    }, {})
22
+    const cookieVal = cookieKey in cookies ? cookies[`${cookieKey}`] : undefined
23
+    return cookieVal
24
+}
25
+
26
+const verifySession = async () => {
27
+    const hashedAccessToken = grabStoredCookie('siimee_access')
28
+    if (!hashedAccessToken)
29
+        return console.warn('WARNING :=> accessToken is not defined')
30
+    const validatedToken = await authenticator.validateSession(
31
+        hashedAccessToken,
32
+    )
33
+    if (validatedToken.error) {
34
+        console.error('ERROR :=>', validatedToken.error)
35
+    } else {
36
+        return validatedToken
37
+    }
38
+}
39
+
40
+const loginIfToken = async () => {
41
+    const sessionData = await verifySession()
42
+    if (
43
+        sessionData?.profileId &&
44
+        sessionData?.accessToken &&
45
+        !currentProfile.isLoggedIn
46
+    ) {
47
+        await currentProfile.login(
48
+            sessionData.profileId,
49
+            WaveUI.notify,
50
+            sessionData.accessToken,
51
+        )
52
+    }
53
+}
54
+
55
+const checkLoginStatus = async (destination, nextCb) => {
56
+    await loginIfToken()
17
     log(destination)
57
     log(destination)
18
     if (DEV_MODE) {
58
     if (DEV_MODE) {
19
         nextCb()
59
         nextCb()

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

17
         return await db.post('/user/validatesession', hashedAccessToken, true)
17
         return await db.post('/user/validatesession', hashedAccessToken, true)
18
     }
18
     }
19
 }
19
 }
20
+const authenticator = new Authenticator()
20
 
21
 
21
-export { Authenticator }
22
+export { authenticator, Authenticator }

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

39
 import stepViews from '@/components/onboarding'
39
 import stepViews from '@/components/onboarding'
40
 import SurveyCompleteView from './SurveyCompleteView.vue'
40
 import SurveyCompleteView from './SurveyCompleteView.vue'
41
 let hashedAccessToken = null
41
 let hashedAccessToken = null
42
-// TODO: remove once currentProfile from services is fully enforced
43
-let currentProfileId = null
44
 
42
 
45
 export default {
43
 export default {
46
     name: 'OnboardingView',
44
     name: 'OnboardingView',
61
         this.survey = await surveyFactory.createSurvey()
59
         this.survey = await surveyFactory.createSurvey()
62
         this.authenticator = new Authenticator()
60
         this.authenticator = new Authenticator()
63
         hashedAccessToken = this.grabStoredCookie('siimee_access')
61
         hashedAccessToken = this.grabStoredCookie('siimee_access')
62
+        console.log('currentProfile.isLoggedIn :=>', currentProfile.isLoggedIn)
64
         try {
63
         try {
65
             const sessionData = await this.verifySession(hashedAccessToken)
64
             const sessionData = await this.verifySession(hashedAccessToken)
66
-            currentProfileId = sessionData.profileId
67
             await currentProfile.login(
65
             await currentProfile.login(
68
-                currentProfileId,
66
+                sessionData.profileId,
69
                 this.$waveui.notify,
67
                 this.$waveui.notify,
70
                 sessionData.accessToken,
68
                 sessionData.accessToken,
71
             )
69
             )
72
-            // TODO: responses can now be gotten from currentProfile.responses
73
-            // TODO: assign token to currentProfile object?
74
-            console.log('currentProfile :=>', currentProfile)
75
-            // TODO: create a boolean toggle on currentProfile that determines
76
-            // whether user has returned to survey from HomeView?
77
-            this.$router.push('/')
78
-
79
-            this.responses = sessionData.responses
70
+            this.responses = this.formatResponses(
71
+                currentProfile._profile.responses,
72
+            )
80
             this.currentStep = this.responses.length + 3
73
             this.currentStep = this.responses.length + 3
81
             this.goToStep(this.currentStep)
74
             this.goToStep(this.currentStep)
82
         } catch (err) {
75
         } catch (err) {
115
                 return validatedToken
108
                 return validatedToken
116
             }
109
             }
117
         },
110
         },
111
+        formatResponses(responses) {
112
+            return responses.map(response => {
113
+                return {
114
+                    response_key_id: response.response_key_id,
115
+                    val: response.val,
116
+                }
117
+            })
118
+        },
118
         async updateAnswers(payload) {
119
         async updateAnswers(payload) {
119
             if (payload) {
120
             if (payload) {
120
                 const k = payload.question.survey_stage
121
                 const k = payload.question.survey_stage
133
                 this.responses.push(response)
134
                 this.responses.push(response)
134
                 if (k === 'aspects') return
135
                 if (k === 'aspects') return
135
             }
136
             }
136
-            // NOTE: If user has finished minimum profile creation,
137
-            // Adds survey answers to responses table and verifies tokens on each step
138
-            // TODO: currentProfileId can now be gotten from currentProfile.responses
139
-            if (currentProfileId) {
137
+            if (currentProfile._profile?.profile_id) {
140
                 await surveyFactory.addNewSurveyAnswer(
138
                 await surveyFactory.addNewSurveyAnswer(
141
                     this.responses[this.responses.length - 1],
139
                     this.responses[this.responses.length - 1],
142
-                    currentProfileId,
140
+                    currentProfile._profile.profile_id,
143
                 )
141
                 )
144
                 try {
142
                 try {
145
                     await this.verifySession(hashedAccessToken)
143
                     await this.verifySession(hashedAccessToken)

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

5
 </template>
5
 </template>
6
 
6
 
7
 <script>
7
 <script>
8
-import { Authenticator } from '../services/auth.service.js'
8
+import { currentProfile, authenticator } from '../services'
9
 let hash = null
9
 let hash = null
10
 let hashedAccessToken = null
10
 let hashedAccessToken = null
11
 export default {
11
 export default {
12
     name: 'VerifyView',
12
     name: 'VerifyView',
13
-    data: () => ({
14
-        authenticator: {},
15
-    }),
16
     async created() {
13
     async created() {
17
-        this.authenticator = new Authenticator()
18
         hash = this.$route.params.hashedToken
14
         hash = this.$route.params.hashedToken
19
         hashedAccessToken = this.grabCookie('siimee_access')
15
         hashedAccessToken = this.grabCookie('siimee_access')
20
         try {
16
         try {
21
             this.isHashInUrl(hash)
17
             this.isHashInUrl(hash)
22
             await this.doesAccessTokenExist(hashedAccessToken)
18
             await this.doesAccessTokenExist(hashedAccessToken)
23
             await this.verifyActiveSession(hash)
19
             await this.verifyActiveSession(hash)
24
-            await this.isSessionTokenValid(hash)
20
+            const sessionData = await this.isSessionTokenValid(hash)
21
+            await currentProfile.login(
22
+                sessionData.profileId,
23
+                this.$waveui.notify,
24
+                sessionData.accessToken,
25
+            )
25
         } catch (err) {
26
         } catch (err) {
26
             console.error(err)
27
             console.error(err)
27
         }
28
         }
28
-        // TODO: push to Home instead
29
-        this.$router.push('/onboarding')
29
+        this.$router.push('/')
30
     },
30
     },
31
     methods: {
31
     methods: {
32
         grabCookie(cookieKey) {
32
         grabCookie(cookieKey) {
49
                 throw new Error('accessToken not in cookie store!')
49
                 throw new Error('accessToken not in cookie store!')
50
         },
50
         },
51
         async verifyActiveSession(hashedToken) {
51
         async verifyActiveSession(hashedToken) {
52
-            const sessionData = await this.authenticator.verifyAuthSession(
52
+            const sessionData = await authenticator.verifyAuthSession(
53
                 hashedToken,
53
                 hashedToken,
54
             )
54
             )
55
             if (!sessionData.hashesMatch)
55
             if (!sessionData.hashesMatch)
56
                 throw new Error('Hash is not in activeSessions!')
56
                 throw new Error('Hash is not in activeSessions!')
57
         },
57
         },
58
         async isSessionTokenValid(hash) {
58
         async isSessionTokenValid(hash) {
59
-            const sessionTokenIsValid =
60
-                await this.authenticator.validateSession(hash)
59
+            const sessionTokenIsValid = await authenticator.validateSession(
60
+                hash,
61
+            )
61
             if (sessionTokenIsValid.error) {
62
             if (sessionTokenIsValid.error) {
62
                 throw new Error(sessionTokenIsValid.error)
63
                 throw new Error(sessionTokenIsValid.error)
63
-            }
64
+            } else return sessionTokenIsValid
64
         },
65
         },
65
     },
66
     },
66
 }
67
 }

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