How to use the routing-controllers.Authorized function in routing-controllers

To help you get started, we’ve selected a few routing-controllers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github geli-lms / geli / api / src / controllers / UploadUnitController.ts View on Github external
import {Body, Post, JsonController, UseBefore, UploadedFile, BadRequestError, Authorized} from 'routing-controllers';
import fs = require('fs');
import passportJwtMiddleware from '../security/passportJwtMiddleware';

import {VideoUnit} from '../models/units/VideoUnit';
import {UnitController} from './UnitController';

const uploadOptions = {destination: 'uploads/'};

@JsonController('/units/upload')
@UseBefore(passportJwtMiddleware)
export class UploadUnitController extends UnitController {

  @Authorized(['teacher', 'admin'])
  @Post('/')
  addVideoUnit(@UploadedFile('file', {options: uploadOptions}) file: any, @Body() data: any) {
    // discard invalid requests
    if (!data.lectureId) {
      throw new BadRequestError('Misssing lectureId');
    }
    if (!data.name) {
      throw new BadRequestError('Misssing name');
    }

    // path for file upload units (for now video only)
    if (file) {
      return new VideoUnit({
        name: data.name,
        description: data.description,
        _course: data.courseId,
github geli-lms / geli / api / src / controllers / TaskUnitController.ts View on Github external
const savedTask: ITaskModel = savedTasks[i];
          data.model.tasks.push(savedTask._id);
        }

        return new TaskUnit(data.model).save();
      })
      .then((savedTaskUnit) => {
        return this.pushToLecture(data.lectureId, savedTaskUnit);
      });
  }

  private addTask(task: ITask) {
    return new Task(task).save();
  }

  @Authorized(['teacher', 'admin'])
  @Put('/:id')
  async updateUnit(@Param('id') id: string, @Body() unit: ITaskUnit) {
    if (unit.tasks) {
      unit.tasks = await Promise.all(unit.tasks.map((task) => {
        // update task if exists
        if (task._id) {
          return Task.findByIdAndUpdate(task._id, task, {'new': true});
        }

        return new Task(task).save();
      }));
    }

    return TaskUnit.findByIdAndUpdate(id, unit, {'new': true})
      .then((u) => u.toObject());
  }
github geli-lms / geli / api / src / controllers / CourseController.ts View on Github external
*             "id": "5a037e6a60f72236d8e7c815"
   *         },
   *         "active": true,
   *         "__v": 1,
   *         "whitelist": [],
   *         "enrollType": "free",
   *         "lectures": [],
   *         "students": [],
   *         "teachers": [],
   *         "id": "5a037e6b60f72236d8e7c83d",
   *         "hasAccessKey": false
   *     }
   *
   * @apiError BadRequestError Course name already in use.
   */
  @Authorized(['teacher', 'admin'])
  @Post('/')
  addCourse(@Body() course: ICourse, @Req() request: Request, @CurrentUser() currentUser: IUser) {
    course.courseAdmin = currentUser;
    return Course.findOne({name: course.name})
      .then((existingCourse) => {
        if (existingCourse) {
          throw new BadRequestError(errorCodes.errorCodes.course.duplicateName.code);
        }
        return new Course(course).save()
          .then((c) => c.toObject());
      });
  }

  /**
   * @api {post} /api/courses/mail Send mail to selected users
   * @apiName PostCourseMail
github shanmugharajk / react-point-of-sale / api / src / controllers / products / ProductsController.ts View on Github external
JsonController,
  Authorized,
  QueryParam,
  Param,
  Put,
  Delete
} from "routing-controllers";
import {
  PaginationInfo,
  IPaginationQueryParam
} from "../../decorators/PaginationInfo";
import { CrudServices, IFetchPageQuery } from "../../services/CrudServices";
import { CurrentUser } from "../../decorators/CurrentUser";

@JsonController("/products")
@Authorized()
export class ProductsController {
  private crudServices: CrudServices;

  constructor() {
    this.crudServices = new CrudServices();
    this.crudServices.setEntity(Product);
  }

  @Get("/:id")
  public async getProductById(@Param("id") id: string): Promise {
    const res = await this.crudServices.fetchById(id);
    return res || {};
  }

  @Get()
  public async getProducts(
github geli-lms / geli / api / src / controllers / PageController.ts View on Github external
@Get('/')
  async getPages() {
    const pages = await Page.find();
    return pages.map((page) => page.toObject());
  }

  @Get('/detail/:path')
  async getPage(@Param('path') path: string, @CurrentUser() currentUser: IUser) {
    const accessedPage = await Page.findOne({'path': path});
    return accessedPage.toObject();
  }

  @Post('/')
  @UseBefore(passportJwtMiddleware)
  @Authorized(['admin'])
  async addPage(@Body() data: any) {
    try {
      const page = await Page.create(data);
      return page.toObject();
    } catch (error) {
      const debug = error;
    }
  }

  @Put('/:path')
  @UseBefore(passportJwtMiddleware)
  @Authorized(['admin'])
  async  updatePage() {
    return new BadRequestError('Not implemented');
  }
}
github nicolaspearson / node.api.boilerplate / src / controllers / UserController.ts View on Github external
*         $ref: '#/responses/Forbidden'
	 *       404:
	 *         $ref: '#/responses/NotFound'
	 *       405:
	 *         $ref: '#/responses/MethodNotAllowed'
	 *       406:
	 *         $ref: '#/responses/NotAcceptable'
	 *       500:
	 *         $ref: '#/responses/InternalServerError'
	 *       504:
	 *         $ref: '#/responses/GatewayTimeout'
	 *       default:
	 *         $ref: '#/responses/DefaultError'
	 */
	@Delete('/users/:id')
	@Authorized()
	public async deleteUser(@Param('id') id: number): Promise {
		return await this.userService.delete(id);
	}

	/**
	 * @swagger
	 * /users/login:
	 *   post:
	 *     summary: Authenticates a specific user
	 *     description: Authenticates the provided user on the database using username / email address and password
	 *     operationId: loginUser
	 *     tags: [user]
	 *     consumes:
	 *       - application/json
	 *     produces:
	 *       - application/json
github geli-lms / geli / api / src / controllers / WhitelistController.ts View on Github external
*     {
   *         "__v": 0,
   *         "updatedAt": "2018-03-21T23:22:23.758Z",
   *         "createdAt": "2018-03-21T23:22:23.758Z",
   *         "_id": "5ab2e92fda32ac2ab0f04b78",
   *         "firstName": "max",
   *         "lastName": "mustermann",
   *         "uid": "876543",
   *         "courseId": {...},
   *         "id": "5ab2e92fda32ac2ab0f04b78"
   *     }
   *
   * @apiError BadRequestError That matriculation number is already in use for this course.
   */
  @Post('/')
  @Authorized(['teacher', 'admin'])
  async addWhitelistUser(@Body() whitelistUser: IWhitelistUser) {
    let savedWhitelistUser;
    try {
      savedWhitelistUser = await new WhitelistUser(this.toMongooseObjectId(whitelistUser)).save();
    } catch (err) {
      throw new BadRequestError(errorCodes.whitelist.duplicateWhitelistUser.text);
    }
    await this.addUserIfFound(whitelistUser);
    return savedWhitelistUser.toObject();
  }

  /**
   * @api {put} /api/whitelist/:id Update whitelist user
   * @apiName PutWhitelistUser
   * @apiGroup Whitelist
   * @apiPermission teacher
github geli-lms / geli / api / src / controllers / MediaController.ts View on Github external
name: uploadedFile.originalname,
      physicalPath: uploadedFile.path,
      link: uploadedFile.filename,
      size: uploadedFile.size,
      mimeType: uploadedFile.mimetype,
    });
    const savedFile = await new File(file).save();

    const parent = await Directory.findById(parentDirectoryId);
    parent.files.push(savedFile);
    await parent.save();

    return savedFile.toObject();
  }

  @Authorized(['teacher', 'admin'])
  @Put('/directory/:id')
  async updateDirectory(@Param('id') directoryId: string, @Body() updatedDirectory: IDirectory) {
    const directory = await Directory.findById(directoryId);
    directory.set(updatedDirectory);
    const savedDirectory = await directory.save();
    return savedDirectory.toObject();
  }

  @Authorized(['teacher', 'admin'])
  @Put('/file/:id')
  async updateFile(@Param('id') fileId: string, @Body() updatedFile: IFile) {
    const file = await File.findById(fileId);
    file.set(updatedFile);
    const savedFile = await file.save();
    return savedFile.toObject();
  }
github w3tecch / express-typescript-boilerplate / src / api / controllers / UserController.ts View on Github external
import {
    Authorized, Body, Delete, Get, JsonController, OnUndefined, Param, Post, Put, Req
} from 'routing-controllers';

import { UserNotFoundError } from '../errors/UserNotFoundError';
import { User } from '../models/User';
import { UserService } from '../services/UserService';

@Authorized()
@JsonController('/users')
export class UserController {

    constructor(
        private userService: UserService
    ) { }

    @Get()
    public find(): Promise {
        return this.userService.find();
    }

    @Get('/me')
    public findMe(@Req() req: any): Promise {
        return req.user;
    }
github geli-lms / geli / api / src / controllers / ImportController.ts View on Github external
import {Authorized, CurrentUser, JsonController, Param, Post, UploadedFile, UseBefore} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {Course} from '../models/Course';
import {Lecture} from '../models/Lecture';
import {Unit} from '../models/units/Unit';
import {IUser} from '../../../shared/models/IUser';

@JsonController('/import')
@UseBefore(passportJwtMiddleware)
@Authorized(['teacher', 'admin'])
export class ImportController {

  /**
   * @api {post} /api/import/course Import course
   * @apiName PostImportCourse
   * @apiGroup Import
   * @apiPermission teacher
   * @apiPermission admin
   *
   * @apiParam {Object} file Uploaded file.
   * @apiParam {IUser} currentUser Currently logged in user.
   *
   * @apiSuccess {Course} course Imported course.
   *
   * @apiSuccessExample {json} Success-Response:
   *     {