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

DR-762 Apply Prettier linting to code base #155

Merged
merged 7 commits into from
Mar 11, 2024
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
71 changes: 71 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
name: Code Quality

on:
push:
branches:
- develop
pull_request:
branches:
- develop

jobs:
lint-prettier:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3

- name: Setup Pages
uses: actions/configure-pages@v2

- uses: actions/setup-node@v4
with:
node-version: lts/gallium

- name: Install tooling
run: |
npm i -g yarn
npm i -g @microsoft/rush
npm i -g pnpm

- name: Install drec-api
working-directory: apps/drec-api
run: |
rush update
rush install

- name: Run Prettier
working-directory: apps/drec-api
run: pnpm run prettier

lint-eslint:
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3

- name: Setup Pages
uses: actions/configure-pages@v2

- uses: actions/setup-node@v4
with:
node-version: lts/gallium

- name: Install tooling
run: |
npm i -g yarn
npm i -g @microsoft/rush
npm i -g pnpm

- name: Install drec-api
working-directory: apps/drec-api
run: |
rush update
rush install

- name: Run ESLint
working-directory: apps/drec-api
run: pnpm run lint
continue-on-error: true
10 changes: 9 additions & 1 deletion .prettierrc
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,13 @@
"useTabs": false,
"semi": true,
"tabWidth": 4,
"trailingComma": "none"
"trailingComma": "none",
"overrides": [
{
"files": "*.{yaml,yml}",
"options": {
"tabWidth": 2
}
}
]
}
6 changes: 4 additions & 2 deletions apps/drec-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"drop": "yarn redis:drop && yarn typeorm:drop && yarn typeorm:drop:issuer",
"redis:drop": "redis-cli flushall",
"deploy:heroku": "make -B build deploy-heroku",
"prettier": "prettier --write --config-precedence file-override './src/**/*'",
"prettier": "prettier --check --config-precedence file-override './src/**/*'",
"prettier:fix": "prettier --write --config-precedence file-override './src/**/*'",
"lint": "eslint \"src/**/*{.ts,.tsx}\" \"test/**/*{.ts,.tsx}\" \"migrations/**/*{.ts,.tsx}\" --no-error-on-unmatched-pattern",
"lint:fix": "eslint \"src/**/*{.ts,.tsx}\" \"test/**/*{.ts,.tsx}\" \"migrations/**/*{.ts,.tsx}\" --fix --no-error-on-unmatched-pattern",
"migrate": "yarn typeorm:run:issuer && yarn typeorm:run && yarn typeorm:run:certificate",
Expand Down Expand Up @@ -149,7 +150,8 @@
"ts-jest": "^26.5.0",
"ts-node": "9.1.0",
"typescript": "4.1.3",
"wait-on": "5.2.1"
"wait-on": "5.2.1",
"prettier": "~3.2.5"
},
"jest": {
"moduleFileExtensions": [
Expand Down
27 changes: 16 additions & 11 deletions apps/drec-api/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ import { LoginDataDTO } from './dto/login-data.dto';
@ApiTags('auth')
@ApiBearerAuth('access-token')
@Controller()
export class AuthController {
export class AuthController {
private readonly logger = new Logger(AuthController.name);

constructor(private readonly authService: AuthService) { }
constructor(private readonly authService: AuthService) {}

@UseGuards(AuthGuard('local'))
@Post('auth/login')
Expand All @@ -34,26 +34,31 @@ export class AuthController {
description: 'Log in',
})
async login(@Request() req: ExpressRequest): Promise<LoginReturnDataDTO> {
this.logger.verbose("Within login");
return await this.authService.login(req.user as Omit<IUser, 'password'>);
this.logger.verbose('Within login');
return await this.authService.login(req.user as Omit<IUser, 'password'>);
}


@UseGuards(AuthGuard('jwt'))
@Post('auth/logout')
@HttpCode(HttpStatus.OK)
async logout(@Request() req: ExpressRequest
) {
this.logger.verbose("Within login");
async logout(@Request() req: ExpressRequest) {
this.logger.verbose('Within login');
await this.authService.logout(req.user as Omit<IUser, 'password'>);
return { message: 'Logout successful' };
}

@UseGuards(AuthGuard('local'))
@Post('auth/getAccess')
@ApiBody({ type: LoginDataDTO })
async generateToken(@Request() req: ExpressRequest, @Query('privateKey') privateKey: string) {//: Promise<LoginReturnDataDTO> {
this.logger.verbose("With in generateToken");
return await this.authService.generateToken(req.user as Omit<IUser, 'password'>, privateKey);
async generateToken(
@Request() req: ExpressRequest,
@Query('privateKey') privateKey: string,
) {
//: Promise<LoginReturnDataDTO> {
this.logger.verbose('With in generateToken');
return await this.authService.generateToken(
req.user as Omit<IUser, 'password'>,
privateKey,
);
}
}
15 changes: 9 additions & 6 deletions apps/drec-api/src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { PassportModule } from '@nestjs/passport';
import { ConfigService } from '@nestjs/config';
import { OrganizationModule } from '../pods/organization/organization.module';
import { UserModule } from '../pods/user/user.module';
import {PermissionModule} from '../pods/permission/permission.module'
import { PermissionModule } from '../pods/permission/permission.module';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
Expand All @@ -21,14 +21,17 @@ import { ClientJwtStrategy } from './client-jwt.strategy';
EmailConfirmationModule,
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.registerAsync({
useFactory: async (configService: ConfigService) =>{
return ({
useFactory: async (configService: ConfigService) => {
return {
secret: configService.get<string>('JWT_SECRET') || 'thisisnotsecret',
signOptions: {
expiresIn: '180 days' || configService.get<string>('JWT_EXPIRY_TIME') || '7 days',
expiresIn:
'180 days' ||
configService.get<string>('JWT_EXPIRY_TIME') ||
'7 days',
},
})
} ,
};
},
inject: [ConfigService],
}),
],
Expand Down
43 changes: 26 additions & 17 deletions apps/drec-api/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, Logger, } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import bcrypt from 'bcryptjs';
import { UserLoginReturnData } from '@energyweb/origin-backend-core';
Expand All @@ -24,13 +24,13 @@ export class AuthService {
private readonly userService: UserService,
private readonly jwtService: JwtService,
private readonly oauthClientService: OauthClientCredentialsService,
) { }
) {}

async validateUser(
email: string,
unencryptedPassword: string,
): Promise<UserDTO | null> {
this.logger.verbose("With in validateUser")
this.logger.verbose('With in validateUser');
const user = await this.userService.getUserAndPasswordByEmail(
email.toLowerCase(),
);
Expand All @@ -41,40 +41,49 @@ export class AuthService {
}

async login(user: Omit<IUser, 'password'>): Promise<UserLoginReturnData> {
this.logger.verbose("With in login")
this.logger.verbose('With in login');
const payload: IJWTPayload = {
email: user.email.toLowerCase(),
id: user.id,
role: user.role
role: user.role,
};
const token = this.jwtService.sign(payload)
this.userService.createUserSession(user, token)
const token = this.jwtService.sign(payload);
this.userService.createUserSession(user, token);
return {
accessToken: token,
};
}
async logout(payload: IJWTPayload){
return await this.userService.removeUsersession(payload.id)

async logout(payload: IJWTPayload) {
return await this.userService.removeUsersession(payload.id);
}

async isTokenBlacklisted(token: string, payload: IJWTPayload):Promise<boolean> {
async isTokenBlacklisted(
token: string,
payload: IJWTPayload,
): Promise<boolean> {
//hasUser({ email })
const tokeninvalidate = await this.userService.hasgetUserTokenvalid({ accesstoken_hash:token, userId: payload.id })
const tokeninvalidate = await this.userService.hasgetUserTokenvalid({
accesstoken_hash: token,
userId: payload.id,
});
return tokeninvalidate;
}

async generateToken(user: Omit<IUser, 'password'>, fileData: string) {//: Promise<UserLoginReturnData> {
this.logger.verbose("With in generateToken");
async generateToken(user: Omit<IUser, 'password'>, fileData: string) {
//: Promise<UserLoginReturnData> {
this.logger.verbose('With in generateToken');
const payload: IJWTPayload = {
email: user.email.toLowerCase(),
id: user.id,
role: user.role
role: user.role,
};

const token = this.jwtService.sign(payload, {privateKey: fileData, secret: 'my-secret'});
const token = this.jwtService.sign(payload, {
privateKey: fileData,
secret: 'my-secret',
});
return {
accessToken: token,
}
};
}
}
74 changes: 40 additions & 34 deletions apps/drec-api/src/auth/client-jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,40 @@
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { OauthClientCredentialsService } from '../pods/user/oauth_client.service';
import { IJWTPayload } from './auth.service';
import { UserService } from '../pods/user/user.service';
import { Role } from '../utils/enums';

@Injectable()
export class ClientJwtStrategy extends PassportStrategy(Strategy, 'oauth2-client-password') {
constructor(
private readonly jwtService: JwtService,
private readonly oauthClientService: OauthClientCredentialsService,
private readonly userService: UserService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'my-secret',
passReqToCallback: true,
})
}

async validate(request: Request, payload: IJWTPayload) {
//@ts-ignore
const token = request.headers.authorization?.split(' ')[1];
const user = await this.userService.findByEmail(payload.email);
//@ts-ignore
const publicKey = this.oauthClientService.get(user.api_user_id);
const verifiedData = await this.jwtService.verify(token, {publicKey:(await publicKey).client_id, secret: 'my-secret'});
return user;
}
}
import { Strategy, ExtractJwt } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { OauthClientCredentialsService } from '../pods/user/oauth_client.service';
import { IJWTPayload } from './auth.service';
import { UserService } from '../pods/user/user.service';
import { Role } from '../utils/enums';

@Injectable()
export class ClientJwtStrategy extends PassportStrategy(
Strategy,
'oauth2-client-password',
) {
constructor(
private readonly jwtService: JwtService,
private readonly oauthClientService: OauthClientCredentialsService,
private readonly userService: UserService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'my-secret',
passReqToCallback: true,
});
}

async validate(request: Request, payload: IJWTPayload) {
//@ts-ignore
const token = request.headers.authorization?.split(' ')[1];
const user = await this.userService.findByEmail(payload.email);
//@ts-ignore
const publicKey = this.oauthClientService.get(user.api_user_id);
const verifiedData = await this.jwtService.verify(token, {
publicKey: (await publicKey).client_id,
secret: 'my-secret',
});
return user;
}
}
Loading
Loading