在React Native中使用Supabase身份验证
学习如何在React Native中使用Supabase身份验证
1
SQL_EDITOR
1select * from auth.users;
2
创建React应用
使用create-expo-app
命令创建一个React应用。
Terminal
1npx create-expo-app -t expo-template-blank-typescript my-app
3
安装Supabase客户端库
安装supabase-js
及所需依赖项。
Terminal
1cd my-app && npx expo install @supabase/supabase-js @react-native-async-storage/async-storage @rneui/themed react-native-url-polyfill
4
设置登录组件
创建一个辅助文件lib/supabase.ts
,使用您的项目URL和公共API(anon)密钥导出一个Supabase客户端。
lib/supabase.ts
12345678910111213141516171819202122232425262728import { AppState } from 'react-native'import 'react-native-url-polyfill/auto'import AsyncStorage from '@react-native-async-storage/async-storage'import { createClient, processLock } from '@supabase/supabase-js'const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URLconst supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_ANON_KEYexport const supabase = createClient(supabaseUrl, supabaseAnonKey, { auth: { storage: AsyncStorage, autoRefreshToken: true, persistSession: true, detectSessionInUrl: false, lock: processLock, },})// 告诉Supabase Auth在应用处于前台时自动持续刷新会话// 添加此功能后,当用户会话终止时,您将继续收到带有`TOKEN_REFRESHED`或// `SIGNED_OUT`事件的`onAuthStateChange`通知。此功能应仅注册一次。AppState.addEventListener('change', (state) => { if (state === 'active') { supabase.auth.startAutoRefresh() } else { supabase.auth.stopAutoRefresh() }})
5
创建登录组件
让我们设置一个React Native组件来管理登录和注册功能。
components/Auth.tsx
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import React, { useState } from 'react'import { Alert, StyleSheet, View } from 'react-native'import { supabase } from '../lib/supabase'import { Button, Input } from '@rneui/themed'export default function Auth() { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [loading, setLoading] = useState(false) async function signInWithEmail() { setLoading(true) const { error } = await supabase.auth.signInWithPassword({ email: email, password: password, }) if (error) Alert.alert(error.message) setLoading(false) } async function signUpWithEmail() { setLoading(true) const { data: { session }, error, } = await supabase.auth.signUp({ email: email, password: password, }) if (error) Alert.alert(error.message) if (!session) Alert.alert('请检查您的收件箱以完成邮箱验证!') setLoading(false) } return ( <View style={styles.container}> <View style={[styles.verticallySpaced, styles.mt20]}> <Input label="邮箱" leftIcon={{ type: 'font-awesome', name: 'envelope' }} onChangeText={(text) => setEmail(text)} value={email} placeholder="email@address.com" autoCapitalize={'none'} /> </View> <View style={styles.verticallySpaced}> <Input label="密码" leftIcon={{ type: 'font-awesome', name: 'lock' }} onChangeText={(text) => setPassword(text)} value={password} secureTextEntry={true} placeholder="密码" autoCapitalize={'none'} /> </View> <View style={[styles.verticallySpaced, styles.mt20]}> <Button title="登录" disabled={loading} onPress={() => signInWithEmail()} /> </View> <View style={styles.verticallySpaced}> <Button title="注册" disabled={loading} onPress={() => signUpWithEmail()} /> </View> </View> )}const styles = StyleSheet.create({ container: { marginTop: 40, padding: 12, }, verticallySpaced: { paddingTop: 4, paddingBottom: 4, alignSelf: 'stretch', }, mt20: { marginTop: 20, },})
6
将Auth组件添加到应用
将Auth
组件添加到您的App.tsx
文件中。如果用户已登录,则在屏幕上显示用户ID。
App.tsx
123456789101112131415161718192021222324252627import 'react-native-url-polyfill/auto'import { useState, useEffect } from 'react'import { supabase } from './lib/supabase'import Auth from './components/Auth'import { View, Text } from 'react-native'import { Session } from '@supabase/supabase-js'export default function App() { const [session, setSession] = useState<Session | null>(null) useEffect(() => { supabase.auth.getSession().then(({ data: { session } }) => { setSession(session) }) supabase.auth.onAuthStateChange((_event, session) => { setSession(session) }) }, []) return ( <View> <Auth /> {session && session.user && <Text>{session.user.id}</Text>} </View> )}
7
启动应用
启动应用,并按照终端中的指示操作。
Terminal
1npm start