Skip to content

Instantly share code, notes, and snippets.

@varmil
Last active November 14, 2021 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varmil/b3b0ad65c98d12b44603f61e54853da0 to your computer and use it in GitHub Desktop.
Save varmil/b3b0ad65c98d12b44603f61e54853da0 to your computer and use it in GitHub Desktop.
the singleton class when run e2e testing with Firebase Authentication x Local Emulator Suite
import * as admin from 'firebase-admin'
import axios from 'axios'
const PROJECT_ID = 'your-project-id'
type FirebaseAuthAPIUser = {
idToken: string // 新しく作成されたユーザーのFirebaseAuthIDトークン。
email: string // 新しく作成されたユーザーの電子メール。
refreshToken: string // 新しく作成されたユーザーのFirebaseAuth更新トークン。
expiresIn: string // IDトークンの有効期限が切れる秒数。
localId: string // 新しく作成されたユーザーのuid。
}
/**
* Firebase AuthenticationのSeeding用シングルトンクラス
* テスト用に1ユーザーのみを内部で状態保持する
*
* @example
* await LocalEmulatorAuthSingleton.seed()
* await LocalEmulatorAuthSingleton.signin()
* const idToken = LocalEmulatorAuthSingleton.idToken()
*/
class LocalEmulatorAuthSingleton {
private readonly EMail = 'e2e-user@example.com'
private readonly Password = 'secretPassword'
private user: FirebaseAuthAPIUser
constructor() {
// エミュレータに接続
// see:
// https://firebase.google.com/docs/emulator-suite/connect_auth?hl=ja#android_ios_and_web_sdks
admin.initializeApp({ projectId: PROJECT_ID })
}
seed = async () => {
await this.clearUser()
this.user = await this.signup()
console.log('Successfully created new user')
}
/**
* 既にsignup済みのユーザーアカウントでsigninします
* https://firebase.google.com/docs/reference/rest/auth?hl=ja#section-sign-in-email-password
*/
signin = async (): Promise<void> => {
const payload = {
email: this.EMail,
password: this.Password,
returnSecureToken: true
}
const { data } = await axios.post(
'http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=fake-api-key',
payload
)
this.user = data
}
uid = () => this.user.localId
idToken = () => this.user.idToken
/**
* https://firebase.google.com/docs/reference/rest/auth?hl=ja#section-create-email-password
*/
private signup = async (): Promise<FirebaseAuthAPIUser> => {
const payload = {
email: this.EMail,
password: this.Password,
returnSecureToken: true
}
const { data } = await axios.post(
'http://localhost:9099/identitytoolkit.googleapis.com/v1/accounts:signUp?key=fake-api-key',
payload
)
return data
}
/**
* https://firebase.google.com/docs/reference/rest/auth?hl=ja#section-auth-emulator-clearaccounts
*/
private clearUser = async () => {
await axios.delete(
`http://localhost:9099/emulator/v1/projects/${PROJECT_ID}/accounts`
)
}
}
export const LocalEmulatorAuth = new LocalEmulatorAuthSingleton()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment