import { createSlice, PayloadAction } from '@reduxjs/toolkit' import * as SecureStore from '@/utils/SecureStore' import { Platform } from 'react-native' 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: SecureStore.getItem('apiName') !== null && SecureStore.getItem('apiToken') !== null, name: SecureStore.getItem('apiName'), token: SecureStore.getItem('apiToken'), } export const authSlice = createSlice({ name: 'auth', initialState: initialState, reducers: { login: (state, action: PayloadAction) => { 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