Deployed the page to Github Pages.

This commit is contained in:
Batuhan Berk Başoğlu 2024-11-03 21:30:09 -05:00
parent 1d79754e93
commit 2c89899458
Signed by: batuhan-basoglu
SSH key fingerprint: SHA256:kEsnuHX+qbwhxSAXPUQ4ox535wFHu/hIRaa53FzxRpo
62797 changed files with 6551425 additions and 15279 deletions

View file

@ -0,0 +1,162 @@
# 5. Getting started with Firebase Authentication
`AngularFireAuth.user` provides you an `Observable<User|null>` to monitor your application's authentication State.
`AngularFireAuth` promise proxies an initialized
`firebase.auth.Auth` instance, allowing you to log users in, out, etc. [See
the Firebase docs for more information on what methods are available.](https://firebase.google.com/docs/reference/js/firebase.auth.Auth)
> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md).
**Example app:**
```ts
import { Component } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';
@Component({
selector: 'app-root',
template: `
<div *ngIf="auth.user | async as user; else showLogin">
<h1>Hello {{ user.displayName }}!</h1>
<button (click)="logout()">Logout</button>
</div>
<ng-template #showLogin>
<p>Please login.</p>
<button (click)="login()">Login with Google</button>
</ng-template>
`,
})
export class AppComponent {
constructor(public auth: AngularFireAuth) {
}
login() {
this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
}
logout() {
this.auth.signOut();
}
}
```
## Configuration with Dependency Injection
The AngularFireAuth Module provides several DI tokens to further configure your
authentication process.
### Configure
Using the `SETTINGS` DI Token (*default: null*), we can set the current Auth
instance's settings. This is used to edit/read configuration related options
like app verification mode for phone authentication, which is useful for
[testing](https://cloud.google.com/identity-platform/docs/test-phone-numbers).
```ts
import { SETTINGS as AUTH_SETTINGS } from '@angular/fire/compat/auth';
@NgModule({
// ... Existing configuration
providers: [
// ... Existing Providers
{ provide: AUTH_SETTINGS, useValue: { appVerificationDisabledForTesting: true } },
]
})
export class AppModule { }
```
Read more at [Firebase Auth Settings](https://firebase.google.com/docs/reference/js/firebase.auth.AuthSettings).
### Use Current Browser Language
Using the `USE_DEVICE_LANGUAGE` DI Token (*default: null*), which is a boolean
that allow you to set the current language to the default device/browser
preference. This allows to localize emails but be aware that this only applies
if you use the standard template provided by Firebase.
```ts
import { USE_DEVICE_LANGUAGE } from '@angular/fire/compat/auth';
@NgModule({
// ... Existing configuration
providers: [
// ... Existing Providers
{ provide: USE_DEVICE_LANGUAGE, useValue: true },
]
})
export class AppModule { }
```
If you want to set a different language, you can use `LANGUAGE_CODE` DI Token
(*default: null*).
More info at the [firebase auth docs](https://firebase.google.com/docs/reference/js/firebase.auth.Auth#languagecode).
```ts
import { LANGUAGE_CODE } from '@angular/fire/compat/auth';
@NgModule({
// ... Existing configuration
providers: [
// ... Existing Providers
{ provide: LANGUAGE_CODE, useValue: 'fr' },
]
})
export class AppModule { }
```
### Persistence
Firebase Auth default behavior is to persist a user's session even after the
user closes the browser. To change the current type of persistence on the
current Auth instance for the currently saved Auth session and apply this type
of persistence for future sign-in requests, including sign-in with redirect
requests, you can use the `PERSISTENCE` DI Token (*default: null*).
The possible types are `'local'`, `'session'` or `'none'`. Read more at
[authentication state persistence](https://firebase.google.com/docs/auth/web/auth-state-persistence).
```ts
import { PERSISTENCE } from '@angular/fire/compat/auth';
@NgModule({
// ... Existing configuration
providers: [
// ... Existing Providers
{ provide: PERSISTENCE, useValue: 'session' },
]
})
export class AppModule { }
```
### Tenant
If you need to use multi-tenancy, you can set the current Auth instance's tenant
ID using `TENANT_ID` DI Token (*default: null*).
More tutorials regarding this topic are _coming soon_.
```ts
import { TENANT_ID } from '@angular/fire/compat/auth';
@NgModule({
// ... Existing configuration
providers: [
// ... Existing Providers
{ provide: TENANT_ID, useValue: 'tenant-id-app-one' },
]
})
export class AppModule { }
```
- [Multi-Tenancy Authentication](https://cloud.google.com/identity-platform/docs/multi-tenancy-authentication)
- [Firebase Auth Tenant](https://firebase.google.com/docs/reference/js/firebase.auth.Auth#tenantid)
## UI Libraries
- Material Design : [ngx-auth-firebaseui](https://github.com/AnthonyNahas/ngx-auth-firebaseui)
- Bootstrap : [@firebaseui/ng-bootstrap](https://github.com/firebaseui/ng-bootstrap)
## Cordova
Learn how to [setup Firebase Authentication with Cordova](https://firebase.google.com/docs/auth/web/cordova) in the Firebase Guides.

View file

@ -0,0 +1,104 @@
# Route users with AngularFire guards
`AngularFireAuthGuard` provides a prebuilt [`canActivate` Router Guard](https://angular.io/api/router/CanActivate) using `AngularFireAuth`. By default unauthenticated users are not permitted to navigate to protected routes:
> **NOTE**: [AngularFire has a new tree-shakable API](../../../README.md#developer-guide), you're looking at the documentation for the compatability version of the library. [See the v7 upgrade guide for more information on this change.](../../version-7-upgrade.md).
```ts
import { AngularFireAuthGuard } from '@angular/fire/compat/auth-guard';
export const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'items', component: ItemListComponent, canActivate: [AngularFireAuthGuard] },
]
```
## Customizing the behavior of `AngularFireAuthGuard`
To customize the behavior of `AngularFireAuthGuard`, you can pass an RXJS pipe through the route data's `authGuardPipe` key.
The `auth-guard` module provides the following pre-built pipes:
| Exported pipe | Functionality |
|-|-|
| `loggedIn` | The default pipe, rejects if the user is not authenticated. |
| `isNotAnonymous` | Rejects if the user is anonymous |
| `emailVerified` | Rejects if the user's email is not verified |
| `hasCustomClaim(claim)` | Rejects if the user does not have the specified claim |
| `redirectUnauthorizedTo(redirect)` | Redirect unauthenticated users to a different route |
| `redirectLoggedInTo(redirect)` | Redirect authenticated users to a different route |
Example use:
```ts
import { AngularFireAuthGuard, hasCustomClaim, redirectUnauthorizedTo, redirectLoggedInTo } from '@angular/fire/compat/auth-guard';
const adminOnly = () => hasCustomClaim('admin');
const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['login']);
const redirectLoggedInToItems = () => redirectLoggedInTo(['items']);
const belongsToAccount = (next) => hasCustomClaim(`account-${next.params.id}`);
export const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'login', component: LoginComponent, canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectLoggedInToItems }},
{ path: 'items', component: ItemListComponent, canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectUnauthorizedToLogin }},
{ path: 'admin', component: AdminComponent, canActivate: [AngularFireAuthGuard], data: { authGuardPipe: adminOnly }},
{ path: 'accounts/:id', component: AdminComponent, canActivate: [AngularFireAuthGuard], data: { authGuardPipe: belongsToAccount }}
];
```
Use the provided `canActivate` helper and spread syntax to make your routes more readable:
```ts
import { canActivate } from '@angular/fire/compat/auth-guard';
export const routes: Routes = [
{ path: '', component: AppComponent },
{ path: 'login', component: LoginComponent, ...canActivate(redirectLoggedInToItems) },
{ path: 'items', component: ItemListComponent, ...canActivate(redirectUnauthorizedToLogin) },
{ path: 'admin', component: AdminComponent, ...canActivate(adminOnly) },
{ path: 'accounts/:id', component: AdminComponent, ...canActivate(belongsToAccount) }
];
```
### Compose your own pipes
`AngularFireAuthGuard` pipes are RXJS operators which transform an optional User to a boolean or Array (for redirects). You can easily build your own to customize behavior further:
```ts
import { map } from 'rxjs/operators';
// This pipe redirects a user to their "profile edit" page or the "login page" if they're unauthenticated
// { path: 'profile', ...canActivate(redirectToProfileEditOrLogin) }
const redirectToProfileEditOrLogin = () => map(user => user ? ['profiles', user.uid, 'edit'] : ['login']);
```
The `auth-guard` modules provides a `customClaims` operator to reduce boiler plate when checking a user's claims:
```ts
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { customClaims } from '@angular/fire/compat/auth-guard';
// This pipe will only allow users with the editor role to access the route
// { path: 'articles/:id/edit', component: ArticleEditComponent, ...canActivate(editorOnly) }
const editorOnly = () => pipe(customClaims, map(claims => claims.role === 'editor'));
```
### Using router state
`AngularFireAuthGuard` will also accept `AuthPipeGenerator`s which generate `AuthPipe`s given the router state:
```ts
import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { customClaims } from '@angular/fire/compat/auth-guard';
// Only allow navigation to the route if :userId matches the authenticated user's uid
// { path: 'user/:userId/edit', component: ProfileEditComponent, ...canActivate(onlyAllowSelf) }
const onlyAllowSelf = (next) => map(user => !!user && next.params.userId === user.uid);
// Only allow navigation to the route if the user has a custom claim matching :accountId
// { path: 'accounts/:accountId/billing', component: BillingDetailsComponent, ...canActivate(accountAdmin) }
const accountAdmin = (next) => pipe(customClaims, map(claims => claims[`account-${next.params.accountId}-role`] === 'admin'));
```