[ Firebase 인증 ]
[ 파이어베이스 인증 ]
파이어 베이스는 앱에서 사용자 인증 시 필요한 백엔드 서비스와 사용하기 쉬운 SDK를 제공한다 .
이메일 / 구글 /Apple등 다양한 인증 방식이 존재한다 .
[ 기본 원리 ]
사용자를 앱에 로그인 시키려면 사용자에게 인증정보를 받아야 한다 .
해당 정보는 이메일주소/비밀번호이거나 제휴ID공급업체에서 받은 OAuth 토큰일수도 있다 .
해당 인증정보를 Firebase인증 SDK로 전달한다 . 이후 Firebase의 백엔드 서비스가 정보를 확인 , 클라이언트에
응답을 반환한다 .
[ 구현 경로 ]
=>다음의 과정을 거쳐 인증을 구현 할 것이다 .
[ Unity에서 Firebase 인증 시작하기 ]
[ 기본작업 ]
=>그전에 받은 유니티 패키지에서 FirebaseAuth를 프로젝트에 임포트 해준다 .
=>임포트중 다음과 같은 에러가 발생하였다 .JAVA_Home 해결을 통해 문제를 해결한다 .
=>콘솔로 이동하여 Authentification에서 SignInMethod를 클릭 사용하고자 하는 방식에서 설정을 진행한다 .
먼저 이메일 / 비밀번호를 사용해보겠다 .
=>해당 방식의 사용설정을 활성화 하고,저장해준다 .
=>Auth의 Setting에서 승인된 도메인에서온 로그인만 승인해주는 기능을 추가 할 수 있다.
=>이메일당 주소를 한개 혹은 여러개 만들기 선택 가능하다 .
=>버그성 플레이를 하는 사람들이 아이디 수백개를 생성후 돌릴수 있으므로 가입 할당량 역시 조절 가능하다 .
[ ui 구현 ]
[ 신규가입 ]
=>ID / PW를 입력할 수 있는 창을 생성한다 .
=>이때 , 파이어베이스의 내부규칙에 의해서 암호는 6자리 이상이 되어야지 다음의 오류가 생기지 않는다 .
그렇기에 , 6자리 이상의 PW를 쳤을때 계정생성과 로그인 버튼을 누를수 있게 해야 한다 .
=>이건 확인해봐여 하는데 암호규칙을 설정하는 것인듯? 아직 미확인인데 링크만 걸어둔다
[ 코드 구현 ]
[ 코드 구 ]
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Analytics;
using Firebase.Auth;
using System;
using TMPro;
public class Test : MonoBehaviour
{
Firebase.FirebaseApp app;
FirebaseAuth auth;//로그인 , 회원가입등에 사용
FirebaseUser user;
[SerializeField]TMP_InputField id;
[SerializeField] TMP_InputField pw;
// Start is called before the first frame update
void Start()
{
InitFirebase();
}
void InitFirebase()
{
//Check Dependencies
Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {
var dependencyStatus = task.Result;
if (dependencyStatus == Firebase.DependencyStatus.Available)
{
// Create and hold a reference to your FirebaseApp,
// where app is a Firebase.FirebaseApp property of your application class.
app = Firebase.FirebaseApp.DefaultInstance;
// Set a flag here to indicate whether Firebase is ready to use by your app.
FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
}
else
{
UnityEngine.Debug.LogError(System.String.Format(
"Could not resolve all Firebase dependencies: {0}", dependencyStatus));
// Firebase Unity SDK is not safe to use here.
}
});
//auth Init
auth = FirebaseAuth.DefaultInstance;
auth.StateChanged += OnChanged;
}
//계정 생성
public void MakeAccount()
{
auth.CreateUserWithEmailAndPasswordAsync(id.text, pw.text).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.Log("계정 생성이 실패하였습니다");
return;
}
if (task.IsFaulted)
{
Debug.Log($"{task.Exception} 의에러가 발생하며 계정생성이 실패");
}
//유저 생성이 성공했다면
AuthResult result = task.Result;
Debug.LogFormat("Firebase 유저가 생성되었습니다{0} / {1}", result.User.DisplayName, result.User.UserId);
});
}
//로그인
public void LogIn()
{
auth.SignInWithEmailAndPasswordAsync(id.text, pw.text).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.Log("로그인이 실패하였습니다");
return;
}
if (task.IsFaulted)
{
Debug.Log($"{task.Exception} 의에러가 발생하며 로그인이 실패");
}
//유저 생성이 성공했다면
AuthResult result = task.Result;
Debug.LogFormat("Firebase 유저가 로그인되었습니다{0} / {1}", result.User.DisplayName, result.User.UserId);
});
}
//로그아웃
public void LogOut()
{
auth.SignOut();
Debug.Log("로그아웃");
}
//계정 상태가 바뀔때마다 호출
void OnChanged(object sender,EventArgs e)
{
if(auth.CurrentUser!=user)//계정상태에 변화가 있다면
{
bool signedIn = auth.CurrentUser != user && auth.CurrentUser != null && auth.CurrentUser.IsValid() ;
if (signedIn == false && user != null)
Debug.Log("로그아웃" + user.UserId);
//로그아웃이 아니라면 로그인을 새롭게 한 것이다
user = auth.CurrentUser;
if (signedIn)
{
Debug.Log("로그인");
//로그인까지 진행
}
}
}
}
=>계정생성 성공시 다음과 같이 사용자가 추가된다 .
https://inyongs.tistory.com/35 : GPGS와 연결
'유니티 > Firebase' 카테고리의 다른 글
[ Firebase ] IOS 인증 구현 02 . 구현하기 (0) | 2023.07.11 |
---|---|
[ Firebase ] IOS 인증 구현 01 . 세팅하기 (0) | 2023.07.11 |
[ Firebase ] Storage (0) | 2023.06.18 |
[ Firebase ] 01 . 기초 알아보기 (0) | 2023.06.16 |