All files / store/auth auth.ts

92.3% Statements 72/78
84.61% Branches 22/26
100% Functions 14/14
93.42% Lines 71/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200                                      127x                         127x         2x 2x               2x 1x   1x                   127x         2x 2x         1x 1x   1x     1x                 127x     72x     72x     66x 61x 61x       66x     62x           62x 62x   62x       127x           37x     37x 37x 37x 37x 37x       113x   76x     88x 88x 88x 88x 88x   88x 88x       8x 8x 8x     9x     7x 7x 7x 7x 7x 7x     6x 5x   1x   6x 6x     12x     9x 9x 9x 9x 9x 9x     10x 9x   1x   10x 10x 10x         127x 127x  
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
import { refreshTokenApi } from '../../services/api/auth/refreshToken'
import { LOCAL_STORAGE_KEY, createSession, getSession, setAndSaveSession } from '../../services/auth/session'
import { AuthErrorResponse, SessionData, TokensResponse } from '../../types/auth'
 
export type AuthState = {
	/** Check if user has session. */
	isAuthenticated: boolean
	/** Check if auth context is initialized. */
	isInitialized: boolean
	/** Session data. */
	sessionData: SessionData | null
	/** Error message register. */
	registerError: string | null
	/** Error message login. */
	loginError: string | null
}
 
const initialState: AuthState = {
	isAuthenticated: false,
	isInitialized: false,
	sessionData: null,
	registerError: null,
	loginError: null,
}
 
/**
 * Register a user and return the tokens.
 * @param credentials credentials from user
 * @returns the tokens.
 */
export const registerApi = createAsyncThunk<
	TokensResponse,
	{ email: string; password: string },
	{ rejectValue: AuthErrorResponse }
>('auth/register', async ({ email, password }, { rejectWithValue }) => {
	try {
		const response = await axios.post<TokensResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/auth/register`, {
			email,
			password,
		})
 
		const tokens = response.data
		return tokens
	} catch (error) {
		if (axios.isAxiosError(error) && error.response) {
			return rejectWithValue(error.response.data)
		} else {
			throw new Error('Register failed.')
		}
	}
})
 
/**
 * Login a user and return the tokens.
 * @param credentials credentials from user
 * @returns the tokens.
 */
export const loginApi = createAsyncThunk<
	TokensResponse,
	{ email: string; password: string },
	{ rejectValue: AuthErrorResponse }
>('auth/login', async ({ email, password }, { rejectWithValue }) => {
	try {
		const response = await axios.post<TokensResponse>(`${process.env.NEXT_PUBLIC_API_BASE_URL}/auth/login`, {
			email,
			password,
		})
 
		const tokens = response.data
		return tokens
	} catch (error) {
		Iif (axios.isAxiosError(error) && error.response) {
			return rejectWithValue(error.response.data)
		} else {
			throw new Error('Login failed.')
		}
	}
})
 
/**
 * Get session data from local storage and update the access token if it has expired.
 * @returns session data or null if no session data is found
 */
export const refreshToken = createAsyncThunk<SessionData, { ignoreExpireCheck: boolean }>(
	'auth/getSessionData',
	async ({ ignoreExpireCheck }, { rejectWithValue }) => {
		const parsedSessionData = getSession()
 
		// No session data found
		if (!parsedSessionData) return rejectWithValue('No session data found')
 
		// Return session data if access token is not expired
		if (!ignoreExpireCheck) {
			const sessionExpired = Date.now() > parsedSessionData.decodedAccessToken.exp * 1000
			Iif (!sessionExpired) return parsedSessionData
		}
 
		// Update token
		const tokens = await refreshTokenApi(parsedSessionData.refreshToken)
 
		// Refresh token failed
		Iif (tokens === null) {
			console.error('Session expired and refresh token failed')
			return rejectWithValue('Session expired and refresh token failed')
		}
 
		// Update session when refresh token succeeded
		const newSession = createSession(tokens)
		setAndSaveSession(newSession)
 
		return newSession
	}
)
 
const authSlice = createSlice({
	name: 'auth',
	initialState,
	reducers: {
		logout: (state) => {
			// Clear local storage
			localStorage.removeItem(LOCAL_STORAGE_KEY)
 
			// Clear state
			state.isAuthenticated = false
			state.sessionData = null
			state.registerError = null
			state.loginError = null
			state.isInitialized = true
		},
	},
	extraReducers: (builder) => {
		builder
			.addCase(refreshToken.pending, (state) => {
				state.isInitialized = false
			})
			.addCase(refreshToken.fulfilled, (state, action) => {
				state.isInitialized = true
				state.loginError = null
				state.registerError = null
				state.isAuthenticated = action.payload !== null
				state.sessionData = action.payload
 
				Eif (action.payload) {
					setAndSaveSession(action.payload)
				}
			})
			.addCase(refreshToken.rejected, (state, action) => {
				state.isInitialized = true
				state.isAuthenticated = false
				console.error(action.payload)
			})
			.addCase(loginApi.pending, (state) => {
				state.isInitialized = false
			})
			.addCase(loginApi.fulfilled, (state, action) => {
				state.isInitialized = true
				state.loginError = null
				state.registerError = null
				state.isAuthenticated = true
				state.sessionData = createSession(action.payload)
				setAndSaveSession(state.sessionData)
			})
			.addCase(loginApi.rejected, (state, action) => {
				if (action.payload?.message === 'Unauthorized' && action.payload?.statusCode === 401) {
					state.loginError = 'Hoppla! Die von Ihnen eingegebene E-Mail oder das Passwort ist falsch.'
				} else {
					state.loginError = 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.'
				}
				state.isInitialized = true
				state.isAuthenticated = false
			})
			.addCase(registerApi.pending, (state) => {
				state.isInitialized = false
			})
			.addCase(registerApi.fulfilled, (state, action) => {
				state.isInitialized = true
				state.registerError = null
				state.loginError = null
				state.isAuthenticated = true
				state.sessionData = createSession(action.payload)
				setAndSaveSession(state.sessionData)
			})
			.addCase(registerApi.rejected, (state, action) => {
				if (action.payload?.message === 'Email is already taken.' && action.payload?.statusCode === 409) {
					state.registerError = 'Hoppla! Die von Ihnen eingegebene E-Mail ist bereits mit einem Konto verknüpft.'
				} else {
					state.registerError = 'Ein Fehler ist aufgetreten. Bitte versuchen Sie es später erneut.'
				}
				state.isInitialized = true
				state.isAuthenticated = false
				console.error(action.payload)
			})
	},
})
 
export const authReducer = authSlice.reducer
export const { logout } = authSlice.actions