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 function isAuthValid({ loggedIn, token }: AuthState): boolean { if (!loggedIn || token === null) return false const arrayToken = token.split('.') const tokenPayload = JSON.parse(atob(arrayToken[1])) const expTime: number = tokenPayload.exp * 1000 const now: number = Math.floor(new Date().getTime()) return expTime >= now } 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