1 |
37f6ff02
|
Vaclav Honzik
|
import { createAsyncThunk } from '@reduxjs/toolkit'
|
2 |
|
|
import axiosInstance from '../../api/api'
|
3 |
|
|
import { UserDto } from '../../swagger/data-contracts'
|
4 |
fc79a8cb
|
Vaclav Honzik
|
import { setErr, setUserState, UserState } from './userSlice'
|
5 |
|
|
import jwt from 'jwt-decode'
|
6 |
|
|
import { RootState } from '../redux/store'
|
7 |
37f6ff02
|
Vaclav Honzik
|
|
8 |
8370b6c1
|
Vaclav Honzik
|
const loginError =
|
9 |
|
|
'Server error occurred while logging in. Please contact help service to resolve this issue or try again later.'
|
10 |
|
|
|
11 |
fc79a8cb
|
Vaclav Honzik
|
// This is not present in the swagger since spring generates
|
12 |
|
|
export interface UserLogin {
|
13 |
|
|
username: string,
|
14 |
|
|
password: string
|
15 |
|
|
}
|
16 |
8370b6c1
|
Vaclav Honzik
|
|
17 |
|
|
export const logIn = createAsyncThunk(
|
18 |
|
|
'user/login',
|
19 |
fc79a8cb
|
Vaclav Honzik
|
async (userDto: UserLogin, { dispatch, getState }) => {
|
20 |
37f6ff02
|
Vaclav Honzik
|
try {
|
21 |
8370b6c1
|
Vaclav Honzik
|
// @ts-ignore
|
22 |
|
|
if (getState().user.isLoggedIn) {
|
23 |
fc79a8cb
|
Vaclav Honzik
|
return Promise.reject(undefined)
|
24 |
8370b6c1
|
Vaclav Honzik
|
}
|
25 |
fc79a8cb
|
Vaclav Honzik
|
|
26 |
8370b6c1
|
Vaclav Honzik
|
const { data, status } = await axiosInstance.post('/login', userDto)
|
27 |
fc79a8cb
|
Vaclav Honzik
|
const [ accessToken, refreshToken ] = [data.access_token, data.refresh_token]
|
28 |
8370b6c1
|
Vaclav Honzik
|
if (status !== 200) {
|
29 |
|
|
// TODO read API err
|
30 |
fc79a8cb
|
Vaclav Honzik
|
return Promise.reject(loginError)
|
31 |
|
|
}
|
32 |
|
|
|
33 |
|
|
// Strip bearer from access token
|
34 |
|
|
const userInfo = jwt(accessToken.replace('Bearer ', '')) as any
|
35 |
|
|
const { sub, authorities } = userInfo
|
36 |
|
|
if (!sub || !authorities) {
|
37 |
|
|
return Promise.reject(loginError)
|
38 |
8370b6c1
|
Vaclav Honzik
|
}
|
39 |
37f6ff02
|
Vaclav Honzik
|
|
40 |
fc79a8cb
|
Vaclav Honzik
|
const userState: UserState = {
|
41 |
|
|
accessToken,
|
42 |
|
|
refreshToken,
|
43 |
|
|
username: sub,
|
44 |
|
|
roles: authorities,
|
45 |
|
|
isLoggedIn: true
|
46 |
|
|
}
|
47 |
|
|
|
48 |
|
|
return userState
|
49 |
8370b6c1
|
Vaclav Honzik
|
} catch (err: any) {
|
50 |
fc79a8cb
|
Vaclav Honzik
|
console.log(err)
|
51 |
|
|
return Promise.reject(loginError)
|
52 |
37f6ff02
|
Vaclav Honzik
|
}
|
53 |
|
|
}
|
54 |
|
|
)
|