1
|
import { AnyAction } from 'redux'
|
2
|
import { persist, load } from '../../utils/statePersistence'
|
3
|
|
4
|
export interface UserInfo {
|
5
|
accessToken: string | undefined // to send api requests
|
6
|
refreshToken: string | undefined // to refresh the api key
|
7
|
username: string // to display the username
|
8
|
roles: string[]
|
9
|
}
|
10
|
|
11
|
export interface AuthState extends UserInfo {
|
12
|
isAuthenticated: boolean // if this is false all other values should be ignored
|
13
|
}
|
14
|
|
15
|
const statePersistName = 'auth'
|
16
|
|
17
|
// Initial state when the user first starts the application
|
18
|
const initialState: AuthState = (load(statePersistName) as AuthState) || {
|
19
|
isAuthenticated: false,
|
20
|
username: '',
|
21
|
roles: [],
|
22
|
}
|
23
|
|
24
|
// All possible actions
|
25
|
export enum AuthStateActions {
|
26
|
LOG_IN = 'LOG_IN',
|
27
|
LOG_OUT = 'LOG_OUT',
|
28
|
UPDATE_ACCESS_TOKEN = 'REFRESH_ACCESS_TOKEN',
|
29
|
UPDATE_REFRESH_TOKEN = 'UPDATE_REFRESH_TOKEN',
|
30
|
UPDATE_TOKENS = 'UPDATE_TOKENS',
|
31
|
}
|
32
|
|
33
|
// Actions
|
34
|
const authReducer = (state: AuthState = initialState, action: AnyAction) => {
|
35
|
switch (action.type) {
|
36
|
case AuthStateActions.LOG_IN:
|
37
|
return persist(statePersistName, {
|
38
|
...action.payload,
|
39
|
isAuthenticated: true,
|
40
|
})
|
41
|
|
42
|
case AuthStateActions.LOG_OUT:
|
43
|
return persist(statePersistName, initialState)
|
44
|
|
45
|
case AuthStateActions.UPDATE_ACCESS_TOKEN:
|
46
|
return persist(statePersistName, {
|
47
|
...state,
|
48
|
accessToken: action.payload,
|
49
|
})
|
50
|
|
51
|
case AuthStateActions.UPDATE_REFRESH_TOKEN:
|
52
|
return persist(statePersistName, {
|
53
|
...state,
|
54
|
refreshToken: action.payload,
|
55
|
})
|
56
|
|
57
|
case AuthStateActions.UPDATE_TOKENS:
|
58
|
return persist(statePersistName, { ...state, ...action.payload })
|
59
|
|
60
|
default:
|
61
|
return state
|
62
|
}
|
63
|
}
|
64
|
|
65
|
export default authReducer
|