Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Компонент авторизации
- @Component({
- selector: "app-auth",
- templateUrl: "./route-auth.component.html",
- styleUrls: ["./route-auth.component.css"]
- })
- export class RouteAuthComponent implements OnInit, OnDestroy, AfterViewInit {
- @ViewChild("authorizationComponent", { static: false })
- authorizationComponent: AuthorizationComponent;
- public status: any = MyStatus;
- public authData: AuthData = {
- auth: { data: { email: "", password: "" }, status: MyStatus.PENDING },
- isSaveLogin: true
- };
- public isTokens: boolean;
- public txtLoader: string = "";
- private param: Params;
- private jwt = new JwtHelperService();
- private componentDestroyed: Subject<any> = new Subject();
- constructor(
- private router: Router,
- private store: Store<AppStore>,
- private actions$: Actions,
- private route: ActivatedRoute,
- private location: Location,
- private localStorageService: LocalStorageService
- ) {}
- ngOnInit() {
- this.isTokens = !!this.localStorageService.getTokensStorage();
- this.store
- .pipe(select(selectAuthStatus), takeUntil(this.componentDestroyed))
- .subscribe(data => {
- this.authData.auth.status = data;
- });
- this.store
- .pipe(
- select(selectCurrUser),
- take(1),
- filter(data => data.login.status === MyStatus.LOADED),
- takeUntil(this.componentDestroyed)
- )
- .subscribe(data => this.store.dispatch(new LogOut()));
- this.actions$
- .pipe(
- ofType(LOGIN, CREATE_GUEST),
- takeUntil(this.componentDestroyed),
- map((action: CustomAction) => action),
- map(action =>
- action.type === LOGIN ? Messages.AUTHORIZATION : Messages.CREATE_GUEST
- )
- )
- .subscribe(data => (this.txtLoader = data));
- this.actions$
- .pipe(
- ofType(LOGIN_COMPLETE, REFRESH_TOKEN_COMPLETE),
- takeUntil(this.componentDestroyed)
- )
- .subscribe(action => this.router.navigateByUrl(DEFAULT_ROUTE));
- this.actions$
- .pipe(
- ofType(CREATE_GUEST_COMPLETE, CONFORM_REGISTRATION),
- takeUntil(this.componentDestroyed)
- )
- .subscribe(() => {
- this.router.navigateByUrl(MyRoutes.INTRO);
- });
- }
- ngAfterViewInit(): void {
- this.route.queryParams
- .pipe(takeUntil(this.componentDestroyed))
- .subscribe((qparam: Params) => {
- this.param = qparam;
- this.handleParams();
- });
- }
- private handleParams() {
- console.log("handleParams", this.param);
- if (this.param.success && this.param.code) {
- if (this.param.success === "true") {
- console.log(this.param.code);
- this.store.dispatch(
- new ShowSnackbar(ErrorCodes.getText(this.param.code))
- );
- if (this.param.token) {
- this.store.dispatch(new ConformRegistration(this.param.token));
- }
- } else {
- this.store.dispatch(
- new ShowError({ message: ErrorCodes.getText(this.param.code) })
- );
- }
- }
- if (
- this.param.create_guest &&
- this.param.create_guest === "true" &&
- !this.isTokens
- ) {
- this.store.dispatch(new CreateGuest());
- }
- }
- onLogin() {
- if (
- this.authorizationComponent.emailInputComponent.formControl.valid &&
- this.authorizationComponent.passwordInputComponent.formControl.valid
- ) {
- const authModel: AuthModel = {
- email: this.authorizationComponent.emailInputComponent.formControl
- .value,
- password: this.authorizationComponent.passwordInputComponent.formControl
- .value
- };
- this.store.dispatch(new Login(authModel));
- }
- if (
- this.authorizationComponent.emailInputComponent.formControl.touched ===
- false
- ) {
- this.authorizationComponent.emailInputComponent.formControl.markAsTouched();
- }
- if (
- this.authorizationComponent.passwordInputComponent.formControl.touched ===
- false
- ) {
- this.authorizationComponent.passwordInputComponent.formControl.markAsTouched();
- }
- }
- onRegister() {
- this.router.navigate([MyRoutes.REGISTER]);
- }
- onRestorePassword() {
- this.router.navigate([MyRoutes.RESTORE]);
- }
- onSetSave(data: boolean) {
- this.store.dispatch(new SetIsSaveLogin(data));
- }
- onCreateGuest() {
- this.store.dispatch(new CreateGuest());
- }
- ngOnDestroy(): void {
- this.location.replaceState(this.location.path().split("?")[0], "");
- if (this.authData.auth.status === MyStatus.LOADING) {
- this.store.dispatch(new LoginCancel());
- }
- this.componentDestroyed.next();
- this.componentDestroyed.complete();
- }
- }
- // Редюсер авторизации
- export function authReducer(
- state: AuthStore = environment.isApi === false
- ? INITIAL_AUTH_STORE_DATA_MOCK
- : INITIAL_AUTH_STORE_DATA,
- action: AuthActions.Actions | ComponentsActions.Actions
- ): AuthStore {
- // Section 3
- switch (action.type) {
- case AuthActions.LOGIN:
- return handleLogin(state);
- case AuthActions.LOGIN_COMPLETE:
- return handleLoginComplete(state, action);
- case AuthActions.LOGIN_ERROR:
- return handleLoginError(state);
- case AuthActions.LOGIN_CANCEL:
- return handleLoginCancel(state);
- // Функции редюсера
- export function handleLogin(state: AuthStore): AuthStore {
- const newStoreState: AuthStore = _.cloneDeep(state);
- newStoreState.authData.login.data = null;
- newStoreState.authData.login.status = MyStatus.LOADING;
- return newStoreState;
- }
- export function handleLoginComplete(
- state: AuthStore,
- action: LoginComplete
- ): AuthStore {
- return _setLogin(state, action.token);
- }
- export function handleLoginError(state: AuthStore): AuthStore {
- const newStoreState: AuthStore = _.cloneDeep(state);
- newStoreState.authData.login.status = MyStatus.FAILED;
- return newStoreState;
- }
- export function handleLoginCancel(state: AuthStore): AuthStore {
- const newStoreState: AuthStore = _.cloneDeep(state);
- newStoreState.authData.login.status = MyStatus.CANCEL;
- return newStoreState;
- }
- // Effects auth
- @Effect() login$: Observable<any> = this.actions$.pipe(
- ofType(LOGIN),
- map((action: Login) => action.payload),
- switchMap(login =>
- this.httpService.login(login).pipe(
- switchMap(result => of(new LoginComplete(result.data.token))),
- catchError((err: MyError) =>
- of(new LoginError(), new ShowError({ message: err.message }))
- ),
- takeUntil(this.actions$.pipe(ofType(LOGIN_CANCEL)))
- )
- )
- );
- @Effect() initData$: Observable<any> = this.actions$.pipe(
- ofType(
- CONFORM_REGISTRATION,
- CREATE_GUEST_COMPLETE,
- LOGIN_COMPLETE,
- REFRESH_TOKEN_COMPLETE
- ),
- map((action: AuthAction) => action),
- withLatestFrom(this.store.pipe(select(selectIsSaveLogin))),
- tap(([action, isSavePassword]) => {
- if (isSavePassword) {
- this.storage.storeToken(action.token);
- } else {
- this.storage.deleteToken(action.token);
- }
- this.sessionStorage.storeToken(action.token);
- }),
- switchMap(([action, isSavePassword]) =>
- of(
- new InitMap(),
- new InitSocket(action.token),
- new LoadConversations(),
- new LoadMyTasks(),
- new LoadSubscriptions(),
- new LoadSupportChat(),
- new LoadMyInfo()
- )
- )
- );
- // Auth state
- export const INITIAL_AUTH_STORE_DATA: AuthStore = {
- authData: {
- login: { data: null, status: MyStatus.PENDING },
- myInfo: {
- data: { image: null, contacts: null, email: null, notify: null },
- status: MyStatus.PENDING
- }
- },
- register: { status: MyStatus.PENDING },
- restore: MyStatus.PENDING,
- change: MyStatus.PENDING,
- conformRegister: MyStatus.PENDING,
- isSaveLogin: true
- };
- // Auth service
- public login(data: AuthModel): Observable<Result<ResultToken>> {
- console.log("login");
- return this.https.post<Result<ResultToken>>(
- this.REST_API.auth,
- JSON.stringify(data),
- this.httpOptions
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment