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

Feature/spgo 14 #6

Merged
merged 18 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
proto:
protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto.cmd -I=./src/proto --ts_proto_out=./src/auth src/proto/auth.proto --ts_proto_opt=nestJs=true --ts_proto_opt=fileSuffix=.pb
protoc --plugin=./node_modules/.bin/protoc-gen-ts_proto -I=./src/proto --ts_proto_out=./src/auth src/proto/auth.proto --ts_proto_opt=nestJs=true --ts_proto_opt=fileSuffix=.pb

server:
yarn start:dev

prisma:
yarn prisma generate
yarn prisma db push --accept-data-loss
yarn prisma migrate dev
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"@nestjs/microservices": "^10.2.5",
"@nestjs/passport": "^10.0.2",
"@nestjs/platform-express": "^9.0.0",
"@prisma/client": "^5.2.0",
"@prisma/client": "^5.3.1",
"@types/bcrypt": "^5.0.0",
"@types/passport-jwt": "^3.0.9",
"bcrypt": "^5.1.1",
Expand Down
9 changes: 8 additions & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import {
LoginRequest,
LoginResponse,
LoginResponse, LogoutRequest, LogoutResponse,
RegisterRequest,
RegisterResponse,
ValidateGoogleRequest,
Expand All @@ -24,6 +24,13 @@ export class AuthController {
return this.authService.register(request);
}


@GrpcMethod('AuthService', 'Logout')
logout(request: LogoutRequest): Promise<LogoutResponse> {
return this.authService.logout(request);
}


@GrpcMethod('AuthService', 'ValidateGoogle')
validateGoogle(
request: ValidateGoogleRequest,
Expand Down
7 changes: 3 additions & 4 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
import { UserRepository } from '../repository/user.repository';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { APP_FILTER } from '@nestjs/core';
import { GrpcServerExceptionFilter } from 'nestjs-grpc-exceptions';
import { JwtModule, JwtService } from '@nestjs/jwt';

Check warning on line 6 in src/auth/auth.module.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'JwtService' is defined but never used
import { AccessTokenStrategy } from './strategies/accessToken.strategy';
import { ConfigService } from '@nestjs/config';
import { BlacklistRepository } from 'src/repository/blacklist.repository';

@Module({
imports: [PrismaModule, JwtModule.register({})],
providers: [AuthService, UserRepository, AccessTokenStrategy, ConfigService],
providers: [AuthService, UserRepository, AccessTokenStrategy, ConfigService, BlacklistRepository],
controllers: [AuthController],
})
export class AuthModule {}
export class AuthModule { }
78 changes: 28 additions & 50 deletions src/auth/auth.pb.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* eslint-disable */
import { GrpcMethod, GrpcStreamMethod } from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { GrpcMethod, GrpcStreamMethod } from "@nestjs/microservices";
import { Observable } from "rxjs";

export const protobufPackage = 'auth';
export const protobufPackage = "auth";

export interface RegisterRequest {
firstName: string;
Expand Down Expand Up @@ -52,6 +52,14 @@ export interface RefreshTokenResponse {
credential: Credential | undefined;
}

export interface LogoutRequest {
credential: Credential | undefined;
}

export interface LogoutResponse {
isDone: boolean;
}

export interface ValidateGoogleRequest {
user: GoogleUser | undefined;
}
Expand All @@ -60,7 +68,7 @@ export interface ValidateGoogleResponse {
credential: Credential | undefined;
}

export const AUTH_PACKAGE_NAME = 'auth';
export const AUTH_PACKAGE_NAME = "auth";

export interface AuthServiceClient {
login(request: LoginRequest): Observable<LoginResponse>;
Expand All @@ -69,70 +77,40 @@ export interface AuthServiceClient {

register(request: RegisterRequest): Observable<RegisterResponse>;

validateGoogle(
request: ValidateGoogleRequest,
): Observable<ValidateGoogleResponse>;
logout(request: LogoutRequest): Observable<LogoutResponse>;

validateGoogle(request: ValidateGoogleRequest): Observable<ValidateGoogleResponse>;
}

export interface AuthServiceController {
login(
request: LoginRequest,
): Promise<LoginResponse> | Observable<LoginResponse> | LoginResponse;
login(request: LoginRequest): Promise<LoginResponse> | Observable<LoginResponse> | LoginResponse;

refreshToken(
request: RefreshTokenRequest,
):
| Promise<RefreshTokenResponse>
| Observable<RefreshTokenResponse>
| RefreshTokenResponse;

register(
request: RegisterRequest,
):
| Promise<RegisterResponse>
| Observable<RegisterResponse>
| RegisterResponse;
): Promise<RefreshTokenResponse> | Observable<RefreshTokenResponse> | RefreshTokenResponse;

register(request: RegisterRequest): Promise<RegisterResponse> | Observable<RegisterResponse> | RegisterResponse;

logout(request: LogoutRequest): Promise<LogoutResponse> | Observable<LogoutResponse> | LogoutResponse;

validateGoogle(
request: ValidateGoogleRequest,
):
| Promise<ValidateGoogleResponse>
| Observable<ValidateGoogleResponse>
| ValidateGoogleResponse;
): Promise<ValidateGoogleResponse> | Observable<ValidateGoogleResponse> | ValidateGoogleResponse;
}

export function AuthServiceControllerMethods() {
return function (constructor: Function) {
const grpcMethods: string[] = [
'login',
'refreshToken',
'register',
'validateGoogle',
];
const grpcMethods: string[] = ["login", "refreshToken", "register", "logout", "validateGoogle"];
for (const method of grpcMethods) {
const descriptor: any = Reflect.getOwnPropertyDescriptor(
constructor.prototype,
method,
);
GrpcMethod('AuthService', method)(
constructor.prototype[method],
method,
descriptor,
);
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
GrpcMethod("AuthService", method)(constructor.prototype[method], method, descriptor);
}
const grpcStreamMethods: string[] = [];
for (const method of grpcStreamMethods) {
const descriptor: any = Reflect.getOwnPropertyDescriptor(
constructor.prototype,
method,
);
GrpcStreamMethod('AuthService', method)(
constructor.prototype[method],
method,
descriptor,
);
const descriptor: any = Reflect.getOwnPropertyDescriptor(constructor.prototype, method);
GrpcStreamMethod("AuthService", method)(constructor.prototype[method], method, descriptor);
}
};
}

export const AUTH_SERVICE_NAME = 'AuthService';
export const AUTH_SERVICE_NAME = "AuthService";
8 changes: 8 additions & 0 deletions src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { UserRepository } from '../repository/user.repository';
import { BlacklistRepository } from '../repository/blacklist.repository';
describe('AuthService', () => {
let service: AuthService;
const mockJwtService = {
sign: jest.fn(),
};
const mockBlacklistService = {

Check warning on line 12 in src/auth/auth.service.spec.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'mockBlacklistService' is assigned a value but never used
insertToken: jest.fn(),
check: jest.fn(),
};
Expand All @@ -20,6 +21,9 @@
const mockConfigService = {
get: jest.fn(),
}
const mockBlacklistRepository = {
addOutdatedToken: jest.fn(),
}
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService,
Expand All @@ -36,6 +40,10 @@
{
provide: ConfigService,
useValue: mockConfigService,
},
{
provide: BlacklistRepository,
useValue: mockBlacklistRepository,
}
],
}).compile();
Expand Down
47 changes: 46 additions & 1 deletion src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
Credential,
LoginRequest,
LoginResponse,
LogoutRequest,
LogoutResponse,
RefreshTokenRequest,
RefreshTokenResponse,
RegisterRequest,
Expand All @@ -20,14 +22,17 @@
import { $Enums, Prisma } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';
import { Role } from '@prisma/client';
import { BlacklistRepository } from '../repository/blacklist.repository';
import { JwtPayload } from './strategies/accessToken.strategy';

@Injectable()
export class AuthService implements AuthServiceController {
constructor(
private userRepo: UserRepository,
private blacklistRepo: BlacklistRepository,
private jwtService: JwtService,
private configService: ConfigService,
) {}
) { }

public async login(request: LoginRequest): Promise<LoginResponse> {
try {
Expand Down Expand Up @@ -81,7 +86,7 @@
}

public async refreshToken(
request: RefreshTokenRequest,

Check warning on line 89 in src/auth/auth.service.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'request' is defined but never used
): Promise<RefreshTokenResponse> {
return null;
}
Expand Down Expand Up @@ -210,4 +215,44 @@
throw err;
}
}


public async logout(request: LogoutRequest): Promise<LogoutResponse> {

try {
await this.blacklistRepo.addOutdatedToken({
outDatedAccessToken: request.credential.accessToken,
})

let credential = this.jwtService.decode(request.credential.refreshToken) as JwtPayload;
let userId = credential.sub

await this.userRepo.update(userId, {
refreshToken: null,
})




} catch (e) {
if (e instanceof Prisma.PrismaClientKnownRequestError) {

console.log(
'There is a unique constraint violation, a blacklist should not outdated twice!'
)

}
throw new RpcException({
code: status.INTERNAL,
message: e.message,
});

}


const response: LogoutResponse = { isDone: true };
return response;

}

}
2 changes: 1 addition & 1 deletion src/auth/strategies/accessToken.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ type RegisteredClaims = {
issuedAt: Date;
};

type JwtPayload = {
export type JwtPayload = {
sub: string;
registeredClaims: RegisteredClaims;
};
Expand Down
7 changes: 7 additions & 0 deletions src/database/migrations/20230921140038_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- CreateTable
CREATE TABLE "Blacklist" (
"outDatedRefreshToken" TEXT NOT NULL
);

-- CreateIndex
CREATE UNIQUE INDEX "Blacklist_outDatedRefreshToken_key" ON "Blacklist"("outDatedRefreshToken");
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
Warnings:

- You are about to drop the column `outDatedRefreshToken` on the `Blacklist` table. All the data in the column will be lost.
- A unique constraint covering the columns `[outDatedAccessToken]` on the table `Blacklist` will be added. If there are existing duplicate values, this will fail.
- Added the required column `outDatedAccessToken` to the `Blacklist` table without a default value. This is not possible if the table is not empty.

*/
-- DropIndex
DROP INDEX "Blacklist_outDatedRefreshToken_key";

-- AlterTable
ALTER TABLE "Blacklist" DROP COLUMN "outDatedRefreshToken",
ADD COLUMN "outDatedAccessToken" TEXT NOT NULL;

-- CreateIndex
CREATE UNIQUE INDEX "Blacklist_outDatedAccessToken_key" ON "Blacklist"("outDatedAccessToken");
4 changes: 4 additions & 0 deletions src/database/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ enum Status {
ACTIVE
BANNED
}

model Blacklist {
outDatedAccessToken String @unique
}
10 changes: 9 additions & 1 deletion src/proto/auth.proto
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ service AuthService {
rpc Login(LoginRequest) returns (LoginResponse) {}
rpc RefreshToken(RefreshTokenRequest) returns (RefreshTokenResponse) {}
rpc Register(RegisterRequest) returns (RegisterResponse) {}
rpc Logout(LogoutRequest) returns (LogoutResponse) {}
rpc ValidateGoogle(ValidateGoogleRequest) returns (ValidateGoogleResponse) {}
}

Expand Down Expand Up @@ -57,10 +58,17 @@ message RefreshTokenResponse {
Credential credential = 1;
}

message LogoutRequest {
Credential credential = 1;
}

message LogoutResponse {
bool is_done = 1;
}
message ValidateGoogleRequest {
GoogleUser user = 1;
}

message ValidateGoogleResponse {
Credential credential = 1;
}
}
15 changes: 15 additions & 0 deletions src/repository/blacklist.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Injectable } from '@nestjs/common';
import { PrismaClient, Status, Blacklist } from '@prisma/client';

Check warning on line 2 in src/repository/blacklist.repository.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'PrismaClient' is defined but never used

Check warning on line 2 in src/repository/blacklist.repository.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'Status' is defined but never used
import { PrismaService } from '../prisma/service/prisma.service';
import { Prisma } from '@prisma/client';

@Injectable()
export class BlacklistRepository {
constructor(private db: PrismaService) { }

async addOutdatedToken(outDatedToken: Prisma.BlacklistCreateInput): Promise<Blacklist> {
return await this.db.blacklist.create({
data: outDatedToken,
})
}
}
Loading
Loading