All files / store/auth auth.ts

91.02% Statements 71/78
80.76% Branches 21/26
100% Functions 14/14
92.1% Lines 70/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                                      125x                         125x         2x 2x               2x 1x   1x                   125x         2x 2x         1x 1x   1x 1x                     125x     67x     67x     63x 58x 58x       63x     60x           60x 60x   60x       125x           33x     33x 33x 33x 33x 33x       111x   71x     86x 86x 86x 86x 86x   86x 86x       6x 6x 6x     9x     7x 7x 7x 7x 7x 7x     6x 6x       6x 6x     12x     9x 9x 9x 9x 9x 9x     10x 9x   1x   10x 10x 10x         125x 125x  
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) {
		if (axios.isAxiosError(error) && error.response) {
			return rejectWithValue(error.response.data)
		} else E{
			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 E{
					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