Projekt

Obecné

Profil

Stáhnout (1.75 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { createAsyncThunk } from '@reduxjs/toolkit'
2
import axiosInstance from '../../api/api'
3
import { UserDto } from '../../swagger/data-contracts'
4
import { setErr, setUserState, UserState } from './userSlice'
5
import jwt from 'jwt-decode' 
6
import { RootState } from '../redux/store'
7

    
8
const loginError =
9
    'Server error occurred while logging in. Please contact help service to resolve this issue or try again later.'
10

    
11
// This is not present in the swagger since spring generates
12
export interface UserLogin {
13
    username: string,
14
    password: string
15
}
16

    
17
export const logIn = createAsyncThunk(
18
    'user/login',
19
    async (userDto: UserLogin, { dispatch, getState }) => {
20
        try {
21
            // @ts-ignore
22
            if (getState().user.isLoggedIn) {
23
                return Promise.reject(undefined)
24
            }
25

    
26
            const { data, status } = await axiosInstance.post('/login', userDto)
27
            const [ accessToken, refreshToken ] = [data.access_token, data.refresh_token]
28
            if (status !== 200) {
29
                // TODO read API err
30
                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
            }
39

    
40
            const userState: UserState = {
41
                accessToken,
42
                refreshToken,
43
                username: sub,
44
                roles: authorities,
45
                isLoggedIn: true
46
            }
47
            
48
            return userState
49
        } catch (err: any) {
50
            console.log(err)
51
            return Promise.reject(loginError)
52
        }
53
    }
54
)
(4-4/4)