useGeinsAuth
The useGeinsAuth composable provides Geins specific authentication and session management features. It build on top of NuxtAuth's composable useAuth to handle tasks like login, logout, token parsing, and session refresh.
TIP
Read more about the full authentication flow in Geins MC here: Authentication
Features
- Retrieve the current session and access token.
- Check if the user is authenticated.
- Log in and log out users.
- Refresh tokens and manage token expiration.
- Decode and parse JWT tokens.
Usage
import { useGeinsAuth } from '@/composables/useGeinsAuth';
const {
session,
accessToken,
isAuthenticated,
isRefreshing,
authStateDiffers,
accountKey,
preLogin,
login,
verify,
setAccount,
setSession,
sessionsAreEqual,
logout,
refresh,
setIsRefreshing,
parseToken,
isExpired,
expiresSoon,
} = useGeinsAuth();Properties and Methods
session
A computed reference to the current session data.
accessToken
A computed reference to the access token from the session.
isAuthenticated
A computed reference that returns true if the user is authenticated.
isRefreshing
A ref that indicates whether a token refresh is in progress.
authStateDiffers
A computed reference that returns true if the auth state indicates the user is authenticated but the session data does not.
accountKey
A computed reference to the current account key from the session.
preLogin
preLogin(): Promise<void>Prepares the authentication environment by pinging auth and account endpoints.
- Returns: Promise that resolves when pre-login setup is complete
login
login(credentials: LoginCredentials): Promise<any>Logs in the user using the provided credentials.
- Parameters:
credentials: An object containingusernameandpassword
- Returns: A promise that resolves to the login response
verify
verify(tokens: AuthTokens): Promise<any>Verifies the user's tokens for MFA authentication.
- Parameters:
tokens: An object containingloginTokenandmfaCode
- Returns: A promise that resolves to the verification response
setAccount
setAccount(accountKey: string): Promise<any>Sets the account context for the current session.
- Parameters:
accountKey: The account key to set for the session
- Returns: A promise that resolves to the updated session
setSession
setSession(session: Session): Promise<any>Updates the current session with new session data.
- Parameters:
session: The complete session object to set
- Returns: A promise that resolves to the updated session
sessionsAreEqual
sessionsAreEqual(session1: Session, session2: Session): booleanCompares two session objects for equality, excluding expires and accounts properties.
- Parameters:
session1: First session to comparesession2: Second session to compare
- Returns:
trueif sessions are equal, otherwisefalse
logout
logout(): Promise<void>Logs out the user and clears the session.
- Returns: A promise that resolves when the logout process is complete
refresh
refresh(): Promise<Session>Refreshes the session and retrieves a new access token.
- Returns: A promise that resolves to the updated session
setIsRefreshing
setIsRefreshing(value: boolean): voidSets the isRefreshing state.
- Parameters:
value: A boolean indicating the refresh state
parseToken
parseToken(token?: string | null): any | nullDecodes the given JWT token and returns its payload.
- Parameters:
token: Optional. The token to decode. If not provided, the currentaccessTokenfrom the session will be used
- Returns: The parsed token payload or
nullif decoding fails
isExpired
isExpired(token?: string | null): booleanChecks if a given token (or the current accessToken) is expired.
- Parameters:
token: Optional. The token to check
- Returns:
trueif the token is expired, otherwisefalse
expiresSoon
expiresSoon(token?: string | null, threshold?: number): booleanChecks if a token (or the current accessToken) is close to expiration.
- Parameters:
token: Optional. The token to checkthreshold: Optional. Time (in milliseconds) before expiration to consider as "soon". Default is300000
- Returns:
trueif the token expires within the threshold, otherwisefalse
Example
Here is an example of how you can use the useGeinsAuth composable:
<script setup lang="ts">
const {
isAuthenticated,
accountKey,
login,
verify,
setAccount,
logout,
refresh,
isExpired,
expiresSoon,
} = useGeinsAuth();
const handleLogin = async () => {
const credentials = { username: 'user', password: 'password' };
await login(credentials);
};
const handleVerify = async () => {
const tokens = { loginToken: 'token', mfaCode: 'code' };
await verify(tokens);
if (isAuthenticated.value) {
console.log('User is authenticated!');
}
};
const handleSetAccount = async (accountKey: string) => {
await setAccount(accountKey);
};
const handleLogout = async () => {
await logout();
};
const handleRefresh = async () => {
if (isExpired() || expiresSoon()) {
await refresh();
}
};
</script>Type Definitions
function useGeinsAuth(): UseGeinsAuthReturnType;
interface UseGeinsAuthReturnType {
session: ComputedRef<Session | null>;
accessToken: ComputedRef<string | undefined>;
isAuthenticated: ComputedRef<boolean>;
isRefreshing: Ref<boolean>;
authStateDiffers: ComputedRef<boolean>;
accountKey: ComputedRef<string | undefined>;
preLogin: () => Promise<void>;
login: (credentials: LoginCredentials) => Promise<any>;
verify: (tokens: AuthTokens) => Promise<any>;
setAccount: (accountKey: string) => Promise<any>;
setSession: (session: Session) => Promise<any>;
sessionsAreEqual: (session1: Session, session2: Session) => boolean;
logout: () => Promise<void>;
refresh: () => Promise<Session>;
setIsRefreshing: (value: boolean) => void;
parseToken: (token?: string | null) => any | null;
isExpired: (token?: string | null) => boolean;
expiresSoon: (token?: string | null, threshold?: number) => boolean;
}
interface LoginCredentials {
username: string;
password: string;
}
interface AuthTokens {
loginToken: string;
mfaCode: string;
}
interface Session {
isAuthenticated?: boolean;
accessToken?: string;
accountKey?: string;
expires?: string;
accounts?: any[];
[key: string]: any;
}Dependencies
This composable depends on:
- NuxtAuth: Ensure the
NuxtAuthfunction is correctly set up. - jwt-decode: The
jwt-decodeplugin is used to parse JWT tokens.