Angular Firebase身份验证,如何检查用户是否已登录以隐藏导航链接? [英] Angular Firebase auth, how to check if user is logged in to hide login link from navigation?

查看:66
本文介绍了Angular Firebase身份验证,如何检查用户是否已登录以隐藏导航链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了有角度的Firebase电子邮件和密码注册和登录,但是现在我要做的是在导航模板中检查用户的状态,如果用户已登录,则隐藏登录按钮以及隐藏注册按钮.我尝试使用Google搜索有关此问题的一些教程,发现我必须使用AuthService和AuthInfo,如您在此处看到的那样:

I implemented angular firebase email and password registration and login, but now what I want to do is check in my navigation template the state of the user, if the user is logged in, then hide login button, as well as hide register button. I tried googling for some tutorials on this, and found out that I must use AuthService and AuthInfo as you can see here:

https://github.com/angular-university/angular-firebase-app/blob/master/src/app/shared/security/auth.service.ts

问题是他们使用了很多诺言和东西,我不熟悉这些,这确实使我感到困惑.我正在尝试以最基本的方式实现这一目标,并正在寻找可以指导我并帮助我的人.

The thing is that they are using a lot of promises and stuff, which I'm not familiar with and it really confuses me. I'm trying to achieve this in the most basic way and looking for someone to guide me and help me.

这是我的代码:

导航-

navigation -

<ul class="nav navbar-nav">
    <li><a routerLink="" routerLinkActive="active">Home</a></li>
    <li><a routerLink="login" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Login</a></li>
    <li><a routerLink="register" routerLinkActive="active" *ngIf="!authInfo?.isLoggedIn()">Register</a></li>
    <li><a routerLink="quiz" routerLinkActive="active">Quiz</a></li>
</ul>

我的 Auth服务 文件,其中所有用户都创建并登录到Firebase逻辑-

My Auth service file with all the user create and login to firebase logic -

@Injectable({
    providedIn: 'root'
})
export class AuthService {
    private user: Observable<firebase.User>;
    constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
        this.user = _firebaseAuth.authState;

        this.user.subscribe(
            (user) => {
                if (user) {
                    this.userDetails = user;

                    console.log(this.userDetails);
                } else {
                    this.userDetails = null;
                }
            }
        );
    }

    logUserIn(email, pass) {
        firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
            // Handle Errors here.
            var errorCode = error.code;
            var errorMessage = error.message;
            console.log("error" + error);
        })

        if (this.userDetails) {
            email = this.userDetails.email;
            console.log("hello im user" + " " + email);

        } else {
            console.log("not working");
        }

        this.router.navigate(['']);
    }

    regUser(email, pass) {
        firebase.auth().createUserWithEmailAndPassword(email, pass)
            .catch(function (error) {
                // Handle Errors here.
                var errorCode = error.code;
                var errorMessage = error.message;

            });
    }
}

登录组件-

Login component -

@Component({
    selector: 'login',
    templateUrl: 'login.component.html'
})
export class LoginComponent {

    form: FormGroup;

    constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService) {

        this.form = fb.group({
            email: ['', Validators.required],
            password: ['', Validators.compose([Validators.required,
            PasswordValidator.cannotContainSpace])]
        })

    }

    login() {
        this.auth.logUserIn(this.form.value.email, this.form.value.password);
    };
}

上面github链接中的

auth-info.ts 文件-

auth-info.ts file from the github link above -

export class AuthInfo {

    constructor(public $uid: string) { }

    isLoggedIn() {
        return !!this.$uid;
    }
}

因此,感谢Tushar Walzade,我设法显示和隐藏了这些按钮,但是我的行为确实很奇怪.注销时没有问题,但是登录后什么也没发生,我收到not working消息到Chrome控制台,该消息来自Auth服务中的logUserIn方法.但是,当我刷新页面一次时,它表明它正在运行,我在控制台中获得了用户信息详细信息,并且按钮被隐藏了.我不知道为什么会这样,但是我认为这可能与sessionStorage有关,我一无所知.

So thanks to Tushar Walzade I managed to show and hide these buttons, but I get really weird behaviour. There are no problems when logging out, but when I login, nothing happens, I get not working message to Chrome console which comes from my logUserIn method in Auth service. But when I refresh page one time, then it shows me that it's working, I get user information details in console and buttons get hidden. I don't know why this happens, but I think this might be something with sessionStorage which I know nothing about.

这是代码:

身份验证服务

Auth service

export class AuthService {
  private user: Observable<firebase.User>;
  private userDetails: firebase.User = null;
  public loggedIn = false;



  constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
    this.user = _firebaseAuth.authState;
    this.loggedIn = !!sessionStorage.getItem('user');

    this.user.subscribe(
        (user) => {
          if (user) {
            this.userDetails = user;

            console.log(this.userDetails);
          } else {
            this.userDetails = null;
          }
        }
      );
  }

  // Set current user in your session after a successful login
    setCurrentUser(email: string): void {
        sessionStorage.setItem('user', email);
        this.loggedIn = true;
    }

    // Get currently logged in user from session
    getCurrentUser(): string | any {
        return sessionStorage.getItem('user') || undefined;
    }

    isLoggedIn() {
    return this.loggedIn;
    }

  logUserIn(email, pass) {
    firebase.auth().signInWithEmailAndPassword(email, pass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log("error" + error);
})
//var user = firebase.auth().currentUser;
//var email;
if (this.userDetails) {
email = this.userDetails.email;
console.log("hello im user" + " " + email);
//email = user.email;
this.setCurrentUser(email);
 this.loggedIn = true;
} else {
console.log("not working");
}

this.router.navigate(['']);
}

  regUser(email, pass) {
    firebase.auth().createUserWithEmailAndPassword(email, pass)
 .catch(function(error) {
   // Handle Errors here.
   var errorCode = error.code;
   var errorMessage = error.message;
   // ...
 });
//console.log(this.form.controls['email'].value);
    }

    logOut() {
      this.loggedIn = false;
      firebase.auth().signOut().then(function() {
        // Sign-out successful.
        console.log("signout successful");
    }).catch(function(error) {
        // An error happened.
        console.log("error happened");
      });
    }

  }

登录组件

Login component

导出类LoginComponent {

export class LoginComponent {

form: FormGroup;

constructor(fb: FormBuilder, private _loginService: LoginService, private auth: AuthService){

    this.form = fb.group({
        email:['',Validators.required ],
  password:['',Validators.compose([Validators.required,

PasswordValidator.cannotContainSpace])] })

PasswordValidator.cannotContainSpace])] })

}

login(){
      this.auth.logUserIn(this.form.value.email, this.form.value.password);

};

}

app.component.ts ,因为我在 app.component.html

app.component.ts because I have my router outlet and links in app.component.html

export class AppComponent {

  title = 'angular-draganddrop';
  constructor(private auth: AuthService) { }
  LoggedIn() {
      return this.auth.isLoggedIn();
  }
  logout() {
    return this.auth.logOut();
  }
}

编辑

EDIT

因此,我检查了Chrome中的应用程序会话存储,并且注销后确实看到了我的用户电子邮件.我必须手动删除它.然后,在尝试首次登录时,它不起作用,会话存储中也没有用户电子邮件.第二次添加.在将sessionStorage功能添加到代码中之前,登录系统运行良好,因此肯定与此相关.我不知道sessionStorage的工作原理,所以我正在寻找帮助来解决这个问题.

So I checked application session storage in Chrome and when I log out I indeed see my user email still there. I have to delete it by hand. Then when trying to log in first time it doesn't work and there is also no user email in session storage. Second time it gets added. The login system was working fine until adding sessionStorage functionality to code so it's definitely related to it. I don't know how sessionStorage works so I'm looking for a help to solve this.

推荐答案

您需要使用会话,以便您可以考虑刷新页面来进行检查.

You'll need to use session, so that you can check it considering page refreshes.

只需设置&在服务AuthService-

public loggedIn = false;

constructor(private _firebaseAuth: AngularFireAuth, private router: Router) {
    this.loggedIn = !!sessionStorage.getItem('user');
}

// Set current user in your session after a successful login
setCurrentUser(email: String): void {
    sessionStorage.setItem('user', email);
    this.loggedIn = true;
}

// Get currently logged in user from session
getCurrentUser(): string | any {
    return sessionStorage.getItem('user') || undefined;
}

// Clear the session for current user & log the user out
logout() {
    sessionStorage.removeItem('user');
    this.loggedIn = false;
    // ... other code for logout
}

// The method to check whether user is logged in or not
isLoggedIn() {
    return this.loggedIn;
}

因此,您更新后的 logUserIn 方法为-

So, your updated logUserIn method would be -

logUserIn(email, pass) {
    firebase.auth().signInWithEmailAndPassword(email, pass).catch(function (error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        console.log("error" + error);
    })

    if (this.userDetails) {
        email = this.userDetails.email;
        console.log("hello im user" + " " + email);
        // setting user in session here --->
        this.setCurrentUser(email);
    } else {
        console.log("not working");
    }

    this.router.navigate(['']);
}

注销后,只需调用 logout() 即可,如上所示.

And while logging out, simply call the logout() as shown above.

然后只需将其添加为-

<li><a routerLink="login" routerLinkActive="active" *ngIf="!auth.isLoggedIn()">Login</a></li>

这篇关于Angular Firebase身份验证,如何检查用户是否已登录以隐藏导航链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆