Projekt

Obecné

Profil

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