All files / services/auth session.ts

91.66% Statements 22/24
100% Branches 2/2
85.71% Functions 6/7
91.3% Lines 21/23

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        357x             357x 66x     66x     66x           66x             357x 138x             357x 138x 138x           357x               357x 132x 132x 132x 102x                   357x 74x             357x 138x    
import axios from 'axios'
import { parseJwt } from '../../../utils/jwt'
import { SessionData, TokensResponse } from '../../types/auth'
 
export const LOCAL_STORAGE_KEY = 'session'
 
/**
 * Create a session object from the tokens.
 * @param tokens access and refresh tokens
 * @returns session object
 */
export const createSession = (tokens: TokensResponse) => {
	const { access_token, refresh_token } = tokens
 
	// Decode access token
	const decodedAccessToken = parseJwt(access_token)
 
	// Create session object
	const sessionData: SessionData = {
		accessToken: access_token,
		refreshToken: refresh_token,
		decodedAccessToken,
	}
 
	return sessionData
}
 
/**
 * Save session data in local storage.
 * @param sessionData session data to save in local storage
 */
const saveSession = (sessionData: SessionData): void => {
	localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(sessionData))
}
 
/**
 * Set the authorization header for axios and save session data in local storage.
 * @param sessionData session data to save in local storage
 */
export const setAndSaveSession = (sessionData: SessionData): void => {
	setAxiosAuthHeader(sessionData.accessToken)
	saveSession(sessionData)
}
 
/**
 * Remove session data from local storage.
 */
export const endSession = (): void => {
	localStorage.removeItem(LOCAL_STORAGE_KEY)
}
 
/**
 * Get the session data from local storage.
 * @returns session data or null if not found or an error occurred
 */
export const getSession = (): SessionData | null => {
	try {
		const sessionData = localStorage.getItem(LOCAL_STORAGE_KEY)
		if (!sessionData) return null
		return JSON.parse(sessionData)
	} catch (error) {
		return null
	}
}
 
/**
 * Check if the user has a session.
 * @returns true if the user has a session, false otherwise
 */
export const hasSession = (): boolean => {
	return getSession() !== null
}
 
/**
 * Set the authorization header for axios.
 * @param accessToken access token
 */
export const setAxiosAuthHeader = (accessToken: string): void => {
	axios.defaults.headers.common['Authorization'] = 'Bearer ' + accessToken
}