feat: auth store with composition api #2602

Merged
konrad merged 1 commits from dpschen/frontend:feature/feat-pinia-composition-auth-store into main 2022-10-31 20:25:37 +00:00
1 changed files with 344 additions and 309 deletions

View File

@ -1,3 +1,4 @@
import {computed, readonly, ref} from 'vue'
import {defineStore, acceptHMRUpdate} from 'pinia' import {defineStore, acceptHMRUpdate} from 'pinia'
import {HTTPFactory, AuthenticatedHTTPFactory} from '@/http-common' import {HTTPFactory, AuthenticatedHTTPFactory} from '@/http-common'
@ -16,352 +17,386 @@ import {useConfigStore} from '@/stores/config'
import UserSettingsModel from '@/models/userSettings' import UserSettingsModel from '@/models/userSettings'
import {MILLISECONDS_A_SECOND} from '@/constants/date' import {MILLISECONDS_A_SECOND} from '@/constants/date'
export interface AuthState { function redirectToProviderIfNothingElseIsEnabled() {
authenticated: boolean, const {auth} = useConfigStore()
isLinkShareAuth: boolean, if (
info: IUser | null, auth.local.enabled === false &&
needsTotpPasscode: boolean, auth.openidConnect.enabled &&
avatarUrl: string, auth.openidConnect.providers?.length === 1 &&
lastUserInfoRefresh: Date | null, window.location.pathname.startsWith('/login') // Kinda hacky, but prevents an endless loop.
settings: IUserSettings, ) {
isLoading: boolean, redirectToProvider(auth.openidConnect.providers[0], auth.openidConnect.redirectUrl)
isLoadingGeneralSettings: boolean }
} }
export const useAuthStore = defineStore('auth', { export const useAuthStore = defineStore('auth', () => {
state: () : AuthState => ({ const authenticated = ref(false)
authenticated: false, const isLinkShareAuth = ref(false)
isLinkShareAuth: false, const needsTotpPasscode = ref(false)
needsTotpPasscode: false,
const info = ref<IUser | null>(null)
info: null, const avatarUrl = ref('')
avatarUrl: '', const settings = ref<IUserSettings>(new UserSettingsModel())
settings: new UserSettingsModel(),
const lastUserInfoRefresh = ref<Date | null>(null)
lastUserInfoRefresh: null, const isLoading = ref(false)
isLoading: false, const isLoadingGeneralSettings = ref(false)
isLoadingGeneralSettings: false,
}),
getters: {
authUser(state) {
return state.authenticated && (
state.info &&
state.info.type === AUTH_TYPES.USER
)
},
authLinkShare(state) {
return state.authenticated && (
state.info &&
state.info.type === AUTH_TYPES.LINK_SHARE
)
},
userDisplayName(state) {
return state.info ? getDisplayName(state.info) : undefined
},
},
actions: {
setIsLoading(isLoading: boolean) {
this.isLoading = isLoading
},
setIsLoadingGeneralSettings(isLoading: boolean) { const authUser = computed(() => {
this.isLoadingGeneralSettings = isLoading return authenticated.value && (
}, info.value &&
info.value.type === AUTH_TYPES.USER
)
})
setUser(info: IUser | null) { const authLinkShare = computed(() => {
this.info = info return authenticated.value && (
if (info !== null) { info.value &&
this.reloadAvatar() info.value.type === AUTH_TYPES.LINK_SHARE
)
})
if (info.settings) { const userDisplayName = computed(() => info.value ? getDisplayName(info.value) : undefined)
this.settings = new UserSettingsModel(info.settings)
}
this.isLinkShareAuth = info.id < 0
}
},
setUserSettings(settings: IUserSettings) {
this.settings = new UserSettingsModel(settings)
this.info = new UserModel({
...this.info !== null ? this.info : {},
name: settings.name,
})
},
setAuthenticated(authenticated: boolean) {
this.authenticated = authenticated
},
setIsLinkShareAuth(isLinkShareAuth: boolean) {
this.isLinkShareAuth = isLinkShareAuth
},
setNeedsTotpPasscode(needsTotpPasscode: boolean) {
this.needsTotpPasscode = needsTotpPasscode
},
reloadAvatar() {
if (!this.info) return
this.avatarUrl = `${getAvatarUrl(this.info)}&=${+new Date()}`
},
updateLastUserRefresh() {
this.lastUserInfoRefresh = new Date()
},
// Logs a user in with a set of credentials. function setIsLoading(newIsLoading: boolean) {
async login(credentials) { isLoading.value = newIsLoading
const HTTP = HTTPFactory() }
this.setIsLoading(true)
// Delete an eventually preexisting old token function setIsLoadingGeneralSettings(isLoading: boolean) {
removeToken() isLoadingGeneralSettings.value = isLoading
}
try { function setUser(newUser: IUser | null) {
const response = await HTTP.post('login', objectToSnakeCase(credentials)) info.value = newUser
// Save the token to local storage for later use if (newUser !== null) {
saveToken(response.data.token, true) reloadAvatar()
// Tell others the user is autheticated if (newUser.settings) {
await this.checkAuth() settings.value = new UserSettingsModel(newUser.settings)
} catch (e) {
if (
e.response &&
e.response.data.code === 1017 &&
!credentials.totpPasscode
) {
this.setNeedsTotpPasscode(true)
}
throw e
} finally {
this.setIsLoading(false)
}
},
/**
* Registers a new user and logs them in.
* Not sure if this is the right place to put the logic in, maybe a seperate js component would be better suited.
*/
async register(credentials) {
const HTTP = HTTPFactory()
this.setIsLoading(true)
try {
await HTTP.post('register', credentials)
return this.login(credentials)
} catch (e) {
if (e.response?.data?.message) {
throw e.response.data
}
throw e
} finally {
this.setIsLoading(false)
}
},
async openIdAuth({provider, code}) {
const HTTP = HTTPFactory()
this.setIsLoading(true)
const data = {
code: code,
} }
// Delete an eventually preexisting old token isLinkShareAuth.value = newUser.id < 0
removeToken() }
try { }
const response = await HTTP.post(`/auth/openid/${provider}/callback`, data)
// Save the token to local storage for later use
saveToken(response.data.token, true)
// Tell others the user is autheticated function setUserSettings(newSettings: IUserSettings) {
await this.checkAuth() settings.value = new UserSettingsModel(newSettings)
} finally { info.value = new UserModel({
this.setIsLoading(false) ...info.value !== null ? info.value : {},
} name: newSettings.name,
}, })
}
async linkShareAuth({hash, password}) { function setAuthenticated(newAuthenticated: boolean) {
const HTTP = HTTPFactory() authenticated.value = newAuthenticated
const response = await HTTP.post('/shares/' + hash + '/auth', { }
password: password,
})
saveToken(response.data.token, false)
await this.checkAuth()
return response.data
},
/** function setIsLinkShareAuth(newIsLinkShareAuth: boolean) {
* Populates user information from jwt token saved in local storage in store isLinkShareAuth.value = newIsLinkShareAuth
*/ }
async checkAuth() {
const now = new Date() function setNeedsTotpPasscode(newNeedsTotpPasscode: boolean) {
const inOneMinute = new Date(new Date().setMinutes(now.getMinutes() + 1)) needsTotpPasscode.value = newNeedsTotpPasscode
// This function can be called from multiple places at the same time and shortly after one another. }
// To prevent hitting the api too frequently or race conditions, we check at most once per minute.
function reloadAvatar() {
if (!info.value) return
avatarUrl.value = `${getAvatarUrl(info.value)}&=${new Date().valueOf()}`
}
function updateLastUserRefresh() {
lastUserInfoRefresh.value = new Date()
}
// Logs a user in with a set of credentials.
async function login(credentials) {
const HTTP = HTTPFactory()
setIsLoading(true)
// Delete an eventually preexisting old token
removeToken()
try {
const response = await HTTP.post('login', objectToSnakeCase(credentials))
// Save the token to local storage for later use
saveToken(response.data.token, true)
// Tell others the user is autheticated
await checkAuth()
} catch (e) {
if ( if (
this.lastUserInfoRefresh !== null && e.response &&
this.lastUserInfoRefresh > inOneMinute e.response.data.code === 1017 &&
!credentials.totpPasscode
) { ) {
return setNeedsTotpPasscode(true)
} }
const jwt = getToken() throw e
let authenticated = false } finally {
if (jwt) { setIsLoading(false)
const base64 = jwt }
.split('.')[1] }
.replace('-', '+')
.replace('_', '/')
const info = new UserModel(JSON.parse(atob(base64)))
const ts = Math.round((new Date()).getTime() / MILLISECONDS_A_SECOND)
authenticated = info.exp >= ts
this.setUser(info)
if (authenticated) { /**
await this.refreshUserInfo() * Registers a new user and logs them in.
} * Not sure if this is the right place to put the logic in, maybe a seperate js component would be better suited.
*/
async function register(credentials) {
const HTTP = HTTPFactory()
setIsLoading(true)
try {
await HTTP.post('register', credentials)
return login(credentials)
} catch (e) {
if (e.response?.data?.message) {
throw e.response.data
} }
this.setAuthenticated(authenticated) throw e
if (!authenticated) { } finally {
this.setUser(null) setIsLoading(false)
this.redirectToProviderIfNothingElseIsEnabled() }
} }
return Promise.resolve(authenticated) async function openIdAuth({provider, code}) {
}, const HTTP = HTTPFactory()
setIsLoading(true)
const data = {
code: code,
}
// Delete an eventually preexisting old token
removeToken()
try {
const response = await HTTP.post(`/auth/openid/${provider}/callback`, data)
// Save the token to local storage for later use
saveToken(response.data.token, true)
// Tell others the user is autheticated
await checkAuth()
} finally {
setIsLoading(false)
}
}
async function linkShareAuth({hash, password}) {
const HTTP = HTTPFactory()
const response = await HTTP.post('/shares/' + hash + '/auth', {
password: password,
})
saveToken(response.data.token, false)
await checkAuth()
return response.data
}
/**
* Populates user information from jwt token saved in local storage in store
*/
async function checkAuth() {
const now = new Date()
const inOneMinute = new Date(new Date().setMinutes(now.getMinutes() + 1))
// This function can be called from multiple places at the same time and shortly after one another.
// To prevent hitting the api too frequently or race conditions, we check at most once per minute.
if (
lastUserInfoRefresh.value !== null &&
lastUserInfoRefresh.value > inOneMinute
) {
return
}
const jwt = getToken()
let isAuthenticated = false
if (jwt) {
const base64 = jwt
.split('.')[1]
.replace('-', '+')
.replace('_', '/')
const info = new UserModel(JSON.parse(atob(base64)))
const ts = Math.round((new Date()).getTime() / MILLISECONDS_A_SECOND)
isAuthenticated = info.exp >= ts
setUser(info)
if (isAuthenticated) {
await refreshUserInfo()
}
}
setAuthenticated(isAuthenticated)
if (!isAuthenticated) {
setUser(null)
redirectToProviderIfNothingElseIsEnabled()
}
return Promise.resolve(authenticated)
}
async function refreshUserInfo() {
const jwt = getToken()
if (!jwt) {
return
}
const HTTP = AuthenticatedHTTPFactory()
try {
const response = await HTTP.get('user')
const newUser = new UserModel({
...response.data,
...(info.value?.type && {type: info.value?.type}),
...(info.value?.email && {email: info.value?.email}),
...(info.value?.exp && {exp: info.value?.exp}),
})
setUser(newUser)
updateLastUserRefresh()
redirectToProviderIfNothingElseIsEnabled() {
const {auth} = useConfigStore()
if ( if (
auth.local.enabled === false && newUser.type === AUTH_TYPES.USER &&
auth.openidConnect.enabled && (
auth.openidConnect.providers?.length === 1 && typeof newUser.settings.language === 'undefined' ||
window.location.pathname.startsWith('/login') // Kinda hacky, but prevents an endless loop. newUser.settings.language === ''
)
) { ) {
redirectToProvider(auth.openidConnect.providers[0], auth.openidConnect.redirectUrl) // save current language
} await saveUserSettings({
}, settings: {
...settings.value,
async refreshUserInfo() { language: getCurrentLanguage(),
const jwt = getToken() },
if (!jwt) { showMessage: false,
return
}
const HTTP = AuthenticatedHTTPFactory()
try {
const response = await HTTP.get('user')
const info = new UserModel({
...response.data,
...(this.info?.type && {type: this.info?.type}),
...(this.info?.email && {email: this.info?.email}),
...(this.info?.exp && {exp: this.info?.exp}),
}) })
this.setUser(info)
this.updateLastUserRefresh()
if (
info.type === AUTH_TYPES.USER &&
(
typeof info.settings.language === 'undefined' ||
info.settings.language === ''
)
) {
// save current language
await this.saveUserSettings({
settings: {
...this.settings,
language: getCurrentLanguage(),
},
showMessage: false,
})
}
return info
} catch (e) {
if(e?.response?.data?.message === 'invalid or expired jwt') {
this.logout()
return
}
throw new Error('Error while refreshing user info:', {cause: e})
} }
},
/** return newUser
* Try to verify the email } catch (e) {
*/ if(e?.response?.data?.message === 'invalid or expired jwt') {
async verifyEmail(): Promise<boolean> { logout()
const emailVerifyToken = localStorage.getItem('emailConfirmToken') return
if (emailVerifyToken) {
const stopLoading = setModuleLoading(this)
try {
await HTTPFactory().post('user/confirm', {token: emailVerifyToken})
return true
} catch(e) {
throw new Error(e.response.data.message)
} finally {
localStorage.removeItem('emailConfirmToken')
stopLoading()
}
} }
return false throw new Error('Error while refreshing user info:', {cause: e})
}, }
}
async saveUserSettings({ /**
settings, * Try to verify the email
showMessage = true, */
}: { async function verifyEmail(): Promise<boolean> {
settings: IUserSettings const emailVerifyToken = localStorage.getItem('emailConfirmToken')
showMessage : boolean if (emailVerifyToken) {
}) { const stopLoading = setModuleLoading(this, setIsLoading)
const userSettingsService = new UserSettingsService()
const cancel = setModuleLoading(this, this.setIsLoadingGeneralSettings)
try { try {
saveLanguage(settings.language) await HTTPFactory().post('user/confirm', {token: emailVerifyToken})
await userSettingsService.update(settings) return true
this.setUserSettings({...settings}) } catch(e) {
if (showMessage) { throw new Error(e.response.data.message)
success({message: i18n.global.t('user.settings.general.savedSuccess')})
}
} catch (e) {
throw new Error('Error while saving user settings:', {cause: e})
} finally { } finally {
cancel() localStorage.removeItem('emailConfirmToken')
stopLoading()
} }
}, }
return false
}
/** async function saveUserSettings({
* Renews the api token and saves it to local storage settings,
*/ showMessage = true,
renewToken() { }: {
// FIXME: Timeout to avoid race conditions when authenticated as a user (=auth token in localStorage) and as a settings: IUserSettings
// link share in another tab. Without the timeout both the token renew and link share auth are executed at showMessage : boolean
// the same time and one might win over the other. }) {
setTimeout(async () => { const userSettingsService = new UserSettingsService()
if (!this.authenticated) {
return const cancel = setModuleLoading(this, setIsLoadingGeneralSettings)
try {
saveLanguage(settings.language)
await userSettingsService.update(settings)
setUserSettings({...settings})
if (showMessage) {
success({message: i18n.global.t('user.settings.general.savedSuccess')})
}
} catch (e) {
throw new Error('Error while saving user settings:', {cause: e})
} finally {
cancel()
}
}
/**
* Renews the api token and saves it to local storage
*/
function renewToken() {
// FIXME: Timeout to avoid race conditions when authenticated as a user (=auth token in localStorage) and as a
// link share in another tab. Without the timeout both the token renew and link share auth are executed at
// the same time and one might win over the other.
setTimeout(async () => {
if (!authenticated.value) {
return
}
try {
await refreshToken(!isLinkShareAuth.value)
await checkAuth()
} catch (e) {
// Don't logout on network errors as the user would then get logged out if they don't have
// internet for a short period of time - such as when the laptop is still reconnecting
if (e?.request?.status) {
await logout()
} }
}
}, 5000)
}
try { async function logout() {
await refreshToken(!this.isLinkShareAuth) removeToken()
await this.checkAuth() window.localStorage.clear() // Clear all settings and history we might have saved in local storage.
} catch (e) { await router.push({name: 'user.login'})
// Don't logout on network errors as the user would then get logged out if they don't have await checkAuth()
// internet for a short period of time - such as when the laptop is still reconnecting }
if (e?.request?.status) {
await this.logout()
}
}
}, 5000)
},
async logout() { return {
removeToken() // state
window.localStorage.clear() // Clear all settings and history we might have saved in local storage. authenticated: readonly(authenticated),
await router.push({name: 'user.login'}) isLinkShareAuth: readonly(isLinkShareAuth),
await this.checkAuth() needsTotpPasscode: readonly(needsTotpPasscode),
},
}, info: readonly(info),
avatarUrl: readonly(avatarUrl),
settings: readonly(settings),
lastUserInfoRefresh: readonly(lastUserInfoRefresh),
authUser,
authLinkShare,
userDisplayName,
isLoading: readonly(isLoading),
setIsLoading,
isLoadingGeneralSettings: readonly(isLoadingGeneralSettings),
setIsLoadingGeneralSettings,
setUser,
setUserSettings,
setAuthenticated,
setIsLinkShareAuth,
setNeedsTotpPasscode,
reloadAvatar,
updateLastUserRefresh,
login,
register,
openIdAuth,
linkShareAuth,
checkAuth,
refreshUserInfo,
verifyEmail,
saveUserSettings,
renewToken,
logout,
}
}) })
// support hot reloading // support hot reloading