Skip to main content

Check Authentication

Use the isAuthenticated method to check whether a player is currently authenticated. This is useful for showing different UI states, restricting features, or prompting players to log in.

Basic Usage​

The isAuthenticated method checks the current authentication state without requiring any parameters.

JavaScript Example​

MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
console.log('Player is authenticated');
// Show authenticated features
} else {
console.log('Player is not authenticated');
// Show login prompt or guest features
}
});

TypeScript Example​

import MoitribeSDK from '@veniso/moitribe-js';

interface AuthResult {
success: boolean;
}

MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result: AuthResult) => {
if (result.success) {
console.log('Player is authenticated');
showAuthenticatedUI();
} else {
console.log('Player is not authenticated');
showGuestUI();
}
});

Response Format​

The callback receives a simple result object:

{
success: boolean // true if authenticated, false otherwise
}

When to Check Authentication​

1. After SDK Initialization​

The SDK automatically checks authentication during initialization via the loginCallback. You typically don't need to call isAuthenticated immediately after init.

// Not necessary - init already checks
MoitribeSDK('my-game-id', 'init', {
loginCallback: (result) => {
// Already know auth status here
if (result.success) {
console.log('Authenticated');
}
}
});

2. Before Restricted Features​

Check authentication before accessing features that require a logged-in player:

function submitScore(score) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
// Player is authenticated - submit score
MoitribeSDK('my-game-id', 'submitscore', {
leaderboardid: 'high-scores',
score: score
}, (scoreResult) => {
console.log('Score submitted');
});
} else {
// Player not authenticated - prompt login
showLoginPrompt('Please log in to save your score!');
}
});
}

3. During Gameplay​

Check authentication when players attempt to access authenticated-only features:

function openLeaderboard() {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
loadLeaderboard();
} else {
showMessage('Log in to view leaderboards!');
showLoginOptions();
}
});
}

4. On App Resume​

Check authentication when the game resumes after being backgrounded:

window.addEventListener('focus', () => {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (!result.success) {
// Session may have expired
handleSessionExpired();
}
});
});

Common Use Cases​

Conditional Feature Access​

Enable or disable features based on authentication:

function initializeGame() {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
const isAuthenticated = result.success;

// Enable/disable UI elements
document.getElementById('leaderboard-btn').disabled = !isAuthenticated;
document.getElementById('profile-btn').disabled = !isAuthenticated;
document.getElementById('friends-btn').disabled = !isAuthenticated;

// Show appropriate message
if (!isAuthenticated) {
showBanner('Log in to access all features!');
}
});
}

Progressive Authentication​

Start as guest, prompt for authentication at strategic moments:

let gamesPlayed = 0;

function onGameEnd(score) {
gamesPlayed++;

// Check auth after 3 games
if (gamesPlayed >= 3) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (!result.success) {
// Show login incentive
showDialog({
title: 'Save Your Progress!',
message: 'Log in to save your scores and compete on leaderboards',
buttons: ['Log In', 'Maybe Later']
});
}
});
}
}

Gating Premium Features​

Require authentication for premium features:

function unlockPremiumFeature(featureName) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
activatePremiumFeature(featureName);
} else {
showDialog({
title: 'Authentication Required',
message: 'Please log in to access premium features',
action: () => showLoginScreen()
});
}
});
}

Session Validation​

Periodically validate the session is still active:

// Check every 5 minutes
setInterval(() => {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (!result.success) {
console.log('Session expired - returning to login');
handleSessionExpired();
}
});
}, 5 * 60 * 1000);

Combined with Other Methods​

Check Before Profile Update​

function updatePlayerName(newName) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
MoitribeSDK('my-game-id', 'updateProfile', {
name: newName,
callback: (updateResult) => {
if (updateResult.success) {
console.log('Profile updated');
}
}
});
} else {
showError('You must be logged in to update your profile');
}
});
}

Check Before Tournament Join​

function joinTournament(tournamentId) {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
if (result.success) {
MoitribeSDK('my-game-id', 'groupTournamentJoin', {
tournamentid: tournamentId,
callback: (joinResult) => {
console.log('Tournament joined');
}
});
} else {
showError('Please log in to join tournaments');
}
});
}

TypeScript Helper Function​

Create a reusable helper for authentication checks:

import MoitribeSDK from '@veniso/moitribe-js';

const GAME_ID = 'my-game-id';

function requireAuthentication(
onAuthenticated: () => void,
onNotAuthenticated?: () => void
): void {
MoitribeSDK(GAME_ID, 'isAuthenticated', {}, (result: { success: boolean }) => {
if (result.success) {
onAuthenticated();
} else {
if (onNotAuthenticated) {
onNotAuthenticated();
} else {
console.log('Authentication required');
showLoginScreen();
}
}
});
}

// Usage
requireAuthentication(
() => {
// Authenticated - proceed
submitScore(1000);
},
() => {
// Not authenticated - show prompt
showLoginPrompt();
}
);

Performance Considerations​

The isAuthenticated check is synchronous and very fast - it simply checks for stored credentials. You can call it frequently without performance concerns.

// Safe to call often
function onEveryFrame() {
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
updateAuthIndicator(result.success);
});
}

However, consider caching the result if checking multiple times in quick succession:

let authStatus = null;
let lastCheck = 0;

function getCachedAuthStatus(callback) {
const now = Date.now();

// Use cached result if less than 5 seconds old
if (authStatus !== null && now - lastCheck < 5000) {
callback(authStatus);
return;
}

// Check fresh status
MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
authStatus = result.success;
lastCheck = now;
callback(authStatus);
});
}
tip

Cache authentication status locally if you need to check it frequently (e.g., every frame). The status rarely changes during a single session.

Error Handling​

The isAuthenticated method always returns a result. There are no error conditions to handle:

MoitribeSDK('my-game-id', 'isAuthenticated', {}, (result) => {
// result.success is always a boolean
// No error handling needed
const isAuth = result.success;
});

Next Steps​

Now that you know how to check authentication, learn about authentication methods:

Related topics: