Get Current User
Endpoint: GET /api/v1/me
Description
This endpoint returns information about the currently authenticated user. It uses the user information from the request object, which is populated by the authentication middleware.
Authentication
Required: Yes
Type: Bearer Token (JWT)
Request
Headers
Content-Type: application/json
Authorization: Bearer <your_jwt_token>
No query parameters or body required.
Response
Success Response
Status Code: 200 OK
Content-Type: application/json
interface CurrentUserResponse {
user: {
id: string;
walletAddress: string;
username: string | null;
role: string;
lastLogin: string;
createdAt: string;
updatedAt: string;
}
}
Example Response:
{
"user": {
"id": "user123",
"walletAddress": "SolanaWalletAddress123...",
"username": "cryptoTrader",
"role": "user",
"lastLogin": "2024-02-20T12:00:00.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-02-20T12:00:00.000Z"
}
}
Example Usage
// Basic implementation
async function getCurrentUser() {
try {
const response = await fetch('https://api.cybers.app/api/v1/me', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const { user } = await response.json();
return user;
} catch (error) {
console.error('Error fetching current user:', error);
throw error;
}
}
// React Hook example
function useCurrentUser() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchUser() {
try {
const userData = await getCurrentUser();
setUser(userData);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
fetchUser();
}, []);
return { user, loading, error };
}
Implementation Notes
1. Authentication Check
// Example middleware to verify authentication
function requireAuth(req: FastifyRequest, reply: FastifyReply) {
if (!req.user) {
reply.code(401).send({
error: 'Authentication required'
});
return;
}
}
User Session Management
class UserSessionManager {
private static instance: UserSessionManager;
private currentUser: any = null;
private lastFetch: number = 0;
private readonly CACHE_DURATION = 300000; // 5 minutes
static getInstance() {
if (!UserSessionManager.instance) {
UserSessionManager.instance = new UserSessionManager();
}
return UserSessionManager.instance;
}
async getCurrentUser(forceRefresh = false) {
const now = Date.now();
if (
forceRefresh ||
!this.currentUser ||
now - this.lastFetch > this.CACHE_DURATION
) {
const user = await getCurrentUser();
this.currentUser = user;
this.lastFetch = now;
}
return this.currentUser;
}
clearCache() {
this.currentUser = null;
this.lastFetch = 0;
}
}
Error Handling
class AuthenticationError extends Error {
constructor(message = 'Authentication required') {
super(message);
this.name = 'AuthenticationError';
}
}
async function getAuthenticatedUser() {
try {
const response = await fetch('https://api.cybers.app/api/v1/me', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('auth_token')}`
}
});
if (response.status === 401) {
throw new AuthenticationError();
}
if (!response.ok) {
throw new Error('Failed to fetch user data');
}
return response.json();
} catch (error) {
if (error instanceof AuthenticationError) {
// Handle authentication errors
window.location.href = '/login';
}
throw error;
}
}
Best Practices
1. Token Management
class TokenManager {
private static readonly TOKEN_KEY = 'auth_token';
private static readonly TOKEN_EXPIRY_KEY = 'auth_token_expiry';
static getToken(): string | null {
const token = localStorage.getItem(this.TOKEN_KEY);
const expiry = localStorage.getItem(this.TOKEN_EXPIRY_KEY);
if (!token || !expiry) {
return null;
}
if (Date.now() > Number(expiry)) {
this.clearToken();
return null;
}
return token;
}
static setToken(token: string, expiresIn: number) {
localStorage.setItem(this.TOKEN_KEY, token);
localStorage.setItem(
this.TOKEN_EXPIRY_KEY,
String(Date.now() + expiresIn * 1000)
);
}
static clearToken() {
localStorage.removeItem(this.TOKEN_KEY);
localStorage.removeItem(this.TOKEN_EXPIRY_KEY);
}
}
User Data Validation
function validateUserData(user: any): boolean {
return !!(
user &&
typeof user.walletAddress === 'string' &&
typeof user.role === 'string' &&
typeof user.lastLogin === 'string'
);
}
function sanitizeUserData(user: any) {
return {
id: user.id,
walletAddress: user.walletAddress,
username: user.username || null,
role: user.role,
lastLogin: user.lastLogin,
createdAt: user.createdAt,
updatedAt: user.updatedAt
};
}
3. Request Retry Logic
async function fetchWithRetry(
url: string,
options: RequestInit,
maxRetries = 3
) {
let attempts = 0;
while (attempts < maxRetries) {
try {
const response = await fetch(url, options);
if (response.ok) {
return response.json();
}
if (response.status === 401) {
throw new AuthenticationError();
}
} catch (error) {
attempts++;
if (attempts === maxRetries || error instanceof AuthenticationError) {
throw error;
}
await new Promise(resolve =>
setTimeout(resolve, 1000 * attempts)
);
}
}
throw new Error('Max retry attempts reached');
}
Last updated