masquitos

Frontend

Aug 13th, 2020 (edited)
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Компонент авторизации
  2.  
  3. @Component({
  4.   selector: "app-auth",
  5.   templateUrl: "./route-auth.component.html",
  6.   styleUrls: ["./route-auth.component.css"]
  7. })
  8. export class RouteAuthComponent implements OnInit, OnDestroy, AfterViewInit {
  9.   @ViewChild("authorizationComponent", { static: false })
  10.   authorizationComponent: AuthorizationComponent;
  11.  
  12.   public status: any = MyStatus;
  13.   public authData: AuthData = {
  14.     auth: { data: { email: "", password: "" }, status: MyStatus.PENDING },
  15.     isSaveLogin: true
  16.   };
  17.   public isTokens: boolean;
  18.   public txtLoader: string = "";
  19.   private param: Params;
  20.   private jwt = new JwtHelperService();
  21.   private componentDestroyed: Subject<any> = new Subject();
  22.  
  23.   constructor(
  24.     private router: Router,
  25.     private store: Store<AppStore>,
  26.     private actions$: Actions,
  27.     private route: ActivatedRoute,
  28.     private location: Location,
  29.     private localStorageService: LocalStorageService
  30.   ) {}
  31.  
  32.   ngOnInit() {
  33.     this.isTokens = !!this.localStorageService.getTokensStorage();
  34.  
  35.     this.store
  36.       .pipe(select(selectAuthStatus), takeUntil(this.componentDestroyed))
  37.       .subscribe(data => {
  38.         this.authData.auth.status = data;
  39.       });
  40.  
  41.     this.store
  42.       .pipe(
  43.         select(selectCurrUser),
  44.         take(1),
  45.         filter(data => data.login.status === MyStatus.LOADED),
  46.         takeUntil(this.componentDestroyed)
  47.       )
  48.       .subscribe(data => this.store.dispatch(new LogOut()));
  49.  
  50.     this.actions$
  51.       .pipe(
  52.         ofType(LOGIN, CREATE_GUEST),
  53.         takeUntil(this.componentDestroyed),
  54.         map((action: CustomAction) => action),
  55.         map(action =>
  56.           action.type === LOGIN ? Messages.AUTHORIZATION : Messages.CREATE_GUEST
  57.         )
  58.       )
  59.       .subscribe(data => (this.txtLoader = data));
  60.  
  61.     this.actions$
  62.       .pipe(
  63.         ofType(LOGIN_COMPLETE, REFRESH_TOKEN_COMPLETE),
  64.         takeUntil(this.componentDestroyed)
  65.       )
  66.       .subscribe(action => this.router.navigateByUrl(DEFAULT_ROUTE));
  67.  
  68.     this.actions$
  69.       .pipe(
  70.         ofType(CREATE_GUEST_COMPLETE, CONFORM_REGISTRATION),
  71.         takeUntil(this.componentDestroyed)
  72.       )
  73.       .subscribe(() => {
  74.         this.router.navigateByUrl(MyRoutes.INTRO);
  75.       });
  76.   }
  77.  
  78.   ngAfterViewInit(): void {
  79.     this.route.queryParams
  80.       .pipe(takeUntil(this.componentDestroyed))
  81.       .subscribe((qparam: Params) => {
  82.         this.param = qparam;
  83.         this.handleParams();
  84.       });
  85.   }
  86.  
  87.   private handleParams() {
  88.     console.log("handleParams", this.param);
  89.  
  90.     if (this.param.success && this.param.code) {
  91.       if (this.param.success === "true") {
  92.         console.log(this.param.code);
  93.         this.store.dispatch(
  94.           new ShowSnackbar(ErrorCodes.getText(this.param.code))
  95.         );
  96.         if (this.param.token) {
  97.           this.store.dispatch(new ConformRegistration(this.param.token));
  98.         }
  99.       } else {
  100.         this.store.dispatch(
  101.           new ShowError({ message: ErrorCodes.getText(this.param.code) })
  102.         );
  103.       }
  104.     }
  105.  
  106.     if (
  107.       this.param.create_guest &&
  108.       this.param.create_guest === "true" &&
  109.       !this.isTokens
  110.     ) {
  111.       this.store.dispatch(new CreateGuest());
  112.     }
  113.   }
  114.  
  115.   onLogin() {
  116.     if (
  117.       this.authorizationComponent.emailInputComponent.formControl.valid &&
  118.       this.authorizationComponent.passwordInputComponent.formControl.valid
  119.     ) {
  120.       const authModel: AuthModel = {
  121.         email: this.authorizationComponent.emailInputComponent.formControl
  122.           .value,
  123.         password: this.authorizationComponent.passwordInputComponent.formControl
  124.           .value
  125.       };
  126.       this.store.dispatch(new Login(authModel));
  127.     }
  128.     if (
  129.       this.authorizationComponent.emailInputComponent.formControl.touched ===
  130.       false
  131.     ) {
  132.       this.authorizationComponent.emailInputComponent.formControl.markAsTouched();
  133.     }
  134.     if (
  135.       this.authorizationComponent.passwordInputComponent.formControl.touched ===
  136.       false
  137.     ) {
  138.       this.authorizationComponent.passwordInputComponent.formControl.markAsTouched();
  139.     }
  140.   }
  141.  
  142.   onRegister() {
  143.     this.router.navigate([MyRoutes.REGISTER]);
  144.   }
  145.  
  146.   onRestorePassword() {
  147.     this.router.navigate([MyRoutes.RESTORE]);
  148.   }
  149.  
  150.   onSetSave(data: boolean) {
  151.     this.store.dispatch(new SetIsSaveLogin(data));
  152.   }
  153.  
  154.   onCreateGuest() {
  155.     this.store.dispatch(new CreateGuest());
  156.   }
  157.  
  158.   ngOnDestroy(): void {
  159.     this.location.replaceState(this.location.path().split("?")[0], "");
  160.     if (this.authData.auth.status === MyStatus.LOADING) {
  161.       this.store.dispatch(new LoginCancel());
  162.     }
  163.     this.componentDestroyed.next();
  164.     this.componentDestroyed.complete();
  165.   }
  166. }
  167.  
  168.  
  169.  
  170.  
  171.  
  172.  
  173. // Редюсер авторизации
  174. export function authReducer(
  175.   state: AuthStore = environment.isApi === false
  176.     ? INITIAL_AUTH_STORE_DATA_MOCK
  177.     : INITIAL_AUTH_STORE_DATA,
  178.   action: AuthActions.Actions | ComponentsActions.Actions
  179. ): AuthStore {
  180.   // Section 3
  181.   switch (action.type) {
  182.     case AuthActions.LOGIN:
  183.       return handleLogin(state);
  184.     case AuthActions.LOGIN_COMPLETE:
  185.       return handleLoginComplete(state, action);
  186.     case AuthActions.LOGIN_ERROR:
  187.       return handleLoginError(state);
  188.     case AuthActions.LOGIN_CANCEL:
  189.       return handleLoginCancel(state);
  190.  
  191.  
  192. // Функции редюсера
  193. export function handleLogin(state: AuthStore): AuthStore {
  194.   const newStoreState: AuthStore = _.cloneDeep(state);
  195.   newStoreState.authData.login.data = null;
  196.   newStoreState.authData.login.status = MyStatus.LOADING;
  197.   return newStoreState;
  198. }
  199.  
  200. export function handleLoginComplete(
  201.   state: AuthStore,
  202.   action: LoginComplete
  203. ): AuthStore {
  204.   return _setLogin(state, action.token);
  205. }
  206.  
  207. export function handleLoginError(state: AuthStore): AuthStore {
  208.   const newStoreState: AuthStore = _.cloneDeep(state);
  209.   newStoreState.authData.login.status = MyStatus.FAILED;
  210.   return newStoreState;
  211. }
  212.  
  213. export function handleLoginCancel(state: AuthStore): AuthStore {
  214.   const newStoreState: AuthStore = _.cloneDeep(state);
  215.   newStoreState.authData.login.status = MyStatus.CANCEL;
  216.   return newStoreState;
  217. }
  218.  
  219.  
  220.  
  221. // Effects auth
  222.  
  223.   @Effect() login$: Observable<any> = this.actions$.pipe(
  224.     ofType(LOGIN),
  225.     map((action: Login) => action.payload),
  226.     switchMap(login =>
  227.       this.httpService.login(login).pipe(
  228.         switchMap(result => of(new LoginComplete(result.data.token))),
  229.         catchError((err: MyError) =>
  230.           of(new LoginError(), new ShowError({ message: err.message }))
  231.         ),
  232.         takeUntil(this.actions$.pipe(ofType(LOGIN_CANCEL)))
  233.       )
  234.     )
  235.   );
  236.  
  237.   @Effect() initData$: Observable<any> = this.actions$.pipe(
  238.     ofType(
  239.       CONFORM_REGISTRATION,
  240.       CREATE_GUEST_COMPLETE,
  241.       LOGIN_COMPLETE,
  242.       REFRESH_TOKEN_COMPLETE
  243.     ),
  244.     map((action: AuthAction) => action),
  245.     withLatestFrom(this.store.pipe(select(selectIsSaveLogin))),
  246.     tap(([action, isSavePassword]) => {
  247.       if (isSavePassword) {
  248.         this.storage.storeToken(action.token);
  249.       } else {
  250.         this.storage.deleteToken(action.token);
  251.       }
  252.       this.sessionStorage.storeToken(action.token);
  253.     }),
  254.     switchMap(([action, isSavePassword]) =>
  255.       of(
  256.         new InitMap(),
  257.         new InitSocket(action.token),
  258.         new LoadConversations(),
  259.         new LoadMyTasks(),
  260.         new LoadSubscriptions(),
  261.         new LoadSupportChat(),
  262.         new LoadMyInfo()
  263.       )
  264.     )
  265.   );
  266.  
  267.  
  268. // Auth state
  269. export const INITIAL_AUTH_STORE_DATA: AuthStore = {
  270.   authData: {
  271.     login: { data: null, status: MyStatus.PENDING },
  272.     myInfo: {
  273.       data: { image: null, contacts: null, email: null, notify: null },
  274.       status: MyStatus.PENDING
  275.     }
  276.   },
  277.   register: { status: MyStatus.PENDING },
  278.   restore: MyStatus.PENDING,
  279.   change: MyStatus.PENDING,
  280.   conformRegister: MyStatus.PENDING,
  281.   isSaveLogin: true
  282. };
  283.  
  284.  
  285. // Auth service
  286.   public login(data: AuthModel): Observable<Result<ResultToken>> {
  287.     console.log("login");
  288.     return this.https.post<Result<ResultToken>>(
  289.       this.REST_API.auth,
  290.       JSON.stringify(data),
  291.       this.httpOptions
  292.     );
  293.   }
  294.  
Advertisement
Add Comment
Please, Sign In to add comment