Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Added JWT access token strategy

Yevhenii Kulisidifd4fff92616e
diff --git a/.env.example b/.env.example
index c1a46aead..ee482b14d 100644
--- a/.env.example
+++ b/.env.example
@@ -2,6 +2,9 @@
JWT_SECRET=SOME_SECRET_TOKEN
TWO_FACTOR_AUTHENTICATION_APP_NAME=Swetrix
+# JWT Access Token
+JWT_ACCESS_TOKEN_SECRET='jwt-access-token-secret'
+
# Database
MYSQL_HOST=localhost
MYSQL_USER=host_user
diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts
index 10476b739..7711bea6e 100644
--- a/src/auth/auth.module.ts
+++ b/src/auth/auth.module.ts
@@ -1,9 +1,12 @@
import { Module } from '@nestjs/common'
+import { PassportModule } from '@nestjs/passport'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
+import { JwtAccessTokenStrategy } from './strategies'
@Module({
+ imports: [PassportModule],
controllers: [AuthController],
- providers: [AuthService],
+ providers: [AuthService, JwtAccessTokenStrategy],
})
export class AuthModule {}
diff --git a/src/auth/interfaces/index.ts b/src/auth/interfaces/index.ts
new file mode 100644
index 000000000..765786217
--- /dev/null
+++ b/src/auth/interfaces/index.ts
@@ -0,0 +1 @@
+export * from './jwt-payload.interface'
diff --git a/src/auth/interfaces/jwt-payload.interface.ts b/src/auth/interfaces/jwt-payload.interface.ts
new file mode 100644
index 000000000..a38bd4838
--- /dev/null
+++ b/src/auth/interfaces/jwt-payload.interface.ts
@@ -0,0 +1,4 @@
+export interface IJwtPayload {
+ sub: string
+ isSecondFactorAuthenticated: boolean
+}
diff --git a/src/auth/strategies/access-token.strategy.ts b/src/auth/strategies/access-token.strategy.ts
new file mode 100644
index 000000000..3d15e5812
--- /dev/null
+++ b/src/auth/strategies/access-token.strategy.ts
@@ -0,0 +1,23 @@
+import { Injectable } from '@nestjs/common'
+import { ConfigService } from '@nestjs/config'
+import { PassportStrategy } from '@nestjs/passport'
+import { Strategy, ExtractJwt } from 'passport-jwt'
+import { IJwtPayload } from '../interfaces'
+
+@Injectable()
+export class JwtAccessTokenStrategy extends PassportStrategy(
+ Strategy,
+ 'jwt-access-token',
+) {
+ constructor(public readonly configService: ConfigService) {
+ super({
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
+ ignoreExpiration: false,
+ secretOrKey: configService.get('JWT_ACCESS_TOKEN_SECRET'),
+ })
+ }
+
+ validate(payload: IJwtPayload) {
+ return payload
+ }
+}
diff --git a/src/auth/strategies/index.ts b/src/auth/strategies/index.ts
new file mode 100644
index 000000000..06ba33043
--- /dev/null
+++ b/src/auth/strategies/index.ts
@@ -0,0 +1 @@
+export * from './access-token.strategy'