Skip to content

Commit

Permalink
refactor: to module
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <[email protected]>
  • Loading branch information
Innei committed Jul 14, 2024
1 parent b7f4a96 commit 902fbef
Show file tree
Hide file tree
Showing 9 changed files with 92 additions and 60 deletions.
3 changes: 2 additions & 1 deletion apps/core/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { GatewayModule } from './processors/gateway/gateway.module'
import { HelperModule } from './processors/helper/helper.module'
import { RequestContextMiddleware } from './common/middlewares/request-context.middleware'
import { UserModule } from './modules/user/user.module'
import { authConfig } from './modules/auth/auth.config'

// Request ----->
// Response <-----
Expand All @@ -44,7 +45,7 @@ const appInterceptors: Type<any>[] = [
GatewayModule,

// BIZ
AuthModule,
AuthModule.forRoot(authConfig),
UserModule,
],
controllers: [AppController],
Expand Down
10 changes: 8 additions & 2 deletions apps/core/src/common/guards/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
/* eslint-disable dot-notation */
import { isTest } from '@core/global/env.global'
import { getSessionUser } from '@core/modules/auth/auth.util'
import { AuthService } from '@core/modules/auth/auth.service'

import { getNestExecutionContextRequest } from '@core/transformers/get-req.transformer'
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
UnauthorizedException,
} from '@nestjs/common'

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
@Inject(AuthService)
private readonly authService: AuthService,
) {}
async canActivate(context: ExecutionContext): Promise<any> {
if (isTest) {
return true
}

const req = this.getRequest(context)
const session = await getSessionUser(req)
const session = await this.authService.getSessionUser(req.raw)

req.raw['session'] = session
req.raw['isAuthenticated'] = !!session
Expand Down
7 changes: 3 additions & 4 deletions apps/core/src/modules/auth/auth.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DrizzleAdapter, authjs } from '@meta-muse/complied'
import { isDev } from '@core/global/env.global'
import { API_VERSION, AUTH } from '@core/app.config'
import { isDev } from '@core/global/env.global'
import { DrizzleAdapter, authjs } from '@meta-muse/complied'

import { db } from '@core/processors/database/database.service'
import {
Expand All @@ -10,7 +10,7 @@ import {
users,
verificationTokens,
} from '@meta-muse/drizzle/schema'
import { CreateAuth, type ServerAuthConfig } from './auth.implement'
import { type ServerAuthConfig } from './auth.implement'

const {
providers: { github: GitHub },
Expand Down Expand Up @@ -38,4 +38,3 @@ export const authConfig: ServerAuthConfig = {
authenticatorsTable: authenticators,
}),
}
export const authHandler = CreateAuth(authConfig)
1 change: 1 addition & 0 deletions apps/core/src/modules/auth/auth.constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const AuthConfigInjectKey = Symbol()
11 changes: 8 additions & 3 deletions apps/core/src/modules/auth/auth.middleware.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import type { NestMiddleware } from '@nestjs/common'
import { Inject, type NestMiddleware } from '@nestjs/common'
import type { IncomingMessage, ServerResponse } from 'http'
import { authHandler } from './auth.config'
import { AuthConfigInjectKey } from './auth.constant'
import { CreateAuth, ServerAuthConfig } from './auth.implement'

export class AuthMiddleware implements NestMiddleware {
constructor(
@Inject(AuthConfigInjectKey) private readonly config: ServerAuthConfig,
) {}
authHandler = CreateAuth(this.config)
async use(req: IncomingMessage, res: ServerResponse, next: () => void) {
if (req.method !== 'GET' && req.method !== 'POST') {
next()
return
}

await authHandler(req, res)
await this.authHandler(req, res)

next()
}
Expand Down
42 changes: 34 additions & 8 deletions apps/core/src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,48 @@
import {
Global,
Inject,
Module,
type DynamicModule,
type MiddlewareConsumer,
type NestModule,
} from '@nestjs/common'

import { AuthService } from './auth.service'
import { AuthConfigInjectKey } from './auth.constant'
import type { ServerAuthConfig } from './auth.implement'
import { AuthMiddleware } from './auth.middleware'
import { AuthService } from './auth.service'

@Module({
imports: [],
controllers: [],
providers: [AuthService],
exports: [],
})
@Module({})
@Global()
export class AuthModule implements NestModule {
constructor(
@Inject(AuthConfigInjectKey) private readonly config: ServerAuthConfig,
) {}
static forRoot(config: ServerAuthConfig): DynamicModule {
return {
module: AuthModule,
global: true,
exports: [AuthService],
providers: [
{
provide: AuthService,
useFactory() {
return new AuthService(config)
},
},
{
provide: AuthConfigInjectKey,
useValue: config,
},
],
}
}

configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes('/auth/(.*)')
const config = this.config

consumer
.apply(AuthMiddleware)
.forRoutes(`${config.basePath || '/auth'}/(.*)`)
}
}
37 changes: 35 additions & 2 deletions apps/core/src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,40 @@
import { DatabaseService } from '@core/processors/database/database.service'
import { Injectable } from '@nestjs/common'
import { getSessionBase, ServerAuthConfig } from './auth.implement'

import type { Session } from '@meta-muse/complied'
import { IncomingMessage } from 'http'

export interface SessionUser {
sessionToken: string
userId: string
expires: string
}
@Injectable()
export class AuthService {
constructor(private readonly db: DatabaseService) {}
constructor(private readonly authConfig: ServerAuthConfig) {}

getSessionUser(req: IncomingMessage) {
const { authConfig } = this
return new Promise<SessionUser | null>((resolve) => {
getSessionBase(req, {
...authConfig,
callbacks: {
...authConfig.callbacks,
async session(...args) {
resolve(args[0].session as SessionUser)

const session =
(await authConfig.callbacks?.session?.(...args)) ??
args[0].session
const user = args[0].user ?? args[0].token
return { user, ...session } satisfies Session
},
},
}).then((session) => {
if (!session) {
resolve(null)
}
})
})
}
}
38 changes: 0 additions & 38 deletions apps/core/src/modules/auth/auth.util.ts

This file was deleted.

3 changes: 1 addition & 2 deletions apps/core/src/processors/gateway/gateway.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { Global, Module } from '@nestjs/common'

import { AuthModule } from '../../modules/auth/auth.module'
import { SharedGateway } from './shared/events.gateway'
import { WebEventsGateway } from './web/events.gateway'

@Global()
@Module({
imports: [AuthModule],
imports: [],
providers: [WebEventsGateway, SharedGateway],
exports: [WebEventsGateway, SharedGateway],
})
Expand Down

0 comments on commit 902fbef

Please sign in to comment.