Skip to content

Commit ddb088d

Browse files
committed
feat(api): refactored to share more code between frontend and backend
1 parent 67fb833 commit ddb088d

38 files changed

+175
-118
lines changed

apps/api/src/app/auth/auth.module.ts

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,17 @@
1-
import { Module } from '@nestjs/common';
1+
import { forwardRef, Module } from '@nestjs/common';
22
import { APP_GUARD } from '@nestjs/core';
3-
import { TypeOrmModule } from '@nestjs/typeorm';
4-
5-
import { AuthService } from './auth.service';
6-
import { AuthController } from './auth.controller';
7-
import { User } from './user.entity';
83
import { JwtStrategy } from './passport/jwt.strategy';
94
import { AuthGuard } from './guards/auth.guard';
105
import { AllowGuard } from './guards/allow.guard';
116
import { RoleGuard } from './guards/role.guard';
127
import { ComposeGuard } from './guards/compose.guard';
138
import { WsAuthGuard } from './guards/ws-auth.guard';
149
import { WsJwtStrategy } from './passport/ws-jwt.strategy';
10+
import { UserModule } from '../user';
1511

1612
@Module({
17-
imports: [TypeOrmModule.forFeature([User])],
13+
imports: [UserModule],
1814
providers: [
19-
AuthService,
2015
JwtStrategy,
2116
WsJwtStrategy,
2217
AllowGuard,
@@ -40,7 +35,6 @@ import { WsJwtStrategy } from './passport/ws-jwt.strategy';
4035
useClass: ComposeGuard,
4136
},
4237
],
43-
controllers: [AuthController],
44-
exports: [AuthService, AuthGuard, WsAuthGuard],
38+
exports: [AuthGuard, WsAuthGuard],
4539
})
4640
export class AuthModule {}

apps/api/src/app/auth/guards/auth.guard.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
22
import * as passport from 'passport';
33
import { HttpAuthException } from '../auth.exception';
4+
import { User, JwtToken } from '@ngx-starter-kit/models';
45

56
export const defaultOptions = {
67
session: false,
@@ -16,7 +17,7 @@ export const defaultOptions = {
1617
};
1718

1819
const createPassportContext = (request, response) => (type, options) =>
19-
new Promise((resolve, reject) =>
20+
new Promise<{ user: User; info: JwtToken }>((resolve, reject) =>
2021
passport.authenticate(type, options, (err, user, info) => {
2122
try {
2223
return resolve(options.callback(err, user, info));
@@ -36,8 +37,8 @@ export class AuthGuard implements CanActivate {
3637
const [request, response] = [httpContext.getRequest(), httpContext.getResponse()];
3738
const passportFn = createPassportContext(request, response);
3839
const userAndInfo = await passportFn('jwt', defaultOptions);
39-
request[defaultOptions.property] = (userAndInfo as any).user;
40-
request[defaultOptions.infoProperty] = (userAndInfo as any).info;
40+
request[defaultOptions.property] = userAndInfo.user;
41+
request[defaultOptions.infoProperty] = userAndInfo.info;
4142
return true;
4243
}
4344
}

apps/api/src/app/auth/guards/role.guard.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ export class RoleGuard implements CanActivate {
2626
throw new UnauthorizedException('RoleGuard should have been executed after AuthGuard');
2727
}
2828

29+
// FIXME: useless
2930
if (endpointRoles.includes(RolesEnum.SELF)) {
3031
if (token.preferred_username === this.resolveUsername(request)) {
3132
return true;
@@ -38,15 +39,15 @@ export class RoleGuard implements CanActivate {
3839
if (this.isRoleOverlay(token.realm_access.roles, [RolesEnum.ADMIN])) {
3940
return true;
4041
} else {
41-
throw new ForbiddenException(`SumoApp admin users only`);
42+
throw new ForbiddenException(`NgxApp admin users only`);
4243
}
4344
}
4445

4546
if (endpointRoles.includes(RolesEnum.USER)) {
4647
if (this.isRoleOverlay(token.realm_access.roles, [RolesEnum.USER])) {
4748
return true;
4849
} else {
49-
throw new ForbiddenException(`SumoApp users only`);
50+
throw new ForbiddenException(`NgxApp users only`);
5051
}
5152
}
5253

apps/api/src/app/auth/guards/ws-auth.guard.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
22
import * as passport from 'passport';
33
import { WsAuthException } from '../auth.exception';
4+
import { User, JwtToken } from '@ngx-starter-kit/models';
45

56
export const defaultWsOptions = {
67
session: false,
@@ -16,7 +17,7 @@ export const defaultWsOptions = {
1617
};
1718

1819
const createPassportContext = (request, response) => (type, options) =>
19-
new Promise((resolve, reject) =>
20+
new Promise<{ user: User; info: JwtToken }>((resolve, reject) =>
2021
passport.authenticate(type, options, (err, user, info) => {
2122
try {
2223
return resolve(options.callback(err, user, info));
@@ -37,8 +38,8 @@ export class WsAuthGuard implements CanActivate {
3738
const passportFn = createPassportContext(request, {});
3839
try {
3940
const userAndInfo = await passportFn('ws-jwt', defaultWsOptions);
40-
request[defaultWsOptions.property] = (userAndInfo as any).user;
41-
request[defaultWsOptions.infoProperty] = (userAndInfo as any).info;
41+
request[defaultWsOptions.property] = userAndInfo.user;
42+
request[defaultWsOptions.infoProperty] = userAndInfo.info;
4243
return true;
4344
} catch (err) {
4445
request.disconnect();

apps/api/src/app/auth/index.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
export * from './auth.module';
2-
export * from './auth.service';
3-
export * from './user.entity';
1+
export { AuthModule } from './auth.module';
42
export * from './decorators';
5-
export * from './guards/ws-auth.guard';
6-
export * from './guards/auth.guard';
3+
export { WsAuthGuard } from './guards/ws-auth.guard';
4+
export { AuthGuard } from './guards/auth.guard';

apps/api/src/app/auth/passport/jwt.strategy.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ import { PassportStrategy } from '@nestjs/passport';
33
import { Injectable, UnauthorizedException } from '@nestjs/common';
44
import { passportJwtSecret, SigningKeyNotFoundError } from '@xmlking/jwks-rsa';
55

6-
import { AuthService } from '../auth.service';
7-
import { JwtToken } from '../interfaces/jwt-token.interface';
86
import { environment as env } from '@env-api/environment';
7+
import { JwtToken } from '@ngx-starter-kit/models';
8+
import { UserService } from '../../user';
99

1010
@Injectable()
1111
export class JwtStrategy extends PassportStrategy(Strategy) {
12-
constructor(private readonly authService: AuthService) {
12+
constructor(private readonly userService: UserService) {
1313
super({
1414
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
1515
// secretOrKey: env.auth.publicKey,
@@ -36,7 +36,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
3636

3737
// tslint:disable-next-line:ban-types
3838
async validate(token: any, done: Function) {
39-
const user = await this.authService.getLoggedUserOrCreate(token).catch(console.error);
39+
const user = await this.userService.getLoggedUserOrCreate(token).catch(console.error);
4040
if (!user) {
4141
return done(new UnauthorizedException('user not found and cannot create new user in database'), false);
4242
}

apps/api/src/app/auth/passport/ws-jwt.strategy.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import { PassportStrategy } from '@nestjs/passport';
33
import { Injectable, UnauthorizedException } from '@nestjs/common';
44
import { passportJwtSecret, SigningKeyNotFoundError } from '@xmlking/jwks-rsa';
55

6-
import { AuthService } from '../auth.service';
7-
import { JwtToken } from '../interfaces/jwt-token.interface';
86
import { WsException } from '@nestjs/websockets';
97
import { environment as env } from '@env-api/environment';
8+
import { JwtToken } from '@ngx-starter-kit/models';
9+
import { UserService } from '../../user';
1010

1111
const extractJwtFromWsQuery = req => {
1212
let token = null;
@@ -20,7 +20,7 @@ const extractJwtFromWsQuery = req => {
2020

2121
@Injectable()
2222
export class WsJwtStrategy extends PassportStrategy(Strategy, 'ws-jwt') {
23-
constructor(private readonly authService: AuthService) {
23+
constructor(private readonly userService: UserService) {
2424
super({
2525
jwtFromRequest: extractJwtFromWsQuery, // ExtractJwt.fromUrlQueryParameter('token'),
2626
// secretOrKey: env.auth.publicKey,
@@ -47,7 +47,7 @@ export class WsJwtStrategy extends PassportStrategy(Strategy, 'ws-jwt') {
4747

4848
// tslint:disable-next-line:ban-types
4949
async validate(token: any, done: Function) {
50-
const user = await this.authService.getLoggedUserOrCreate(token).catch(console.error);
50+
const user = await this.userService.getLoggedUserOrCreate(token).catch(console.error);
5151
if (!user) {
5252
return done(new WsException('user not found and cannot create new user in database'), false);
5353
}

apps/api/src/app/chat/interfaces/message.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { User } from './user';
1+
import { User } from '@ngx-starter-kit/models';
22

33
export class Message {
44
message: string;

apps/api/src/app/core/context/request-context.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { HttpException, HttpStatus } from '@nestjs/common';
22
import * as cls from 'cls-hooked';
33
import uuid from 'uuid';
4-
import { User } from '../../auth';
4+
import { User } from '@ngx-starter-kit/models';
55

66
export class RequestContext {
77
readonly id: number;
@@ -38,7 +38,7 @@ export class RequestContext {
3838

3939
if (requestContext) {
4040
// tslint:disable-next-line
41-
const user: any = requestContext.request['user'];
41+
const user: User = requestContext.request['user'];
4242
if (user) {
4343
return user;
4444
}

apps/api/src/app/core/core.module.ts

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
22
import { EmailModule } from '../email';
33
import { ConfigModule } from '../config';
4-
import { TypeOrmModule } from '@nestjs/typeorm';
4+
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
55
import { APP_INTERCEPTOR } from '@nestjs/core';
66
import { LoggingInterceptor, TransformInterceptor } from './interceptors';
77
import { RequestContextMiddleware } from './context';
88
import { ConfigService } from '../config';
9-
import { ConnectionOptions } from 'typeorm';
109
import { environment as env } from '@env-api/environment';
1110
import { isClass } from '@ngx-starter-kit/utils';
1211

1312
function requireAllClasses(rc) {
1413
return rc
1514
.keys()
16-
.filter(filePath => !filePath.includes('base'))
1715
.flatMap(key => Object.values(rc(key)))
1816
.filter(isClass);
1917
}
2018

2119
const requireContext = (require as any).context('../..', true, /\.entity.ts/);
22-
// const requireContext = (require as any).context('../..', true, /^\.\/.*\/.*\/(?!(base|audit-base)).*\.entity.ts$/);
2320
const entities = requireAllClasses(requireContext);
2421

22+
// const migrationsRequireContext = (require as any).context('../../../migrations/', true, /\.ts/);
23+
// const migrations = requireAllClasses(migrationsRequireContext);
24+
2525
@Module({
2626
imports: [
2727
ConfigModule,
2828
EmailModule.forRoot(env.email),
2929
TypeOrmModule.forRootAsync({
3030
imports: [ConfigModule],
31-
useFactory: async (config: ConfigService) =>
32-
({
33-
...env.database,
34-
entities,
35-
} as ConnectionOptions),
31+
useFactory: (config: ConfigService): TypeOrmModuleOptions => ({
32+
...env.database,
33+
entities,
34+
// migrations,
35+
}),
3636
inject: [ConfigService],
3737
}),
3838
],

0 commit comments

Comments
 (0)