mirror of
https://github.com/pezkuwichain/pezkuwi-p2p-mobile.git
synced 2026-06-19 04:11:18 +00:00
feat: mobile-optimized P2P with URL param auth support
- Remove blockchain dependencies (@pezkuwi/api) - Use internal ledger for P2P trades - Add URL param authentication from mini-app redirect - State-based navigation instead of react-router-dom - Simplified deposit/withdraw modals
This commit is contained in:
+239
-270
@@ -1,309 +1,278 @@
|
||||
import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
|
||||
import { createContext, useContext, useState, useEffect, useCallback, type ReactNode } from 'react';
|
||||
import { supabase } from '@/lib/supabase';
|
||||
import { User } from '@supabase/supabase-js';
|
||||
import { isMobileApp, getNativeWalletAddress, getNativeAccountName } from '@/lib/mobile-bridge';
|
||||
|
||||
// Session timeout configuration
|
||||
const SESSION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
|
||||
const ACTIVITY_CHECK_INTERVAL_MS = 60 * 1000; // Check every 1 minute
|
||||
const LAST_ACTIVITY_KEY = 'last_activity_timestamp';
|
||||
const REMEMBER_ME_KEY = 'remember_me';
|
||||
// Telegram WebApp types
|
||||
declare global {
|
||||
interface Window {
|
||||
Telegram?: {
|
||||
WebApp: {
|
||||
initData: string;
|
||||
initDataUnsafe: {
|
||||
user?: {
|
||||
id: number;
|
||||
first_name: string;
|
||||
last_name?: string;
|
||||
username?: string;
|
||||
language_code?: string;
|
||||
photo_url?: string;
|
||||
};
|
||||
auth_date: number;
|
||||
hash: string;
|
||||
};
|
||||
ready: () => void;
|
||||
expand: () => void;
|
||||
close: () => void;
|
||||
MainButton: {
|
||||
text: string;
|
||||
show: () => void;
|
||||
hide: () => void;
|
||||
onClick: (callback: () => void) => void;
|
||||
};
|
||||
HapticFeedback: {
|
||||
impactOccurred: (style: 'light' | 'medium' | 'heavy' | 'rigid' | 'soft') => void;
|
||||
notificationOccurred: (type: 'error' | 'success' | 'warning') => void;
|
||||
selectionChanged: () => void;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
interface TelegramUser {
|
||||
id: number;
|
||||
first_name: string;
|
||||
last_name?: string;
|
||||
username?: string;
|
||||
photo_url?: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string; // Supabase user ID
|
||||
telegram_id: number;
|
||||
telegram_username?: string;
|
||||
display_name: string;
|
||||
avatar_url?: string;
|
||||
wallet_address?: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
isAdmin: boolean;
|
||||
signIn: (email: string, password: string, rememberMe?: boolean) => Promise<{ error: Error | null }>;
|
||||
signUp: (email: string, password: string, username: string, referralCode?: string) => Promise<{ error: Error | null }>;
|
||||
signOut: () => Promise<void>;
|
||||
checkAdminStatus: () => Promise<boolean>;
|
||||
telegramUser: TelegramUser | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
error: string | null;
|
||||
login: () => Promise<void>;
|
||||
logout: () => void;
|
||||
linkWallet: (address: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
const AuthContext = createContext<AuthContextType | null>(null);
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [isAdmin, setIsAdmin] = useState(false);
|
||||
const [telegramUser, setTelegramUser] = useState<TelegramUser | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// ========================================
|
||||
// SESSION TIMEOUT MANAGEMENT
|
||||
// ========================================
|
||||
|
||||
// Update last activity timestamp
|
||||
const updateLastActivity = useCallback(() => {
|
||||
|
||||
localStorage.setItem(LAST_ACTIVITY_KEY, Date.now().toString());
|
||||
// Get Telegram user from WebApp
|
||||
const getTelegramUser = useCallback((): TelegramUser | null => {
|
||||
const tg = window.Telegram?.WebApp;
|
||||
if (!tg?.initDataUnsafe?.user) {
|
||||
return null;
|
||||
}
|
||||
return tg.initDataUnsafe.user;
|
||||
}, []);
|
||||
|
||||
const signOut = useCallback(async () => {
|
||||
setIsAdmin(false);
|
||||
setUser(null);
|
||||
localStorage.removeItem(LAST_ACTIVITY_KEY);
|
||||
localStorage.removeItem(REMEMBER_ME_KEY);
|
||||
await supabase.auth.signOut();
|
||||
}, []);
|
||||
|
||||
// Check if session has timed out
|
||||
const checkSessionTimeout = useCallback(async () => {
|
||||
if (!user) return;
|
||||
|
||||
// Skip timeout check if "Remember Me" is enabled
|
||||
const rememberMe = localStorage.getItem(REMEMBER_ME_KEY);
|
||||
if (rememberMe === 'true') {
|
||||
return; // Don't timeout if user chose to be remembered
|
||||
}
|
||||
|
||||
const lastActivity = localStorage.getItem(LAST_ACTIVITY_KEY);
|
||||
if (!lastActivity) {
|
||||
updateLastActivity();
|
||||
return;
|
||||
}
|
||||
|
||||
const lastActivityTime = parseInt(lastActivity, 10);
|
||||
const now = Date.now();
|
||||
const inactiveTime = now - lastActivityTime;
|
||||
|
||||
if (inactiveTime >= SESSION_TIMEOUT_MS) {
|
||||
if (import.meta.env.DEV) console.log('⏱️ Session timeout - logging out due to inactivity');
|
||||
await signOut();
|
||||
}
|
||||
}, [user, updateLastActivity, signOut]);
|
||||
|
||||
// Setup activity listeners
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
// Update activity on user interactions
|
||||
const activityEvents = ['mousedown', 'keydown', 'scroll', 'touchstart'];
|
||||
|
||||
const handleActivity = () => {
|
||||
updateLastActivity();
|
||||
|
||||
|
||||
};
|
||||
|
||||
// Register event listeners
|
||||
activityEvents.forEach((event) => {
|
||||
window.addEventListener(event, handleActivity);
|
||||
});
|
||||
|
||||
// Initial activity timestamp
|
||||
updateLastActivity();
|
||||
|
||||
|
||||
|
||||
// Check for timeout periodically
|
||||
const timeoutChecker = setInterval(checkSessionTimeout, ACTIVITY_CHECK_INTERVAL_MS);
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
activityEvents.forEach((event) => {
|
||||
window.removeEventListener(event, handleActivity);
|
||||
});
|
||||
clearInterval(timeoutChecker);
|
||||
};
|
||||
}, [user, updateLastActivity, checkSessionTimeout]);
|
||||
|
||||
|
||||
const checkAdminStatus = useCallback(async () => {
|
||||
// Admin wallet whitelist (blockchain-based auth)
|
||||
const ADMIN_WALLETS = [
|
||||
'5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', // Founder (original)
|
||||
'5DFwqK698vL4gXHEcanaewnAqhxJ2rjhAogpSTHw3iwGDwd3', // Founder delegate (initial KYC member)
|
||||
'5GgTgG9sRmPQAYU1RsTejZYnZRjwzKZKWD3awtuqjHioki45', // Founder (current dev wallet)
|
||||
];
|
||||
// Login with Telegram
|
||||
const login = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// PRIMARY: Check wallet-based admin (blockchain auth)
|
||||
const connectedWallet = localStorage.getItem('selectedWallet');
|
||||
if (import.meta.env.DEV) console.log('🔍 Admin check - Connected wallet:', connectedWallet);
|
||||
if (import.meta.env.DEV) console.log('🔍 Admin check - Whitelist:', ADMIN_WALLETS);
|
||||
const tg = window.Telegram?.WebApp;
|
||||
|
||||
if (connectedWallet && ADMIN_WALLETS.includes(connectedWallet)) {
|
||||
if (import.meta.env.DEV) console.log('✅ Admin access granted (wallet-based)');
|
||||
setIsAdmin(true);
|
||||
return true;
|
||||
if (!tg?.initData) {
|
||||
throw new Error('Telegram WebApp not available. Open from Telegram.');
|
||||
}
|
||||
|
||||
// SECONDARY: Check Supabase admin_roles (if wallet not in whitelist)
|
||||
const { data: { user } } = await supabase.auth.getUser();
|
||||
if (user) {
|
||||
const { data, error } = await supabase
|
||||
.from('admin_roles')
|
||||
.select('role')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle();
|
||||
// Call Supabase Edge Function to verify initData and get/create user
|
||||
const { data, error: fnError } = await supabase.functions.invoke('telegram-auth', {
|
||||
body: { initData: tg.initData }
|
||||
});
|
||||
|
||||
if (!error && data && ['admin', 'super_admin'].includes(data.role)) {
|
||||
if (import.meta.env.DEV) console.log('✅ Admin access granted (Supabase-based)');
|
||||
setIsAdmin(true);
|
||||
return true;
|
||||
}
|
||||
if (fnError) throw fnError;
|
||||
|
||||
if (!data?.user) {
|
||||
throw new Error('Authentication failed');
|
||||
}
|
||||
|
||||
if (import.meta.env.DEV) console.log('❌ Admin access denied');
|
||||
setIsAdmin(false);
|
||||
return false;
|
||||
setUser(data.user);
|
||||
setTelegramUser(getTelegramUser());
|
||||
|
||||
// Store session token if provided
|
||||
if (data.session_token) {
|
||||
localStorage.setItem('p2p_session', data.session_token);
|
||||
}
|
||||
|
||||
window.Telegram?.WebApp.HapticFeedback.notificationOccurred('success');
|
||||
} catch (err) {
|
||||
if (import.meta.env.DEV) console.error('Admin check error:', err);
|
||||
setIsAdmin(false);
|
||||
const message = err instanceof Error ? err.message : 'Login failed';
|
||||
setError(message);
|
||||
window.Telegram?.WebApp.HapticFeedback.notificationOccurred('error');
|
||||
console.error('Login error:', err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [getTelegramUser]);
|
||||
|
||||
// Logout
|
||||
const logout = useCallback(() => {
|
||||
setUser(null);
|
||||
localStorage.removeItem('p2p_session');
|
||||
window.Telegram?.WebApp.HapticFeedback.impactOccurred('medium');
|
||||
}, []);
|
||||
|
||||
// Link wallet address
|
||||
const linkWallet = useCallback(async (address: string) => {
|
||||
if (!user) throw new Error('Not authenticated');
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('p2p_users')
|
||||
.update({ wallet_address: address })
|
||||
.eq('telegram_id', user.telegram_id);
|
||||
|
||||
if (updateError) throw updateError;
|
||||
|
||||
setUser(prev => prev ? { ...prev, wallet_address: address } : null);
|
||||
window.Telegram?.WebApp.HapticFeedback.notificationOccurred('success');
|
||||
}, [user]);
|
||||
|
||||
// Login via URL params (from mini-app redirect)
|
||||
const loginViaParams = useCallback(async () => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const tgId = params.get('tg_id');
|
||||
const wallet = params.get('wallet');
|
||||
const from = params.get('from');
|
||||
const ts = params.get('ts');
|
||||
|
||||
if (!tgId || from !== 'miniapp') {
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Setup native mobile wallet if running in mobile app
|
||||
const setupMobileWallet = useCallback(() => {
|
||||
if (isMobileApp()) {
|
||||
const nativeAddress = getNativeWalletAddress();
|
||||
const nativeAccountName = getNativeAccountName();
|
||||
|
||||
if (nativeAddress) {
|
||||
// Store native wallet address for admin checks and wallet operations
|
||||
localStorage.setItem('selectedWallet', nativeAddress);
|
||||
if (nativeAccountName) {
|
||||
localStorage.setItem('selectedWalletName', nativeAccountName);
|
||||
}
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Mobile] Native wallet detected:', nativeAddress);
|
||||
}
|
||||
// Dispatch wallet change event
|
||||
window.dispatchEvent(new Event('walletChanged'));
|
||||
// Validate timestamp (not older than 5 minutes)
|
||||
if (ts) {
|
||||
const timestamp = parseInt(ts);
|
||||
const now = Date.now();
|
||||
if (now - timestamp > 5 * 60 * 1000) {
|
||||
console.warn('URL params expired');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Verify with backend and get/create user
|
||||
const { data, error: fnError } = await supabase.functions.invoke('telegram-auth', {
|
||||
body: {
|
||||
telegram_id: parseInt(tgId),
|
||||
wallet_address: wallet || undefined,
|
||||
from_miniapp: true
|
||||
}
|
||||
});
|
||||
|
||||
if (fnError) throw fnError;
|
||||
|
||||
if (!data?.user) {
|
||||
throw new Error('Authentication failed');
|
||||
}
|
||||
|
||||
setUser(data.user);
|
||||
|
||||
// Store session token
|
||||
if (data.session_token) {
|
||||
localStorage.setItem('p2p_session', data.session_token);
|
||||
}
|
||||
|
||||
// Clear URL params after successful login
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error('URL param login error:', err);
|
||||
return false;
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Auto-login on mount
|
||||
useEffect(() => {
|
||||
// Setup mobile wallet first
|
||||
setupMobileWallet();
|
||||
const initAuth = async () => {
|
||||
const tg = window.Telegram?.WebApp;
|
||||
|
||||
// Check active sessions and sets the user
|
||||
supabase.auth.getSession().then(({ data: { session } }) => {
|
||||
setUser(session?.user ?? null);
|
||||
checkAdminStatus(); // Check admin status regardless of Supabase session
|
||||
setLoading(false);
|
||||
}).catch(() => {
|
||||
// If Supabase is not available, still check wallet-based admin
|
||||
checkAdminStatus();
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
// Listen for changes on auth state
|
||||
const { data: { subscription } } = supabase.auth.onAuthStateChange((_event, session) => {
|
||||
setUser(session?.user ?? null);
|
||||
checkAdminStatus(); // Check admin status on auth change
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
// Listen for wallet changes (from PezkuwiContext or native bridge)
|
||||
const handleWalletChange = () => {
|
||||
checkAdminStatus();
|
||||
};
|
||||
window.addEventListener('walletChanged', handleWalletChange);
|
||||
|
||||
// Listen for native bridge ready event (mobile app)
|
||||
const handleNativeReady = () => {
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('[Mobile] Native bridge ready');
|
||||
}
|
||||
setupMobileWallet();
|
||||
checkAdminStatus();
|
||||
};
|
||||
window.addEventListener('pezkuwi-native-ready', handleNativeReady);
|
||||
|
||||
return () => {
|
||||
subscription.unsubscribe();
|
||||
window.removeEventListener('walletChanged', handleWalletChange);
|
||||
window.removeEventListener('pezkuwi-native-ready', handleNativeReady);
|
||||
};
|
||||
}, [checkAdminStatus, setupMobileWallet]);
|
||||
|
||||
const signIn = async (email: string, password: string, rememberMe: boolean = false) => {
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email,
|
||||
password,
|
||||
});
|
||||
|
||||
if (!error && data.user) {
|
||||
// Store remember me preference
|
||||
if (rememberMe) {
|
||||
localStorage.setItem(REMEMBER_ME_KEY, 'true');
|
||||
} else {
|
||||
localStorage.removeItem(REMEMBER_ME_KEY);
|
||||
}
|
||||
await checkAdminStatus();
|
||||
}
|
||||
|
||||
return { error };
|
||||
} catch {
|
||||
return {
|
||||
error: {
|
||||
message: 'Authentication service unavailable. Please try again later.'
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const signUp = async (email: string, password: string, username: string, referralCode?: string) => {
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signUp({
|
||||
email,
|
||||
password,
|
||||
options: {
|
||||
data: {
|
||||
username,
|
||||
referral_code: referralCode || null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!error && data.user) {
|
||||
// Create profile in profiles table with referral code
|
||||
await supabase.from('profiles').insert({
|
||||
id: data.user.id,
|
||||
username,
|
||||
email,
|
||||
referred_by: referralCode || null,
|
||||
});
|
||||
|
||||
// If there's a referral code, track it
|
||||
if (referralCode) {
|
||||
// You can add logic here to reward the referrer
|
||||
// For example, update their referral count or add rewards
|
||||
if (import.meta.env.DEV) console.log(`User registered with referral code: ${referralCode}`);
|
||||
// Check for existing session first
|
||||
const sessionToken = localStorage.getItem('p2p_session');
|
||||
if (sessionToken) {
|
||||
try {
|
||||
const { data, error } = await supabase.functions.invoke('telegram-auth', {
|
||||
body: { sessionToken }
|
||||
});
|
||||
if (!error && data?.user) {
|
||||
setUser(data.user);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
localStorage.removeItem('p2p_session');
|
||||
}
|
||||
}
|
||||
|
||||
return { error };
|
||||
} catch {
|
||||
return {
|
||||
error: {
|
||||
message: 'Registration service unavailable. Please try again later.'
|
||||
}
|
||||
};
|
||||
}
|
||||
// Try Telegram WebApp auth
|
||||
if (tg?.initData) {
|
||||
tg.ready();
|
||||
tg.expand();
|
||||
setTelegramUser(getTelegramUser());
|
||||
await login();
|
||||
return;
|
||||
}
|
||||
|
||||
// Try URL params auth (from mini-app redirect)
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get('from') === 'miniapp' && params.get('tg_id')) {
|
||||
const success = await loginViaParams();
|
||||
if (success) return;
|
||||
}
|
||||
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
initAuth();
|
||||
}, [getTelegramUser, login, loginViaParams]);
|
||||
|
||||
const value: AuthContextType = {
|
||||
user,
|
||||
telegramUser,
|
||||
isLoading,
|
||||
isAuthenticated: !!user,
|
||||
error,
|
||||
login,
|
||||
logout,
|
||||
linkWallet
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{
|
||||
user,
|
||||
loading,
|
||||
isAdmin,
|
||||
signIn,
|
||||
signUp,
|
||||
signOut,
|
||||
checkAdminStatus
|
||||
}}>
|
||||
<AuthContext.Provider value={value}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (!context) {
|
||||
throw new Error('useAuth must be used within AuthProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user