UNPKG

react-native-auth2.0-twitch

Version:

A lightweight React Native library for integrating Twitch OAuth 2.0 authentication using Android Custom Tabs. It allows you to securely authenticate users with Twitch by launching an external browser window (Custom Tabs) and handling the OAuth flow withou

81 lines (80 loc) 2.66 kB
"use strict"; // useTwitchAuth.ts import { useEffect, useState, useCallback, useRef } from 'react'; import { Linking, Platform } from 'react-native'; import Auth20Twitch from "./NativeAuth20Twitch.js"; export function useTwitchAuth({ clientId, redirectUri, scopes = ['user:read:email'], onSuccess, onError, forceVerify = false }) { const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const stateRef = useRef(''); function parseQuery(query) { return query.split('&').map(param => param.split('=')).reduce((acc, [key, value]) => { if (key !== undefined) { acc[decodeURIComponent(key)] = decodeURIComponent(value ?? ''); } return acc; }, {}); } useEffect(() => { const handleDeepLink = event => { const url = event.url; const query = url.split('?')[1]; if (!query) return; const params = parseQuery(query); const code = params['code']; const returnedState = params['state']; if (!code) { const err = new Error('No code in URL'); setError(err.message); onError?.(err); return; } if (stateRef.current !== returnedState) { const err = new Error('Invalid state'); setError(err.message); onError?.(err); return; } onSuccess?.(code); }; const subscription = Linking.addEventListener('url', handleDeepLink); return () => subscription.remove(); }, [onSuccess, onError]); const startAuth = useCallback(async () => { setLoading(true); setError(null); const state = Math.random().toString(36).substring(2); stateRef.current = state; const url = `https://id.twitch.tv/oauth2/authorize` + `?client_id=${encodeURIComponent(clientId)}` + `&redirect_uri=${encodeURIComponent(redirectUri)}` + `&response_type=code` + `&scope=${encodeURIComponent(scopes.join(' '))}` + `&state=${encodeURIComponent(state)}` + (forceVerify ? `&force_verify=true` : ''); try { if (Platform.OS === 'android') { const opened = await Auth20Twitch.open(url); if (!opened) { throw new Error('Could not open auth window'); } } else { const supported = await Linking.canOpenURL(url); if (!supported) throw new Error('Cannot open auth URL'); await Linking.openURL(url); } } catch (err) { setError(err.message || 'Unknown error'); onError?.(err); } finally { setLoading(false); } }, [clientId, redirectUri, scopes, forceVerify]); return { startAuth, loading, error }; } //# sourceMappingURL=useTwitchAuth.js.map