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

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