代码之家  ›  专栏  ›  技术社区  ›  Bhrungarajni

如何重定向到登录页,如果该过程未使用angular2完成

  •  0
  • Bhrungarajni  · 技术社区  · 7 年前

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

    我的问题是,我单击了login,因此提供了登录所需的凭据,如果它的设备不受信任,则弹出窗口将打开,如果我在处理过程中刷新了页面,则它将重定向到主页。

    电话号码:

    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);
            }
          })
    
      }
    

    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>
    

    电话号码:

    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();
            }
          })
        }
      }
    

    2 回复  |  直到 7 年前
        1
  •  0
  •   PENG ZHU    7 年前

    首先,当弹出窗口(我假设它是一个“对话框”,如角度材质对话框)出现时,URL不会改变。 所以,根据你的描述,你的处境似乎是:

    -问题是,每次您输入一个页面来检查用户是否登录时,都应该有一个路由保护程序。此外,您还需要在后端进行身份验证。

    Angular的官方路由文件几乎解释了所有事情,非常有用。以下是链接: https://angular.io/guide/router

    希望这对你有帮助。

        2
  •  0
  •   Karnan Muthukumar    7 年前

    从这条线上,

    处理弹出式ok-click事件(或)使用cookie执行此操作

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

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