首页 > 解决方案 > 如果使用 angular2 未完成该过程,如何重定向到登录页面

问题描述

我有一个弹出窗口,用于设备验证。因此,一旦我在提供正确的凭据后单击登录按钮,如果它不是受信任的设备,则会打开弹出窗口,因此我需要提供信息,然后在成功验证后,它会重定向到主页。

我的问题是,我点击了登录,因此提供了登录所需的凭据,如果它不受信任的设备会打开弹出窗口,如果我在进程中间刷新页面,那么它会重定向到主页。

谁能帮我解决这个问题。

TS:

login(value: any) {
    let userName = value.email.trim();
    let passWord = value.password.trim();
    let password = Md5.hashStr(passWord)
    let params = { username: userName, password: password }
    this.authService.doLogin(params)
      .subscribe((data: any) => {
        else if (data.Body.Data.token && data.Body.Data.id != -2) {
          localStorage.setItem("userId_ls", data.Body.Data.userID)
          localStorage.setItem('accountId_ls', data.Body.Data.accountID)
          if (Cookie.get("DeviceUID") == null || this.DeviceUID == 'undefined') {
            this.isUserDevice = true;

          }
          else if (this.DeviceUID != null && this.DeviceUID != undefined && this.userDId != null) {
            let otpObj = { UserId: this.userDId, otp: "", Guid: this.DeviceUID, savedevice: "" }
            this._userService.confirmDevice(otpObj).subscribe(resp => {
                if(resp.message == "Invalid device.") {

                  Cookie.delete('DeviceUID');
                  this.router.navigate(['/login']);
                  window.location.reload();

                } else {
                this.router.navigate(['/home']); }
            })
          }
        }
        else {
          console.log(data.message);
        }
      })

  }

路由.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CanActivatedAuthGuard } from './core/security-guard/auth.guard';

let routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '', loadChildren: './home/home.module#HomeModule' },
  { path: 'login', loadChildren: './login/login.module#LoginModule' },
  // { path: '**', loadChildren: './login/login.module#LoginModule' },
  { path: 'register', loadChildren: './register/register.module#RegisterModule' },
  { path: 'accountActivation/:userId/:activationCode', loadChildren: './activation/activation.module#ActivationModule' },
]

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { useHash: true, enableTracing: false }
    )
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

弹出式 HTML:

 <p-dialog header="New Device Verification" [(visible)]="isUserDevice" [responsive]="true" showEffect="fade" [modal]="true"
    [width]="400">
    <div class="form-group row g-mb-25">
      <div class="col-sm-9 clear-fix">
        <label class="col-sm-8 col-form-label g-color-gray-dark-v2 g-font-weight-700 g-mb-10">Choose OTP type
        </label>
        <div class="col-sm-9 clear-fix" *ngFor="let oType of otpTypes">
          <label class="form-check-inline u-check g-pl-25">
            <input type="radio" name="otpType" [value]="oType.otpType" (click)="chooseOtpType(oType)"> {{oType.otpType}}
          </label>
        </div>
        <div>
          <div *ngIf="isConfirmEmailOtp">
            <input class="form-control col-lg-12" type="email" [(ngModel)]="enterEmail" name="myEmail" #myEmail="ngModel" email pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" (input)="submitButton &&submitButton.disabled = false"
              #emailOTP>
              <button (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;" class="btn pull-right otp"  #submitButton [disabled] = "enterEmail === ''&& enterSms === ''" >Send OTP</button>
            <div *ngIf="myEmail.errors && (myEmail.dirty || myEmail.touched)">
              <br>
              <div [hidden]="!myEmail.errors" class="error">
                Invalid Email.
              </div>
            </div>
          </div>
          <div *ngIf="isSms">
            <input class="form-control col-lg-12" type="number" [(ngModel)]="enterSms" #smsOTP (input)="submitButton && submitButton.disabled = false">
            <button (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;" class="btn pull-right otp"  #submitButton [disabled] = "enterEmail === ''&& enterSms === ''" >Send OTP</button>
          </div>
        </div>
      </div>
        <div class="col-lg-12 row g-mb-10" *ngIf="isConfirmOtp">
          <label class="col-sm-4 col-form-label g-color-gray-dark-v2 g-font-weight-700 text-sm-left g-mb-10 nopadd">Verify OTP:
            <span class="required">*</span>
          </label>
          <div class="col-sm-8">
            <div class="input-group g-brd-primary--focus">
              <input class="verifyPin" type="text" placeholder="Pin" [(ngModel)] = "otp">
            </div>
          </div>
        </div> 
    </div>
    <!-- End Login Verification -->
    <p-footer>
      <div class="col-sm-9 clear-fix saveDevice">
        <label class="form-check-inline u-check g-pl-25">
          <input class="g-hidden-xs-up g-pos-abs g-top-0 g-left-0" type="checkbox" [(ngModel)] = "checkboxSave">
          <div class="u-check-icon-checkbox-v4 g-absolute-centered--y g-left-0">
            <i class="fa" data-check-icon=""></i>
          </div>
          Save this device
        </label>
      </div>
      <div class="ui-dialog-buttonpane ui-helper-clearfix popup">
        <button type="button" pButton icon="fa-check" label="Save" class="btn u-btn-darkgray g-py-12 g-px-25 g-mr-10" (click)="cancelDevice()">Cancel</button>
        <button type="button" pButton icon="fa-check" label="Save" class="btn u-btn-primary g-py-12 g-px-25" (click)="saveDeviceInfo(enterEmail, enterSms, otp,checkboxSave)" [disabled]="!otp">Ok</button>
      </div>
    </p-footer>
  </p-dialog>

TS:

saveDeviceInfo(enterEmail, enterSms, otp, checkboxSave) {
    var check = checkboxSave;
    var uID = localStorage.getItem('userId_ls');
    if (this.enterEmail != null && this.enterEmail != "") {
      let otpObj = { userId: uID, otp: otp }
      this._userService.confirmOtpEmail(otpObj).subscribe(resp => {
        if (resp.Body.Data == "OTP verified successfully") {
          let otpObj = { UserId: uID, otp: otp, Guid: "", savedevice: check, DeviceName: "webBrowser" }
          if(!this.DeviceUID && this.otp || checkboxSave == true) {
          this._userService.confirmDevice(otpObj).subscribe(resp => {
            if (resp) {
              Cookie.set('DeviceUID', resp.Guid);
              this.router.navigate(['/home']);
            }
          })
         }
        }
        else if (resp.Body.Data == "OTP is not valid.Please check the OTP") {
          this.enterEmail = "";
          this.enterSms = "";
          this.otp = "";
          this.msgs = [{ severity: 'error', summary: 'Error Message', detail: 'OTP is not valid.Please check the OTP' }];
          this.isUserDevice = false;
          this.isSms = false;
          this.isConfirmEmailOtp = false;
          this.isConfirmOtp = false;
          Cookie.delete('token');
          Cookie.delete('userType');
          Cookie.delete('userID');
          Cookie.delete('profilePic');
          Cookie.delete('Id');
          this.router.navigate(['/login']);
          window.location.reload();
        }
      })
    }

    if (this.enterSms != null && this.enterSms != "") {
      let otpObj = { userId: uID, otp: otp, isRequiredToken: this.isRequiredToken }
      this._userService.confirmOtpSMS(otpObj).subscribe(resp => {
        if (resp.Body.Data == "OTP verified successfully") {
          let otpObj = { UserId: uID, otp: otp, Guid: "", savedevice: check, DeviceName: "webBrowser" }
          if(!this.DeviceUID && this.otp || checkboxSave == true) {
          this._userService.confirmDevice(otpObj).subscribe(resp => {
            if (resp) {
              Cookie.set('DeviceUID', resp.Guid);
              this.router.navigate(['/home']);
            }
          })
        }
        } else if (resp.Header.Message == "User Does Not Exist For This OTP") {
          this.enterEmail = "";
          this.enterSms = "";
          this.otp = "";
          this.msgs = [{ severity: 'error', summary: 'Error Message', detail: 'User Does Not Exist For This OTP' }];
          this.isUserDevice = false;
          this.isSms = false;
          this.isConfirmEmailOtp = false;
          this.isConfirmOtp = false;
          Cookie.delete('token');
          Cookie.delete('userType');
          Cookie.delete('userID');
          Cookie.delete('profilePic');
          Cookie.delete('Id');
          this.router.navigate(['/login']);
          window.location.reload();
        }
      })
    }
  }

这里是登录成功后弹出功能,请帮助。

标签: javascriptangulartypescriptangular2-routing

解决方案


从这条线,

它必须转到主页,在我的弹出窗口单击确定按钮之后,或者如果 DeviceId 已经存在于 cookie 中,那么它必须去。

使用 cookie 处理弹出确定点击事件(或)这样做

else{
   let deviceId= Cookie.get('DeviceId ');
    if(deviceId && deviceId!=null && deviceId!=undefined){
       this.router.navigate(['/home']); }
    }
}

显示您的 _userService.confirmDevice 您使用的是哪个确认包?


推荐阅读