api_validator 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0e001388521bb57ebafb2c6fd2f6d0d130af547b
4
+ data.tar.gz: 38696b838c273fc595523cd55ac31d7aec3e4029
5
+ SHA512:
6
+ metadata.gz: 59ecdf26a07d570f15006def55a5e4357406ee9e24125f3bce24bbd4979f45000a9e4bb041f304b186abca434391ed44cd53cf6f44a5894ffac29e66da7f4b6d
7
+ data.tar.gz: 5b604d93767fc676ab63b52055af1d48fe73b3f8aeb478de5a7535ebb1d7aae6d5b0eac81e2430c7bdb99379609d6443096e43c36a4ac2571377ee6e1d42b171
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
@@ -0,0 +1,49 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at sandipkaranjekar@gmail.com. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
+ [version]: http://contributor-covenant.org/version/1/3/0/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in api_validator.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 Sandip Karanjekar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,79 @@
1
+ # api_validator
2
+ This gem helpful to validate api calls. You need to set rules and messages in yml file and rest of the things are handle by gem.
3
+
4
+ ## Installation
5
+
6
+ Add this line to your application's Gemfile:
7
+
8
+ ```ruby
9
+ gem 'api_validator'
10
+ ```
11
+
12
+ And then execute:
13
+
14
+ $ bundle
15
+
16
+ Or install it yourself as:
17
+
18
+ $ gem install api_validator
19
+
20
+ Also you need to run generator to set the files -
21
+
22
+ $ rails g api_validator:install api_validator
23
+
24
+ Note : Here you can pass any name you want to set for initilizer file and validation yml file, instead of 'api_validator'.
25
+
26
+ ## Usage
27
+
28
+ Before use of this gem you need to set ```ruby before_filter :request_validation ``` in controller where you want to validate request before reach to controller's method.
29
+
30
+ Also you need to set rules in the api_validator.yml.erb file. Example are mentioned in yml file.
31
+
32
+ Sample pattern for validation as follows -
33
+
34
+ ```yaml
35
+ controller_name:
36
+ method_name:
37
+ param1:
38
+ rules:
39
+ presence: true
40
+ integer: true
41
+ min_length: 5
42
+ max_length: 15
43
+ pattern: <%= /\A^[a-zA-Z\s'.-]*$\Z/.source %>
44
+ messages:
45
+ presence: "Param1 must present."
46
+ integer: "Param1 must contain integer only."
47
+ min_length: "Param1 must have minimum length of 5."
48
+ max_length: "Param1 must have maximum length of 15."
49
+ pattern: "Invalid Param1"
50
+ ```
51
+
52
+ Sample validation for JSON value in request parameter -
53
+
54
+ ```yaml
55
+ controller_name:
56
+ method_name:
57
+ param1:
58
+ rules:
59
+ presence: true
60
+ json_string: true
61
+ messages:
62
+ presence: "Param1 must present."
63
+ json_string: "Invalid json string."
64
+ paramters:
65
+ json_1st_param:
66
+ rules:
67
+ presence: true
68
+ messages:
69
+ presence: "Json first param must prresent."
70
+ json_2nd_param:
71
+ rules:
72
+ integer: true
73
+ messages:
74
+ integer: "Json second param must be integer only."
75
+ ```
76
+ ## License
77
+
78
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
79
+
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'api_validator/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "api_validator"
8
+ spec.version = ApiValidator::VERSION
9
+ spec.authors = ["sandipkaranjekar"]
10
+ spec.email = ["sandipkaranjekar@gmail.com"]
11
+
12
+ spec.summary = %q{RubyGem for API validation}
13
+ spec.description = %q{RubyGem for API validation. Here you need to set rules and messages in yml, rest of the things are handle by gem.}
14
+ spec.homepage = "https://github.com/sandipkaranjekar/api_validator"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.12"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "api_validator"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,104 @@
1
+ require "api_validator/version"
2
+
3
+ module ApiValidator
4
+ INTEGER_REGEX = /^[1-9]([0-9]*)?$/
5
+ # request validation method
6
+ # Input - request params
7
+ # Process - Validate params with there rules & definition
8
+ # Output - report error on invalidity
9
+ def request_validation
10
+ if is_api_validator_applicable?(params[:controller], params[:action])
11
+ # validation - parameters defination
12
+ validation_pd = VALIDATION_CONFIG[params[:controller]][params[:action]]
13
+
14
+ validation_pd.keys.each do |key|
15
+ next if params.has_key?(key) == false && validation_pd[key]["rules"].has_key?("presence") == false
16
+ validation_pd[key]["rules"].each do |rule, definition|
17
+ # when param's value is JSON string then parse it and validate parameters
18
+ if (rule == "json_string" and definition == true)
19
+ begin
20
+ json_data = JSON.parse(params[key])
21
+ json_data = [json_data] unless json_data.class == Array
22
+ json_data.each do |data|
23
+ data.keys.each do |json_data_key|
24
+ if validation_pd[key].has_key?("parameters")
25
+ next unless validation_pd[key]["parameters"].has_key?(json_data_key)
26
+ validation_pd[key]["parameters"][json_data_key]["rules"].each do |json_data_rule, json_data_definition|
27
+ #CAUTION: if nested JSON, this should be recursive
28
+ return error_response(validation_pd[key]["parameters"][json_data_key]["messages"][json_data_rule]) if validate?(json_data_key, data[json_data_key], json_data_rule, json_data_definition, validation_pd[key]["parameters"][json_data_key])
29
+ end
30
+ end
31
+ end
32
+ end
33
+ rescue JSON::ParserError => e
34
+ return error_response(validation_pd[key]["messages"][rule], 422)
35
+ end
36
+ # when param's value is NOT JSON
37
+ else
38
+ return error_response(validation_pd[key]["messages"][rule]) if validate?(key, params[key], rule, definition, validation_pd[key])
39
+ end
40
+ end # param rule loop end
41
+ end # params list loop end
42
+ end # main if end
43
+ end
44
+
45
+ def is_api_validator_applicable?(controller, action)
46
+ VALIDATION_CONFIG[controller].present? && VALIDATION_CONFIG[controller][action].present?
47
+ end
48
+
49
+ def error_response(message = nil, status = 400)
50
+ response = {status: 'error', message: message}
51
+ render json: response, status: status
52
+ end
53
+
54
+ def is_integer?(value)
55
+ !!(value =~ INTEGER_REGEX)
56
+ end
57
+
58
+ def is_pattern_match?(value, pattern)
59
+ !!(value =~ pattern)
60
+ end
61
+
62
+ def validate_array_string?(value, separator)
63
+ parameter_ids = value.split(separator)
64
+ parameter_ids.each do |parameter|
65
+ return false unless !!(parameter =~ INTEGER_REGEX)
66
+ end
67
+ return true
68
+ end
69
+
70
+ def validate?(key, value, rule, definition, dtd)
71
+ is_error_found = false
72
+ case
73
+ when (rule == "ignore_if_present" and definition.present?)
74
+ # return error if not present & defination absence
75
+ is_error_found = true if value.present? == false and params[definition].present? == false
76
+ when (rule == "presence" and definition == true)
77
+ # return error if not present
78
+ is_error_found = true unless value.present?
79
+ when (rule == "array_string" and definition.present?)
80
+ # return error if array string invalid
81
+ is_error_found = true unless validate_array_string?(value, definition)
82
+ when (rule == "integer" and definition == true)
83
+ # return error if not match with integer
84
+ is_error_found = true unless is_integer?(value)
85
+ when (rule == "min_length" and definition > 0)
86
+ # return error if minimum length is not achived
87
+ is_error_found = true unless value.length >= definition
88
+ when (rule == "max_length" and definition > 0)
89
+ # return error if maximum length is not achived
90
+ is_error_found = true unless value.length <= definition
91
+ when (rule == "max_value" and definition > 0)
92
+ # return error if param's value is less or equal to definition
93
+ is_error_found = true unless value.to_f <= definition
94
+ when (rule == "pattern" and definition.present?)
95
+ # return error if pattern doesn't match
96
+ if dtd["rules"].has_key?("presence") == true || value.present?
97
+ is_error_found = true unless is_pattern_match?(value, Regexp.new(definition))
98
+ end
99
+ end
100
+ return is_error_found
101
+ end
102
+ end
103
+ # Require our engine
104
+ require "api_validator/engine"
@@ -0,0 +1,4 @@
1
+ module ApiValidator
2
+ class Engine < Rails::Engine
3
+ end
4
+ end
@@ -0,0 +1,3 @@
1
+ module ApiValidator
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,29 @@
1
+ require 'rails/generators'
2
+
3
+ module ApiValidator
4
+ module Generators
5
+ class InstallGenerator < Rails::Generators::NamedBase
6
+ def self.source_root
7
+ source_root ||= File.join(File.dirname(__FILE__), 'templates/')
8
+ end
9
+
10
+ def copy_initializer_file
11
+ create_file "config/initializers/#{file_name}.rb", <<-FILE
12
+ validation_template = ERB.new(File.new(File.expand_path('../../#{file_name}.yml.erb', __FILE__)).read)
13
+ VALIDATION_CONFIG = HashWithIndifferentAccess.new(YAML.load(validation_template.result(binding)))
14
+ FILE
15
+ end
16
+
17
+ def copy_validate_api_yml_file
18
+ copy_file "validate_api.yml.erb", "config/#{file_name}.yml.erb"
19
+ end
20
+
21
+ def add_module
22
+ line = "class ApplicationController < ActionController::Base"
23
+ gsub_file 'app/controllers/application_controller.rb', /(#{Regexp.escape(line)})/mi do |match|
24
+ "#{match}\n include ApiValidator\n"
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,40 @@
1
+ # This yml used to specify your rules ans messages of parameters
2
+ # You need to follow following pattern to make it applicable
3
+ # controller_name:
4
+ # method_name:
5
+ # param1:
6
+ # rules:
7
+ # presence: true
8
+ # integer: true
9
+ # min_length: 5
10
+ # max_length: 15
11
+ # pattern: <%#= "/\A^[a-zA-Z\s'.-]*$\Z/".source %>
12
+ # messages:
13
+ # presence: "Param1 must present."
14
+ # integer: "Param1 must contain integer only."
15
+ # min_length: "Param1 must have minimum length of 5."
16
+ # max_length: "Param1 must have maximum length of 15."
17
+ # pattern: "Invalid Param1"
18
+ #
19
+ # Also if have some paramters which accepts json as value and that json have some
20
+ # which need to be validate you need to follow following pattern to make it applicable
21
+ # controller_name:
22
+ # method_name:
23
+ # param1:
24
+ # rules:
25
+ # presence: true
26
+ # json_string: true
27
+ # messages:
28
+ # presence: "Param1 must present."
29
+ # json_string: "Invalid json string."
30
+ # paramters:
31
+ # json_1st_param:
32
+ # rules:
33
+ # presence: true
34
+ # messages:
35
+ # presence: "Json first param must prresent."
36
+ # json_2nd_param:
37
+ # rules:
38
+ # integer: true
39
+ # messages:
40
+ # integer: "Json second param must be integer only."
metadata ADDED
@@ -0,0 +1,87 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: api_validator
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - sandipkaranjekar
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-12-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ~>
18
+ - !ruby/object:Gem::Version
19
+ version: '1.12'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.12'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ~>
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ~>
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ description: RubyGem for API validation. Here you need to set rules and messages in
42
+ yml, rest of the things are handle by gem.
43
+ email:
44
+ - sandipkaranjekar@gmail.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - .gitignore
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - LICENSE.txt
53
+ - README.md
54
+ - Rakefile
55
+ - api_validator.gemspec
56
+ - bin/console
57
+ - bin/setup
58
+ - lib/api_validator.rb
59
+ - lib/api_validator/engine.rb
60
+ - lib/api_validator/version.rb
61
+ - lib/generators/api_validator/install/install_generator.rb
62
+ - lib/generators/api_validator/install/templates/validate_api.yml.erb
63
+ homepage: https://github.com/sandipkaranjekar/api_validator
64
+ licenses:
65
+ - MIT
66
+ metadata: {}
67
+ post_install_message:
68
+ rdoc_options: []
69
+ require_paths:
70
+ - lib
71
+ required_ruby_version: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - '>='
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - '>='
79
+ - !ruby/object:Gem::Version
80
+ version: '0'
81
+ requirements: []
82
+ rubyforge_project:
83
+ rubygems_version: 2.4.8
84
+ signing_key:
85
+ specification_version: 4
86
+ summary: RubyGem for API validation
87
+ test_files: []