Одна из самых запрашиваемых тем, среди подписчиков моего канала Димка Реактнативный - это аутентификация и авторизация в приложении React Native. Поэтому я решил посветить этому вопросу отделный пост и видео. Перед тем как мы начнем кодить, необходимо разобраться с определением Аутентификация/Авторизация.
Аутентификация - это проверка соответствия субъекта и того, за кого он пытается себя выдать, с помощью некой уникальной информации (отпечатки пальцев, цвет радужки, голос и тд.), в простейшем случае - с помощью почты и пароля.
Авторизация - это проверка и определение полномочий на выполнение некоторых действий в соответствии с ранее выполненной аутентификацией
Поехали!!!
react-native init chatARiOS
cd chatAR && react-native run-iosAndroid
cd chatAR && react-native run-androidТак как иконки используются фреймворком AWS Amplify подключаем их согласно этой инструкции 📃.
Проверяем наличие ошибок. Добавляем в App.js
import Icon from 'react-native-vector-icons/FontAwesome5'
const App = () => {
return (
<Fragment>
<Icon name="comments" size={30} color="#900" />
</Fragment>
)
}Регестрируемся согласно этой инструкции 📃 и видеоучебника📺. Внимание!!! Потребуется банковская карта 💳, где должно быть более 1$ 💵 Там же смотрим и ставим Amplify Command Line Interface (CLI)
В корневой директории проекта React Native инициализируем наш бэкенд
amplify initОтвечаем на вопросы:
? Enter a name for the project (yourname)
? Enter a name for the environment test
? Choose your default editor:
❯ Vim (via Terminal, Mac OS only)
? Choose the type of app that you're building (Use arrow keys)
❯ javascript
? What javascript framework are you using (Use arrow keys)
❯ react-native
? Source Directory Path: (/)
? Distribution Directory Path: (/)
? Build Command: (npm run-script build)
? Start Command: (npm run-script start)
? Do you want to use an AWS profile? (Y/n)
? Please choose the profile you want to use
❯ default
Дальше начинается инициализация проекта ⠧ Initializing project in the cloud... Your project has been successfully initialized and connected to the cloud!
Теперь, когда приложение находится в облаке, вы можете добавить некоторые функции, такие как предоставление пользователям возможности зарегистрироваться в нашем приложении и войти в систему.
Командой
amplify add authподключаем плагин аутентификации. Выбираем конфигурацию по умолчанию. Это добавляет конфигурации ресурсов auth локально в ваш каталог ampify/backend/auth.
Do you want to use the default authentication and security configuration? (Use arrow keys)
❯ Default configuration
How do you want users to be able to sign in?
Do you want to configure advanced settings? (Use arrow keys)
❯ No, I am done.
Successfully added resource yourname locally
amplify push✔ All resources are updated in the cloud
Подробности в этой инструкции 📃, а коротко и по прямой так:
yarn add aws-amplify aws-amplify-react-native amazon-cognito-identity-jsСоздаем директорию /src и переносим туда файл App.js, переименовывая его в index.js c этим содержанием
Правим импорт в рутовом /yourname/index.js
- import App from './App'
+ import App from './src'Amplify.configure - конфигурация проекта
Authenticator - Модуль AWS Amplify Authentication предоставляет API-интерфейсы аутентификации и стандартные блоки для разработчиков, которые хотят создавать возможности аутентификации пользователей.
import React from 'react'
import {StatusBar} from 'react-native'
import awsconfig from '../aws-exports'
import Amplify from '@aws-amplify/core'
import {Authenticator} from 'aws-amplify-react-native'
Amplify.configure({
...awsconfig,
Analytics: {
disabled: true,
},
})
const App = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<Authenticator usernameAttributes="email" />
</>
)
}
export default AppЗдесь картинка
const signUpConfig = {
hideAllDefaults: true,
signUpFields: [
{
label: 'Email',
key: 'email',
required: true,
displayOrder: 1,
type: 'string',
},
{
label: 'Password',
key: 'password',
required: true,
displayOrder: 2,
type: 'password',
},
],
}
<Authenticator
usernameAttributes="email"
+ signUpConfig={signUpConfig}
/>
Создаем точку экспорта наших будущих компонентов /src/components/index.js с содержанием
export * from './AmplifyTheme'и соответствено создаем сам файл /src/components/AmplifyTheme.js темы с содержанием
import {StyleSheet} from 'react-native'
export const deepSquidInk = '#152939'
export const linkUnderlayColor = '#FFF'
export const errorIconColor = '#30d0fe'
const AmplifyTheme = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'space-around',
paddingTop: 20,
width: '100%',
backgroundColor: '#FFF',
},
section: {
flex: 1,
width: '100%',
padding: 30,
},
sectionHeader: {
width: '100%',
marginBottom: 32,
},
sectionHeaderText: {
color: deepSquidInk,
fontSize: 20,
fontWeight: '500',
},
sectionFooter: {
width: '100%',
padding: 10,
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 15,
marginBottom: 20,
},
sectionFooterLink: {
fontSize: 14,
color: '#30d0fe',
alignItems: 'baseline',
textAlign: 'center',
},
navBar: {
marginTop: 35,
padding: 15,
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center',
},
navButton: {
marginLeft: 12,
borderRadius: 4,
},
cell: {
flex: 1,
width: '50%',
},
errorRow: {
flexDirection: 'row',
justifyContent: 'center',
},
errorRowText: {
marginLeft: 10,
},
photo: {
width: '100%',
},
album: {
width: '100%',
},
button: {
backgroundColor: '#30d0fe',
alignItems: 'center',
padding: 16,
},
buttonDisabled: {
backgroundColor: '#85E4FF',
alignItems: 'center',
padding: 16,
},
buttonText: {
color: '#fff',
fontSize: 14,
fontWeight: '600',
},
formField: {
marginBottom: 22,
},
input: {
padding: 16,
borderWidth: 1,
borderRadius: 3,
borderColor: '#C4C4C4',
},
inputLabel: {
marginBottom: 8,
},
phoneContainer: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
},
phoneInput: {
flex: 2,
padding: 16,
borderWidth: 1,
borderRadius: 3,
borderColor: '#C4C4C4',
},
picker: {
flex: 1,
height: 44,
},
pickerItem: {
height: 44,
},
})
export {AmplifyTheme}И подключаем тему в компонент Authenticator src/index.js
+import {AmplifyTheme} from './components'
<Authenticator
usernameAttributes="email"
signUpConfig={signUpConfig}
+ theme={AmplifyTheme}
/>
Добавляем экспорт в /src/components/index.js
export * from './Localei18n'и создаем сам файл /src/components/Localei18n.js с содержанием
import {NativeModules, Platform} from 'react-native'
import {I18n} from '@aws-amplify/core'
let langRegionLocale = 'en_US'
// If we have an Android phone
if (Platform.OS === 'android') {
langRegionLocale = NativeModules.I18nManager.localeIdentifier || ''
} else if (Platform.OS === 'ios') {
langRegionLocale = NativeModules.SettingsManager.settings.AppleLocale || ''
}
const authScreenLabels = {
en: {
'Sign Up': 'Create new account',
'Sign Up Account': 'Create a new account',
},
ru: {
'Sign Up': 'Создать аккаунт',
'Forgot Password': 'Забыли пароль?',
'Sign In Account': 'Войдите в систему',
'Enter your email': 'Введите email',
'Enter your password': 'Введите пароль',
Password: 'Пароль',
'Sign In': 'Вход',
'Please Sign In / Sign Up': 'Войти / Создать аккаунт',
'Sign in to your account': 'Войдите в свой аккаунт',
'Create a new account': 'Cоздайте свой аккаунт',
'Confirm a Code': 'Подтвердите код',
'Confirm Sign Up': 'Подтвердите регистрацию',
'Resend code': 'Еще отправить код',
'Back to Sign In': 'Вернуться к входу',
Confirm: 'Подтвердить',
'Confirmation Code': 'Код подтверждения',
'Sign Out': 'Выход',
},
}
// "en_US" -> "en", "es_CL" -> "es", etc
let languageLocale = langRegionLocale.substring(0, 2)
I18n.setLanguage(languageLocale)
I18n.putVocabularies(authScreenLabels)
const Localei18n = () => null
export {Localei18n}И подключаем компонент Localei18n в src/index.js
import {
AmplifyTheme,
+ Localei18n
} from './components'
...
+ <Localei18n />
<Authenticator
usernameAttributes="email"
signUpConfig={signUpConfig}
theme={AmplifyTheme}
/>