Add authorization
This commit is contained in:
@@ -3,24 +3,22 @@ import { CreateTokenInput } from "./token.schema";
|
||||
import { createToken, getToken } from "./token.service";
|
||||
|
||||
export async function createTokenHandler(
|
||||
req: FastifyRequest<{ Body: CreateTokenInput }>,
|
||||
req: FastifyRequest,
|
||||
res: FastifyReply
|
||||
) {
|
||||
const input = req.body;
|
||||
const input = req.body as CreateTokenInput;
|
||||
|
||||
try {
|
||||
const result = await createToken(input);
|
||||
const authUser = req.user;
|
||||
const result = await createToken(input, authUser.tenantId);
|
||||
return res.code(201).send(result);
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getTokenHandler(
|
||||
req: FastifyRequest<{ Params: { tokenId: string } }>,
|
||||
res: FastifyReply
|
||||
) {
|
||||
const { tokenId } = req.params;
|
||||
export async function getTokenHandler(req: FastifyRequest, res: FastifyReply) {
|
||||
const { tokenId } = req.params as { tokenId: string };
|
||||
|
||||
try {
|
||||
const token = await getToken(tokenId);
|
||||
|
||||
@@ -12,13 +12,19 @@ export async function tokenRoutes(fastify: FastifyInstance) {
|
||||
201: $token("createTokenResponse"),
|
||||
},
|
||||
},
|
||||
config: { requiredClaims: ["token:write"] },
|
||||
preHandler: [fastify.authorize],
|
||||
},
|
||||
createTokenHandler
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/:tokenId",
|
||||
{ schema: { response: { 200: $token("getTokenResponse") } } },
|
||||
{
|
||||
schema: { response: { 200: $token("getTokenResponse") } },
|
||||
config: { requiredClaims: ["token:read"] },
|
||||
preHandler: [fastify.authorize],
|
||||
},
|
||||
getTokenHandler
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { buildJsonSchemas } from "fastify-zod";
|
||||
import mongoose from "mongoose";
|
||||
import { z } from "zod";
|
||||
import { Claim } from "../utils/claims";
|
||||
|
||||
export const tokenModel = mongoose.model(
|
||||
"token",
|
||||
new mongoose.Schema({
|
||||
tenantId: String,
|
||||
tenantId: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
pid: {
|
||||
type: String,
|
||||
unique: true,
|
||||
|
||||
@@ -2,12 +2,13 @@ import bcrypt from "bcrypt";
|
||||
import { generateId, generateToken } from "../utils/id";
|
||||
import { CreateTokenInput, tokenModel } from "./token.schema";
|
||||
|
||||
export async function createToken(input: CreateTokenInput) {
|
||||
export async function createToken(input: CreateTokenInput, tenantId: string) {
|
||||
const tokenId = generateId();
|
||||
const newToken = await generateToken();
|
||||
const tokenHash = await bcrypt.hash(newToken, 10);
|
||||
|
||||
const tokenInDb = await tokenModel.create({
|
||||
tenantId: tenantId,
|
||||
pid: tokenId,
|
||||
hash: tokenHash,
|
||||
createdAt: new Date(),
|
||||
|
||||
Reference in New Issue
Block a user