How to use the @loopback/rest.post function in @loopback/rest

To help you get started, we’ve selected a few @loopback/rest 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 strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user-order.controller.ts View on Github external
import {authorize} from '@loopback/authorization';
import {AuthenticationBindings, authenticate} from '@loopback/authentication';
import {compareId} from '../services/id.compare.authorizor';

/**
 * Controller for User's Orders
 */
export class UserOrderController {
  constructor(@repository(UserRepository) protected userRepo: UserRepository) {}

  /**
   * Create or update the orders for a given user
   * @param userId User id
   * @param cart Shopping cart
   */
  @post('/users/{userId}/orders', {
    responses: {
      '200': {
        description: 'User.Order model instance',
        content: {'application/json': {schema: {'x-ts-type': Order}}},
      },
    },
  })
  @authenticate('jwt')
  @authorize({resource: 'order', scopes: ['create']})
  async createOrder(
    @param.path.string('userId') userId: string,
    @requestBody() order: Order,
  ): Promise {
    // validate the payload value
    // has nothing to do with authorization
    if (userId !== order.userId) {
github strongloop / loopback-next / packages / rest-crud / src / crud-rest.controller.ts View on Github external
): CrudRestControllerCtor {
  const modelName = modelCtor.name;
  const idPathParam: ParameterObject = {
    name: 'id',
    in: 'path',
    schema: getIdSchema(modelCtor),
  };

  @api({basePath: options.basePath, paths: {}})
  class CrudRestControllerImpl
    implements CrudRestController {
    constructor(
      public readonly repository: EntityCrudRepository,
    ) {}

    @post('/', {
      ...response.model(200, `${modelName} instance created`, modelCtor),
    })
    async create(
      @body(modelCtor, {
        title: `New${modelName}`,
        exclude: modelCtor.getIdProperties() as (keyof T)[],
      })
      data: Omit,
    ): Promise {
      return this.repository.create(
        // FIXME(bajtos) Improve repository API to support this use case
        // with no explicit type-casts required
        data as DataObject,
      );
    }
github gobackhuoxing / first-web-game-lb4 / firstgame / src / controllers / admin.controller.ts View on Github external
requestBody,
} from '@loopback/rest';
import {inject} from '@loopback/core';
import {Character} from '../models';
import {CharacterRepository} from '../repositories';
import {HttpErrors} from '@loopback/rest';
import {PermissionKey,} from '../authorization';
import {authenticate} from '@loopback/authentication';

export class AdminController {
  constructor(
    @repository(CharacterRepository)
    public characterRepository : CharacterRepository,
  ) {}

  @post('/admin', {
    responses: {
      '200': {
        description: 'create admin',
        content: {'application/json': {schema: {'x-ts-type': Character}}},
      },
    },
  })
  async create(
    @param.query.string('admin_code') admin_code: string,
    @requestBody() character: Character,
  ): Promise {
      if(admin_code != '901029'){
        throw new HttpErrors.Forbidden('WRONG_ADMIN_CODE');
      }

      character.permissions = [PermissionKey.ViewOwnUser,
github iqbaldjulfri / lb4-jwt-role-based-auth-sample / src / controllers / user.controller.ts View on Github external
const {sign} = require('jsonwebtoken');
const signAsync = promisify(sign);

export class UserController {
  constructor(
    @repository(UserRepository) private userRepository: UserRepository,
    @repository(UserRoleRepository) private userRoleRepository: UserRoleRepository,
  ) {}

  @post('/users')
  async createUser(@requestBody() user: User): Promise {
    return await this.userRepository.create(user);
  }

  @post('/users/login')
  async login(@requestBody() credentials: Credentials) {
    if (!credentials.username || !credentials.password) throw new HttpErrors.BadRequest('Missing Username or Password');
    const user = await this.userRepository.findOne({where: {id: credentials.username}});
    if (!user) throw new HttpErrors.Unauthorized('Invalid credentials');

    const isPasswordMatched = user.password === credentials.password;
    if (!isPasswordMatched) throw new HttpErrors.Unauthorized('Invalid credentials');

    const tokenObject = {username: credentials.username};
    const token = await signAsync(tokenObject, JWT_SECRET);
    const roles = await this.userRoleRepository.find({where: {userId: user.id}});
    const {id, email} = user;

    return {
      token,
      id: id as string,
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user.controller.ts View on Github external
}

export class UserController {
  constructor(
    @repository(UserRepository) public userRepository: UserRepository,
    @inject('services.RecommenderService')
    public recommender: RecommenderService,
    @inject(PasswordHasherBindings.PASSWORD_HASHER)
    public passwordHasher: PasswordHasher,
    @inject(TokenServiceBindings.TOKEN_SERVICE)
    public jwtService: TokenService,
    @inject(UserServiceBindings.USER_SERVICE)
    public userService: UserService,
  ) {}

  @post('/users', {
    responses: {
      '200': {
        description: 'User',
        content: {
          'application/json': {
            schema: {
              'x-ts-type': User,
            },
          },
        },
      },
    },
  })
  async create(
    @requestBody({
      content: {
github strongloop / loopback-next / examples / todo / src / controllers / model-admin.controller.ts View on Github external
[tableName: string]: string;
  };

  constructor(data?: Partial) {
    super(data);
    if (!this.endpoints) this.endpoints = {};
  }
}

export class ModelAdminController {
  constructor(
    @inject(CoreBindings.APPLICATION_INSTANCE)
    private app: TodoListApplication,
  ) {}

  @post('/discover', {
    responses: {
      200: {
        description: 'Information about discovered models',
        content: {
          'application/json': {schema: getModelSchemaRef(DiscoverResponse)},
        },
      },
    },
  })
  async discoverAndPublishModels(
    @requestBody() {connectionString, tableNames}: DiscoverRequest,
  ): Promise {
    const result = new DiscoverResponse();

    const ds = await getDataSourceForConnectionString(
      this.app,
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / user.controller.ts View on Github external
items: {
                'x-ts-type': Product,
              },
            },
          },
        },
      },
    },
  })
  async productRecommendations(
    @param.path.string('userId') userId: string,
  ): Promise {
    return this.recommender.getProductRecommendations(userId);
  }

  @post('/users/login', {
    responses: {
      '200': {
        description: 'Token',
        content: {
          'application/json': {
            schema: {
              type: 'object',
              properties: {
                token: {
                  type: 'string',
                },
              },
            },
          },
        },
      },
github sourcefuse / loopback4-starter / src / modules / auth / login.controller.ts View on Github external
}
    try {
      const payload: ClientAuthCode = {
        clientId: this.client.clientId,
        user: this.user,
      };
      return await this.createJWT(payload, this.client);
    } catch (error) {
      throw new HttpErrors.InternalServerError(
        AuthErrorKeys.InvalidCredentials,
      );
    }
  }

  @authorize(['*'])
  @post('/auth/token', {
    responses: {
      [STATUS_CODE.OK]: {
        description: 'Token Response',
        content: {
          [CONTENT_TYPE.JSON]: {
            schema: {'x-ts-type': TokenResponse},
          },
        },
      },
    },
  })
  async getToken(@requestBody() req: AuthTokenRequest): Promise {
    const authClient = await this.authClientRepository.findOne({
      where: {
        clientId: req.clientId,
      },
github iqbaldjulfri / lb4-jwt-role-based-auth-sample / src / controllers / user.controller.ts View on Github external
import {User} from '../models';
import {UserRepository, UserRoleRepository} from '../repositories';
import {repository} from '@loopback/repository';
import {Credentials, JWT_SECRET} from '../auth';
import {promisify} from 'util';

const {sign} = require('jsonwebtoken');
const signAsync = promisify(sign);

export class UserController {
  constructor(
    @repository(UserRepository) private userRepository: UserRepository,
    @repository(UserRoleRepository) private userRoleRepository: UserRoleRepository,
  ) {}

  @post('/users')
  async createUser(@requestBody() user: User): Promise {
    return await this.userRepository.create(user);
  }

  @post('/users/login')
  async login(@requestBody() credentials: Credentials) {
    if (!credentials.username || !credentials.password) throw new HttpErrors.BadRequest('Missing Username or Password');
    const user = await this.userRepository.findOne({where: {id: credentials.username}});
    if (!user) throw new HttpErrors.Unauthorized('Invalid credentials');

    const isPasswordMatched = user.password === credentials.password;
    if (!isPasswordMatched) throw new HttpErrors.Unauthorized('Invalid credentials');

    const tokenObject = {username: credentials.username};
    const token = await signAsync(tokenObject, JWT_SECRET);
    const roles = await this.userRoleRepository.find({where: {userId: user.id}});
github strongloop / loopback4-example-shopping / packages / shopping / src / controllers / shopping-cart.controller.ts View on Github external
'204': {
        description: 'User shopping cart is deleted',
      },
    },
  })
  async remove(@param.path.string('userId') userId: string): Promise {
    debug('Remove shopping cart %s', userId);
    await this.shoppingCartRepository.delete(userId);
  }

  /**
   * Add an item to the shopping cart for a given user
   * @param userId User id
   * @param cart Shopping cart item to be added
   */
  @post('/shoppingCarts/{userId}/items', {
    responses: {
      '200': {
        description: 'User shopping cart item is created',
        content: {
          'application/json': {schema: {'x-ts-type': ShoppingCart}},
        },
      },
    },
  })
  async addItem(
    @param.path.string('userId') userId: string,
    @requestBody({description: 'shopping cart item'}) item: ShoppingCartItem,
  ): Promise {
    debug('Add item %j to shopping cart %s', item, userId);
    return this.shoppingCartRepository.addItem(userId, item);
  }