programing

사용자가 이미 Firebase에 로그인되어 있는지 어떻게 탐지합니까?

javajsp 2023. 6. 28. 21:19

사용자가 이미 Firebase에 로그인되어 있는지 어떻게 탐지합니까?

구글 로그인을 위해 자바스크립트 파일에 파이어베이스 노드 api를 사용하고 있습니다.

firebase.initializeApp(config);
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider);

이것은 잘 작동하며 사용자는 Google 자격 증명으로 로그인할 수 있습니다.사용자가 페이지를 다시 방문하면 팝업이 다시 열리지만 이미 로그인했기 때문에 사용자의 조작 없이 팝업이 닫힙니다.팝업을 표시하기 전에 로그인한 사용자가 있는지 확인할 수 있는 방법이 있습니까?

https://firebase.google.com/docs/auth/web/manage-users

인증 상태 변경 관찰자를 추가해야 합니다.

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

또한 현재 사용자가 있는지 확인할 수 있습니다.

var user = firebase.auth().currentUser;

if (user) {
  // User is signed in.
} else {
  // No user is signed in.
}

페이지를 로드하기 시작할 때 사용자가 서명할지 여부는 알 수 없지만 해결 방법이 있습니다.

localStorage에 대한 마지막 인증 상태를 기억하여 세션 간 및 탭 간에 유지할 수 있습니다.

다음 로드되기 까지 대화 할 것이라고 으로 가정할 수 즉, 다음에 " 그다페가다로자다고확사시하로때실질해있이까대수후지상연니다시습화간할기자를음인용그런자가동작면으하로음시이드기지되다▁then▁until▁dialogie▁the▁starts,▁the▁when이▁will후▁you,▁optim▁you▁().onAuthStateChanged화재).그렇지 않으면, 만약에localStorage키가 비어 있습니다. 대화 상자를 바로 표시할 수 있습니다.

기지onAuthStateChanged이벤트는 페이지 로드 후 약 2초 후에 실행됩니다.

// User signed out in previous session, show dialog immediately because there will be no auto-login
if (!localStorage.getItem('myPage.expectSignIn')) showDialog() // or redirect to sign-in page

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // User just signed in, we should not display dialog next time because of firebase auto-login
    localStorage.setItem('myPage.expectSignIn', '1')
  } else {
    // User just signed-out or auto-login failed, we will show sign-in form immediately the next time he loads the page
    localStorage.removeItem('myPage.expectSignIn')

    // Here implement logic to trigger the login dialog or redirect to sign-in page, if necessary. Don't redirect if dialog is already visible.
    // e.g. showDialog()
  }
})



I am using this with 반응 and 반응 반응성의. I put the code above into componentDidMount of my App root component. There, in the render, I have some PrivateRoutes

<Router>
  <Switch>
    <PrivateRoute
      exact path={routes.DASHBOARD}
      component={pages.Dashboard}
    />
...

다음은 내 Private Route가 구현되는 방법입니다.

export default function PrivateRoute(props) {
  return firebase.auth().currentUser != null
    ? <Route {...props}/>
    : localStorage.getItem('myPage.expectSignIn')
      // if user is expected to sign in automatically, display Spinner, otherwise redirect to login page.
      ? <Spinner centered size={400}/>
      : (
        <>
          Redirecting to sign in page.
          { location.replace(`/login?from=${props.path}`) }
        </>
      )
}

    // Using router Redirect instead of location.replace
    // <Redirect
    //   from={props.path}
    //   to={{pathname: routes.SIGN_IN, state: {from: props.path}}}
    // />

이 시나리오에서는 AuthStateChanged() 함수를 사용할 필요가 없습니다.

다음을 실행하여 사용자가 기록되었는지 여부를 쉽게 탐지할 수 있습니다.

var user = firebase.auth().currentUser;

"귀환 무효" 문제에 직면한 사람들의 경우, 소방서 호출이 완료되기를 기다리지 않기 때문입니다.

A페이지에서 로그인 작업을 수행한 다음 B페이지를 호출한다고 가정하고, B페이지에서 다음 JS 코드를 호출하여 예상되는 동작을 테스트할 수 있습니다.

  var config = {
    apiKey: "....",
    authDomain: "...",
    databaseURL: "...",
    projectId: "..",
    storageBucket: "..",
    messagingSenderId: ".."
  };
  firebase.initializeApp(config);

    $( document ).ready(function() {
        console.log( "testing.." );
        var user = firebase.auth().currentUser;
        console.log(user);
    });

사용자가 기록되면 "var user"에 예상되는 JSON 페이로드가 포함되고, 그렇지 않으면 "null"이 됩니다.

그리고 그것이 당신이 필요로 하는 전부입니다.

안부 전해요

또 다른 방법은 소방대가 사용하는 것과 같은 것을 사용하는 것입니다.

예를 들어 사용자가 로그인할 때 Firebase는 아래의 세부 정보를 로컬 저장소에 저장합니다.사용자가 페이지로 돌아오면, 파이어베이스는 동일한 방법을 사용하여 사용자가 자동으로 로그인해야 하는지 여부를 식별합니다.

enter image description here

ATTN: 이것은 소방대에 의해 나열되거나 권장되지 않기 때문입니다.당신은 이 방법을 비공식적인 방법이라고 부를 수 있습니다.즉, 나중에 소방서에서 내부 작업을 변경하면 이 방법이 작동하지 않을 수 있습니다.아니면 간단히 말하면.본인 부담으로 사용하세요! :)

효과:

async function IsLoggedIn(): Promise<boolean> {
  try {
    await new Promise((resolve, reject) =>
      app.auth().onAuthStateChanged(
        user => {
          if (user) {
            // User is signed in.
            resolve(user)
          } else {
            // No user is signed in.
            reject('no user logged in')
          }
        },
        // Prevent console error
        error => reject(error)
      )
    )
    return true
  } catch (error) {
    return false
  }
}

전자 메일로 로그인한 사용자뿐만 아니라 익명 사용자도 허용하는 경우 사용할 수 있습니다.firebase.auth().currentUser.isAnonymous어느 쪽이든 돌아올 것입니다.true또는false.

기술적으로 약속에는 세 가지 가능성이 있습니다.

// 1) best option, as it waits on user...

const isLoggedIn: any = await new Promise((resolve: any, reject: any) =>
this.afa.onAuthStateChanged((user: any) =>
  resolve(user), (e: any) => reject(e)));

console.log(isLoggedIn);

// 2) may experience logging out state problems...

const isLoggedIn2 = await this.afa.authState.pipe(first()).toPromise();

console.log(isLoggedIn2);

// 3) technically has a 3rd option 'unknown' before user is loaded...

const isLoggedIn3 = await this.afa.currentUser;

console.log(isLoggedIn3);


// then do something like (depending on your needs) with 1, 2, or 3:

if (!!isLoggedIn) {
  // logged in
}

또한 예제는 각도가 있지만 대체할 수 있습니다.this.afa와 함께firebase.auth()

사용하다Firebase.getAuth()Firebase 클라이언트의 현재 상태를 반환합니다.그렇지 않으면 반환 값은 다음과 같습니다.null다음 문서가 있습니다. https://www.firebase.com/docs/web/api/firebase/getauth.html

최신 라이브러리 버전의 사용 예

import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth";

const firebaseConfig = {
  ...
};

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

onAuthStateChanged(auth, user => {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
})

Firebase v9.8.1 및 Angular v13.3.5의 경우 Angular Fire를 사용하지 않고 잘 작동하는 이 서비스를 사용했습니다.

@Injectable({providedIn: 'root'})
export class IsAuthenticatedGuard implements CanActivate {

  canActivate(): Promise<boolean> {
    return new Promise(resolve =>
      onAuthStateChanged(getAuth(),
        user => resolve(!!user),
        _ => resolve(false)));
  }

}

또한 컨텍스트에서 사용 효과 후크를 사용하여 사용자가 페이지별로 인증되었는지 확인할 수 있습니다(사용자가 페이지로 이동할 때).그러나 인증 페이지는 포함하지 마십시오.

  React.useEffect(() => {
    if (router.asPath !== "/auth") {
      onAuthStateChanged(auth, (user) => {
        if (!user) {
          window.location.href = "/auth";
        }
      });
    }
  }, [router]);

여기서 나는 nextJS를 사용하고 있었지만 반응만 해도 거의 같습니다.제이에스

먼저 다음을 가져옵니다.

import Firebase
import FirebaseAuth

그리고나서

    // Check if logged in
    if (Auth.auth().currentUser != null) {
      // User is logged in   
    }else{
      // User is not logged in
    }

언급URL : https://stackoverflow.com/questions/37873608/how-do-i-detect-if-a-user-is-already-logged-in-firebase