traintrape-moi/client/utils/features/location/authSlice.ts

60 lines
1.6 KiB
TypeScript

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import * as SecureStore from '@/utils/SecureStore'
import { Platform } from 'react-native'
export interface AuthState {
loggedIn: boolean,
name: string | null,
token: string | null,
}
export interface AuthPayload {
name: string,
password?: string | null,
token: string | null,
}
const initialState: AuthState = {
loggedIn: false,
name: null,
token: null,
}
export const authSlice = createSlice({
name: 'auth',
initialState: initialState,
reducers: {
login: (state, action: PayloadAction<AuthPayload>) => {
state.loggedIn = action.payload.token !== null
state.name = action.payload.name
state.token = action.payload.token
SecureStore.setItem('apiName', action.payload.name)
if (action.payload.password !== undefined && Platform.OS !== "web") {
// Le stockage navigateur n'est pas sûr, on évite de stocker un mot de passe à l'intérieur
if (action.payload.password)
SecureStore.setItem('apiPassword', action.payload.password)
else
SecureStore.deleteItemAsync('apiPassword')
}
if (action.payload.token)
SecureStore.setItem('apiToken', action.payload.token)
else
SecureStore.deleteItemAsync('apiToken')
},
logout: (state) => {
state.loggedIn = false
state.name = null
state.token = null
SecureStore.deleteItemAsync('apiName')
SecureStore.deleteItemAsync('apiPassword')
SecureStore.deleteItemAsync('apiToken')
}
},
})
export const { login, logout } = authSlice.actions
export default authSlice.reducer