bigbuffet-rw/app/soapbox/reducers/auth.js

47 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-04-05 16:39:22 -07:00
import {
AUTH_APP_CREATED,
AUTH_LOGGED_IN,
AUTH_APP_AUTHORIZED,
2020-04-11 12:41:13 -07:00
AUTH_LOGGED_OUT,
SWITCH_ACCOUNT,
2020-04-05 16:39:22 -07:00
} from '../actions/auth';
import { Map as ImmutableMap, fromJS } from 'immutable';
2020-04-05 14:54:51 -07:00
2021-03-23 19:52:08 -07:00
const defaultState = ImmutableMap({
app: ImmutableMap(),
user: ImmutableMap(),
users: ImmutableMap(),
me: null,
2020-04-05 14:54:51 -07:00
});
2021-03-23 19:52:08 -07:00
const localState = fromJS(JSON.parse(localStorage.getItem('soapbox:auth')));
const initialState = defaultState.merge(localState);
const reducer = (state, action) => {
2020-04-05 14:54:51 -07:00
switch(action.type) {
case AUTH_APP_CREATED:
2021-03-23 19:52:08 -07:00
return state.set('app', fromJS(action.app));
2020-04-05 16:39:22 -07:00
case AUTH_APP_AUTHORIZED:
2021-03-23 19:52:08 -07:00
return state.update('app', ImmutableMap(), app => app.merge(fromJS(action.app)));
2020-04-05 14:54:51 -07:00
case AUTH_LOGGED_IN:
2021-03-23 19:52:08 -07:00
return state.set('user', fromJS(action.token));
2020-04-11 12:41:13 -07:00
case AUTH_LOGGED_OUT:
2020-06-05 13:43:03 -07:00
return state.set('user', ImmutableMap());
case SWITCH_ACCOUNT:
2021-03-23 19:52:08 -07:00
return state.set('me', action.accountId);
2020-04-05 14:54:51 -07:00
default:
return state;
}
};
2021-03-23 19:52:08 -07:00
export default function auth(state = initialState, action) {
state = reducer(state, action);
localStorage.setItem('soapbox:auth', JSON.stringify(state.toJS()));
if (action.type === SWITCH_ACCOUNT) {
location.reload();
}
return state;
};