video-flow-b/lib/auth.ts
2025-06-30 20:33:53 +08:00

103 lines
2.8 KiB
TypeScript

// Mock Google OAuth configuration
const GOOGLE_CLIENT_ID = '1016208801816-qtvcvki2jobmcin1g4e7u4sotr0p8g3u.apps.googleusercontent.com';
const GOOGLE_REDIRECT_URI = typeof window !== 'undefined'
? 'https://movieflow.api.huiying.video/oauth/callback'
: '';
/**
* Initiates Google OAuth authentication flow
*/
export const signInWithGoogle = () => {
const state = generateOAuthState();
const params = new URLSearchParams({
client_id: GOOGLE_CLIENT_ID,
redirect_uri: GOOGLE_REDIRECT_URI,
response_type: 'code',
scope: 'email profile',
prompt: 'select_account',
state: state,
});
// Redirect to Google's OAuth endpoint
window.location.href = `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
};
/**
* Gets the current user from session storage (mock implementation)
*/
export const getCurrentUser = () => {
if (typeof window === 'undefined') return null;
const userJson = sessionStorage.getItem('currentUser');
if (!userJson) return null;
try {
return JSON.parse(userJson);
} catch (error) {
console.error('Failed to parse user data from session', error);
return null;
}
};
/**
* Handles user login (mock implementation)
*/
export const loginUser = async (email: string, password: string) => {
// This is a mock implementation
// In a real app, you would make an API call to your backend
return new Promise((resolve) => {
setTimeout(() => {
// Mock user data
const user = {
id: '123',
name: 'Test User',
email,
avatar: 'https://i.pravatar.cc/150?u=' + email,
};
// Store in session storage (just for demo purposes)
sessionStorage.setItem('currentUser', JSON.stringify(user));
resolve(user);
}, 1000);
});
};
/**
* Handles user logout
*/
export const logoutUser = () => {
if (typeof window === 'undefined') return;
sessionStorage.removeItem('currentUser');
window.location.href = '/login';
};
/**
* Generates and stores a state parameter for OAuth to prevent CSRF attacks
*/
export const generateOAuthState = () => {
if (typeof window === 'undefined') return '';
// Generate a random string for state
const state = Math.random().toString(36).substring(2, 15);
// Store the state in session storage to validate later
sessionStorage.setItem('oauthState', state);
return state;
};
/**
* Validates the state parameter returned from OAuth to prevent CSRF attacks
*/
export const validateOAuthState = (state: string): boolean => {
if (typeof window === 'undefined') return false;
const storedState = sessionStorage.getItem('oauthState');
// Clean up the stored state regardless of validity
sessionStorage.removeItem('oauthState');
// Validate that the returned state matches what we stored
return state === storedState;
};