Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Passport #2809

Merged
merged 29 commits into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
57a00e0
Remove passport
fraxachun Nov 22, 2024
463d7f3
Update packages/api/cms-api/src/auth/services/static-authed-user.auth…
fraxachun Nov 28, 2024
481e411
Merge next
fraxachun Dec 2, 2024
9fdf4f8
Add tests
fraxachun Dec 2, 2024
94602e1
Add tests
fraxachun Dec 2, 2024
3070ae0
Add @nestjs/jwt as peer dependency
fraxachun Dec 2, 2024
c2f7ea5
Add JwtAuthService to demo
fraxachun Dec 2, 2024
12419de
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 2, 2024
41d52ee
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 13, 2024
daab325
Update packages/api/cms-api/src/auth/util/auth-guard.providers.ts
fraxachun Dec 18, 2024
ff8f140
Update packages/api/cms-api/src/auth/services/basic.auth-service.ts
fraxachun Dec 18, 2024
33bf4f0
Merge remote-tracking branch 'origin/remove-passport' into remove-pas…
fraxachun Dec 18, 2024
d1a1b3a
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 18, 2024
8bd18ee
Remove jsonwebtoken dependency
fraxachun Dec 18, 2024
84316fd
Add migration guide
fraxachun Dec 18, 2024
ebf1e7d
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 18, 2024
8326884
Add changeset
fraxachun Dec 18, 2024
6f3f9e3
Fix typo
fraxachun Dec 18, 2024
a39e806
Update docs/docs/migration/migration-from-v7-to-v8.md
fraxachun Dec 19, 2024
7b66355
Add note to migration guide
fraxachun Dec 19, 2024
ae27da5
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 19, 2024
f8e57ec
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 19, 2024
0f52509
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 19, 2024
f864172
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Dec 20, 2024
aa15c4a
Fix docs
fraxachun Dec 20, 2024
2cf4ff2
Merge remote-tracking branch 'origin/next' into remove-passport
fraxachun Feb 6, 2025
9938b0c
Merge branch 'next' into remove-passport
fraxachun Feb 6, 2025
2a237f5
Merge branch 'next' into remove-passport
fraxachun Feb 14, 2025
9a73b06
Remove dependency
fraxachun Feb 14, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions demo/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"@nestjs/config": "^2.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/graphql": "^10.0.0",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/auto-instrumentations-node": "^0.50.0",
Expand Down Expand Up @@ -70,7 +69,6 @@
"multer": "^1.0.0",
"nestjs-console": "^8.0.0",
"node-fetch": "^2.0.0",
"passport": "^0.4.0",
"reflect-metadata": "^0.1.13",
"response-time": "^2.3.2",
"rimraf": "^3.0.0",
Expand All @@ -94,7 +92,6 @@
"@types/mime": "^2.0.0",
"@types/multer": "^1.0.0",
"@types/node": "^22.0.0",
"@types/passport": "^1.0.0",
"@types/pg": "^8.0.0",
"@types/response-time": "^2.3.8",
"@types/rimraf": "^3.0.0",
Expand Down
56 changes: 28 additions & 28 deletions demo/api/schema.gql
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,6 @@
# THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)
# ------------------------------------------------------

type User {
id: String!
name: String!
email: String!
permissionsCount: Int!
contentScopesCount: Int!
}

type CurrentUserPermission {
permission: String!
contentScopes: [JSONObject!]!
}

"""
The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSONObject @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")

type CurrentUser {
id: String!
name: String!
email: String!
permissions: [CurrentUserPermission!]!
impersonated: Boolean
authenticatedUser: User
permissionsForScope(scope: JSONObject!): [String!]!
}

type UserPermission {
id: ID!
source: UserPermissionSource!
Expand All @@ -53,6 +25,34 @@ A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date
"""
scalar DateTime

"""
The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSONObject @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")

type User {
id: String!
name: String!
email: String!
permissionsCount: Int!
contentScopesCount: Int!
}

type CurrentUserPermission {
permission: String!
contentScopes: [JSONObject!]!
}

type CurrentUser {
id: String!
name: String!
email: String!
permissions: [CurrentUserPermission!]!
impersonated: Boolean
authenticatedUser: User
permissionsForScope(scope: JSONObject!): [String!]!
}

type Dependency {
rootId: String!
rootGraphqlObjectType: String!
Expand Down
19 changes: 9 additions & 10 deletions demo/api/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createAuthResolver, createCometAuthGuard, createStaticAuthedUserStrategy, createStaticCredentialsBasicStrategy } from "@comet/cms-api";
import { CometAuthGuard, createAuthGuardProviders, createAuthResolver, createBasicAuthService, createStaticUserAuthService } from "@comet/cms-api";
import { DynamicModule, Module } from "@nestjs/common";
import { APP_GUARD } from "@nestjs/core";
import { Config } from "@src/config/config";
Expand All @@ -15,18 +15,17 @@ export class AuthModule {
return {
module: AuthModule,
providers: [
createStaticCredentialsBasicStrategy({
username: SYSTEM_USER_NAME,
password: config.auth.systemUserPassword,
strategyName: "system-user",
}),
createStaticAuthedUserStrategy({
staticAuthedUser: staticUsers[0],
}),
...createAuthGuardProviders(
createBasicAuthService({
username: SYSTEM_USER_NAME,
password: config.auth.systemUserPassword,
}),
createStaticUserAuthService({ staticUser: staticUsers[0] }),
),
createAuthResolver(),
{
provide: APP_GUARD,
useClass: createCometAuthGuard(["system-user", "static-authed-user"]),
useClass: CometAuthGuard,
},
UserService,
AccessControlService,
Expand Down
7 changes: 0 additions & 7 deletions packages/api/cms-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
"@hapi/accept": "^5.0.2",
"@nestjs/jwt": "^9.0.0",
"@nestjs/mapped-types": "^1.2.2",
"@nestjs/passport": "^9.0.0",
"@opentelemetry/api": "^1.9.0",
"@smithy/node-http-handler": "3.1.4",
"@types/get-image-colors": "^4.0.0",
Expand All @@ -68,10 +67,6 @@
"mime-db": "^1.0.0",
"multer": "^1.4.4",
"node-fetch": "^2.0.0",
"passport": "^0.6.0",
"passport-custom": "^1.1.1",
"passport-http": "^0.3.0",
"passport-jwt": "^4.0.0",
"pluralize": "^8.0.0",
"probe-image-size": "^7.0.0",
"reflect-metadata": "^0.1.0",
Expand Down Expand Up @@ -107,8 +102,6 @@
"@types/multer": "^1.4.4",
"@types/node": "^22.0.0",
"@types/node-fetch": "^2.6.2",
"@types/passport-http": "^0.3.9",
"@types/passport-jwt": "^3.0.7",
"@types/pluralize": "^0.0.29",
"@types/probe-image-size": "^7.0.0",
"@types/request-ip": "^0.0.41",
Expand Down
56 changes: 28 additions & 28 deletions packages/api/cms-api/schema.gql
Original file line number Diff line number Diff line change
@@ -1,31 +1,3 @@
type User {
id: String!
name: String!
email: String!
permissionsCount: Int!
contentScopesCount: Int!
}

type CurrentUserPermission {
permission: String!
contentScopes: [JSONObject!]!
}

"""
The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSONObject @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")

type CurrentUser {
id: String!
name: String!
email: String!
permissions: [CurrentUserPermission!]!
impersonated: Boolean
authenticatedUser: User
permissionsForScope(scope: JSONObject!): [String!]!
}

type UserPermission {
id: ID!
source: UserPermissionSource!
Expand All @@ -49,6 +21,34 @@ A date-time string at UTC, such as 2019-12-03T09:54:33Z, compliant with the date
"""
scalar DateTime

"""
The `JSONObject` scalar type represents JSON objects as specified by [ECMA-404](http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).
"""
scalar JSONObject @specifiedBy(url: "http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf")

type User {
id: String!
name: String!
email: String!
permissionsCount: Int!
contentScopesCount: Int!
}

type CurrentUserPermission {
permission: String!
contentScopes: [JSONObject!]!
}

type CurrentUser {
id: String!
name: String!
email: String!
permissions: [CurrentUserPermission!]!
impersonated: Boolean
authenticatedUser: User
permissionsForScope(scope: JSONObject!): [String!]!
}

type Dependency {
rootId: String!
rootGraphqlObjectType: String!
Expand Down
96 changes: 55 additions & 41 deletions packages/api/cms-api/src/auth/guards/comet.guard.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,73 @@
import { CanActivate, ExecutionContext, HttpException, Injectable, mixin } from "@nestjs/common";
import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { GqlContextType, GqlExecutionContext } from "@nestjs/graphql";
import { AuthGuard, IAuthGuard, Type } from "@nestjs/passport";
import { Request } from "express";
import { isObservable, lastValueFrom } from "rxjs";

export function createCometAuthGuard(type?: string | string[]): Type<IAuthGuard> {
@Injectable()
class CometAuthGuard extends AuthGuard(type) implements CanActivate {
constructor(private reflector: Reflector) {
super();
import { CurrentUser } from "../../user-permissions/dto/current-user";
import { UserPermissionsService } from "../../user-permissions/user-permissions.service";
import { AuthServiceInterface } from "../util/auth-service.interface";

@Injectable()
export class CometAuthGuard implements CanActivate {
constructor(
private reflector: Reflector,
private readonly service: UserPermissionsService,
@Inject("COMET_AUTH_SERVICES") private readonly authServices: AuthServiceInterface[],
) {}

private getRequest(context: ExecutionContext): Request & { user: CurrentUser } {
return context.getType().toString() === "graphql"
? GqlExecutionContext.create(context).getContext().req
: context.switchToHttp().getRequest();
}

async canActivate(context: ExecutionContext): Promise<boolean> {
const request = this.getRequest(context);

const disableCometGuard = this.reflector.getAllAndOverride("disableCometGuards", [context.getHandler(), context.getClass()]);
const hasIncludeInvisibleContentHeader = !!request.headers["x-include-invisible-content"];
if (disableCometGuard && !hasIncludeInvisibleContentHeader) {
return true;
}

getRequest(context: ExecutionContext): Request {
return context.getType().toString() === "graphql"
? GqlExecutionContext.create(context).getContext().req
: context.switchToHttp().getRequest();
if (this.isResolvingGraphQLField(context)) {
return true;
}

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
handleRequest<CurrentUser>(err: unknown, user: any): CurrentUser {
if (err) {
throw err;
}
if (user) {
return user;
let user = await this.getAuthenticatedUser(request);
if (!user) return false;

if (typeof user === "string") {
const userId = user;
const userService = this.service.getUserService();
if (!userService) throw new UnauthorizedException(`User authenticated by ID but no user service given: ${userId}`);
try {
user = await userService.getUser(userId); // TODO Cache this call
} catch (e) {
throw new UnauthorizedException(`Could not get user from UserService: ${userId}`);
}
throw new HttpException("UNAUTHENTICATED", 401);
}

async canActivate(context: ExecutionContext): Promise<boolean> {
const disableCometGuard = this.reflector.getAllAndOverride("disableCometGuards", [context.getHandler(), context.getClass()]);
const hasIncludeInvisibleContentHeader = !!this.getRequest(context).headers["x-include-invisible-content"];
if (disableCometGuard && !hasIncludeInvisibleContentHeader) {
return true;
}
request["user"] = await this.service.createCurrentUser(user);

if (this.isResolvingGraphQLField(context)) {
return true;
}
return true;
}

const canActivate = await super.canActivate(context);
return isObservable(canActivate) ? lastValueFrom(canActivate) : canActivate;
private async getAuthenticatedUser(request: Request) {
for (const authService of this.authServices) {
const user = await authService.authenticateUser(request);
if (user) return user;
}
}

// See https://docs.nestjs.com/graphql/other-features#execute-enhancers-at-the-field-resolver-level
private isResolvingGraphQLField(context: ExecutionContext): boolean {
if (context.getType<GqlContextType>() === "graphql") {
const gqlContext = GqlExecutionContext.create(context);
const info = gqlContext.getInfo();
const parentType = info.parentType.name;
return parentType !== "Query" && parentType !== "Mutation";
}
return false;
// See https://docs.nestjs.com/graphql/other-features#execute-enhancers-at-the-field-resolver-level
private isResolvingGraphQLField(context: ExecutionContext): boolean {
if (context.getType<GqlContextType>() === "graphql") {
const gqlContext = GqlExecutionContext.create(context);
const info = gqlContext.getInfo();
const parentType = info.parentType.name;
return parentType !== "Query" && parentType !== "Mutation";
}
return false;
}
return mixin(CometAuthGuard);
}
30 changes: 30 additions & 0 deletions packages/api/cms-api/src/auth/services/basic.auth-service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { Request } from "express";

import { AuthServiceInterface } from "../util/auth-service.interface";

interface BasicAuthServiceConfig {
username: string;
password: string;
}

export function createBasicAuthService({ username: requiredUsername, password: requiredPassword }: BasicAuthServiceConfig) {
if (requiredUsername === "") throw new Error(`username for BasicAuthService must no be empty`);
if (requiredPassword === "") throw new Error(`password for BasicAuthService (username "${requiredUsername}") must no be empty`);

@Injectable()
class BasicAuthService implements AuthServiceInterface {
authenticateUser(request: Request) {
const [type, token] = request.header("authorization")?.split(" ") ?? [];
if (type !== "Basic") return;

const [username, password] = Buffer.from(token, "base64").toString("ascii").split(":");
if (username !== requiredUsername) return;

if (password !== requiredPassword) throw new UnauthorizedException(`Wrong password for Basic Auth user "${username}".`);

return username;
}
}
return BasicAuthService;
}
Loading
Loading