Skip to content

Commit

Permalink
th-23: Protected routing [BE] (BinaryStudioAcademy#157)
Browse files Browse the repository at this point in the history
* th-23: + group access strategies

* th-23: + default strategies to the business controller

* th-23: + a user injection strategy
  • Loading branch information
h0wter committed Sep 4, 2023
1 parent f1b0cee commit 66ffe45
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 8 deletions.
3 changes: 3 additions & 0 deletions backend/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { type UserEntityObjectWithGroupT } from './packages/users/users.js';

declare module 'fastify' {
interface FastifyInstance {
[AuthStrategy.INJECT_USER]: FastifyAuthFunction;
[AuthStrategy.VERIFY_JWT]: FastifyAuthFunction;
[AuthStrategy.VERIFY_BUSINESS_GROUP]: FastifyAuthFunction;
[AuthStrategy.VERIFY_DRIVER_GROUP]: FastifyAuthFunction;
}

interface FastifyRequest {
Expand Down
17 changes: 16 additions & 1 deletion backend/src/libs/packages/controller/controller.package.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { type ILogger } from '~/libs/packages/logger/logger.js';
import { type ServerAppRouteParameters } from '~/libs/packages/server-application/server-application.js';
import { type ValueOf } from '~/libs/types/types.js';
import { type AuthStrategy } from '~/packages/auth/auth.js';

import { type IController } from './libs/interfaces/interface.js';
import {
Expand All @@ -8,24 +10,37 @@ import {
type ControllerRouteParameters,
} from './libs/types/types.js';

type DefaultStrategies =
| ValueOf<typeof AuthStrategy>
| ValueOf<typeof AuthStrategy>[]
| undefined;

class Controller implements IController {
private logger: ILogger;

private apiUrl: string;

public routes: ServerAppRouteParameters[];

public constructor(logger: ILogger, apiPath: string) {
public defaultStrategies: DefaultStrategies;

public constructor(
logger: ILogger,
apiPath: string,
strategies?: DefaultStrategies,
) {
this.logger = logger;
this.apiUrl = apiPath;
this.routes = [];
this.defaultStrategies = strategies;
}

public addRoute(options: ControllerRouteParameters): void {
const { handler, path } = options;
const fullPath = this.apiUrl + path;

this.routes.push({
authStrategy: this.defaultStrategies,
...options,
path: fullPath,
handler: (request, reply) => this.mapHandler(handler, request, reply),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import { type AuthStrategy } from '~/packages/auth/auth.js';

type AuthStrategyHandler =
| ValueOf<typeof AuthStrategy>
| ValueOf<typeof AuthStrategy>[]
| ((
fastify: FastifyInstance,
) =>
| FastifyAuthFunction[]
| (FastifyAuthFunction | FastifyAuthFunction[])[]);
| (FastifyAuthFunction | FastifyAuthFunction[])[])
| null;

export { type AuthStrategyHandler };
10 changes: 9 additions & 1 deletion backend/src/libs/packages/server-application/server-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,15 @@ class ServerApp implements IServerApp {
strategy?: AuthStrategyHandler,
): undefined | preHandlerHookHandler {
if (Array.isArray(strategy)) {
return this.app.auth(strategy);
const strategies = [];

for (const it of strategy) {
if (typeof it === 'string' && it in this.app) {
strategies.push(this.app[it]);
}
}

return this.app.auth(strategies, { relation: 'and' });
}

if (typeof strategy === 'string' && strategy in this.app) {
Expand Down
37 changes: 33 additions & 4 deletions backend/src/packages/auth/auth.app-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { type FastifyReply, type FastifyRequest } from 'fastify';
import fp from 'fastify-plugin';

import { HttpMessage } from '~/libs/packages/http/http.js';
import { type ValueOf } from '~/libs/types/types.js';

import { AuthStrategy } from './auth.js';
import { UserGroupKey } from './libs/enums/enums.js';
import { createUnauthorizedError } from './libs/helpers/create-unauthorized-error.helper.js';
import { type AuthPluginOptions } from './libs/types/auth-plugin-options.type.js';
import { jwtPayloadSchema } from './libs/validation-schemas/validation-schemas.js';
Expand All @@ -13,8 +15,8 @@ const authPlugin = fp<AuthPluginOptions>((fastify, options, done) => {

fastify.decorateRequest('user', null);

fastify.decorate(
AuthStrategy.VERIFY_JWT,
const verifyJwtStrategy =
(isJwtRequired: boolean) =>
async (
request: FastifyRequest,
_: FastifyReply,
Expand All @@ -23,8 +25,10 @@ const authPlugin = fp<AuthPluginOptions>((fastify, options, done) => {
try {
const token = request.headers.authorization?.replace('Bearer ', '');

if (!token) {
if (!token && isJwtRequired) {
return done(createUnauthorizedError(HttpMessage.UNAUTHORIZED));
} else if (!token) {
return;
}

const rawPayload = await jwtService.verifyToken(token);
Expand All @@ -48,7 +52,32 @@ const authPlugin = fp<AuthPluginOptions>((fastify, options, done) => {
} catch (error) {
return done(createUnauthorizedError(HttpMessage.UNAUTHORIZED, error));
}
},
};

const verifyGroup =
(group: ValueOf<typeof UserGroupKey>) =>
async (
request: FastifyRequest,
_: FastifyReply,
done: (error?: Error) => void,
): Promise<void> => {
if (request.user.group.key !== group) {
return done(createUnauthorizedError(HttpMessage.UNAUTHORIZED));
}
};

fastify.decorate(AuthStrategy.INJECT_USER, verifyJwtStrategy(false));

fastify.decorate(AuthStrategy.VERIFY_JWT, verifyJwtStrategy(true));

fastify.decorate(
AuthStrategy.VERIFY_BUSINESS_GROUP,
verifyGroup(UserGroupKey.BUSINESS),
);

fastify.decorate(
AuthStrategy.VERIFY_DRIVER_GROUP,
verifyGroup(UserGroupKey.DRIVER),
);

done();
Expand Down
3 changes: 3 additions & 0 deletions backend/src/packages/auth/libs/enums/auth-strategy.enum.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
const AuthStrategy = {
INJECT_USER: 'injectUser',
VERIFY_JWT: 'verifyJWT',
VERIFY_BUSINESS_GROUP: 'verifyBusinessGroup',
VERIFY_DRIVER_GROUP: 'verifyDriverGroup',
} as const;

export { AuthStrategy };
8 changes: 7 additions & 1 deletion backend/src/packages/business/business.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '~/libs/packages/controller/controller.js';
import { HttpCode } from '~/libs/packages/http/http.js';
import { type ILogger } from '~/libs/packages/logger/logger.js';
import { AuthStrategy } from '~/packages/auth/libs/enums/enums.js';

import { type BusinessService } from './business.service.js';
import { BusinessApiPath } from './libs/enums/enums.js';
Expand Down Expand Up @@ -139,7 +140,12 @@ class BusinessController extends Controller {
private businessService: BusinessService;

public constructor(logger: ILogger, businessService: BusinessService) {
super(logger, ApiPath.BUSINESS);
const defaultStrategies = [
AuthStrategy.VERIFY_JWT,
AuthStrategy.VERIFY_BUSINESS_GROUP,
];

super(logger, ApiPath.BUSINESS, defaultStrategies);

this.businessService = businessService;

Expand Down

0 comments on commit 66ffe45

Please sign in to comment.