Skip to content
Open
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
2 changes: 2 additions & 0 deletions apps/todo-tasks/.env
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ DB_PASSWORD=admin
DB_PORT=5432
DB_URL=postgres://admin:admin@localhost:5432/my-db
DB_USER=admin
JWT_EXPIRATION=2d
JWT_SECRET_KEY=Change_ME!!!
PORT=3000
2 changes: 2 additions & 0 deletions apps/todo-tasks/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ services:
- ${PORT}:3000
environment:
BCRYPT_SALT: ${BCRYPT_SALT}
JWT_SECRET_KEY: ${JWT_SECRET_KEY}
JWT_EXPIRATION: ${JWT_EXPIRATION}
DB_URL: postgres://${DB_USER}:${DB_PASSWORD}@db:5432/${DB_NAME}
depends_on:
- migrate
Expand Down
6 changes: 5 additions & 1 deletion apps/todo-tasks/nest-cli.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
{
"sourceRoot": "src",
"compilerOptions": {
"assets": ["swagger"]
"assets": [
{
"include": "swagger/**/*"
}
]
}
}
5 changes: 3 additions & 2 deletions apps/todo-tasks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@
"dotenv": "16.3.1",
"graphql": "^16.8.1",
"graphql-type-json": "0.3.2",
"nest-access-control": "^3.1.0",
"npm-run-all": "4.1.5",
"passport": "0.6.0",
"passport-http": "0.3.0",
"passport-jwt": "4.0.1",
"reflect-metadata": "0.1.13",
"ts-node": "10.9.1",
"ts-node": "10.9.2",
"type-fest": "2.19.0",
"validator": "13.11.0"
},
Expand All @@ -63,7 +64,7 @@
"prisma": "^5.4.2",
"supertest": "^6.3.3",
"ts-jest": "^29.1.1",
"typescript": "~5.3.0"
"typescript": "^5.4.3"
},
"jest": {
"preset": "ts-jest",
Expand Down
10 changes: 10 additions & 0 deletions apps/todo-tasks/scripts/customSeed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@ import { PrismaClient } from "@prisma/client";

export async function customSeed() {
const client = new PrismaClient();
const username = "admin";

//replace this sample code to populate your database
//with data that is required for your service to start
await client.user.update({
where: { username: username },
data: {
username,
},
});

client.$disconnect();
}
26 changes: 25 additions & 1 deletion apps/todo-tasks/scripts/seed.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import * as dotenv from "dotenv";
import { PrismaClient } from "@prisma/client";
import { customSeed } from "./customSeed";
import { Salt, parseSalt } from "../src/auth/password.service";
import { hash } from "bcrypt";

if (require.main === module) {
dotenv.config();
Expand All @@ -10,12 +12,34 @@ if (require.main === module) {
if (!BCRYPT_SALT) {
throw new Error("BCRYPT_SALT environment variable must be defined");
}
const salt = parseSalt(BCRYPT_SALT);

seed(salt).catch((error) => {
console.error(error);
process.exit(1);
});
}

async function seed() {
async function seed(bcryptSalt: Salt) {
console.info("Seeding database...");

const client = new PrismaClient();

const data = {
username: "admin",
password: await hash("admin", bcryptSalt),
roles: ["user"],
};

await client.user.upsert({
where: {
username: data.username,
},

update: {},
create: data,
});

void client.$disconnect();

console.info("Seeding database with custom seed...");
Expand Down
5 changes: 5 additions & 0 deletions apps/todo-tasks/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,14 @@ import { ServeStaticModule } from "@nestjs/serve-static";
import { ServeStaticOptionsService } from "./serveStaticOptions.service";
import { ConfigModule } from "@nestjs/config";

import { ACLModule } from "./auth/acl.module";
import { AuthModule } from "./auth/auth.module";

@Module({
controllers: [],
imports: [
ACLModule,
AuthModule,
TaskModule,
UserModule,
CommentModule,
Expand Down
21 changes: 21 additions & 0 deletions apps/todo-tasks/src/auth/Credentials.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { ApiProperty } from "@nestjs/swagger";
import { InputType, Field } from "@nestjs/graphql";
import { IsString } from "class-validator";

@InputType()
export class Credentials {
@ApiProperty({
required: true,
type: String,
})
@IsString()
@Field(() => String, { nullable: false })
username!: string;
@ApiProperty({
required: true,
type: String,
})
@IsString()
@Field(() => String, { nullable: false })
password!: string;
}
6 changes: 6 additions & 0 deletions apps/todo-tasks/src/auth/IAuthStrategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { UserInfo } from "./UserInfo";

export interface IAuthStrategy {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validate: (...any: any) => Promise<UserInfo>;
}
9 changes: 9 additions & 0 deletions apps/todo-tasks/src/auth/ITokenService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface ITokenPayload {
id: string;
username: string;
password: string;
}

export interface ITokenService {
createToken: ({ id, username, password }: ITokenPayload) => Promise<string>;
}
12 changes: 12 additions & 0 deletions apps/todo-tasks/src/auth/LoginArgs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ArgsType, Field } from "@nestjs/graphql";
import { ValidateNested } from "class-validator";
import { Type } from "class-transformer";
import { Credentials } from "./Credentials";

@ArgsType()
export class LoginArgs {
@Field(() => Credentials, { nullable: false })
@Type(() => Credentials)
@ValidateNested()
credentials!: Credentials;
}
14 changes: 14 additions & 0 deletions apps/todo-tasks/src/auth/UserInfo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Field, ObjectType } from "@nestjs/graphql";
import { User } from "../user/base/User";

@ObjectType()
export class UserInfo implements Partial<User> {
@Field(() => String)
id!: string;
@Field(() => String)
username!: string;
@Field(() => [String])
roles!: string[];
@Field(() => String, { nullable: true })
accessToken?: string;
}
19 changes: 19 additions & 0 deletions apps/todo-tasks/src/auth/abac.util.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Permission } from "accesscontrol";

/**
* @returns attributes not allowed to appear on given data according to given
* attributeMatchers
*/
export function getInvalidAttributes(
permission: Permission,
// eslint-disable-next-line @typescript-eslint/ban-types
data: Object
): string[] {
// The structuredClone call is necessary because the
// `Permission.filter` function doesn't consider objects
// with null prototypes. And in graphql requests, the
// object passed here by the request interceptor is an object
// with a null prototype.
const filteredData = permission.filter(structuredClone(data));
return Object.keys(data).filter((key) => !(key in filteredData));
}
6 changes: 6 additions & 0 deletions apps/todo-tasks/src/auth/acl.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { AccessControlModule, RolesBuilder } from "nest-access-control";

import grants from "../grants.json";

// eslint-disable-next-line @typescript-eslint/naming-convention
export const ACLModule = AccessControlModule.forRoles(new RolesBuilder(grants));
15 changes: 15 additions & 0 deletions apps/todo-tasks/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Body, Controller, Post } from "@nestjs/common";
import { ApiTags } from "@nestjs/swagger";
import { AuthService } from "./auth.service";
import { Credentials } from "../auth/Credentials";
import { UserInfo } from "./UserInfo";

@ApiTags("auth")
@Controller()
export class AuthController {
constructor(private readonly authService: AuthService) {}
@Post("login")
async login(@Body() body: Credentials): Promise<UserInfo> {
return this.authService.login(body);
}
}
57 changes: 57 additions & 0 deletions apps/todo-tasks/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { forwardRef, Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { JWT_EXPIRATION } from "../constants";
import { SecretsManagerModule } from "../providers/secrets/secretsManager.module";
import { SecretsManagerService } from "../providers/secrets/secretsManager.service";
import { EnumSecretsNameKey } from "../providers/secrets/secretsNameKey.enum";
import { AuthController } from "./auth.controller";
import { AuthResolver } from "./auth.resolver";
import { AuthService } from "./auth.service";
import { JwtStrategy } from "./jwt/jwt.strategy";
import { jwtSecretFactory } from "./jwt/jwtSecretFactory";
import { PasswordService } from "./password.service";
import { TokenService } from "./token.service";
import { UserModule } from "../user/user.module";
@Module({
imports: [
forwardRef(() => UserModule),
PassportModule,
SecretsManagerModule,
JwtModule.registerAsync({
imports: [SecretsManagerModule],
inject: [SecretsManagerService, ConfigService],
useFactory: async (
secretsService: SecretsManagerService,
configService: ConfigService
) => {
const secret = await secretsService.getSecret<string>(
EnumSecretsNameKey.JwtSecretKey
);
const expiresIn = configService.get(JWT_EXPIRATION);
if (!secret) {
throw new Error("Didn't get a valid jwt secret");
}
if (!expiresIn) {
throw new Error("Jwt expire in value is not valid");
}
return {
secret: secret,
signOptions: { expiresIn },
};
},
}),
],
providers: [
AuthService,
PasswordService,
AuthResolver,
JwtStrategy,
jwtSecretFactory,
TokenService,
],
controllers: [AuthController],
exports: [AuthService, PasswordService],
})
export class AuthModule {}
23 changes: 23 additions & 0 deletions apps/todo-tasks/src/auth/auth.resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as common from "@nestjs/common";
import { Args, Mutation, Query, Resolver } from "@nestjs/graphql";
import * as gqlACGuard from "../auth/gqlAC.guard";
import { AuthService } from "./auth.service";
import { GqlDefaultAuthGuard } from "./gqlDefaultAuth.guard";
import { UserData } from "./userData.decorator";
import { LoginArgs } from "./LoginArgs";
import { UserInfo } from "./UserInfo";

@Resolver(UserInfo)
export class AuthResolver {
constructor(private readonly authService: AuthService) {}
@Mutation(() => UserInfo)
async login(@Args() args: LoginArgs): Promise<UserInfo> {
return this.authService.login(args.credentials);
}

@Query(() => UserInfo)
@common.UseGuards(GqlDefaultAuthGuard, gqlACGuard.GqlACGuard)
async userInfo(@UserData() entityInfo: UserInfo): Promise<UserInfo> {
return entityInfo;
}
}
Loading