auth.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. import {
  2. User,
  3. getAuth,
  4. onAuthStateChanged,
  5. onIdTokenChanged,
  6. signInWithPopup,
  7. GoogleAuthProvider,
  8. GithubAuthProvider,
  9. signInWithEmailAndPassword as signInWithEmailAndPass,
  10. isSignInWithEmailLink as isSignInWithEmailLinkFB,
  11. fetchSignInMethodsForEmail,
  12. sendSignInLinkToEmail,
  13. signInWithEmailLink as signInWithEmailLinkFB,
  14. ActionCodeSettings,
  15. signOut,
  16. linkWithCredential,
  17. AuthCredential,
  18. UserCredential,
  19. updateProfile,
  20. } from "firebase/auth"
  21. import {
  22. onSnapshot,
  23. getFirestore,
  24. setDoc,
  25. doc,
  26. updateDoc,
  27. } from "firebase/firestore"
  28. import {
  29. BehaviorSubject,
  30. distinctUntilChanged,
  31. filter,
  32. map,
  33. Subject,
  34. Subscription,
  35. } from "rxjs"
  36. import { onBeforeUnmount, onMounted } from "@nuxtjs/composition-api"
  37. import {
  38. setLocalConfig,
  39. getLocalConfig,
  40. removeLocalConfig,
  41. } from "~/newstore/localpersistence"
  42. export type HoppUser = User & {
  43. provider?: string
  44. accessToken?: string
  45. }
  46. type AuthEvents =
  47. | { event: "probable_login"; user: HoppUser } // We have previous login state, but the app is waiting for authentication
  48. | { event: "login"; user: HoppUser } // We are authenticated
  49. | { event: "logout" } // No authentication and we have no previous state
  50. | { event: "authTokenUpdate"; user: HoppUser; newToken: string | null } // Token has been updated
  51. /**
  52. * A BehaviorSubject emitting the currently logged in user (or null if not logged in)
  53. */
  54. export const currentUser$ = new BehaviorSubject<HoppUser | null>(null)
  55. /**
  56. * A BehaviorSubject emitting the current idToken
  57. */
  58. export const authIdToken$ = new BehaviorSubject<string | null>(null)
  59. /**
  60. * A subject that emits events related to authentication flows
  61. */
  62. export const authEvents$ = new Subject<AuthEvents>()
  63. /**
  64. * Like currentUser$ but also gives probable user value
  65. */
  66. export const probableUser$ = new BehaviorSubject<HoppUser | null>(null)
  67. /**
  68. * Resolves when the probable login resolves into proper login
  69. */
  70. export const waitProbableLoginToConfirm = () =>
  71. new Promise<void>((resolve, reject) => {
  72. if (authIdToken$.value) resolve()
  73. if (!probableUser$.value) reject(new Error("no_probable_user"))
  74. const sub = authIdToken$.pipe(filter((token) => !!token)).subscribe(() => {
  75. sub?.unsubscribe()
  76. resolve()
  77. })
  78. })
  79. /**
  80. * Initializes the firebase authentication related subjects
  81. */
  82. export function initAuth() {
  83. const auth = getAuth()
  84. const firestore = getFirestore()
  85. let extraSnapshotStop: (() => void) | null = null
  86. probableUser$.next(JSON.parse(getLocalConfig("login_state") ?? "null"))
  87. onAuthStateChanged(auth, (user) => {
  88. /** Whether the user was logged in before */
  89. const wasLoggedIn = currentUser$.value !== null
  90. if (user) {
  91. probableUser$.next(user)
  92. } else {
  93. probableUser$.next(null)
  94. removeLocalConfig("login_state")
  95. }
  96. if (!user && extraSnapshotStop) {
  97. extraSnapshotStop()
  98. extraSnapshotStop = null
  99. } else if (user) {
  100. // Merge all the user info from all the authenticated providers
  101. user.providerData.forEach((profile) => {
  102. if (!profile) return
  103. const us = {
  104. updatedOn: new Date(),
  105. provider: profile.providerId,
  106. name: profile.displayName,
  107. email: profile.email,
  108. photoUrl: profile.photoURL,
  109. uid: profile.uid,
  110. }
  111. setDoc(doc(firestore, "users", user.uid), us, { merge: true }).catch(
  112. (e) => console.error("error updating", us, e)
  113. )
  114. })
  115. extraSnapshotStop = onSnapshot(
  116. doc(firestore, "users", user.uid),
  117. (doc) => {
  118. const data = doc.data()
  119. const userUpdate: HoppUser = user
  120. if (data) {
  121. // Write extra provider data
  122. userUpdate.provider = data.provider
  123. userUpdate.accessToken = data.accessToken
  124. }
  125. currentUser$.next(userUpdate)
  126. }
  127. )
  128. }
  129. currentUser$.next(user)
  130. // User wasn't found before, but now is there (login happened)
  131. if (!wasLoggedIn && user) {
  132. authEvents$.next({
  133. event: "login",
  134. user: currentUser$.value!!,
  135. })
  136. } else if (wasLoggedIn && !user) {
  137. // User was found before, but now is not there (logout happened)
  138. authEvents$.next({
  139. event: "logout",
  140. })
  141. }
  142. })
  143. onIdTokenChanged(auth, async (user) => {
  144. if (user) {
  145. authIdToken$.next(await user.getIdToken())
  146. authEvents$.next({
  147. event: "authTokenUpdate",
  148. newToken: authIdToken$.value,
  149. user: currentUser$.value!!, // Force not-null because user is defined
  150. })
  151. setLocalConfig("login_state", JSON.stringify(user))
  152. } else {
  153. authIdToken$.next(null)
  154. }
  155. })
  156. }
  157. export function getAuthIDToken(): string | null {
  158. return authIdToken$.getValue()
  159. }
  160. /**
  161. * Sign user in with a popup using Google
  162. */
  163. export async function signInUserWithGoogle() {
  164. return await signInWithPopup(getAuth(), new GoogleAuthProvider())
  165. }
  166. /**
  167. * Sign user in with a popup using Github
  168. */
  169. export async function signInUserWithGithub() {
  170. return await signInWithPopup(
  171. getAuth(),
  172. new GithubAuthProvider().addScope("gist")
  173. )
  174. }
  175. /**
  176. * Sign user in with email and password
  177. */
  178. export async function signInWithEmailAndPassword(
  179. email: string,
  180. password: string
  181. ) {
  182. return await signInWithEmailAndPass(getAuth(), email, password)
  183. }
  184. /**
  185. * Gets the sign in methods for a given email address
  186. *
  187. * @param email - Email to get the methods of
  188. *
  189. * @returns Promise for string array of the auth provider methods accessible
  190. */
  191. export async function getSignInMethodsForEmail(email: string) {
  192. return await fetchSignInMethodsForEmail(getAuth(), email)
  193. }
  194. export async function linkWithFBCredential(
  195. user: User,
  196. credential: AuthCredential
  197. ) {
  198. return await linkWithCredential(user, credential)
  199. }
  200. /**
  201. * Sends an email with the signin link to the user
  202. *
  203. * @param email - Email to send the email to
  204. * @param actionCodeSettings - The settings to apply to the link
  205. */
  206. export async function signInWithEmail(
  207. email: string,
  208. actionCodeSettings: ActionCodeSettings
  209. ) {
  210. return await sendSignInLinkToEmail(getAuth(), email, actionCodeSettings)
  211. }
  212. /**
  213. * Checks and returns whether the sign in link is an email link
  214. *
  215. * @param url - The URL to look in
  216. */
  217. export function isSignInWithEmailLink(url: string) {
  218. return isSignInWithEmailLinkFB(getAuth(), url)
  219. }
  220. /**
  221. * Sends an email with sign in with email link
  222. *
  223. * @param email - Email to log in to
  224. * @param url - The action URL which is used to validate login
  225. */
  226. export async function signInWithEmailLink(email: string, url: string) {
  227. return await signInWithEmailLinkFB(getAuth(), email, url)
  228. }
  229. /**
  230. * Signs out the user
  231. */
  232. export async function signOutUser() {
  233. if (!currentUser$.value) throw new Error("No user has logged in")
  234. await signOut(getAuth())
  235. }
  236. /**
  237. * Sets the provider id and relevant provider auth token
  238. * as user metadata
  239. *
  240. * @param id - The provider ID
  241. * @param token - The relevant auth token for the given provider
  242. */
  243. export async function setProviderInfo(id: string, token: string) {
  244. if (!currentUser$.value) throw new Error("No user has logged in")
  245. const us = {
  246. updatedOn: new Date(),
  247. provider: id,
  248. accessToken: token,
  249. }
  250. try {
  251. await updateDoc(
  252. doc(getFirestore(), "users", currentUser$.value.uid),
  253. us
  254. ).catch((e) => console.error("error updating", us, e))
  255. } catch (e) {
  256. console.error("error updating", e)
  257. throw e
  258. }
  259. }
  260. /**
  261. * Sets the user's display name
  262. *
  263. * @param name - The new display name
  264. */
  265. export async function setDisplayName(name: string) {
  266. if (!currentUser$.value) throw new Error("No user has logged in")
  267. const us = {
  268. displayName: name,
  269. }
  270. try {
  271. await updateProfile(currentUser$.value, us).catch((e) =>
  272. console.error("error updating", us, e)
  273. )
  274. } catch (e) {
  275. console.error("error updating", e)
  276. throw e
  277. }
  278. }
  279. export function getGithubCredentialFromResult(result: UserCredential) {
  280. return GithubAuthProvider.credentialFromResult(result)
  281. }
  282. /**
  283. * A Vue composable function that is called when the auth status
  284. * is being updated to being logged in (fired multiple times),
  285. * this is also called on component mount if the login
  286. * was already resolved before mount.
  287. */
  288. export function onLoggedIn(exec: (user: HoppUser) => void) {
  289. let sub: Subscription | null = null
  290. onMounted(() => {
  291. sub = currentUser$
  292. .pipe(
  293. map((user) => !!user), // Get a logged in status (true or false)
  294. distinctUntilChanged(), // Don't propagate unless the status updates
  295. filter((x) => x) // Don't propagate unless it is logged in
  296. )
  297. .subscribe(() => {
  298. exec(currentUser$.value!)
  299. })
  300. })
  301. onBeforeUnmount(() => {
  302. sub?.unsubscribe()
  303. })
  304. }