Skip to content

Commit

Permalink
changed project structure, redesigned handlers implementation from fu…
Browse files Browse the repository at this point in the history
…nction to class
  • Loading branch information
LCcodder committed Nov 14, 2024
1 parent dc5b6e9 commit d32ec89
Show file tree
Hide file tree
Showing 33 changed files with 979 additions and 960 deletions.
20 changes: 7 additions & 13 deletions source/api/v1/auth/AuthPreHandler.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
import { extractToken } from "../utils/common/TokenExtractor";
import { extractToken } from "../shared/utils/common/TokenExtractor";
import { extractJwtPayload } from "./jwt/PayloadExtractor";
import { validateSignature } from "./jwt/SignatureValidator";
import { USER_EXCEPTIONS } from "../exceptions/UserExceptions";
import { USER_EXCEPTIONS } from "../shared/exceptions/UserExceptions";
import { IAuthService } from "../services/interfaces/AuthServiceInterface";
import { isException } from "../utils/guards/ExceptionGuard";
import { isException } from "../shared/utils/guards/ExceptionGuard";

export type AuthentificationPreHandler = (request: FastifyRequest, reply: FastifyReply, done: HookHandlerDoneFunction) => void

export const authenticationFactory = (authService: IAuthService) =>
async (request: FastifyRequest, reply: FastifyReply, _done: HookHandlerDoneFunction) => {
async (request: FastifyRequest, reply: FastifyReply, _done: HookHandlerDoneFunction): Promise<AuthentificationPreHandler> => {
const token = extractToken(request)
if (!token) {
reply.code(401).send(USER_EXCEPTIONS.NotAuthorized)
Expand All @@ -26,19 +28,11 @@ async (request: FastifyRequest, reply: FastifyReply, _done: HookHandlerDoneFunct
return
}

// try {
const relevanceState = await authService.checkTokenRelevance(payload.login, token)
if (isException(relevanceState)) {
reply.code(
relevanceState.statusCode
).send(relevanceState)
return
}
// } catch (exception: any) {
// reply.code(
// exception.statusCode
// ).send(exception)
// return
// }

}
}
2 changes: 1 addition & 1 deletion source/api/v1/auth/jwt/SignatureValidator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as jwt from 'jsonwebtoken'
import { CONFIG } from '../../config/ServerConfiguration'
import { CONFIG } from '../../shared/config/ServerConfiguration'

export const validateSignature = (token: string): boolean => {
try {
Expand Down
2 changes: 1 addition & 1 deletion source/api/v1/auth/jwt/TokenGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as jwt from 'jsonwebtoken'
import { CONFIG } from '../../config/ServerConfiguration'
import { CONFIG } from '../../shared/config/ServerConfiguration'

export const generateToken = (login: string): string => {
return jwt.sign({ login }, CONFIG.jwtSecret, {expiresIn: CONFIG.jwtExpiration})
Expand Down
138 changes: 71 additions & 67 deletions source/api/v1/handlers/AuthHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,79 @@
import { FastifyInstance, FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
import { FastifyInstance } from "fastify";
import { IAuthService } from "../services/interfaces/AuthServiceInterface";
import { UserCredentials } from "../database/entities/User";
import { AUTH_EXCEPTIONS } from "../exceptions/AuthExceptions";
import { AUTH_EXCEPTIONS } from "../shared/exceptions/AuthExceptions";
import { AuthUserSchema, ChangePasswordSchema } from "../validation/schemas/AuthSchemas";
import { extractJwtPayload } from "../auth/jwt/PayloadExtractor";
import { extractToken } from "../utils/common/TokenExtractor";
import { isException } from "../utils/guards/ExceptionGuard";
import { USER_EXCEPTIONS } from "../exceptions/UserExceptions";
import { extractToken } from "../shared/utils/common/TokenExtractor";
import { isException } from "../shared/utils/guards/ExceptionGuard";
import { USER_EXCEPTIONS } from "../shared/exceptions/UserExceptions";
import { Handler } from "./Handler";
import { AuthentificationPreHandler } from "../auth/AuthPreHandler";

export const handleAuthRoutes = (
server: FastifyInstance,
authService: IAuthService,
authenticate: (
request: FastifyRequest,
reply: FastifyReply,
done: HookHandlerDoneFunction
) => void
) => {
server.post<{
Body: UserCredentials,
Reply: {
200: { token: string, expiresIn: string },
400: typeof AUTH_EXCEPTIONS.WrongCredentials,
503: typeof AUTH_EXCEPTIONS.ServiceUnavailable | typeof USER_EXCEPTIONS.ServiceUnavailable
}
}>("/auth", {
schema: AuthUserSchema
}, async (request, reply) => {
const credentials: UserCredentials = request.body

const result = await authService.authorizeAndGenerateToken(
credentials.email,
credentials.password
)
if (isException(result)) {
reply.code(result.statusCode).send(result)
return
}
export class AuthHandler extends Handler<IAuthService> {
constructor(
server: FastifyInstance,
authentificationPreHandler: AuthentificationPreHandler,
authService: IAuthService
) {
super(server, authentificationPreHandler, authService)
}

reply.code(200).send(result)
public override handleRoutes(): void {
this.server.post<{
Body: UserCredentials,
Reply: {
200: { token: string, expiresIn: string },
400: typeof AUTH_EXCEPTIONS.WrongCredentials,
503: typeof AUTH_EXCEPTIONS.ServiceUnavailable | typeof USER_EXCEPTIONS.ServiceUnavailable
}
}>("/auth", {
schema: AuthUserSchema
}, async (request, reply) => {
const credentials: UserCredentials = request.body

const result = await this.service.authorizeAndGenerateToken(
credentials.email,
credentials.password
)
if (isException(result)) {
reply.code(result.statusCode).send(result)
return
}

})

server.patch<{
Body: { oldPassword: string, newPassword: string },
Reply: {
200: { success: true },
400: typeof AUTH_EXCEPTIONS.WrongCredentials | typeof AUTH_EXCEPTIONS.NewPasswordIsSame,
503: typeof AUTH_EXCEPTIONS.ServiceUnavailable | typeof USER_EXCEPTIONS.ServiceUnavailable
}
}>("/auth/password", {
schema: ChangePasswordSchema,
preHandler: authenticate
}, async (request, reply) => {
const passwords = request.body
const { login } = extractJwtPayload(
extractToken(request)
)

const state = await authService.changePassword(
login,
passwords.oldPassword,
passwords.newPassword
)

if (isException(state)) {
reply.code(state.statusCode).send(state)
return
}
reply.code(200).send(result)

reply.code(200).send(state)

})
}
})

this.server.patch<{
Body: { oldPassword: string, newPassword: string },
Reply: {
200: { success: true },
400: typeof AUTH_EXCEPTIONS.WrongCredentials | typeof AUTH_EXCEPTIONS.NewPasswordIsSame,
503: typeof AUTH_EXCEPTIONS.ServiceUnavailable | typeof USER_EXCEPTIONS.ServiceUnavailable
}
}>("/auth/password", {
schema: ChangePasswordSchema,
preHandler: this.authentificationPreHandler
}, async (request, reply) => {
const passwords = request.body
const { login } = extractJwtPayload(
extractToken(request)
)

const state = await this.service.changePassword(
login,
passwords.oldPassword,
passwords.newPassword
)

if (isException(state)) {
reply.code(state.statusCode).send(state)
return
}

reply.code(200).send(state)

})
}
}
12 changes: 12 additions & 0 deletions source/api/v1/handlers/Handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { FastifyInstance, FastifyReply, FastifyRequest, HookHandlerDoneFunction } from "fastify";
import { AuthentificationPreHandler } from "../auth/AuthPreHandler";

export abstract class Handler<TService> {
constructor(
protected server: FastifyInstance,
protected authentificationPreHandler: AuthentificationPreHandler,
protected service: TService
) {}

public abstract handleRoutes(): void
}
Loading

0 comments on commit d32ec89

Please sign in to comment.