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
// All possible actions
14
export enum AuthStateActions {
15
    LOG_IN = 'LOG_IN',
16
    LOG_OUT = 'LOG_OUT',
17
    UPDATE_ACCESS_TOKEN = 'REFRESH_ACCESS_TOKEN',
18
    UPDATE_REFRESH_TOKEN = 'UPDATE_REFRESH_TOKEN',
19
    UPDATE_TOKENS = 'UPDATE_TOKENS',
20
}
21

    
22
// Only needed if the state is to be persisted
23
const persistConfig = {
24
    key: 'auth',
25
    storage
26
}
27

    
28
const initialState: UserState = {
29
    roles: [],
30
    isLoggedIn: false,
31
    username: '',
32
}
33

    
34

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

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

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

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

    
63
        default:
64
            return state
65
    }
66
}
67

    
68
const authReducer = persistReducer(persistConfig, _authReducer)
69

    
70
export default authReducer
(3-3/5)