简体   繁体   English

Firebase - 重定向到不同页面时保持用户登录

[英]Firebase - Keep user signed in when redirecting to different page

I have 2 components to my website:我的网站有 2 个组件:

  1. The landing page with a sign up form ( https://example.com )带有注册表单的登录页面 ( https://example.com )

  2. The single page anuglarjs application ( https://app.example.com )单页 anuglarjs 应用程序 ( https://app.example.com )

What I want to achieve is when the users comes to the landing page, they are able to sign up using Firebase, and once the sign up is complete, redirect the user to the single page application and automatically be signed in, so they don't have to enter their information again.我想要实现的是,当用户来到登陆页面时,他们能够使用 Firebase 进行注册,一旦注册完成,将用户重定向到单页应用程序并自动登录,这样他们就不会'不必再次输入他们的信息。

Here is my code for the landing page sign up:这是我的登陆页面注册代码:

Handling the sign up button press处理注册按钮按下

$('.signUpBtn').click(function() {
        let name = $('#firstName').val();
        let email = $('#clientEmail').val();
        let pw = $('#clientPw').val();
        if (name != "" && email != "" && pw != "") {
            if (pw.length > 7) {
                firebase.auth().createUserWithEmailAndPassword(email, pw)
                    .then(function(user) {
                        ga('send', 'event', 'New account via landing page', 'created');
                        updateUser(name, email, true);
                        user.sendEmailVerification();
                    })
                    .catch(function(error) {
                        // Handle Errors here.
                        var errorCode = error.code;
                        var errorMessage = error.message;
                        showError(errorMessage);
                        console.log(errorMessage);
                        // ...
                    });
            } else {
                showError("Oops. The password must be at least 8 characters...");
            }
        } else {
            showError("Oops. The email, name, and password can not be empty...");
        }
    });

Handling the information that should get pushed to the user 'profile':处理应该推送到用户“个人资料”的信息:

    function updateUser(name, email, clicked) {
        firebase.auth().onAuthStateChanged(function(user) {
            if (user && name != "" && email != "" && name != undefined && email != undefined) {
               name = name.charAt(0).toUpperCase() + name.slice(1);
                user.updateProfile({
                    displayName: name
                  }).then(function() {
                    firebase.database().ref('users/' + user.uid + '/user/').update({
                          name: name,
                          email: email,
                          first_signin: new Date(),
                          email_verified: false,
                          email_reminders: true,
                          pts: 0,
                          first_visit: true
                      }).then((snap) => {
                          console.log(snap)
                          window.location = 'https://app.example.com';
                      });
                  });
            } else {

            }
        });
    }

Pretty elementary Firebase stuff...相当基本的 Firebase 东西......

Here is my code for the app.example.com single page angularjs app for handling the user authentication:这是我用于处理用户身份验证的app.example.com单页 angularjs 应用程序的代码:

firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
           //show their data
      } else {
           //show login component
      }
});

Again, pretty simple stuff.再次,非常简单的东西。

The problem I'm having is that when it redirects the user, it doesn't have them signed in. It shows the login component, which, if you then type in the credentials you just signed up, totally works, but I want the user to be logged in as soon as they hit the page.我遇到的问题是,当它重定向用户时,并没有让他们登录。它显示了登录组件,如果你输入刚刚注册的凭据,它完全可以工作,但我想要用户在点击页面后立即登录。

Is there something I'm missing?有什么我想念的吗? It should work as far as I can tell..据我所知,它应该有效..

Any ideas?有任何想法吗? Thank you.谢谢你。

Firebase Auth sessions are single host origin. Firebase Auth会话是单个主机来源。 They are persisted via localStorage/indexedDB. 它们通过localStorage / indexedDB持久化。 (They do offer session and no persistence too: https://firebase.google.com/docs/auth/web/auth-state-persistence ) (他们确实提供会话并且也没有持久性: https : //firebase.google.com/docs/auth/web/auth-state-persistence

This is why you are unable to access the auth state in a different subdomain. 这就是为什么您无法在其他子域中访问身份验证状态的原因。 You are signing in on https://example.com and then navigating to https://app.example.com , but the auth state is only persisted in the former. 您正在https://example.com上登录,然后导航到https://app.example.com ,但是auth状态仅在前者中保持不变。

I think that's possible:我认为这是可能的:

firebase.auth().signInWithCustomToken(token)
  .then((userCredential) => {
    // Signed in
    var user = userCredential.user;
    // ...
  })
  .catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    // ...
  });

But you need to generate a token before.但是之前需要生成一个token。 I am not a Firebase expert.我不是 Firebase 专家。 Can someone please correct me?有人可以纠正我吗?

Source: https://firebase.google.com/docs/auth/admin/create-custom-tokens#web来源: https : //firebase.google.com/docs/auth/admin/create-custom-tokens#web

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM