Application Android et IOS pour l'amicale des élèves
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LoginScreen.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // @flow
  2. import * as React from 'react';
  3. import {Image, KeyboardAvoidingView, StyleSheet, View} from 'react-native';
  4. import {
  5. Button,
  6. Card,
  7. HelperText,
  8. TextInput,
  9. withTheme,
  10. } from 'react-native-paper';
  11. import i18n from 'i18n-js';
  12. import {StackNavigationProp} from '@react-navigation/stack';
  13. import LinearGradient from 'react-native-linear-gradient';
  14. import ConnectionManager from '../../managers/ConnectionManager';
  15. import ErrorDialog from '../../components/Dialogs/ErrorDialog';
  16. import type {CustomThemeType} from '../../managers/ThemeManager';
  17. import AsyncStorageManager from '../../managers/AsyncStorageManager';
  18. import AvailableWebsites from '../../constants/AvailableWebsites';
  19. import {MASCOT_STYLE} from '../../components/Mascot/Mascot';
  20. import MascotPopup from '../../components/Mascot/MascotPopup';
  21. import CollapsibleScrollView from '../../components/Collapsible/CollapsibleScrollView';
  22. type PropsType = {
  23. navigation: StackNavigationProp,
  24. route: {params: {nextScreen: string}},
  25. theme: CustomThemeType,
  26. };
  27. type StateType = {
  28. email: string,
  29. password: string,
  30. isEmailValidated: boolean,
  31. isPasswordValidated: boolean,
  32. loading: boolean,
  33. dialogVisible: boolean,
  34. dialogError: number,
  35. mascotDialogVisible: boolean,
  36. };
  37. const ICON_AMICALE = require('../../../assets/amicale.png');
  38. const RESET_PASSWORD_PATH = 'https://www.amicale-insat.fr/password/reset';
  39. const emailRegex = /^.+@.+\..+$/;
  40. const styles = StyleSheet.create({
  41. container: {
  42. flex: 1,
  43. },
  44. card: {
  45. marginTop: 'auto',
  46. marginBottom: 'auto',
  47. },
  48. header: {
  49. fontSize: 36,
  50. marginBottom: 48,
  51. },
  52. textInput: {},
  53. btnContainer: {
  54. marginTop: 5,
  55. marginBottom: 10,
  56. },
  57. });
  58. class LoginScreen extends React.Component<PropsType, StateType> {
  59. onEmailChange: (value: string) => void;
  60. onPasswordChange: (value: string) => void;
  61. passwordInputRef: {current: null | TextInput};
  62. nextScreen: string | null;
  63. constructor(props: PropsType) {
  64. super(props);
  65. this.passwordInputRef = React.createRef();
  66. this.onEmailChange = (value: string) => {
  67. this.onInputChange(true, value);
  68. };
  69. this.onPasswordChange = (value: string) => {
  70. this.onInputChange(false, value);
  71. };
  72. props.navigation.addListener('focus', this.onScreenFocus);
  73. this.state = {
  74. email: '',
  75. password: '',
  76. isEmailValidated: false,
  77. isPasswordValidated: false,
  78. loading: false,
  79. dialogVisible: false,
  80. dialogError: 0,
  81. mascotDialogVisible: AsyncStorageManager.getBool(
  82. AsyncStorageManager.PREFERENCES.loginShowMascot.key,
  83. ),
  84. };
  85. }
  86. onScreenFocus = () => {
  87. this.handleNavigationParams();
  88. };
  89. /**
  90. * Navigates to the Amicale website screen with the reset password link as navigation parameters
  91. */
  92. onResetPasswordClick = () => {
  93. const {navigation} = this.props;
  94. navigation.navigate('website', {
  95. host: AvailableWebsites.websites.AMICALE,
  96. path: RESET_PASSWORD_PATH,
  97. title: i18n.t('screens.websites.amicale'),
  98. });
  99. };
  100. /**
  101. * Called when the user input changes in the email or password field.
  102. * This saves the new value in the State and disabled input validation (to prevent errors to show while typing)
  103. *
  104. * @param isEmail True if the field is the email field
  105. * @param value The new field value
  106. */
  107. onInputChange(isEmail: boolean, value: string) {
  108. if (isEmail) {
  109. this.setState({
  110. email: value,
  111. isEmailValidated: false,
  112. });
  113. } else {
  114. this.setState({
  115. password: value,
  116. isPasswordValidated: false,
  117. });
  118. }
  119. }
  120. /**
  121. * Focuses the password field when the email field is done
  122. *
  123. * @returns {*}
  124. */
  125. onEmailSubmit = () => {
  126. if (this.passwordInputRef.current != null)
  127. this.passwordInputRef.current.focus();
  128. };
  129. /**
  130. * Called when the user clicks on login or finishes to type his password.
  131. *
  132. * Checks if we should allow the user to login,
  133. * then makes the login request and enters a loading state until the request finishes
  134. *
  135. */
  136. onSubmit = () => {
  137. const {email, password} = this.state;
  138. if (this.shouldEnableLogin()) {
  139. this.setState({loading: true});
  140. ConnectionManager.getInstance()
  141. .connect(email, password)
  142. .then(this.handleSuccess)
  143. .catch(this.showErrorDialog)
  144. .finally(() => {
  145. this.setState({loading: false});
  146. });
  147. }
  148. };
  149. /**
  150. * Gets the form input
  151. *
  152. * @returns {*}
  153. */
  154. getFormInput(): React.Node {
  155. const {email, password} = this.state;
  156. return (
  157. <View>
  158. <TextInput
  159. label={i18n.t('screens.login.email')}
  160. mode="outlined"
  161. value={email}
  162. onChangeText={this.onEmailChange}
  163. onBlur={this.validateEmail}
  164. onSubmitEditing={this.onEmailSubmit}
  165. error={this.shouldShowEmailError()}
  166. textContentType="emailAddress"
  167. autoCapitalize="none"
  168. autoCompleteType="email"
  169. autoCorrect={false}
  170. keyboardType="email-address"
  171. returnKeyType="next"
  172. secureTextEntry={false}
  173. />
  174. <HelperText type="error" visible={this.shouldShowEmailError()}>
  175. {i18n.t('screens.login.emailError')}
  176. </HelperText>
  177. <TextInput
  178. ref={this.passwordInputRef}
  179. label={i18n.t('screens.login.password')}
  180. mode="outlined"
  181. value={password}
  182. onChangeText={this.onPasswordChange}
  183. onBlur={this.validatePassword}
  184. onSubmitEditing={this.onSubmit}
  185. error={this.shouldShowPasswordError()}
  186. textContentType="password"
  187. autoCapitalize="none"
  188. autoCompleteType="password"
  189. autoCorrect={false}
  190. keyboardType="default"
  191. returnKeyType="done"
  192. secureTextEntry
  193. />
  194. <HelperText type="error" visible={this.shouldShowPasswordError()}>
  195. {i18n.t('screens.login.passwordError')}
  196. </HelperText>
  197. </View>
  198. );
  199. }
  200. /**
  201. * Gets the card containing the input form
  202. * @returns {*}
  203. */
  204. getMainCard(): React.Node {
  205. const {props, state} = this;
  206. return (
  207. <View style={styles.card}>
  208. <Card.Title
  209. title={i18n.t('screens.login.title')}
  210. titleStyle={{color: '#fff'}}
  211. subtitle={i18n.t('screens.login.subtitle')}
  212. subtitleStyle={{color: '#fff'}}
  213. left={({size}: {size: number}): React.Node => (
  214. <Image
  215. source={ICON_AMICALE}
  216. style={{
  217. width: size,
  218. height: size,
  219. }}
  220. />
  221. )}
  222. />
  223. <Card.Content>
  224. {this.getFormInput()}
  225. <Card.Actions style={{flexWrap: 'wrap'}}>
  226. <Button
  227. icon="lock-question"
  228. mode="contained"
  229. onPress={this.onResetPasswordClick}
  230. color={props.theme.colors.warning}
  231. style={{marginRight: 'auto', marginBottom: 20}}>
  232. {i18n.t('screens.login.resetPassword')}
  233. </Button>
  234. <Button
  235. icon="send"
  236. mode="contained"
  237. disabled={!this.shouldEnableLogin()}
  238. loading={state.loading}
  239. onPress={this.onSubmit}
  240. style={{marginLeft: 'auto'}}>
  241. {i18n.t('screens.login.title')}
  242. </Button>
  243. </Card.Actions>
  244. <Card.Actions>
  245. <Button
  246. icon="help-circle"
  247. mode="contained"
  248. onPress={this.showMascotDialog}
  249. style={{
  250. marginLeft: 'auto',
  251. marginRight: 'auto',
  252. }}>
  253. {i18n.t('screens.login.mascotDialog.title')}
  254. </Button>
  255. </Card.Actions>
  256. </Card.Content>
  257. </View>
  258. );
  259. }
  260. /**
  261. * The user has unfocused the input, his email is ready to be validated
  262. */
  263. validateEmail = () => {
  264. this.setState({isEmailValidated: true});
  265. };
  266. /**
  267. * The user has unfocused the input, his password is ready to be validated
  268. */
  269. validatePassword = () => {
  270. this.setState({isPasswordValidated: true});
  271. };
  272. hideMascotDialog = () => {
  273. AsyncStorageManager.set(
  274. AsyncStorageManager.PREFERENCES.loginShowMascot.key,
  275. false,
  276. );
  277. this.setState({mascotDialogVisible: false});
  278. };
  279. showMascotDialog = () => {
  280. this.setState({mascotDialogVisible: true});
  281. };
  282. /**
  283. * Shows an error dialog with the corresponding login error
  284. *
  285. * @param error The error given by the login request
  286. */
  287. showErrorDialog = (error: number) => {
  288. this.setState({
  289. dialogVisible: true,
  290. dialogError: error,
  291. });
  292. };
  293. hideErrorDialog = () => {
  294. this.setState({dialogVisible: false});
  295. };
  296. /**
  297. * Navigates to the screen specified in navigation parameters or simply go back tha stack.
  298. * Saves in user preferences to not show the login banner again.
  299. */
  300. handleSuccess = () => {
  301. const {navigation} = this.props;
  302. // Do not show the home login banner again
  303. AsyncStorageManager.set(
  304. AsyncStorageManager.PREFERENCES.homeShowMascot.key,
  305. false,
  306. );
  307. if (this.nextScreen == null) navigation.goBack();
  308. else navigation.replace(this.nextScreen);
  309. };
  310. /**
  311. * Saves the screen to navigate to after a successful login if one was provided in navigation parameters
  312. */
  313. handleNavigationParams() {
  314. const {route} = this.props;
  315. if (route.params != null) {
  316. if (route.params.nextScreen != null)
  317. this.nextScreen = route.params.nextScreen;
  318. else this.nextScreen = null;
  319. }
  320. }
  321. /**
  322. * Checks if the entered email is valid (matches the regex)
  323. *
  324. * @returns {boolean}
  325. */
  326. isEmailValid(): boolean {
  327. const {email} = this.state;
  328. return emailRegex.test(email);
  329. }
  330. /**
  331. * Checks if we should tell the user his email is invalid.
  332. * We should only show this if his email is invalid and has been checked when un-focusing the input
  333. *
  334. * @returns {boolean|boolean}
  335. */
  336. shouldShowEmailError(): boolean {
  337. const {isEmailValidated} = this.state;
  338. return isEmailValidated && !this.isEmailValid();
  339. }
  340. /**
  341. * Checks if the user has entered a password
  342. *
  343. * @returns {boolean}
  344. */
  345. isPasswordValid(): boolean {
  346. const {password} = this.state;
  347. return password !== '';
  348. }
  349. /**
  350. * Checks if we should tell the user his password is invalid.
  351. * We should only show this if his password is invalid and has been checked when un-focusing the input
  352. *
  353. * @returns {boolean|boolean}
  354. */
  355. shouldShowPasswordError(): boolean {
  356. const {isPasswordValidated} = this.state;
  357. return isPasswordValidated && !this.isPasswordValid();
  358. }
  359. /**
  360. * If the email and password are valid, and we are not loading a request, then the login button can be enabled
  361. *
  362. * @returns {boolean}
  363. */
  364. shouldEnableLogin(): boolean {
  365. const {loading} = this.state;
  366. return this.isEmailValid() && this.isPasswordValid() && !loading;
  367. }
  368. render(): React.Node {
  369. const {mascotDialogVisible, dialogVisible, dialogError} = this.state;
  370. return (
  371. <LinearGradient
  372. style={{
  373. height: '100%',
  374. }}
  375. colors={['#9e0d18', '#530209']}
  376. start={{x: 0, y: 0.1}}
  377. end={{x: 0.1, y: 1}}>
  378. <KeyboardAvoidingView
  379. behavior="height"
  380. contentContainerStyle={styles.container}
  381. style={styles.container}
  382. enabled
  383. keyboardVerticalOffset={100}>
  384. <CollapsibleScrollView>
  385. <View style={{height: '100%'}}>{this.getMainCard()}</View>
  386. <MascotPopup
  387. visible={mascotDialogVisible}
  388. title={i18n.t('screens.login.mascotDialog.title')}
  389. message={i18n.t('screens.login.mascotDialog.message')}
  390. icon="help"
  391. buttons={{
  392. action: null,
  393. cancel: {
  394. message: i18n.t('screens.login.mascotDialog.button'),
  395. icon: 'check',
  396. onPress: this.hideMascotDialog,
  397. },
  398. }}
  399. emotion={MASCOT_STYLE.NORMAL}
  400. />
  401. <ErrorDialog
  402. visible={dialogVisible}
  403. onDismiss={this.hideErrorDialog}
  404. errorCode={dialogError}
  405. />
  406. </CollapsibleScrollView>
  407. </KeyboardAvoidingView>
  408. </LinearGradient>
  409. );
  410. }
  411. }
  412. export default withTheme(LoginScreen);