-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgateway.controller.ts
More file actions
86 lines (79 loc) · 2.61 KB
/
Copy pathgateway.controller.ts
File metadata and controls
86 lines (79 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { FastifyInstance } from 'fastify';
import { AppConfig } from '../config';
import { UsersService } from '../services/users.service';
import fastifyLimit from '@fastify/rate-limit';
import { NotFoundError, UnauthorizedError } from '../errors/Errors';
import Logger from '../Logger';
import CacheService from '../services/cache.service';
import { Service } from '../core/users/Tier';
import { User } from '../core/users/User';
import { UserFeaturesOverridesService } from '../services/userFeaturesOverride.service';
import { withAuth } from '../plugins/withAuth.plugin';
interface GatewayControllerPayload {
cacheService: CacheService;
usersService: UsersService;
userFeaturesOverridesService: UserFeaturesOverridesService;
config: AppConfig;
}
export function gatewayController({
cacheService,
usersService,
userFeaturesOverridesService,
config,
}: GatewayControllerPayload) {
return async function (fastify: FastifyInstance) {
await withAuth(fastify, {
jwtOptions: {
algorithms: ['RS256'],
},
secret: {
public: Buffer.from(config.PAYMENTS_GATEWAY_PUBLIC_SECRET, 'base64').toString('utf-8'),
},
});
fastify.register(fastifyLimit, {
max: 20,
timeWindow: '1 minute',
});
fastify.addHook('onRequest', async (request, reply) => {
try {
await request.jwtVerify();
} catch (err) {
Logger.warn(`JWT verification failed with error: ${(err as Error).message}`);
throw new UnauthorizedError();
}
});
fastify.post<{ Body: { feature: Service; userUuid: string } }>(
'/activate',
{
schema: {
body: {
type: 'object',
required: ['userUuid', 'feature'],
properties: {
feature: {
type: 'string',
enum: [Service.Antivirus, Service.Backups, Service.Cleaner, Service.Cli],
},
userUuid: {
type: 'string',
},
},
},
},
},
async (request, response) => {
let user: User;
const { feature, userUuid } = request.body;
try {
user = await usersService.findUserByUuid(userUuid);
} catch (error) {
Logger.error(`[PRODUCTS/ACTIVATE]: Error ${(error as Error).message} for user ${userUuid}`);
throw new NotFoundError(`User with uuid ${userUuid} was not found`);
}
await userFeaturesOverridesService.upsertCustomUserFeatures(user, feature);
await cacheService.clearUserTier(userUuid);
return response.status(204).send();
},
);
};
}