Projekt

Obecné

Profil

Stáhnout (1.6 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { AnyAction } from 'redux'
2
import persistReducer from 'redux-persist/es/persistReducer'
3
import storage from 'redux-persist/lib/storage'
4

    
5
export interface UserState {
6
    accessToken?: string
7
    refreshToken?: string
8
    username: string
9
    roles: string[]
10
    isLoggedIn: boolean
11
}
12

    
13
const initialState: UserState = {
14
    roles: [],
15
    isLoggedIn: false,
16
    username: '',
17
}
18

    
19
// All possible actions
20
export enum AuthStateActions {
21
    LOG_IN = 'LOG_IN',
22
    LOG_OUT = 'LOG_OUT',
23
    UPDATE_ACCESS_TOKEN = 'REFRESH_ACCESS_TOKEN',
24
    UPDATE_REFRESH_TOKEN = 'UPDATE_REFRESH_TOKEN',
25
    UPDATE_TOKENS = 'UPDATE_TOKENS',
26
}
27

    
28
// Only needed if the state is to be persisted
29
const persistConfig = {
30
    key: 'auth',
31
    storage
32
}
33

    
34
const _authReducer = (
35
    state: UserState = initialState,
36
    action: AnyAction
37
): UserState => {
38
    switch (action.type) {
39
        case AuthStateActions.LOG_IN:
40
            return {
41
                ...action.payload,
42
                isAuthenticated: true,
43
            }
44
        case AuthStateActions.LOG_OUT:
45
            return initialState
46

    
47
        case AuthStateActions.UPDATE_ACCESS_TOKEN:
48
            return {
49
                ...state,
50
                accessToken: action.payload,
51
            }
52

    
53
        case AuthStateActions.UPDATE_REFRESH_TOKEN:
54
            return {
55
                ...state,
56
                refreshToken: action.payload,
57
            }
58

    
59
        case AuthStateActions.UPDATE_TOKENS:
60
            return { ...state, ...action.payload }
61

    
62
        default:
63
            return state
64
    }
65
}
66

    
67
const authReducer = persistReducer(persistConfig, _authReducer)
68

    
69
export default authReducer
(3-3/3)