Skip to content

Commit

Permalink
Refactor access control guard into AdOwner decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaudrenaud committed May 14, 2024
1 parent 1c039bf commit 33a900e
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions back-end/src/resolvers/AdResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,22 @@ import {
Mutation,
Query,
Resolver,
createMethodDecorator,
} from "type-graphql";
import Ad from "../entities/ad";
import { CreateOrUpdateAd } from "../entities/ad.args";
import { Context } from "..";
import User from "../entities/user";

export function AdOwner() {
return createMethodDecorator(async ({ args, context }, next) => {
if (await (context as Context).user?.isAdOwner(args.id)) {
return next();
}
throw new Error("You must own the ad to perform this action.");
});
}

@Resolver()
export class AdResolver {
@Query(() => [Ad])
Expand All @@ -32,24 +42,19 @@ export class AdResolver {
}

@Authorized()
@AdOwner()
@Mutation(() => Ad)
async updateAd(
@Arg("id", () => ID) id: string,
@Args() args: CreateOrUpdateAd,
@Ctx() { user }: Context,
) {
if (await user?.isAdOwner(id)) {
return Ad.updateAd(id, args);
}
throw new Error("Only the ad owner is allowed to update it.");
return Ad.updateAd(id, args);
}

@Authorized()
@AdOwner()
@Mutation(() => Ad)
async deleteAd(@Arg("id", () => ID) id: string, @Ctx() { user }: Context) {
if (await user?.isAdOwner(id)) {
return Ad.deleteAd(id);
}
throw new Error("Only the ad owner is allowed to delete it.");
async deleteAd(@Arg("id", () => ID) id: string) {
return Ad.deleteAd(id);
}
}

0 comments on commit 33a900e

Please sign in to comment.