All files / store/auth auth.ts

88.46% Statements 69/78
62.5% Branches 15/24
100% Functions 15/15
89.47% Lines 68/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 201                                      118x                         118x         3x 3x         1x 1x   2x 1x   1x                   118x         1x 1x         1x 1x                           118x     58x     58x     52x           52x     49x           49x 49x   49x       118x         72x 72x 72x   72x       35x     35x 35x 35x 35x 35x       104x   62x     58x 58x 58x 58x 58x     2x 2x     8x     7x 7x 7x 7x 7x 7x     5x 5x       5x 5x     13x     10x 10x 10x 10x 10x 10x     10x 9x   1x   10x 10x         118x 118x  
import { PayloadAction, 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 {
			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 | null, { bypassExpiryCheck: boolean }>(
	'auth/getSessionData',
	async ({ bypassExpiryCheck }) => {
		const parsedSessionData = getSession()
 
		// No session data found
		if (!parsedSessionData) return null
 
		// Return session data if access token is not expired
		Iif (!bypassExpiryCheck) {
			const sessionExpired = Date.now() > parsedSessionData.decodedAccessToken.exp * 1000
			if (!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 null
		}
 
		// Update session when refresh token succeeded
		const newSession = createSession(tokens)
		setAndSaveSession(newSession)
 
		return newSession
	}
)
 
const authSlice = createSlice({
	name: 'auth',
	initialState,
	reducers: {
		login: (state, action: PayloadAction<SessionData>) => {
			state.isInitialized = true
			state.isAuthenticated = true
			state.sessionData = action.payload
 
			setAndSaveSession(action.payload)
		},
		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
			})
			.addCase(refreshToken.rejected, (state) => {
				state.isInitialized = true
				state.isAuthenticated = false
			})
			.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
			})
	},
})
 
export const authReducer = authSlice.reducer
export const { logout, login } = authSlice.actions