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

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