From 1676ecb8d9d3327793cb8fa2a2a1af3c08f5e219 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Mon, 3 Feb 2020 17:12:16 +0530 Subject: [PATCH 01/22] Added Api for sports for a city --- .rspec | 1 + Gemfile | 9 ++ Gemfile.lock | 39 ++++++++ .../api/v1/city_sports_controller.rb | 37 +++++++ config/routes.rb | 8 +- spec/rails_helper.rb | 63 ++++++++++++ spec/spec_helper.rb | 96 +++++++++++++++++++ test/controllers/.keep | 0 test/fixtures/.keep | 0 test/fixtures/cities.yml | 11 --- test/fixtures/city_sports.yml | 11 --- test/fixtures/files/.keep | 0 test/fixtures/level_city_sports.yml | 11 --- test/fixtures/levels.yml | 11 --- test/fixtures/matches.yml | 11 --- test/fixtures/sports.yml | 11 --- test/fixtures/user_city_sports.yml | 11 --- test/fixtures/users.yml | 11 --- test/integration/.keep | 0 test/mailers/.keep | 0 test/models/.keep | 0 test/models/city_sport_test.rb | 7 -- test/models/city_test.rb | 7 -- test/models/level_city_sport_test.rb | 7 -- test/models/level_test.rb | 7 -- test/models/match_test.rb | 7 -- test/models/sport_test.rb | 7 -- test/models/user_city_sport_test.rb | 7 -- test/models/user_test.rb | 7 -- test/test_helper.rb | 10 -- 30 files changed, 252 insertions(+), 155 deletions(-) create mode 100644 .rspec create mode 100644 app/controllers/api/v1/city_sports_controller.rb create mode 100644 spec/rails_helper.rb create mode 100644 spec/spec_helper.rb delete mode 100644 test/controllers/.keep delete mode 100644 test/fixtures/.keep delete mode 100644 test/fixtures/cities.yml delete mode 100644 test/fixtures/city_sports.yml delete mode 100644 test/fixtures/files/.keep delete mode 100644 test/fixtures/level_city_sports.yml delete mode 100644 test/fixtures/levels.yml delete mode 100644 test/fixtures/matches.yml delete mode 100644 test/fixtures/sports.yml delete mode 100644 test/fixtures/user_city_sports.yml delete mode 100644 test/fixtures/users.yml delete mode 100644 test/integration/.keep delete mode 100644 test/mailers/.keep delete mode 100644 test/models/.keep delete mode 100644 test/models/city_sport_test.rb delete mode 100644 test/models/city_test.rb delete mode 100644 test/models/level_city_sport_test.rb delete mode 100644 test/models/level_test.rb delete mode 100644 test/models/match_test.rb delete mode 100644 test/models/sport_test.rb delete mode 100644 test/models/user_city_sport_test.rb delete mode 100644 test/models/user_test.rb delete mode 100644 test/test_helper.rb diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..c99d2e7 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/Gemfile b/Gemfile index fd5fdc6..09aea61 100644 --- a/Gemfile +++ b/Gemfile @@ -33,6 +33,15 @@ gem 'bootsnap', '>= 1.1.0', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] + gem 'database_cleaner', '~> 1.7' + gem 'factory_bot_rails', '~> 5.1', '>= 5.1.1' + gem 'faker', '~> 2.10', '>= 2.10.1' + gem 'rspec', '~> 3.9' + gem 'rspec-rails', '~> 3.9' + gem 'jwt' + gem 'bcrypt', '~> 3.1.7' + + end group :development do diff --git a/Gemfile.lock b/Gemfile.lock index 69fb2db..a5ee45e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -43,18 +43,29 @@ GEM minitest (~> 5.1) tzinfo (~> 1.1) arel (9.0.0) + bcrypt (3.1.13) bootsnap (1.4.5) msgpack (~> 1.0) builder (3.2.4) byebug (11.1.0) concurrent-ruby (1.1.5) crass (1.0.6) + database_cleaner (1.8.2) + diff-lcs (1.3) erubi (1.9.0) + factory_bot (5.1.1) + activesupport (>= 4.2.0) + factory_bot_rails (5.1.1) + factory_bot (~> 5.1.0) + railties (>= 4.2.0) + faker (2.10.1) + i18n (>= 1.6, < 2) ffi (1.12.1) globalid (0.4.2) activesupport (>= 4.2.0) i18n (1.8.2) concurrent-ruby (~> 1.0) + jwt (2.2.1) listen (3.1.5) rb-fsevent (~> 0.9, >= 0.9.4) rb-inotify (~> 0.9, >= 0.9.7) @@ -109,6 +120,27 @@ GEM rb-inotify (0.10.1) ffi (~> 1.0) rb-readline (0.5.5) + rspec (3.9.0) + rspec-core (~> 3.9.0) + rspec-expectations (~> 3.9.0) + rspec-mocks (~> 3.9.0) + rspec-core (3.9.1) + rspec-support (~> 3.9.1) + rspec-expectations (3.9.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.9.0) + rspec-mocks (3.9.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.9.0) + rspec-rails (3.9.0) + actionpack (>= 3.0) + activesupport (>= 3.0) + railties (>= 3.0) + rspec-core (~> 3.9.0) + rspec-expectations (~> 3.9.0) + rspec-mocks (~> 3.9.0) + rspec-support (~> 3.9.0) + rspec-support (3.9.2) ruby_dep (1.5.0) spring (2.1.0) spring-watcher-listen (2.0.1) @@ -133,13 +165,20 @@ PLATFORMS ruby DEPENDENCIES + bcrypt (~> 3.1.7) bootsnap (>= 1.1.0) byebug + database_cleaner (~> 1.7) + factory_bot_rails (~> 5.1, >= 5.1.1) + faker (~> 2.10, >= 2.10.1) + jwt listen (>= 3.0.5, < 3.2) pg (~> 1.2, >= 1.2.2) puma (~> 3.11) rails (~> 5.2.4, >= 5.2.4.1) rb-readline + rspec (~> 3.9) + rspec-rails (~> 3.9) spring spring-watcher-listen (~> 2.0.0) tzinfo-data diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb new file mode 100644 index 0000000..f341750 --- /dev/null +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -0,0 +1,37 @@ +module Api + module V1 + class CitySportsController < ApplicationController + def index + #@user_id = params['user_id'] + @user = User.where(id: 1) + @city_id = @user.first.city_id + @sport_list = [] + @city_sports = CitySport.where(city_id: @city_id) + @city_sports.find_each do |citysport| + @sport_list = @sport_list + Sport.where(id: citysport.sport_id) + end + render json: @sport_list.as_json + end + + + def displaysports + @user_id = params['user_id'] + @user = User.where(id: 1) + @city_id = @user.first.city_id + @sport_list = [] + @city_sports = CitySport.where(city_id: @city_id) + @city_sports.find_each do |citysport| + @sport_list = @sport_list + Sport.where(id: citysport.sport_id) + end + render json: @sport_list.as_json + + end + + def permit_params + params.permit(:user).permit(:user_id) + end + + + end + end +end diff --git a/config/routes.rb b/config/routes.rb index 787824f..3d85332 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,3 +1,9 @@ Rails.application.routes.draw do - # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html + namespace :api do + namespace :v1 do + resources :city_sports + post '/city_sports/display', to: 'city_sports#displaysports' + + end + end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000..b06351b --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,63 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' + +require File.expand_path('../config/environment', __dir__) + +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +# Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f } + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + puts e.to_s.strip + exit 1 +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_path = "#{::Rails.root}/spec/fixtures" + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, :type => :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://relishapp.com/rspec/rspec-rails/docs + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..ce33d66 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,96 @@ +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = "doc" + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/test/controllers/.keep b/test/controllers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/fixtures/.keep b/test/fixtures/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/fixtures/cities.yml b/test/fixtures/cities.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/cities.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/city_sports.yml b/test/fixtures/city_sports.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/city_sports.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/fixtures/level_city_sports.yml b/test/fixtures/level_city_sports.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/level_city_sports.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/levels.yml b/test/fixtures/levels.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/levels.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/matches.yml b/test/fixtures/matches.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/matches.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/sports.yml b/test/fixtures/sports.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/sports.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/user_city_sports.yml b/test/fixtures/user_city_sports.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/user_city_sports.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml deleted file mode 100644 index 80aed36..0000000 --- a/test/fixtures/users.yml +++ /dev/null @@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value diff --git a/test/integration/.keep b/test/integration/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/mailers/.keep b/test/mailers/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/models/.keep b/test/models/.keep deleted file mode 100644 index e69de29..0000000 diff --git a/test/models/city_sport_test.rb b/test/models/city_sport_test.rb deleted file mode 100644 index d11219f..0000000 --- a/test/models/city_sport_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class CitySportTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/city_test.rb b/test/models/city_test.rb deleted file mode 100644 index 660f995..0000000 --- a/test/models/city_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class CityTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/level_city_sport_test.rb b/test/models/level_city_sport_test.rb deleted file mode 100644 index ba82a39..0000000 --- a/test/models/level_city_sport_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class LevelCitySportTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/level_test.rb b/test/models/level_test.rb deleted file mode 100644 index 17d745d..0000000 --- a/test/models/level_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class LevelTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/match_test.rb b/test/models/match_test.rb deleted file mode 100644 index 14436b1..0000000 --- a/test/models/match_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class MatchTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/sport_test.rb b/test/models/sport_test.rb deleted file mode 100644 index 8eb1819..0000000 --- a/test/models/sport_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class SportTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/user_city_sport_test.rb b/test/models/user_city_sport_test.rb deleted file mode 100644 index 5fb9edf..0000000 --- a/test/models/user_city_sport_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class UserCitySportTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/models/user_test.rb b/test/models/user_test.rb deleted file mode 100644 index 82f61e0..0000000 --- a/test/models/user_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class UserTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/test/test_helper.rb b/test/test_helper.rb deleted file mode 100644 index 3ab84e3..0000000 --- a/test/test_helper.rb +++ /dev/null @@ -1,10 +0,0 @@ -ENV['RAILS_ENV'] ||= 'test' -require_relative '../config/environment' -require 'rails/test_help' - -class ActiveSupport::TestCase - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - fixtures :all - - # Add more helper methods to be used by all tests here... -end From 3c3ffae794322ea92a39b20853b6e02a93cbe6a8 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Mon, 3 Feb 2020 21:14:50 +0530 Subject: [PATCH 02/22] Added sports list for city --- app/controllers/api/v1/city_sports_controller.rb | 16 +++++++++------- config/application.rb | 1 + lib/json_web_token.rb | 13 +++++++++++++ 3 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 lib/json_web_token.rb diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb index f341750..47748c3 100644 --- a/app/controllers/api/v1/city_sports_controller.rb +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -1,3 +1,7 @@ +#require 'lib/json_web_token.rb' +#SECRET_KEY = Rails.application.secrets.secret_key_base. to_s +require 'jwt' +$hmac_secret = "your-256-bit-secret" module Api module V1 class CitySportsController < ApplicationController @@ -13,10 +17,11 @@ def index render json: @sport_list.as_json end - - def displaysports - @user_id = params['user_id'] - @user = User.where(id: 1) + def displaysports + @token_array = JWT.decode(params['token'],$hmac_secret,true,{algorithm: 'HS256'}) + @token = @token_array[0] + @user_id = @token["user_id"] + @user = User.where(id: @user_id) @city_id = @user.first.city_id @sport_list = [] @city_sports = CitySport.where(city_id: @city_id) @@ -24,14 +29,11 @@ def displaysports @sport_list = @sport_list + Sport.where(id: citysport.sport_id) end render json: @sport_list.as_json - end def permit_params params.permit(:user).permit(:user_id) end - - end end end diff --git a/config/application.rb b/config/application.rb index eb79c93..4765d00 100644 --- a/config/application.rb +++ b/config/application.rb @@ -31,5 +31,6 @@ class Application < Rails::Application # Middleware like session, flash, cookies can be added back manually. # Skip views, helpers and assets when generating a new resource. config.api_only = true + config.autoload_paths << Rails.root.join('lib') end end diff --git a/lib/json_web_token.rb b/lib/json_web_token.rb new file mode 100644 index 0000000..0c0b43a --- /dev/null +++ b/lib/json_web_token.rb @@ -0,0 +1,13 @@ +class JsonWebToken + SECRET_KEY = Rails.application.secrets.secret_key_base. to_s + + def self.encode(payload, exp = 24.hours.from_now) + payload[:exp] = exp.to_i + JWT.encode(payload, SECRET_KEY) + end + + def self.decode(token) + decoded = JWT.decode(token, SECRET_KEY)[0] + HashWithIndifferentAccess.new decoded + end +end \ No newline at end of file From c266abd1dc19ab51d5883192982faf0bce02bfae Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Tue, 4 Feb 2020 10:09:10 +0530 Subject: [PATCH 03/22] removed index method --- .../api/v1/city_sports_controller.rb | 52 +++++++------------ 1 file changed, 20 insertions(+), 32 deletions(-) diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb index 47748c3..76a97b7 100644 --- a/app/controllers/api/v1/city_sports_controller.rb +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -3,37 +3,25 @@ require 'jwt' $hmac_secret = "your-256-bit-secret" module Api - module V1 - class CitySportsController < ApplicationController - def index - #@user_id = params['user_id'] - @user = User.where(id: 1) - @city_id = @user.first.city_id - @sport_list = [] - @city_sports = CitySport.where(city_id: @city_id) - @city_sports.find_each do |citysport| - @sport_list = @sport_list + Sport.where(id: citysport.sport_id) - end - render json: @sport_list.as_json - end + module V1 + class CitySportsController < ApplicationController + def displaysports + @token_array = JWT.decode(params['token'],$hmac_secret,true,{algorithm: 'HS256'}) + @token = @token_array[0] + @user_id = @token["user_id"] + @user = User.where(id: @user_id) + @city_id = @user.first.city_id + @sport_list = [] + @city_sports = CitySport.where(city_id: @city_id) + @city_sports.find_each do |citysport| + @sport_list = @sport_list + Sport.where(id: citysport.sport_id) + end + render json: @sport_list.as_json + end - def displaysports - @token_array = JWT.decode(params['token'],$hmac_secret,true,{algorithm: 'HS256'}) - @token = @token_array[0] - @user_id = @token["user_id"] - @user = User.where(id: @user_id) - @city_id = @user.first.city_id - @sport_list = [] - @city_sports = CitySport.where(city_id: @city_id) - @city_sports.find_each do |citysport| - @sport_list = @sport_list + Sport.where(id: citysport.sport_id) - end - render json: @sport_list.as_json - end - - def permit_params - params.permit(:user).permit(:user_id) - end - end - end + def permit_params + params.permit(:user).permit(:user_id) + end + end + end end From 58566995229a750aacad46c36bfc7d9528429d85 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Tue, 4 Feb 2020 17:27:07 +0530 Subject: [PATCH 04/22] added test cases --- config/database.yml | 1 + spec/factories.rb | 10 +++++++++ spec/rails_helper.rb | 25 ++++++++++++++++++++++- spec/requests/post_display_sports_spec.rb | 16 +++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 spec/factories.rb create mode 100644 spec/requests/post_display_sports_spec.rb diff --git a/config/database.yml b/config/database.yml index baf7ab9..bfbb101 100644 --- a/config/database.yml +++ b/config/database.yml @@ -58,6 +58,7 @@ development: test: <<: *default database: level_me_up_test + password: "1234" # As with config/secrets.yml, you never want to store sensitive information, # like your database password, in your source code. If your source code is diff --git a/spec/factories.rb b/spec/factories.rb new file mode 100644 index 0000000..a58a975 --- /dev/null +++ b/spec/factories.rb @@ -0,0 +1,10 @@ +require 'faker' +Faker::Config.random = Random.new(42) + +FactoryBot.define do + factory :new_user do + name { Faker::Name.name } + contact_number { Faker::Number.number(digits: 4)} + role { Faker::Boolean.boolean } + end +end \ No newline at end of file diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index b06351b..0cd09bb 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -39,7 +39,30 @@ # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. - config.use_transactional_fixtures = true + config.use_transactional_fixtures = false + + config.before(:suite) do + DatabaseCleaner.clean_with(:truncation) + end + + config.before(:each) do + DatabaseCleaner.strategy = :transaction + end + config.before(:each, :js => true) do + DatabaseCleaner.strategy = :truncation + end + config.before(:each) do + DatabaseCleaner.start + end + config.after(:each) do + DatabaseCleaner.clean + end + config.before(:all) do + DatabaseCleaner.start + end + config.after(:all) do + DatabaseCleaner.clean + end # RSpec Rails can automatically mix in different behaviours to your tests # based on their file location, for example enabling you to call `get` and diff --git a/spec/requests/post_display_sports_spec.rb b/spec/requests/post_display_sports_spec.rb new file mode 100644 index 0000000..3e9c4b8 --- /dev/null +++ b/spec/requests/post_display_sports_spec.rb @@ -0,0 +1,16 @@ +require 'rails_helper' + +describe "post a question route", :type => :request do + + before do + User.create(first_name: "mayur",last_name: "deshmukh",contact_number: 152,role: true,email: "mayur.deshmukh@joshware.com",city_id: 1) + Sport.create(name: "Badminton") + City.create(name: "Pune") + CitySport.create(city_id: 1, sport_id: 1, number_of_boxes: 5,number_of_players: 10) + + post '/api/v1/city_sports/display', params: {:token => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSJ9.O5Y5s_hvEW8BM7E8jq6HihxQ0DDFxO_2_xtnrvVj4PY"} + end + it 'returns a ok status' do + expect(response).to have_http_status(:ok) + end +end \ No newline at end of file From 75ad997d6c6f29775ab4d2fbde42851951b040ea Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 5 Feb 2020 10:32:47 +0530 Subject: [PATCH 05/22] added factory bot --- spec/factories.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spec/factories.rb b/spec/factories.rb index a58a975..fc15095 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -2,9 +2,10 @@ Faker::Config.random = Random.new(42) FactoryBot.define do - factory :new_user do + factory :user do name { Faker::Name.name } contact_number { Faker::Number.number(digits: 4)} role { Faker::Boolean.boolean } + city_id { Faker::Number.between(from: 1, to:2)} end end \ No newline at end of file From fc152d81bf0d4831eca616d804c3949569f188ab Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 5 Feb 2020 15:00:58 +0530 Subject: [PATCH 06/22] add .env file --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index 749cd73..02c4f2c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,8 @@ .byebug_history +.env + # Ignore master key for decrypting credentials and more. /config/master.key # /config/database.yml From 724ecb5f2bf827191ed011b25b99166cacab4180 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 5 Feb 2020 15:01:51 +0530 Subject: [PATCH 07/22] add dotenv-rails gem --- Gemfile | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index 09aea61..8aa071e 100644 --- a/Gemfile +++ b/Gemfile @@ -33,13 +33,15 @@ gem 'bootsnap', '>= 1.1.0', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] + gem 'jwt' + gem 'bcrypt', '~> 3.1.7' gem 'database_cleaner', '~> 1.7' gem 'factory_bot_rails', '~> 5.1', '>= 5.1.1' gem 'faker', '~> 2.10', '>= 2.10.1' gem 'rspec', '~> 3.9' gem 'rspec-rails', '~> 3.9' - gem 'jwt' - gem 'bcrypt', '~> 3.1.7' + gem 'dotenv-rails' + end From bf166f361493acef84901a9fe34fb916712f91a6 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 5 Feb 2020 15:03:19 +0530 Subject: [PATCH 08/22] added dotenv-rails gem --- Gemfile.lock | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Gemfile.lock b/Gemfile.lock index a5ee45e..1cd5e2e 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -52,6 +52,10 @@ GEM crass (1.0.6) database_cleaner (1.8.2) diff-lcs (1.3) + dotenv (2.7.5) + dotenv-rails (2.7.5) + dotenv (= 2.7.5) + railties (>= 3.2, < 6.1) erubi (1.9.0) factory_bot (5.1.1) activesupport (>= 4.2.0) @@ -169,6 +173,7 @@ DEPENDENCIES bootsnap (>= 1.1.0) byebug database_cleaner (~> 1.7) + dotenv-rails factory_bot_rails (~> 5.1, >= 5.1.1) faker (~> 2.10, >= 2.10.1) jwt From 58686cc0700dde535591c9e92711bbd8c890517d Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 5 Feb 2020 15:04:27 +0530 Subject: [PATCH 09/22] removed hardcoded jwt secret key --- app/controllers/api/v1/city_sports_controller.rb | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb index 76a97b7..2bf6d8b 100644 --- a/app/controllers/api/v1/city_sports_controller.rb +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -1,13 +1,8 @@ -#require 'lib/json_web_token.rb' -#SECRET_KEY = Rails.application.secrets.secret_key_base. to_s -require 'jwt' -$hmac_secret = "your-256-bit-secret" module Api module V1 - class CitySportsController < ApplicationController + class Api::V1::CitySportsController < ApplicationController def displaysports - @token_array = JWT.decode(params['token'],$hmac_secret,true,{algorithm: 'HS256'}) - @token = @token_array[0] + @token = JsonWebToken.decode(params['token']) @user_id = @token["user_id"] @user = User.where(id: @user_id) @city_id = @user.first.city_id @@ -18,10 +13,6 @@ def displaysports end render json: @sport_list.as_json end - - def permit_params - params.permit(:user).permit(:user_id) - end end end end From 42ffe0b2aaf6a8a8cb768718ef4db4774463024c Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 5 Feb 2020 15:04:52 +0530 Subject: [PATCH 10/22] added jwt class --- lib/json_web_token.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/json_web_token.rb b/lib/json_web_token.rb index 0c0b43a..8fd6212 100644 --- a/lib/json_web_token.rb +++ b/lib/json_web_token.rb @@ -1,5 +1,5 @@ class JsonWebToken - SECRET_KEY = Rails.application.secrets.secret_key_base. to_s + SECRET_KEY = ENV["JWT_SECRET"] def self.encode(payload, exp = 24.hours.from_now) payload[:exp] = exp.to_i From 51f45e9b0b9654837c6b57be7930bfafa8037bf3 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 6 Feb 2020 12:35:35 +0530 Subject: [PATCH 11/22] Used factory bot for new user --- spec/requests/post_display_sports_spec.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/requests/post_display_sports_spec.rb b/spec/requests/post_display_sports_spec.rb index 3e9c4b8..9c0cc39 100644 --- a/spec/requests/post_display_sports_spec.rb +++ b/spec/requests/post_display_sports_spec.rb @@ -1,9 +1,9 @@ require 'rails_helper' -describe "post a question route", :type => :request do +describe "post a token and display sports", :type => :request do before do - User.create(first_name: "mayur",last_name: "deshmukh",contact_number: 152,role: true,email: "mayur.deshmukh@joshware.com",city_id: 1) + FactoryBot.create(:user) Sport.create(name: "Badminton") City.create(name: "Pune") CitySport.create(city_id: 1, sport_id: 1, number_of_boxes: 5,number_of_players: 10) From 952ab0ef35c0967806f41dd8bae51f8abf36bec1 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 6 Feb 2020 12:36:06 +0530 Subject: [PATCH 12/22] changed name to first and last name --- spec/factories.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spec/factories.rb b/spec/factories.rb index fc15095..4cc500e 100644 --- a/spec/factories.rb +++ b/spec/factories.rb @@ -3,9 +3,10 @@ FactoryBot.define do factory :user do - name { Faker::Name.name } + first_name { Faker::Name.first_name } + last_name { Faker::Name.last_name } contact_number { Faker::Number.number(digits: 4)} role { Faker::Boolean.boolean } - city_id { Faker::Number.between(from: 1, to:2)} + city_id { Faker::Number.between(from: 1, to:1)} end end \ No newline at end of file From ef2372b43b68d0d8fbc1a4b16fbaec00726895e5 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Fri, 7 Feb 2020 17:09:09 +0530 Subject: [PATCH 13/22] removed token validation --- .../api/v1/city_sports_controller.rb | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb index 2bf6d8b..61c813c 100644 --- a/app/controllers/api/v1/city_sports_controller.rb +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -1,17 +1,15 @@ module Api module V1 - class Api::V1::CitySportsController < ApplicationController - def displaysports - @token = JsonWebToken.decode(params['token']) - @user_id = @token["user_id"] - @user = User.where(id: @user_id) - @city_id = @user.first.city_id - @sport_list = [] - @city_sports = CitySport.where(city_id: @city_id) - @city_sports.find_each do |citysport| - @sport_list = @sport_list + Sport.where(id: citysport.sport_id) + class CitySportsController < ApplicationController + + def displaysports + city_id = @current_user.city_id + sport_list = [] + city_sports = CitySport.where(city_id: city_id) + city_sports.find_each do |citysport| + sport_list = sport_list + Sport.where(id: citysport.sport_id) end - render json: @sport_list.as_json + render json: sport_list.as_json end end end From 846abdb1947a6f7e5f6d475cf049d33012d921ff Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Fri, 7 Feb 2020 17:13:19 +0530 Subject: [PATCH 14/22] added validation token method for before action --- app/controllers/application_controller.rb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 4ac8823..d170b0c 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,2 +1,22 @@ class ApplicationController < ActionController::API + before_action :validate_token + + + def validate_token + begin + user_auth_token = request.headers["user-auth-token"] + @current_user = current_user(user_auth_token) + rescue JWT::DecodeError => e + render json: {error: "Unauthorized"}, status: :unauthorized + rescue ActiveRecord::RecordNotFound => e + render json: {error: "Unauthorized"}, status: :unauthorized + end + end + + def current_user(user_auth_token) + token = JsonWebToken.decode(user_auth_token) + user_id = token["user_id"] + user = User.find(user_id) + return user + end end From dfb363c85debe75c0171dbf74681c6d4145a4e4c Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Fri, 7 Feb 2020 17:13:57 +0530 Subject: [PATCH 15/22] changed post to get --- config/routes.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/config/routes.rb b/config/routes.rb index 3d85332..814ac2a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,8 +1,9 @@ Rails.application.routes.draw do namespace :api do namespace :v1 do + + get '/city_sports/display', to: 'city_sports#displaysports' resources :city_sports - post '/city_sports/display', to: 'city_sports#displaysports' end end From d638a79721ac270d05f047d0acb35f8ae3dd171c Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Sun, 9 Feb 2020 12:10:57 +0530 Subject: [PATCH 16/22] added test cases for token validation --- spec/requests/post_display_sports_spec.rb | 32 ++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/spec/requests/post_display_sports_spec.rb b/spec/requests/post_display_sports_spec.rb index 9c0cc39..ff93892 100644 --- a/spec/requests/post_display_sports_spec.rb +++ b/spec/requests/post_display_sports_spec.rb @@ -1,6 +1,6 @@ require 'rails_helper' -describe "post a token and display sports", :type => :request do +describe "should display sports", :type => :request do before do FactoryBot.create(:user) @@ -8,9 +8,35 @@ City.create(name: "Pune") CitySport.create(city_id: 1, sport_id: 1, number_of_boxes: 5,number_of_players: 10) - post '/api/v1/city_sports/display', params: {:token => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSJ9.O5Y5s_hvEW8BM7E8jq6HihxQ0DDFxO_2_xtnrvVj4PY"} + get '/api/v1/city_sports/display', headers: {"user-auth-token" => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSJ9.O5Y5s_hvEW8BM7E8jq6HihxQ0DDFxO_2_xtnrvVj4PY"} end it 'returns a ok status' do expect(response).to have_http_status(:ok) end -end \ No newline at end of file +end + +describe "should return unauthorized due to user not present", :type => :request do + + before do + FactoryBot.create(:user) + get '/api/v1/city_sports/display', headers: {"user-auth-token" => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiOCJ9.9V492uKokeLSu9F62ck-CX2XvrquAsTNc9_agkPcYzk"} + end + + it 'return a unauthorized status' do + expect(response).to have_http_status(:unauthorized) + end +end + +describe "should return unauthorized due to invalid jwt token", :type => :request do + + before do + FactoryBot.create(:user) + get '/api/v1/city_sports/display', headers: {"user-auth-token" => "eyJhbGciOiJIUzI1NiIsInR5cuKokeLSu9F62ck-CX2XvrquAsTNc9_agkPcYzk"} + end + + it 'return a unauthorized status' do + expect(response).to have_http_status(:unauthorized) + end +end + + \ No newline at end of file From 635f821201cc0869f5890b9af1a6388515f178c1 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Wed, 12 Feb 2020 14:11:04 +0530 Subject: [PATCH 17/22] Handled query exceptions --- app/controllers/api/v1/city_sports_controller.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb index cc8ec8f..4241c3a 100644 --- a/app/controllers/api/v1/city_sports_controller.rb +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -7,6 +7,9 @@ def displaysports city_id = @current_user.city_id sport_list = [] city_sports = CitySport.where(city_id: city_id) + if city_sports.nil? + render json: {"message" => "Id not found"}, status: 422 + end city_sports.find_each do |citysport| sport_list += Sport.where(id: citysport.sport_id) end From 744a5faff691f976ad549161680f3847943c50c9 Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 13 Feb 2020 14:08:57 +0530 Subject: [PATCH 18/22] Handled query exceptions --- app/controllers/api/v1/city_sports_controller.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/app/controllers/api/v1/city_sports_controller.rb b/app/controllers/api/v1/city_sports_controller.rb index 4241c3a..cf88953 100644 --- a/app/controllers/api/v1/city_sports_controller.rb +++ b/app/controllers/api/v1/city_sports_controller.rb @@ -7,12 +7,11 @@ def displaysports city_id = @current_user.city_id sport_list = [] city_sports = CitySport.where(city_id: city_id) - if city_sports.nil? - render json: {"message" => "Id not found"}, status: 422 - end + render json: {"error": I18n.t(city_sports.id_not_found)}, status: 422 if city_sports.nil? city_sports.find_each do |citysport| sport_list += Sport.where(id: citysport.sport_id) end + render json: {"error": I18n.t(city_sports.sport_list_empty)}, status: 422 if sport_list.empty? render json: sport_list.as_json end end From 7402ad6e39ef8f132638e961a02c09bf986cb4ac Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 13 Feb 2020 14:09:50 +0530 Subject: [PATCH 19/22] Handled jwt exceptions --- app/controllers/application_controller.rb | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 911edf6..dc72d4c 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -6,16 +6,18 @@ class ApplicationController < ActionController::API def validate_token user_auth_token = request.headers["user-auth-token"] @current_user = current_user(user_auth_token) - rescue JWT::DecodeError => e - render json: {error: e.message}, status: :unauthorized - rescue ActiveRecord::RecordNotFound => e - render json: {error: e.message}, status: :unauthorized end def current_user(user_auth_token) - token = JsonWebToken.decode(user_auth_token) - user_id = token["user_id"] - user = User.find(user_id) + begin + token = JsonWebToken.decode(user_auth_token) + user_id = token["user_id"] + user = User.find(user_id) + rescue JWT::DecodeError => e + render json: {error: e.message}, status: :unauthorized + rescue ActiveRecord::RecordNotFound => e + render json: {error: e.message}, status: :unauthorized + end user end end From d49091e1f2570ac86fdd3bf93f81fbefc6bfb4ed Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 13 Feb 2020 14:10:15 +0530 Subject: [PATCH 20/22] Added error messages --- config/locales/en.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/config/locales/en.yml b/config/locales/en.yml index decc5a8..2d40abb 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -31,3 +31,6 @@ en: hello: "Hello world" + city_sports: + sport_list_empty: "Cannot fetch Sports" + id_not_found: "Id not found" From e343ed938ef0cdb3f56b64c11f192212c208c65c Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 13 Feb 2020 14:11:31 +0530 Subject: [PATCH 21/22] Handled jwt exceptions --- lib/json_web_token.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/json_web_token.rb b/lib/json_web_token.rb index 6fd852b..81438eb 100644 --- a/lib/json_web_token.rb +++ b/lib/json_web_token.rb @@ -5,11 +5,19 @@ class JsonWebToken def self.encode(payload, exp=24.hours.from_now) payload[:exp] = exp.to_i - JWT.encode(payload, SECRET_KEY) + begin + JWT.encode(payload, SECRET_KEY) + rescue JWT::EncodeError + nil + end end def self.decode(token) - decoded = JWT.decode(token, SECRET_KEY)[0] + begin + decoded = JWT.decode(token, SECRET_KEY)[0] + rescue JWT::DecodeError + nil + end HashWithIndifferentAccess.new decoded end end From 69cee4225ec62d17a812c2d86c07f4ebd624083f Mon Sep 17 00:00:00 2001 From: Mayur Deshmukh Date: Thu, 13 Feb 2020 14:12:19 +0530 Subject: [PATCH 22/22] Added context for test cases --- spec/requests/post_display_sports_spec.rb | 57 +++++++++-------------- 1 file changed, 22 insertions(+), 35 deletions(-) diff --git a/spec/requests/post_display_sports_spec.rb b/spec/requests/post_display_sports_spec.rb index 57f7ae8..9eb7d59 100644 --- a/spec/requests/post_display_sports_spec.rb +++ b/spec/requests/post_display_sports_spec.rb @@ -2,43 +2,30 @@ require "rails_helper" -describe "should display sports", type: :request do - before do - @sport = Sport.create(name: "Badminton") - @city = City.create(name: "Pune") - @user = FactoryBot.create(:user, city_id: @city.id) - @cs = CitySport.create(city_id: @city.id, sport_id: @sport.id, number_of_boxes: 5, number_of_players: 10) - @token1 = JsonWebToken.encode(user_id: @user.id) - @token2 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiOCJ9.9V492uKokeLSu9F62ck-CX2XvrquAsTNc9_agkPcYzk" - @token3 = "eyJhbGciOiJIUzI1NiIsInR5cuKokeLSu9F62ck-CX2XvrquAsTNc9_agkPcYzk" - get "/api/v1/city_sports/display", - headers: {"user-auth-token" => @token1} - end - it "returns a ok status" do - expect(response).to have_http_status(:ok) - end -end - -describe "should return unauthorized due to user not present", type: :request do - before do - FactoryBot.create(:user) - get "/api/v1/city_sports/display", - headers: {"user-auth-token" => @token2} +describe "should display all available sports for particular city", type: :request do + context "should return all available sport" do + it "returns a ok status" do + @sport = Sport.create(name: "Badminton") + @city = City.create(name: "Pune") + @user = FactoryBot.create(:user, city_id: @city.id) + @cs = CitySport.create(city_id: @city.id, sport_id: @sport.id, number_of_boxes: 5, number_of_players: 10) + @token1 = JsonWebToken.encode(user_id: @user.id) + get "/api/v1/city_sports/display", headers: {"user-auth-token" => @token1} + expect(response).to have_http_status(:ok) + end end - it "return a unauthorized status" do - expect(response).to have_http_status(:unauthorized) - end -end - -describe "should return unauthorized due to invalid jwt token", type: :request do - before do - FactoryBot.create(:user) - get "/api/v1/city_sports/display", - headers: {"user-auth-token" => @token3} - end + context "should return error", type: :request do + it "returns a unauthorized status due user not present" do + @token2 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiOCJ9.9V492uKokeLSu9F62ck-CX2XvrquAsTNc9_agkPcYzk" + get "/api/v1/city_sports/display", headers: {"user-auth-token" => @token2} + expect(response).to have_http_status(:unauthorized) + end - it "return a unauthorized status" do - expect(response).to have_http_status(:unauthorized) + it "returns a unauthorized status due to jwt invalidation" do + @token3 = "eyJhbGciOiJIUzI1NiIsInR5cuKokeLSu9F62ck-CX2XvrquAsTNc9_agkPcYzk" + get "/api/v1/city_sports/display", headers: {"user-auth-token" => @token3} + expect(response).to have_http_status(:unauthorized) + end end end