Beispiel #1
0
        app[config.method.toLowerCase()](config.path, async function (req: RouterRequest, res: RouterResponse, next: NextFunction) {
            // Shim the request and response objects with expected properties.
            req.domainWithProtocol = `${req.protocol}://${req.hostname}` + (req.hostname === "localhost" ? ":3000" : "");
            req.app = Object.assign({registeredRoutes}, req.app);

            if (config.bodyValidation) {
                const validation = validate(req.body, config.bodyValidation);

                if (validation.error) {
                    const error = badData(validation.error.message, validation.error.details);

                    return next(error);
                }

                req.validatedBody = validation.value;
            }

            if (config.queryValidation) {
                const validation = validate(req.query, config.queryValidation);

                if (validation.error) {
                    const error = badData(validation.error.message, validation.error.details);

                    return next(error);
                }

                req.validatedQuery = validation.value;
            }

            if (config.paramValidation) {
                const validation = validate(req.params, config.paramValidation);

                if (validation.error) {
                    const error = badData(validation.error.message, validation.error.details);

                    return next(error);
                }

                req.validatedParams = validation.value;
            }

            // Pass control to the route's handler. Handlers can be async, so wrap them in try/catch to handle promise rejections.
            try {
                const handler = config.handler(req, res, next);

                if (handler instanceof Promise) {
                    await handler;
                }

                return;
            } catch (e) {
                return next(e);
            }
        });
Beispiel #2
0
 public validate(): boolean {
   var res = Joi.validate(this.config, schema);
   if (res.error) {
     throw res.error;
   }
   return true;
 }
export function createUser(req: Request, res: Response, next: NextFunction) {
  const schema = Joi.object().keys({
    name: Joi.string().min(3).required(),
    email: Joi.string().email().required(),
    password: Joi.string().required().regex(passwordRegex),
    agreeTos: Joi.boolean().only(true).required(),
    referral: Joi.string().email().options({
      language: {
        key: '{{!label}}',
        string: {
          email: 'Not valid referral code'
        }
      }
    }).label(' ') // Joi does not allow empty label but space is working
  });

  if (req.body.referral) {
    req.body.referral = base64decode(req.body.referral);
  }

  const result = Joi.validate(req.body, schema, options);

  if (result.error) {
    return res.status(422).json(result);
  } else {
    return next();
  }
}
Beispiel #4
0
            it('required only', () => {
                let obj = {
                    hello: 'world'
                };

                expect(Joi.validate(obj, this.schema).error).toBeNull();
            });
export function joiValidate(value: any, validator: SchemaLike): ValidationError | null {

    let validationResult = validate(value, validator, {
        abortEarly: false,
        allowUnknown: false
    });

    if (validationResult.error) {

        let duplicates: any = {};
        validationResult.error.details = validationResult.error.details.filter((detail) => {
            if (duplicates[detail.message] || detail.type === "object.allowUnknown")
                return false;
            else {
                duplicates[detail.message] = true;
                return true;
            }
        });

        if (validationResult.error.details.length === 0)
            return null;
        else
            return validationResult.error;
    }
    else
        return null;

}
Beispiel #6
0
export async function setup(server: Server, request: Request, reply: IReply)
{
    let payload = request.payload as {shopUrl: string};
    const props: SetupProps = {
        title: "Connect your Shopify store.",
        shopUrl: payload.shopUrl,
    };
    const validation = joi.validate(payload, setupValidation);
    
    if (validation.error)
    {
        props.error = humanizeError(validation.error);
        
        return reply.view("setup/setup.js", props);
    }
    
    payload = validation.value;
    
    if (! (await isValidShopifyDomain(payload.shopUrl)))
    {
        props.error = "It looks like the URL you entered is not a valid Shopify domain.";
        
        return reply.view("setup/setup.js", props);
    }
    
    const scopes: Enums.AuthScope[] = ["write_script_tags"]
    const redirect = `${getRequestProtocol(request)}://${getDomain(true)}${ConnectRoutes.GetShopify}`.toLowerCase();
    const oauthUrl = await buildAuthorizationUrl(scopes, payload.shopUrl, ShopifyApiKey, redirect);

    return reply.redirect(oauthUrl);
}
Beispiel #7
0
export function validateDevice(state: State, device: Device): Device {
  if (device.interfaceIds) {
    validateInterfaces(state, device.interfaceIds)
  }
  const deviceClass = state.deviceClasses[device.deviceClassId]
  if (!deviceClass) {
    throw raxaError({
      type: 'missingDeviceClass',
      deviceClassId: device.deviceClassId,
    })
  }
  if (!deviceClass.config) {
    if (device.config) throw new Error('no config allowed')
    return device
  }
  const joiSchema = joi.object({
    id: joi.string().allow(''),
    name: joi.string().required(),
    pluginId: joi.string().required(),
    deviceClassId: joi.string().required(),
    config: propertiesToJoi(deviceClass.config),
    interfaceIds: joi.array().items(joi.string().required()),
  })
  const result = joi.validate(device, joiSchema)
  if (result.error) {
    throw raxaError({type: 'invalidDevice', joiError: result.error})
  }

  return result.value
}
Beispiel #8
0
 set: (v) => {
   const vr = joi.validate(v, rule)
   if (vr.error) {
     throw vr.error
   }
   descriptor.set(v);
 },
  private validateInput(envConfig: EnvConfig): EnvConfig {
    const envVarsSchema: Joi.ObjectSchema = Joi.object({
      NODE_ENV: Joi.string()
        .valid(['development', 'production', 'test', 'provision'])
        .default('development'),
      PORT: Joi.number().default(3000),
      JWT_SECRET: Joi.string().required(),
      JWT_EXPIRE: Joi.number().default(3600 * 24 * 7),
      DB_TYPE: Joi.string().default('mysql'),
      DB_HOST: Joi.string().default('localhost'),
      DB_PORT: Joi.number().default(3306),
      DB_USERNAME: Joi.string().required(),
      DB_PASSWORD: Joi.string().required(),
      DB_DATABASE_NAME: Joi.string().required(),
    });

    const { error, value: validatedEnvConfig } = Joi.validate(
      envConfig,
      envVarsSchema,
    );
    if (error) {
      throw new Error(`Config validation error: ${error.message}`);
    }
    return validatedEnvConfig;
  }
Beispiel #10
0
            it('required and invalid optional', () => {
                let obj = {
                    hello: 'world',
                    world: 1
                };

                expect(Joi.validate(obj, this.schema).error).not.toBeNull();
            });