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

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