Skip to content

Commit 026e7e0

Browse files
committed
Adds @Auth decorator for API Gateway endpoints
Introduces the `@Auth` decorator to simplify authentication handling for API Gateway endpoints. This allows developers to easily secure specific methods within a class-based endpoint by leveraging the router's `withAuth` middleware. The decorator supports optional parameters to enable or disable authentication requirements on a per-method basis. Updates documentation to reflect the usage and execution order of the new decorator and its relation to other decorators like `@Before` and `@After`.
1 parent 6fde3d2 commit 026e7e0

File tree

1 file changed

+53
-8
lines changed

1 file changed

+53
-8
lines changed

README.md

Lines changed: 53 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -576,7 +576,7 @@ const records = event.records; // Works!
576576

577577
Acai-TS provides powerful method decorators for clean, declarative API Gateway endpoints using the class-based pattern.
578578

579-
> **⚠️ Important**: The `@Before`, `@After`, `@Timeout`, and `@Validate` decorators are for **Router/API Gateway endpoints only** and work on **class methods** (not classes or standalone functions).
579+
> **⚠️ Important**: The `@Before`, `@After`, `@Auth`, `@Timeout`, and `@Validate` decorators are for **Router/API Gateway endpoints only** and work on **class methods** (not classes or standalone functions).
580580
>
581581
> For **event handlers** (DynamoDB, S3, SQS), these decorators will not work. Instead, use:
582582
> - **Function wrapper patterns** (see Event Processing Patterns section)
@@ -621,7 +621,7 @@ Best for complex endpoints with multiple methods and middleware:
621621

622622
```typescript
623623
// File: src/handlers/users.ts
624-
import { BaseEndpoint, Before, After, Timeout, Validate } from 'acai-ts';
624+
import { BaseEndpoint, Before, After, Timeout, Validate, Auth } from 'acai-ts';
625625

626626
export class UsersEndpoint extends BaseEndpoint {
627627
@Before(authMiddleware)
@@ -713,6 +713,49 @@ export class HeavyTaskEndpoint extends BaseEndpoint {
713713
}
714714
```
715715

716+
#### `@Auth(required?)`
717+
718+
Mark a method as requiring authentication. When used, the router's `withAuth` middleware will be executed:
719+
720+
```typescript
721+
// Configure auth middleware in router
722+
const router = new Router({
723+
basePath: '/api/v1',
724+
routesPath: './src/handlers/**/*.ts',
725+
withAuth: async (request, response) => {
726+
// Your JWT validation logic here
727+
const token = request.headers.authorization?.replace('Bearer ', '');
728+
if (!token || !validateJWT(token)) {
729+
response.code = 401;
730+
response.setError('auth', 'Invalid or missing authentication token');
731+
}
732+
}
733+
});
734+
735+
// Use @Auth decorator on methods that require authentication
736+
export class UsersEndpoint extends BaseEndpoint {
737+
@Auth() // Requires authentication (default: required=true)
738+
async get(request: Request, response: Response): Promise<Response> {
739+
// Auth middleware runs before this method
740+
response.body = { users: [] };
741+
return response;
742+
}
743+
744+
@Auth(false) // Explicitly disable auth requirement
745+
async post(request: Request, response: Response): Promise<Response> {
746+
// No auth required for this endpoint
747+
response.body = { message: 'Public endpoint' };
748+
return response;
749+
}
750+
751+
// No @Auth decorator = no auth requirement
752+
async options(request: Request, response: Response): Promise<Response> {
753+
response.body = { message: 'CORS preflight' };
754+
return response;
755+
}
756+
}
757+
```
758+
716759
#### `@Validate(validationConfig)`
717760

718761
Validate request data against schemas or requirements:
@@ -765,7 +808,8 @@ Stack multiple decorators on a single method. They execute in a specific order:
765808

766809
```typescript
767810
export class UsersEndpoint extends BaseEndpoint {
768-
@Before(authMiddleware, rateLimiter) // Runs first
811+
@Before(rateLimiter) // Runs first (custom middleware)
812+
@Auth() // Auth middleware runs after Before middleware
769813
@Validate({ requiredBody: 'CreateUserRequest' }) // Validates request
770814
@Timeout(5000) // Sets timeout
771815
@After(addTimestamp, logResponse) // Runs last
@@ -778,10 +822,11 @@ export class UsersEndpoint extends BaseEndpoint {
778822
```
779823

780824
**Execution Order:**
781-
1. `@Before` middleware (in order: rateLimiter → authMiddleware)
782-
2. `@Validate` validation
783-
3. Method execution with `@Timeout`
784-
4. `@After` middleware (in order: addTimestamp → logResponse)
825+
1. `@Before` middleware (rateLimiter)
826+
2. `@Auth` authentication (router's `withAuth` middleware)
827+
3. `@Validate` validation
828+
4. Method execution with `@Timeout`
829+
5. `@After` middleware (in order: addTimestamp → logResponse)
785830

786831
### Multiple HTTP Methods in One Class
787832

@@ -1040,7 +1085,7 @@ interface Response {
10401085
**Class for defining API Gateway endpoints with method decorators:**
10411086

10421087
```typescript
1043-
import { BaseEndpoint, Before, After, Timeout, Validate } from 'acai-ts';
1088+
import { BaseEndpoint, Before, After, Timeout, Validate, Auth } from 'acai-ts';
10441089

10451090
export class UsersEndpoint extends BaseEndpoint {
10461091
// Implement HTTP methods: get, post, put, patch, delete

0 commit comments

Comments
 (0)