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 | 364x 364x 76x 76x 76x 76x 364x 162x 364x 162x 162x 364x 364x 147x 147x 147x 121x 364x 80x 364x 162x | 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
}
|