Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add auth store #119

Merged
merged 8 commits into from
May 4, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions adapters/auth/auth.transformer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { type User } from '~/interfaces/User'
import { type SelfInfo } from './auth.type'

export const transformSelfInfoFromApi = (userInfo: any): { info: SelfInfo, user: User } => {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

userInfo: any ???

Copy link
Contributor Author

@pallabez pallabez May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are getting this from API, I don't think we can know the type of userInfo here.

Let me know, if I'm not getting it right

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add types for now once api is integrated you shall be able to fixes if some types are breaking

const info = {
userId: userInfo?.id,
roles: {
archived: userInfo?.roles?.archived,
member: userInfo?.roles?.member
},
status: userInfo?.status,
incompleteUserDetails: userInfo?.incompleteUserDetails
}

const user = {
id: userInfo?.id,
username: userInfo?.username,
firstName: userInfo?.first_name,
lastName: userInfo?.last_name,
githubId: userInfo?.github_id,
githubDisplayName: userInfo?.github_display_name,
avatarUrl: userInfo?.picture?.url
}

return {
info,
user
}
}
9 changes: 9 additions & 0 deletions adapters/auth/auth.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface SelfInfo {
userId: string
roles: {
member: boolean
archived: boolean
}
status: string
incompleteUserDetails: boolean
}
42 changes: 42 additions & 0 deletions adapters/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import axios, { isAxiosError } from 'axios'
import { transformSelfInfoFromApi } from './auth.transformer'
import { type ApiResponse } from '~/interfaces/ApiResponse'
import { type User } from '~/interfaces/User'
import { type SelfInfo } from './auth.type'
import {
type ErrorApiForbidden,
type ErrorApiUnauthorized,
type ErrorApiUnavailable,
type ErrorApiNotFound,
type ErrorApiBase
} from '~/interfaces/ErrorApi'

type GetSelfResponse = ApiResponse<
{
user: User
info: SelfInfo
},
ErrorApiForbidden | ErrorApiUnauthorized | ErrorApiUnavailable | ErrorApiNotFound | ErrorApiBase
>

export const getSelf = async (): Promise<GetSelfResponse> => {
const response: GetSelfResponse = await axios
.get('https://api.realdevsquad.com/users/self/', { withCredentials: true })
.then(res => ({ data: transformSelfInfoFromApi(res.data) }))
.catch((error) => {
if (isAxiosError(error)) {
if (error.response != null) {
const responseData = error.response.data
return {
error: {
status: responseData.statusCode,
error: responseData.error,
message: responseData.message
}
}
}
}
throw error // or Log here
})
return response
}
4 changes: 4 additions & 0 deletions interfaces/ApiResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface ApiResponse<SuccessResponse, ErrorResponse> {
data?: SuccessResponse
error?: ErrorResponse
}
18 changes: 18 additions & 0 deletions interfaces/AuthState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { type User } from '~/interfaces/User'
import { type ErrorApiBase } from '~/interfaces/ErrorApi'

export type AuthState =
| {
kind: 'UNAUTHENTICATED'
isLoading: boolean
error?: ErrorApiBase
}
| {
kind: 'AUTHENTICATED'
isLoading: false
roles: {
archived?: boolean
member?: boolean
}
user: User
}
29 changes: 29 additions & 0 deletions interfaces/ErrorApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
export interface ErrorApiNotFound {
status: 404
error: 'Not Found'
message: string
}

export interface ErrorApiUnauthorized {
status: 401
error: 'Unauthorized'
message: string
}

export interface ErrorApiForbidden {
status: 403
error: 'Forbidden'
message: string
}

export interface ErrorApiUnavailable {
status: 503
error: 'Service Unavailable'
message: string
}

export interface ErrorApiBase {
status: number
error: string
message: string
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"eslint-plugin-n": "^15.0.0",
"eslint-plugin-promise": "^6.0.0",
"eslint-plugin-vue": "^9.10.0",
"local-ssl-proxy": "^2.0.5",
"nuxt": "^3.4.2",
"typescript": "5.0.4",
"vitest": "^0.30.1",
Expand Down
7 changes: 5 additions & 2 deletions pages/test.vue
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
<template>
<div>
<button @click="consoleGoals">Display Goals</button>
<div>{{ JSON.stringify(authStore.$state) }}</div>
</div>
</template>

<script lang="ts" setup>
import { useAuthStore } from '~/store/auth'
import { useGoalsStore } from '../store/goals'
import { useUsersStore } from '../store/users'
import { onMounted } from 'vue'

const goalStore = useGoalsStore()
const userStore = useUsersStore()
const authStore = useAuthStore()

onMounted(() => {
goalStore.fetchGoals()
userStore.fetchUsers()
authStore.fetchSelf()
})

function consoleGoals () {
console.log(goalStore.getGoalDetailList())
console.log('page', authStore.getAuthState)
}

</script>

<script lang="ts">
Expand Down
93 changes: 93 additions & 0 deletions store/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { defineStore } from 'pinia'
import * as authAdapter from '~/adapters/auth'
import { type AuthState } from '~/interfaces/AuthState'
import { type ErrorApiBase } from '~/interfaces/ErrorApi'
import { userRepo } from '~/models/User'

type AuthStoreState =
| {
kind: 'UNAUTHENTICATED'
isLoading: boolean
error: null
authInfo: null
}
| {
kind: 'ERRORED'
isLoading: false
error: ErrorApiBase
authInfo: null
}
| {
kind: 'AUTHENTICATED'
isLoading: false
error: null
authInfo: {
userId: string
status: string
roles: {
archived?: boolean
member?: boolean
}
}
}

export const useAuthStore = defineStore({
id: 'auth-store',
state: (): AuthStoreState => ({
kind: 'UNAUTHENTICATED',
isLoading: false,
error: null,
authInfo: null
}),
actions: {
async fetchSelf () {
if (this.isLoading) return

this.isLoading = true

const { data, error } = await authAdapter.getSelf()
if (error != null) {
this.$patch({
kind: 'ERRORED',
error,
isLoading: false,
authInfo: null
})
} else if (data != null) {
this.$patch({
kind: 'AUTHENTICATED',
authInfo: data.info,
isLoading: false,
error: null
})
userRepo.save(data.user)
}
}
},
getters: {
getAuthState (state): AuthState {
if (state.kind === 'UNAUTHENTICATED') {
return {
kind: 'UNAUTHENTICATED',
isLoading: state.isLoading
}
} else if (state.kind === 'ERRORED') {
return {
kind: 'UNAUTHENTICATED',
isLoading: false,
error: state.error
}
} else {
const user = userRepo.find(state.authInfo.userId)
if (user == null) throw new Error('User not found in repository')

return {
kind: 'AUTHENTICATED',
isLoading: false,
roles: state.authInfo.roles,
user
}
}
}
}
})
19 changes: 19 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,11 @@ ajv@^6.10.0, ajv@^6.12.4:
json-schema-traverse "^0.4.1"
uri-js "^4.2.2"

ansi-colors@^4.1.3:
version "4.1.3"
resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.3.tgz#37611340eb2243e70cc604cad35d63270d48781b"
integrity sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==

ansi-escapes@^4.3.0:
version "4.3.2"
resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e"
Expand Down Expand Up @@ -1788,6 +1793,11 @@ combined-stream@^1.0.8:
dependencies:
delayed-stream "~1.0.0"

commander@^10.0.0:
version "10.0.1"
resolved "https://registry.yarnpkg.com/commander/-/commander-10.0.1.tgz#881ee46b4f77d1c1dccc5823433aa39b022cbe06"
integrity sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==

commander@^2.20.0:
version "2.20.3"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33"
Expand Down Expand Up @@ -3641,6 +3651,15 @@ local-pkg@^0.4.3:
resolved "https://registry.yarnpkg.com/local-pkg/-/local-pkg-0.4.3.tgz#0ff361ab3ae7f1c19113d9bb97b98b905dbc4963"
integrity sha512-SFppqq5p42fe2qcZQqqEOiVRXl+WCP1MdT6k7BDEW1j++sp5fIY+/fdRQitvKgB5BrBcmrs5m/L0v2FrU5MY1g==

local-ssl-proxy@^2.0.5:
version "2.0.5"
resolved "https://registry.yarnpkg.com/local-ssl-proxy/-/local-ssl-proxy-2.0.5.tgz#792ad902a61c36a650f8c45b790e19765fd48a11"
integrity sha512-/oWxo8IX12HTVNWza+Ui1HNz7TfrNsVyD0+ZSyf5UZocJXdR70wfNb/xHgNfEPFyjgbsaRFdqFdfxg2d11aANQ==
dependencies:
ansi-colors "^4.1.3"
commander "^10.0.0"
http-proxy "^1.18.1"

locate-path@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0"
Expand Down