From 79c9c46a9a69ff11e40d752bf678ad9a0ebed3e5 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Wed, 24 Mar 2021 14:15:36 -0500 Subject: [PATCH] Nuke tokens on VERIFY_CREDENTIALS_FAIL --- app/soapbox/reducers/auth.js | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/app/soapbox/reducers/auth.js b/app/soapbox/reducers/auth.js index c6ae6035c..ef099bd4e 100644 --- a/app/soapbox/reducers/auth.js +++ b/app/soapbox/reducers/auth.js @@ -5,6 +5,7 @@ import { AUTH_LOGGED_OUT, SWITCH_ACCOUNT, VERIFY_CREDENTIALS_SUCCESS, + VERIFY_CREDENTIALS_FAIL, } from '../actions/auth'; import { Map as ImmutableMap, fromJS } from 'immutable'; @@ -32,6 +33,26 @@ const importCredentials = (state, token, account) => { }); }; +// If `me` doesn't match an existing user, attempt to shift it. +const maybeShiftMe = state => { + const users = state.get('users', ImmutableMap()); + const me = state.get('me'); + + if (!users.get(me)) { + return state.set('me', users.first(ImmutableMap()).get('id')); + } else { + return state; + } +}; + +const importFailedToken = (state, token) => { + return state.withMutations(state => { + state.update('tokens', ImmutableMap(), tokens => tokens.delete(token)); + state.update('users', ImmutableMap(), users => users.filterNot(user => user.get('access_token') === token)); + maybeShiftMe(state); + }); +}; + const reducer = (state, action) => { switch(action.type) { case AUTH_APP_CREATED: @@ -44,6 +65,8 @@ const reducer = (state, action) => { return state.set('user', ImmutableMap()); case VERIFY_CREDENTIALS_SUCCESS: return importCredentials(state, action.token, action.account); + case VERIFY_CREDENTIALS_FAIL: + return importFailedToken(state, action.token); case SWITCH_ACCOUNT: return state.set('me', action.accountId); default: @@ -51,11 +74,12 @@ const reducer = (state, action) => { } }; -export default function auth(state = initialState, action) { - state = reducer(state, action); +export default function auth(oldState = initialState, action) { + const state = reducer(oldState, action); localStorage.setItem('soapbox:auth', JSON.stringify(state.toJS())); - if (action.type === SWITCH_ACCOUNT) { + // Reload the page when the current user changes. + if (state.get('me') !== oldState.get('me')) { location.reload(); }