Advertisement
Guest User

Untitled

a guest
Jan 28th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { observable, action } from 'mobx';
  2. import AsyncStorage from '@react-native-community/async-storage';
  3. import UserStore from './User';
  4. import { signupUser, loginUser, activateUserAccount, logutUser } from '../../endpoints/user';
  5. import { strings } from '../../utils/constants';
  6.  
  7. export class Auth {
  8.   @observable signupSuccessful = false;
  9.  
  10.   @observable signupErrors = null;
  11.  
  12.   @observable activationError = null;
  13.  
  14.   @observable loginError = null;
  15.  
  16.   @action signup(isPatient, signupData) {
  17.     this.signupErrors = {};
  18.     signupUser(isPatient, { ...signupData, mobile: true })
  19.       .then(() => {
  20.         this.signupSuccessful = true;
  21.       })
  22.       .catch(({ response: { status, data } }) => {
  23.         if (status === 400) {
  24.           this.setSignupErrors((data.error && data.error.errors) || {});
  25.         } else if (status === 500) {
  26.           this.setSignupErrors({ email: { message: strings.validationErrorSameEmail } });
  27.         }
  28.       });
  29.   }
  30.  
  31.   @action login(loginData) {
  32.     this.loginError = null;
  33.     loginUser(loginData)
  34.       .then(({ data }) => {
  35.         if (data) {
  36.           AsyncStorage.setItem('token', data.token);
  37.           UserStore.setUserData(data);
  38.         }
  39.       })
  40.       .catch(({ response: { status, data } }) => {
  41.         if (status === 401) {
  42.           this.setLoginError(data.message);
  43.         }
  44.       });
  45.   }
  46.  
  47.   @action activateAccount(token) {
  48.     activateUserAccount(token)
  49.       .then()
  50.       .catch(({ response }) => {
  51.         if (response.data) {
  52.           this.setActivationError(response.data.message);
  53.         }
  54.       });
  55.   }
  56.  
  57.   @action async logout() {
  58.     await AsyncStorage.removeItem('token');
  59.     logutUser({ userId: this.userId })
  60.       .then(() => {
  61.         this.clear();
  62.         UserStore.clear();
  63.       })
  64.       .catch(error => console.log({ error }));
  65.   }
  66.  
  67.   @action setSignupErrors(errors) {
  68.     this.signupErrors = errors;
  69.   }
  70.  
  71.   @action setActivationError(error) {
  72.     this.activationError = error;
  73.   }
  74.  
  75.   @action setLoginError = error => {
  76.     this.loginError = error;
  77.   };
  78.  
  79.   @action clear() {
  80.     this.signupSuccessful = false;
  81.     this.signupErrors = null;
  82.     this.activationError = null;
  83.     this.loginError = null;
  84.   }
  85. }
  86.  
  87. export default new Auth();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement