Hacktoberfest 2026: những issue maintainer đã đánh dấu cho tháng Mười, đang mở và phù hợp người mới. Xem issue Hacktoberfest

[Feature Request] authCanMatchGuard + helpers

Đang mở
#3,544 1 bình luận 3 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức phù hợp với người mới
35/100
Loại issue
Tính năng
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Đình trệ
Công nghệ
angular, firebase, typescript
Lĩnh vực
authentication, frontend

Hướng nghiên cứu

Trước tiên, hãy đọc src/auth-guard/auth-guard.ts và site/src/auth/route-guards.md, sau đó so sánh chúng với phần triển khai auth-can-match.guard.ts được đề xuất. Hoàn thành khi tích hợp guard canMatch hoạt động và các helper vào AngularFire, đồng thời thêm các bài kiểm thử cho hành vi xác thực và chuyển hướng của chúng.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

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))
Ngôn ngữ chính
TypeScript
Star
7.8k
Fork
2.2k
Merge trung bình
3 ngày 6 giờ
Pull request đã merge (30 ngày)
5

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của angular/angularfire

Tất cả issue của angular/angularfire

Issue tương tự

Thêm issue về TypeScript

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.