programing

업데이트 후 사용자가 FireBase 앱에 로그인하도록 하려면 어떻게 해야 합니까?

iphone6s 2023. 3. 18. 08:23
반응형

업데이트 후 사용자가 FireBase 앱에 로그인하도록 하려면 어떻게 해야 합니까?

파이어베이스에 angular를 내장한 어플리케이션을 가지고 있으며, 페이지를 갱신한 후에도 로그인을 계속할 수 있도록 하고 싶습니다.현재 로그인 화면에는 컨트롤러에 바인드되어 있는2개의 기본 입력 필드가 있습니다.

    this.email = "";
    this.pass = "";
    this.emessage = "";

    this.loginUser = function() {
        ref.authWithPassword({
            email: this.email,
            password: this.pass
        }, function(error, authData) {
            if (error) {
                console.log("Login Failed!", error);
                this.emessage = error.message;
                $scope.$apply();
            } else {
                dataStorage.uid = authData.uid;
                $location.path('/projects');
                $scope.$apply(); 
            }
        }.bind(this));
    }

이 조작은 정상적으로 동작하고 있습니다만, 유저가 페이지를 갱신하면, 로그아웃 됩니다.컨트롤러가 로딩되었을 때 사용자가 이미 로그인하고 있는지 확인하고 자동 리다이렉트를 할 수 있는 방법이 있습니까?감사합니다!

현재 보유하고 있는 코드가 사용자가 로그온하는 경우를 처리합니다.사용자가 이미 로그한 경우를 처리하려면onAuthStateChanged방법:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // User is not signed in.
  }
});

일반적으로 이 기능의 다른 부분에는 로그온 버튼만 표시합니다.

문서: 파이어베이스.auth.auth


오래된 답변(사용되지 않음/보관됨):

현재 보유하고 있는 코드가 사용자가 로그온하는 경우를 처리합니다.사용자가 이미 로그한 경우를 처리하려면 인증 상태를 모니터링합니다.인증 상태 모니터링에 대한 Firebase 문서에서 다음을 수행합니다.

// Create a callback which logs the current auth state
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
  if (authData) {
    console.log("User " + authData.uid + " is logged in with " + authData.provider);
  } else {
    console.log("User is logged out");
  }
});

일반적으로 로그온 버튼은else이 기능을 사용합니다.

댓글에 기재되어 있는 바와 같이, 받아들여진 답변은 더 이상 기능하지 않습니다.현재 사용자가 로그인하고 있는지 확인하는 방법은 다음과 같습니다.

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  }
});

(https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onAuthStateChanged)에서 입수).

웹 앱에 보호된 기능이 있는 공용 페이지가 있다는 문제가 있습니다.다음 코드를 사용하면 사용자는 항상 Firebase SDK를 통해 로드됩니다(로그인한 경우).다만, 로그인 페이지에 인증이 필요한 경우는, 로그인 페이지로 리다이렉트 됩니다.페이지 새로고침 시 이 작업은 정상적으로 수행됩니다.

Router.beforeEach((to, from, next) => {

  // If route required authentication
  if (to.matched.some(record => record.meta.requiresAuth)) {

    // Load user
    firebase.auth().onAuthStateChanged(user => {

      // If user obj does not exist --> redirect to login page
      if (!user) {
        next({ name: 'login' });
      } else {
        store.commit("user/SET_USER", user);
        user.getIdToken().then(token => {
          store.commit("user/SET_TOKEN", token)
        });

        next();
      }
    });
  } else {

    // Path does not required auth - Still we check the user
    firebase.auth().onAuthStateChanged(user => {

      // If user exist (is logged in) --> store in state.
      if (user) {  
        store.commit("user/SET_USER", user);
        user.getIdToken().then(token => {
          store.commit("user/SET_TOKEN", token)
        });
        next();

      } else {
        next();
      }
    });
  }
})

모든 리액트JS 사용자, 현재 사용자가 기록되지 않은 경우 로그인 경로로 사용자를 리디렉션하는 이 스레드에 제공된 답변을 기반으로 만든 간단한 후크입니다.들어가세요.

import { useEffect } from 'react';
import * as firebase from 'firebase';
import { useHistory } from 'react-router-dom';

export default function useProtectedRoute() {
  const history = useHistory();

  useEffect(() => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (!user) {
        console.error(
          'Access to protected route denied, redirecting to login...'
        );
        history.push('/auth/login');
      }
    });
  }, [history]);
}

사용자가 로그인하지 않는 한 렌더링하지 않을 구성 요소 내에서 이 후크를 가져와 실행하면 됩니다.

예:

import React from 'react';
import useProtectedRoute from 'hooks/useProtectedRoute';

export default function UserDetailsComponent() {
  useProtectedRoute();
  return <div>This is only visible when user is logged in</div>;
}

Angular 4를 사용하는 경우 AngularFire2 - 공식 Firebase Integration을 사용할 수 있습니다.

Angular Fire2를 랩하는 Auth Service가 있습니다.서비스 컨스트럭터에서 Auth Session을 가져와 필요할 때 사용합니다.예:

@Injectable()
export class AuthenticationService {

    private authState: any;

    constructor(public afAuth: AngularFireAuth) {
        this.afAuth.authState.subscribe((auth) => {
          this.authState = auth
        });
    }

    get user(): any {
        return this.authenticated ? this.authState : null;
    }
}

Full Angular 4 with Firebase의 완전한 인증 서비스 코드

기타 옵션 session스토리지

여기를 참조해 주세요.

Angular Firebase 인증, 사용자가 로그인 링크를 탐색에서 숨기기 위해 로그인했는지 확인하는 방법

언급URL : https://stackoverflow.com/questions/32253413/how-do-i-keep-a-user-logged-into-a-firebase-app-after-refresh

반응형