Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add authentication for token routes #3

Merged
merged 1 commit into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
JWT_SECRET=
REDIS_URL=

ADMIN_USERNAME=
ADMIN_PASSWORD=

BITCOIN_JSON_RPC_URL=
BITCOIN_JSON_RPC_USERNAME=
BITCOIN_JSON_RPC_PASSWORD=
Expand Down
6 changes: 5 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ if (env.SENTRY_DSN_URL && env.NODE_ENV !== 'development') {
});
}

const isTokenRoutesEnable = env.NODE_ENV === 'production' ? env.ADMIN_USERNAME && env.ADMIN_PASSWORD : true;

async function routes(fastify: FastifyInstance) {
container.register({ logger: asValue(fastify.log) });
fastify.decorate('container', container);
Expand All @@ -39,7 +41,9 @@ async function routes(fastify: FastifyInstance) {
fastify.register(cache);
fastify.register(rateLimit);

fastify.register(tokenRoutes, { prefix: '/token' });
if (isTokenRoutesEnable) {
fastify.register(tokenRoutes, { prefix: '/token' });
}
fastify.register(bitcoinRoutes, { prefix: '/bitcoin/v1' });

fastify.setErrorHandler((error, _, reply) => {
Expand Down
4 changes: 4 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ const envSchema = z.object({
NODE_ENV: z.string().default('development'),
PORT: z.string().optional(),
NETWORK: z.string().default('testnet'),

SENTRY_DSN_URL: z.string().optional(),
REDIS_URL: z.string().optional(),
RATE_LIMIT_PER_MINUTE: z.number().default(100),

ADMIN_USERNAME: z.string().optional(),
ADMIN_PASSWORD: z.string().optional(),

/**
* JWT_SECRET is used to sign the JWT token for authentication.
*/
Expand Down
14 changes: 14 additions & 0 deletions src/plugins/swagger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fp from 'fastify-plugin';
import swagger from '@fastify/swagger';
import swaggerUI from '@fastify/swagger-ui';
import { jsonSchemaTransform } from 'fastify-type-provider-zod';
import { env } from '../env';

export const DOCS_ROUTE_PREFIX = '/docs';

Expand All @@ -24,6 +25,19 @@ export default fp(async (fastify) => {
},
},
transform: jsonSchemaTransform,
transformObject: ({ swaggerObject }) => {
if (env.NODE_ENV === 'production') {
const { paths = {} } = swaggerObject;
const newPaths = Object.entries(paths).reduce((acc, [path, methods]) => {
if (path.startsWith('/token')) {
return acc;
}
return { ...acc, [path]: methods };
}, {});
swaggerObject.paths = newPaths;
}
return swaggerObject;
},
});
fastify.register(swaggerUI, {
routePrefix: DOCS_ROUTE_PREFIX,
Expand Down
25 changes: 24 additions & 1 deletion src/routes/token/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,32 @@
import { FastifyPluginCallback } from 'fastify';
import { Server } from 'http';
import generateRoute from './generate';
import { ZodTypeProvider } from 'fastify-type-provider-zod';
import generateRoute from './generate';
import { env } from '../../env';

const tokenRoutes: FastifyPluginCallback<Record<never, never>, Server, ZodTypeProvider> = (fastify, _, done) => {
if (env.NODE_ENV === 'production') {
fastify.addHook('onRequest', async (request, reply) => {
const { authorization } = request.headers;
if (!authorization) {
reply.code(401).send({ error: 'Unauthorized' });
return;
}

const [scheme, token] = authorization.split(' ');
if (scheme.toLowerCase() !== 'basic') {
reply.code(401).send({ error: 'Unauthorized' });
return;
}

const [username, password] = Buffer.from(token, 'base64').toString().split(':');
if (username !== env.ADMIN_USERNAME || password !== env.ADMIN_PASSWORD) {
reply.code(401).send({ error: 'Unauthorized' });
return;
}
});
}

fastify.register(generateRoute);
done();
};
Expand Down