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 13KB

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