[Feature Request] authCanMatchGuard + helpers
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 4/5
- Tempo estimado
- 3-5 dias
- Facilidade para iniciantes
- 35/100
- Tipo de issue
- Funcionalidade
- Clareza
- Razoavelmente clara
- Status de atividade
- Estagnada
- Stack de tecnologia
- angular, firebase, typescript
- Domínio
- authentication, frontend
Direção de pesquisa
Leia primeiro src/auth-guard/auth-guard.ts e site/src/auth/route-guards.md e, em seguida, compare-os com a implementação proposta de auth-can-match.guard.ts. Está concluído quando o guard canMatch funcional e os helpers forem integrados ao AngularFire e forem adicionados testes para o comportamento de autenticação e redirecionamento deles.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
Feature Request - authCanMatchGuard + helpers
Description
The current auth-guard provided with angular fire is still using the now deprecated class based approach and targets the canActivate property on route definitions.
To freshen things up a bit, I have generated a new guard which utilizes the new functional approach and targets the newer canMatch route definition property. This has the added benefit of preventing components from being unnecessarily loaded which seems to work well and should be more performant.
I based the new code off of the previous implementation documented here. You will notice similarities with the previous guard code here. Would love to see this incorporated into the AngularFire package but honestly I'm too lazy to write tests 😅 so if someone would be interested in owning that and collaborating, I'd be happy to open up a PR.
Code
auth-can-match.guard.ts
import { inject } from '@angular/core';
import { Auth, user, User } from '@angular/fire/auth';
import { CanMatchFn, Route, Router, UrlSegment } from '@angular/router';
import { Observable, of, pipe, UnaryFunction } from 'rxjs';
import { map, switchMap, take } from 'rxjs/operators';
/** Utility type to allow for adding an additional property to the CanMatchFn type */
type ExtendFn<BaseFnT, AddPT extends any[]> = BaseFnT extends (...a: infer P) => infer R
? (...a: [...P, ...AddPT]) => R
: never
export type AuthPipe = UnaryFunction<Observable<User | null>, Observable<boolean | string | any[]>>;
export const authCanMatchGuard: ExtendFn<CanMatchFn, [authPipe: AuthPipe]> = (route, segments, authPipe?) => {
const auth = inject(Auth)
const user$ = user(auth)
const router = inject(Router)
const authPipeFactory = authPipe
? authPipe
: loggedIn
return user$
.pipe(
take(1),
authPipeFactory,
map(can => {
if (typeof can === 'boolean') {
return can;
} else if (Array.isArray(can)) {
return router.createUrlTree(can)
} else {
return router.parseUrl(can)
}
})
)
}
/** canMatch helper to be used with spread operator to make route definitions more concise.
* @example
* const redirectUnauthorizedToLogin = redirectUnauthorizedTo(['login'])
* ...
* export const routes: Routes = [
* {
* ...authCanMatch(redirectUnauthorizedToLogin)
* path: 'authProtectedRoute'
* },
*/
export const authCanMatch = (authPipe: AuthPipe) =>
({ canMatch: [(route: Route, segments: UrlSegment[]) => authCanMatchGuard(route, segments, authPipe)] })
/** Predefined auth guard helper pipes. So friendly & helpful 😍 */
export const loggedIn: AuthPipe = map(user => !!user)
export const isNotAnonymous: AuthPipe = map(user => !!user && !user.isAnonymous)
export const idTokenResult = switchMap((user: User | null) => user ? user.getIdTokenResult() : of(null))
export const emailVerified: AuthPipe = map(user => !!user && user.emailVerified)
export const customClaims = pipe(idTokenResult, map(idTokenResult => idTokenResult ? idTokenResult.claims : []))
export const hasCustomClaim: (claim: string) => AuthPipe =
// eslint-disable-next-line no-prototype-builtins
(claim) => pipe(customClaims, map(claims => claims.hasOwnProperty(claim)))
export const redirectUnauthorizedTo: (redirect: string | any[]) => AuthPipe =
(redirect) => pipe(loggedIn, map(loggedIn => loggedIn || redirect))
export const redirectLoggedInTo: (redirect: string | any[]) => AuthPipe =
(redirect) => pipe(loggedIn, map(loggedIn => loggedIn && redirect || true))
- Linguagem predominante
- TypeScript
- Estrelas
- 7.8k
- Forks
- 2.2k
- Merge médio
- 3d 6h
- PRs com merge (30d)
- 5
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de angular/angularfire
-
comp: build/pipeline type: bug version: current (v17+)
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 74/100
angular/angularfire#3766 ·
-
comp: schematics type: bug version: current (v17+)
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 76/100
angular/angularfire#3768 ·
-
comp: docs type: chore version: current (v17+)
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 58/100
angular/angularfire#3764 ·
-
comp: firestore comp: ssr priority: P0 (critical) type: feature version: current (v17+)
angular/angularfire#3757 · 1 responsável ·
-
Six `firebase` entry points have no `@angular/fire` equivalent, so their exports are unreachable Abertacomp: core type: feature
angular/angularfire#3755 · 1 responsável ·
Todas as issues de angular/angularfire
Issues semelhantes
-
blocklist removal
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
MetaMask/eth-phishing-detect#296544 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
pastelsky/bundlephobia#1122 ·
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
-
category/development priority/P2 scope/file-operations scope/testing type/enhancement
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
-
Enatega Customer and Rider app: Add-ons price is not visible to customer after order is placed. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100