react-native-biometric-auth-complete
v1.0.2
Published
Plugin completo para autenticação biométrica em React Native com templates visuais e CLI de setup
Maintainers
Readme
@azbank/react-native-biometric-auth
🔐 Plugin completo para autenticação biométrica em React Native com Expo.
✨ Setup automático, templates visuais e CLI inteligente
⚡ INSTALAÇÃO SUPER RÁPIDA
1 comando = tudo pronto:
npm install @azbank/react-native-biometric-auth
npx biometric-setupPronto! Sistema de biometria funcionando em 2 minutos.
🎯 O QUE VOCÊ GANHA:
✅ Face ID, Touch ID e Fingerprint funcionando
✅ Setup automático detecta seu tipo de projeto
✅ Templates visuais com design profissional
✅ Modificação automática das telas existentes
✅ Configuração de permissões automática
✅ Documentação completa e exemplos práticos
🚀 INSTALAÇÃO MANUAL (se preferir)
# Instalar plugin
npm install @azbank/react-native-biometric-auth
# Instalar dependências (feito automaticamente pelo CLI)
npx expo install expo-local-authentication crypto-js📋 Configuração
1. Criar Storage Adapter
Primeiro, crie um adapter para o seu sistema de armazenamento:
// MyStorageAdapter.js
import AsyncStorage from '@react-native-async-storage/async-storage';
const MyStorageAdapter = {
async setBiometricEnabled(enabled) {
await AsyncStorage.setItem('biometric_enabled', enabled ? 'true' : 'false');
return true;
},
async getBiometricEnabled() {
const value = await AsyncStorage.getItem('biometric_enabled');
return value === 'true';
},
async setBiometricCredentials(encryptedCredentials) {
await AsyncStorage.setItem('biometric_credentials', encryptedCredentials);
return true;
},
async getBiometricCredentials() {
return await AsyncStorage.getItem('biometric_credentials');
},
async removeBiometricCredentials() {
await AsyncStorage.removeItem('biometric_credentials');
return true;
}
};
export default MyStorageAdapter;2. Configurar o Plugin
// biometricConfig.js
import MyStorageAdapter from './MyStorageAdapter';
import { loginWithMyAPI, saveMySession, fetchMyProfile } from './myAuthSystem';
export const biometricConfig = {
// Funções específicas do seu projeto (OBRIGATÓRIAS)
loginFunction: loginWithMyAPI,
saveSessionFunction: saveMySession,
fetchProfileFunction: fetchMyProfile,
// Adapter de armazenamento (OBRIGATÓRIO)
storageAdapter: MyStorageAdapter,
// Customização visual (OPCIONAL)
theme: {
primaryColor: '#003f36',
accentColor: '#0dbc7c',
backgroundColor: '#ffffff',
textColor: '#333333',
errorColor: '#d32f2f'
},
// Textos personalizados (OPCIONAL)
texts: {
setupModalTitle: 'Ativar {biometricType}?',
setupModalDescription: 'Configure {biometricType} para login rápido e seguro.',
setupModalConfirm: 'Ativar {biometricType}',
setupModalCancel: 'Agora não',
loginButtonText: 'Entrar com {biometricType}',
authenticatingText: 'Autenticando...',
promptMessage: 'Use sua biometria para fazer login',
benefits: [
'Login mais rápido',
'Maior segurança',
'Mais praticidade'
]
},
// Configurações de segurança (OPCIONAL)
security: {
maxDevices: 3,
expirationDays: 30,
encryptionKey: 'my_project_biometric_key_2024'
}
};🎯 Uso Básico
Hook Principal
import { useBiometricAuth } from '@azbank/react-native-biometric-auth';
import { biometricConfig } from './biometricConfig';
const MyScreen = () => {
const {
isAvailable,
isEnabled,
biometricType,
loading,
enableBiometric,
authenticateWithBiometric,
disableBiometric
} = useBiometricAuth(biometricConfig);
// Usar as funções conforme necessário
};📱 Integração em Telas
1. Tela de Login (LoginPasswordScreen)
import { BiometricIntegration } from '@azbank/react-native-biometric-auth';
import { biometricConfig } from './biometricConfig';
const LoginPasswordScreen = ({ route, navigation }) => {
const [password, setPassword] = useState('');
const { documentNumber } = route.params;
const biometric = BiometricIntegration.useLoginIntegration(biometricConfig);
const handleLogin = async () => {
try {
// Seu login normal aqui
const loginResult = await myLoginFunction(documentNumber, password);
if (loginResult.success) {
// Oferecer configuração biométrica
const offered = await biometric.offerBiometricSetup(documentNumber, password);
if (!offered) {
// Se não ofereceu modal, navegar normalmente
navigation.navigate('Dashboard');
}
// Se ofereceu modal, navegação será feita no onSuccess do modal
}
} catch (error) {
// Tratar erro
}
};
return (
<View>
{/* Sua tela de login normal */}
<TextInput value={password} onChangeText={setPassword} />
<Button title="Entrar" onPress={handleLogin} />
{/* Modal de configuração biométrica */}
<biometric.SetupModal
onSuccess={() => navigation.navigate('Dashboard')}
/>
</View>
);
};2. Tela de Welcome
import { BiometricIntegration } from '@azbank/react-native-biometric-auth';
import { biometricConfig } from './biometricConfig';
const WelcomeScreen = ({ navigation }) => {
const biometric = BiometricIntegration.useWelcomeIntegration(biometricConfig);
const handleBiometricLogin = async () => {
const result = await biometric.handleBiometricLogin(
// onSuccess
() => navigation.navigate('Dashboard'),
// onError
(error) => alert(error)
);
};
return (
<View>
<Button title="Entrar" onPress={() => navigation.navigate('Login')} />
<Button title="Criar Conta" onPress={() => navigation.navigate('Register')} />
{/* Botão biométrico (só aparece se disponível) */}
<biometric.LoginButton onPress={handleBiometricLogin} />
</View>
);
};3. Tela de Configurações
import { BiometricIntegration } from '@azbank/react-native-biometric-auth';
import { biometricConfig } from './biometricConfig';
const SettingsScreen = () => {
const biometric = BiometricIntegration.useSettingsIntegration(biometricConfig);
const settingsInfo = biometric.getSettingsInfo();
const handleToggleBiometric = async () => {
if (biometric.isEnabled) {
await biometric.disableBiometric();
} else {
// Solicitar credenciais do usuário
const cpf = await promptForCPF();
const password = await promptForPassword();
await biometric.enableBiometric(cpf, password);
}
};
return (
<View>
<Text>Biometria: {settingsInfo.statusText}</Text>
{settingsInfo.isAvailable && (
<Switch
value={biometric.isEnabled}
onValueChange={handleToggleBiometric}
/>
)}
</View>
);
};🔧 Configuração iOS
Adicione a permissão no app.json:
{
"expo": {
"ios": {
"infoPlist": {
"NSFaceIDUsageDescription": "Use Face ID para login rápido e seguro na sua conta."
}
}
}
}📚 API Reference
useBiometricAuth(config)
Hook principal que retorna:
Estados:
isAvailable: boolean- Se biometria está disponível no dispositivoisEnabled: boolean- Se biometria está configuradabiometricType: string- Tipo de biometria ('Face ID', 'Touch ID', etc.)loading: boolean- Estado de carregamento
Funções:
enableBiometric(cpf, password)- Ativa biometriaauthenticateWithBiometric()- Faz login biométricodisableBiometric()- Desativa biometriashouldOfferSetup()- Verifica se deve oferecer configuração
BiometricIntegration
Helpers para integração:
useLoginIntegration(config)- Para telas de loginuseWelcomeIntegration(config)- Para telas de welcomeuseSettingsIntegration(config)- Para telas de configurações
🛡️ Segurança
- Credenciais são criptografadas com AES
- Expiração automática configurável
- Suporte a múltiplos dispositivos (com limite)
- Limpeza automática em logout
📝 Exemplo Completo
Veja a pasta examples/ para implementações completas em diferentes cenários.
🤝 Contribuição
- Fork o projeto
- Crie uma branch para sua feature
- Commit suas mudanças
- Push para a branch
- Abra um Pull Request
📄 Licença
MIT © AZ Bank
