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

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