type-graphql#Authorized TypeScript Examples

The following examples show how to use type-graphql#Authorized. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: plugin-newsletter.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
/** Restrict via decorator: */
    @Authorized<TAuthRole>("administrator", 'guest')
    @Query(() => String)
    async pluginNewsletterStats(@Ctx() ctx: TGraphQLContext): Promise<string> {
        
        // Or via checking manually user info: (both methods can work independently)
        if (ctx.user?.role !== 'administrator')
            throw new UnauthorizedException('Forbidden');

        return (await getManager().find(PluginNewsletter) ?? []).length + '';
    }
Example #2
Source File: user.resolver.ts    From liferay-grow with MIT License 6 votes vote down vote up
@Authorized()
  @Query(() => User, { name: 'getUserByLogin' })
  async getUserByLogin(@Arg('login') login: string): Promise<User | Error> {
    try {
      const profile = await Profile.findOneOrFail({
        relations: ['user'],
        where: { github_login: login },
      });

      return User.findOneOrFail(profile.user.id, { relations });
    } catch (e) {
      throw new Error('Account not exists');
    }
  }
Example #3
Source File: mutations.ts    From backend with MIT License 6 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.ADMIN)
    async tutoringInterestCreate(@Arg("pupilId") pupilId: number, @Arg("status") status: InterestConfirmationStatus) {
        const pupil = await getPupil(pupilId);
        const existing = await prisma.pupil_tutoring_interest_confirmation_request.findFirst({
            where: { pupilId }
        });

        if (existing) {
            await changeStatus(existing.token, status);
            return true;
        }

        await prisma.pupil_tutoring_interest_confirmation_request.create({
            data: { token: generateToken(), pupilId, status }
        });

        logTransaction("pupilInterestConfirmationRequestStatusChange", pupil, {
            changeDate: Date.now(),
            previousStatus: InterestConfirmationStatus.PENDING,
            newStatus: status
        });

        return true;
    }
Example #4
Source File: user-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 500 }))
  @Mutation(returns => Member)
  async setUserLinks(@Args() links: setUserLinksArgs, @Ctx() context: Context) {
    try {
      const foundUser = await UserModel.findOne({
        _id: context.currentUser.id,
      });
      if (!foundUser) throw new ApolloError("User not found with id");

      const linksToBeUpdated = { ...foundUser.toObject().links, ...links };

      const user = await UserModel.findOneAndUpdate(
        { _id: context.currentUser.id },
        {
          $set: { links: linksToBeUpdated },
        },
        { new: true }
      );
      return user;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #5
Source File: order.resolver.ts    From Cromwell with MIT License 6 votes vote down vote up
@Authorized<TAuthRole>("all")
    @Query(() => Order)
    async [getOneByIdPath](
        @Ctx() ctx: TGraphQLContext,
        @Arg("id", () => Int) id: number
    ): Promise<Order | undefined> {
        if (!ctx?.user?.role) throw new HttpException('Access denied.', HttpStatus.UNAUTHORIZED);

        const order = await this.repository.getOrderById(id);
        if (ctx.user.role === 'guest' || ctx.user.role === 'administrator' ||
            (order?.userId && ctx.user.id + '' === order.userId + ''))
            return order;
    }
Example #6
Source File: invitation-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @Mutation(() => InvitationLinkResult)
  async createInvitationLink(
    @Arg("roomId", { nullable: false }) roomId: ObjectID,
    @Ctx() context: Context
  ) {
    const existingInvitation = await InvitationModel.findOne({
      roomId: roomId,
      invitedBy: context.currentUser.id,
      isPublic: true,
    });

    const baseURL =
      process.env.NODE_ENV !== "production"
        ? "http://localhost:3000"
        : "https://convoychat.herokuapp.com";

    if (existingInvitation) {
      return {
        link: `${baseURL}/invitation/${existingInvitation.token}`,
      };
    }

    const validRoom = await RoomModel.findOne({ _id: roomId });
    if (!validRoom) throw new Error("Not a valid room");

    // TODO: add expiry time in invitation token
    const token = crypto.randomBytes(16).toString("hex");
    const invite = new InvitationModel({
      isPublic: true,
      roomId: roomId,
      invitedBy: context.currentUser.id,
      token: token,
    });

    await invite.save();

    return { link: `${baseURL}/invitation/${token}` };
  }
Example #7
Source File: fields.ts    From backend with MIT License 5 votes vote down vote up
@FieldResolver(type => [ParticipationCertificate])
    @Authorized(Role.ADMIN, Role.OWNER)
    @LimitEstimated(10)
    async participationCertificatesToSign(@Root() pupil: Required<Pupil>) {
        return await prisma.participation_certificate.findMany({
            where: { pupilId: pupil.id }
        });
    }
Example #8
Source File: order.resolver.ts    From Cromwell with MIT License 5 votes vote down vote up
@Authorized<TAuthRole>("administrator", "guest")
    @Query(() => Order)
    async [getOneBySlugPath](@Arg("slug") slug: string): Promise<TOrder | undefined> {
        return this.repository.getOrderBySlug(slug);
    }
Example #9
Source File: mutations.ts    From backend with MIT License 5 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.ADMIN, Role.TUTEE)
    async pupilDeleteMatchRequest(@Ctx() context: GraphQLContext, @Arg("pupilId", { nullable: true }) pupilId?: number): Promise<boolean> {
        const pupil = await getSessionPupil(context, /* elevated override */ pupilId);
        await deletePupilMatchRequest(pupil);

        return true;
    }
Example #10
Source File: coupon.resolver.ts    From Cromwell with MIT License 5 votes vote down vote up
@Authorized<TAuthRole>('administrator', 'guest')
    @Query(() => PagedCoupon)
    async [getFilteredPath](
        @Arg("pagedParams", { nullable: true }) pagedParams?: PagedParamsInput<TCoupon>,
        @Arg("filterParams", () => BaseFilterInput, { nullable: true }) filterParams?: BaseFilterInput,
    ): Promise<TPagedList<TCoupon> | undefined> {
        return this.repository.getFilteredCoupons(pagedParams, filterParams);
    }
Example #11
Source File: mutations.ts    From backend with MIT License 5 votes vote down vote up
@Mutation(returns => Boolean)
    @Authorized(Role.ADMIN)
    async pupilDeactivate(@Arg("pupilId") pupilId: number): Promise<boolean> {
        const pupil = await getPupil(pupilId);
        await deactivatePupil(pupil);
        return true;
    }
Example #12
Source File: order.resolver.ts    From Cromwell with MIT License 5 votes vote down vote up
@Authorized<TAuthRole>("administrator", "guest")
    @Query(() => PagedOrder)
    async [getManyPath](
        @Arg("pagedParams", { nullable: true }) pagedParams?: PagedParamsInput<TOrder>
    ): Promise<TPagedList<TOrder>> {
        return this.repository.getOrders(pagedParams);
    }
Example #13
Source File: mutations.ts    From backend with MIT License 5 votes vote down vote up
@Mutation(returns => String)
    @Authorized(Role.ADMIN)
    async notificationImport(@Arg("notifications", type => [NotificationInput]) notifications: NotificationInput[], @Arg("overwrite", { nullable: true }) overwrite: boolean = false, @Arg("apply", { nullable: true }) apply: boolean = false) {
        return await Notification.importNotifications(notifications, overwrite, apply);
    }