Projekt

Obecné

Profil

Stáhnout (1.59 KB) Statistiky
| Větev: | Tag: | Revize:
1
import { createAsyncThunk } from '@reduxjs/toolkit'
2
import axiosInstance from '../../api/api'
3
import {  UserState } from './userSlice'
4
import jwt from 'jwt-decode' 
5

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

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

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

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

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