1
|
import { createSlice } from "@reduxjs/toolkit"
|
2
|
import { checkAuth, login, logout } from "../actions/userThunks"
|
3
|
|
4
|
export enum UserRole {
|
5
|
Admin = "admin",
|
6
|
User = "user",
|
7
|
Contributor = "contributor",
|
8
|
Unauthorized = "unauthorized"
|
9
|
}
|
10
|
|
11
|
|
12
|
export interface UserState {
|
13
|
username: string
|
14
|
userId: string
|
15
|
loggedIn: boolean
|
16
|
role: UserRole
|
17
|
lastError?: string
|
18
|
checkedAuth: boolean
|
19
|
}
|
20
|
|
21
|
const initialState: UserState = {
|
22
|
username: "",
|
23
|
userId: "",
|
24
|
loggedIn: false,
|
25
|
role: UserRole.Unauthorized,
|
26
|
checkedAuth: false
|
27
|
}
|
28
|
|
29
|
export const userSlice = createSlice({
|
30
|
name: "user",
|
31
|
initialState: initialState,
|
32
|
reducers: {
|
33
|
resetState: (state) => {
|
34
|
state = initialState
|
35
|
},
|
36
|
consumeError: (state) => {
|
37
|
state.lastError = undefined
|
38
|
}
|
39
|
},
|
40
|
extraReducers: (builder) => {
|
41
|
builder.addCase(login.fulfilled, (state, action) => {
|
42
|
state.username = action.payload.username
|
43
|
state.userId = action.payload.userId
|
44
|
state.loggedIn = true
|
45
|
state.role = action.payload.role
|
46
|
state.lastError = undefined
|
47
|
})
|
48
|
builder.addCase(login.rejected, (state, action) => {
|
49
|
state.lastError = action.error.message
|
50
|
})
|
51
|
builder.addCase(checkAuth.fulfilled, (state, action) => {
|
52
|
state.loggedIn = action.payload.isLogged
|
53
|
state.lastError = undefined
|
54
|
state.userId = action.payload.userId
|
55
|
state.checkedAuth = true
|
56
|
})
|
57
|
builder.addCase(checkAuth.rejected, (state, action) => {
|
58
|
state.lastError = action.error.message
|
59
|
state.checkedAuth = true
|
60
|
state.loggedIn = false
|
61
|
})
|
62
|
builder.addCase(logout.fulfilled, (state, action) => initialState)
|
63
|
}
|
64
|
})
|
65
|
|
66
|
export const { resetState, consumeError } = userSlice.actions
|
67
|
|
68
|
export default userSlice.reducer
|