import { jwtDecode } from 'jwt-decode' import UserSourceService from '@baserow/modules/core/services/userSource' import { getRefreshTokenSessionId, getToken, isRefreshTokenAlreadyRevoked, setToken, unsetToken, userSourceCookieTokenName, } from '@baserow/modules/core/utils/auth' const getUserSourceCookie = (getters) => { const authConfig = getters.getCurrentUserSourceAuthConfig return { name: authConfig?.cookieName || userSourceCookieTokenName, options: { path: '/', ...authConfig?.cookieOptions, }, } } export const state = () => ({ // The client handler needs the current application to select its user source token. currentApplication: null, currentUserSourceAuthConfig: null, }) const checkApplication = (application) => { if (!application.userSourceUser) { application.userSourceUser = { refreshing: false, token: null, refreshToken: null, tokenUpdatedAt: 0, tokenPayload: null, user: { email: '', id: 0, username: '', role: '', user_source_uid: '' }, authenticated: false, savedInCookie: false, } } } export const mutations = { SET_TOKENS(state, { application, access, refresh, tokenUpdatedAt }) { checkApplication(application) application.userSourceUser = { ...application.userSourceUser, token: access, refreshToken: refresh, tokenUpdatedAt: tokenUpdatedAt || new Date().getTime(), tokenPayload: jwtDecode(access), } }, SET_USER_DATA(state, { application, data }) { checkApplication(application) application.userSourceUser = { ...application.userSourceUser, user: { ...data }, } }, CLEAR_USER_DATA(state, { application }) { checkApplication(application) application.userSourceUser = { ...application.userSourceUser, user: {}, } }, LOGOFF(state, { application }) { checkApplication(application) application.userSourceUser = { ...application.userSourceUser, refreshing: false, token: null, refreshToken: null, tokenUpdatedAt: 0, tokenPayload: null, user: {}, authenticated: false, savedInCookie: false, } }, SET_AUTHENTICATED(state, { application, authenticated }) { checkApplication(application) application.userSourceUser.authenticated = authenticated }, SET_SAVED_IN_COOKIE(state, { application, savedInCookie }) { checkApplication(application) application.userSourceUser.savedInCookie = savedInCookie }, SET_REFRESHING(state, { application, refreshing }) { checkApplication(application) application.userSourceUser.refreshing = refreshing }, SET_CURRENT_APPLICATION(state, { application, userSourceAuthConfig = null }) { state.currentApplication = application state.currentUserSourceAuthConfig = userSourceAuthConfig }, } export const actions = { setCurrentApplication( { commit }, { application, userSourceAuthConfig = null } ) { commit('SET_CURRENT_APPLICATION', { application, userSourceAuthConfig }) }, async forceAuthenticate({ dispatch }, { application, userSource, user }) { const { $registry, $i18n, $client, $config } = this const { data: { access_token: access, refresh_token: refresh }, } = await UserSourceService($client).forceAuthenticate( userSource.id, user.id ) dispatch('login', { application, userSource, access, refresh, setCookie: false, }) }, async authenticate( { dispatch, getters }, { application, userSource, credentials, setCookie } ) { const { $registry, $i18n, $client, $config } = this const { data: { access_token: access, refresh_token: refresh }, } = await UserSourceService($client).authenticate( userSource.id, credentials, getters.getCurrentUserSourceAuthConfig?.authenticationUrls?.[ userSource.id ] ) dispatch('login', { application, userSource, access, refresh, setCookie, }) }, async login( { commit, getters }, { application, access, refresh, tokenUpdatedAt, setCookie = true } ) { const nuxtApp = this.app commit('SET_TOKENS', { application, access, refresh, tokenUpdatedAt }) const tokenPayload = jwtDecode(access) commit('SET_USER_DATA', { application, data: { id: tokenPayload.user_id, username: tokenPayload.username, email: tokenPayload.email, user_source_uid: tokenPayload.user_source_uid, role: tokenPayload.role, }, }) commit('SET_AUTHENTICATED', { application, authenticated: true }) let savedInCookie = false if (setCookie) { const userSourceCookie = getUserSourceCookie(getters) // Set the token for next page load await setToken( nuxtApp, getters.refreshToken(application), userSourceCookie.name, { sameSite: 'Lax', cookieUrl: nuxtApp.$config.public.publicWebFrontendUrl, ...userSourceCookie.options, } ) // The browser can refuse the cookie, when the application is embedded in // an iframe on another site for example, so it's read back to know whether // it holds this login. const cookieToken = await getToken(nuxtApp, userSourceCookie.name, { path: userSourceCookie.options.path, }) const sessionId = getRefreshTokenSessionId(refresh) savedInCookie = !!sessionId && sessionId === getRefreshTokenSessionId(cookieToken) } commit('SET_SAVED_IN_COOKIE', { application, savedInCookie }) }, /** * Logs off the user by removing the token as a cookie and clearing the user * data. */ async logoff({ commit, getters }, { application, invalidateToken = true }) { const userSourceCookie = getUserSourceCookie(getters) await unsetToken(this.app, userSourceCookie.name, { path: userSourceCookie.options.path, }) if (!getters.isAuthenticated(application)) { return } const refreshToken = getters.refreshToken(application) commit('LOGOFF', { application }) if (refreshToken && invalidateToken) { try { await UserSourceService(this.$client).blacklistToken(refreshToken) } catch (e) { if (!isRefreshTokenAlreadyRevoked(e)) { throw e } } } }, /** * Forgets the login of this tab without touching the cookie or the server, * because the login has already ended. */ forgetLogin({ commit }, { application }) { commit('LOGOFF', { application }) }, /** * The tabs of a browser share the refresh token cookie, but each one keeps its * own copy of the tokens. When another tab logs out, the session and its tokens * are revoked and the cookie is removed. When another tab logs in again, the * cookie holds another session. In both cases the login of this tab has ended * and it's forgotten. * * A login that was never saved in the cookie only lives in this tab, so the * cookie tells nothing about it and it's kept. * * @returns {Promise} Whether the login has been forgotten. */ async forgetLoginEndedElsewhere({ dispatch, getters }, { application }) { if ( !getters.isAuthenticated(application) || !application.userSourceUser.savedInCookie ) { return false } const userSourceCookie = getUserSourceCookie(getters) const cookieToken = await getToken(this.app, userSourceCookie.name, { path: userSourceCookie.options.path, }) const sessionId = getRefreshTokenSessionId( getters.refreshToken(application) ) if (sessionId && sessionId === getRefreshTokenSessionId(cookieToken)) { return false } await dispatch('forgetLogin', { application }) return true }, /** * Refresh the existing token. If successful commit the new token and start a * new refresh timeout. If the refresh token is refused, because the user logged * out in another tab for example, the login is forgotten. */ async refreshAuth( { getters, dispatch, commit }, { application, token = null } ) { const refreshToken = token || getters.refreshToken(application) if (!refreshToken) { throw new Error('Invalid refresh token') } commit('SET_REFRESHING', { application, refreshing: true }) try { const tokenUpdatedAt = new Date().getTime() const { data: { refresh_token: refresh = null, access_token: access }, } = await UserSourceService(this.$client).refreshAuth( refreshToken, getters.getCurrentUserSourceAuthConfig?.refreshUrl ) // if ROTATE_REFRESH_TOKEN=False in the backend the response will not contain // a new refresh token. In that case, we keep the one we just used. dispatch('login', { application, refresh: refresh || refreshToken, access, tokenUpdatedAt, }) } catch (error) { if (error.response?.status === 401) { await dispatch('forgetLogin', { application }) } throw error } finally { commit('SET_REFRESHING', { application, refreshing: false }) } }, } export const getters = { getCurrentApplication: (state) => { return state.currentApplication }, getCurrentUserSourceAuthConfig: (state) => { return state.currentUserSourceAuthConfig }, isAuthenticated: (state) => (application) => { return !!application?.userSourceUser?.authenticated }, isRefreshing: (state) => (application) => { return application.userSourceUser.refreshing }, accessToken: (state) => (application) => { return application.userSourceUser.token }, refreshToken: (state) => (application) => { if (!Object.prototype.hasOwnProperty.call(application, 'userSourceUser')) { return null } return application.userSourceUser.refreshToken }, role(state) { if (!state.authenticated) { return '' } return state.user.role }, getUser: (state, getters) => (application) => { if (getters.isAuthenticated(application)) { return application.userSourceUser.user } return { email: '', id: 0, username: '', role: '', user_source_uid: '' } }, shouldRefreshToken: (state, getters) => (application) => { // the user must be authenticated to refresh the token if (!getters.isAuthenticated(application)) { return false } const data = application.userSourceUser.tokenPayload const now = new Date().getTime() const tokenLifespan = (data.exp - data.iat) * 1000 return ( (now - application.userSourceUser.tokenUpdatedAt) / tokenLifespan > 0.8 ) }, } export default { namespaced: true, state, getters, actions, mutations, }