From 319066aa59f58ea790a97fa598dbf966a8e7aa5d Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Tue, 7 Jun 2016 12:33:39 -0300 Subject: [PATCH 01/36] Change rubocop configuration --- .rubocop.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.rubocop.yml b/.rubocop.yml index 8217dd58..c260368c 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,6 +1,7 @@ inherit_from: .rubocop_todo.yml +Rails: + Enabled: true AllCops: - RunRailsCops: true Exclude: - bin/**/* - vendor/**/* From 4b288eaf69a2853ca22fa9fec47b64d8975c3bf1 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Tue, 7 Jun 2016 12:34:28 -0300 Subject: [PATCH 02/36] Fix Rubocop issues --- Rakefile | 2 +- examples/ruby-api/Gemfile | 2 +- examples/ruby-api/config.ru | 2 +- examples/ruby-api/main.rb | 28 ++++++--------- examples/ruby-on-rails-api/Gemfile | 12 +++---- .../app/controllers/application_controller.rb | 1 + .../app/controllers/ping_controller.rb | 3 +- .../controllers/secured_ping_controller.rb | 10 +++--- .../app/helpers/application_helper.rb | 1 + examples/ruby-on-rails-api/bin/setup | 16 ++++----- examples/ruby-on-rails-api/config.ru | 2 +- .../ruby-on-rails-api/config/application.rb | 1 - .../config/environments/test.rb | 2 +- .../config/initializers/cookies_serializer.rb | 2 +- .../config/initializers/knock.rb | 10 ++---- examples/ruby-on-rails-api/config/routes.rb | 1 - examples/ruby-on-rails-api/db/schema.rb | 1 - .../test/ping_controller_test.rb | 4 +-- .../test/secured_ping_controller_test.rb | 3 +- .../ruby-on-rails-api/test/test_helper.rb | 19 +++++----- lib/auth0/api/authentication_endpoints.rb | 35 +++++++++---------- lib/auth0/api/v1/clients.rb | 2 +- lib/auth0/api/v1/connections.rb | 4 +-- lib/auth0/api/v1/logs.rb | 2 +- lib/auth0/api/v1/rules.rb | 2 +- lib/auth0/api/v1/users.rb | 8 ++--- lib/auth0/api/v2/clients.rb | 2 +- lib/auth0/api/v2/connections.rb | 2 +- lib/auth0/api/v2/rules.rb | 4 +-- lib/auth0/api/v2/users.rb | 2 +- lib/auth0/mixins/httparty_proxy.rb | 15 ++++---- lib/auth0/mixins/initializer.rb | 4 +-- lib/auth0/version.rb | 2 +- .../lib/auth0/api/v2/api_email_spec.rb | 2 +- .../lib/auth0/api/v2/api_jobs_spec.rb | 6 ++-- .../api/authentication_endpoints_spec.rb | 32 ++++++++--------- spec/lib/auth0/mixins/httparty_proxy_spec.rb | 13 ++++--- spec/spec_helper_full.rb | 4 +-- spec/spec_helper_unit.rb | 4 +-- 39 files changed, 123 insertions(+), 144 deletions(-) diff --git a/Rakefile b/Rakefile index e56a9c9f..cd01add8 100644 --- a/Rakefile +++ b/Rakefile @@ -10,7 +10,7 @@ begin RuboCop::RakeTask.new(:rubocop) require 'yard' - DOC_FILES = ['lib/auth0/api/v2/*.rb', 'lib/auth0/api/authentication_endpoints.rb'] + DOC_FILES = ['lib/auth0/api/v2/*.rb', 'lib/auth0/api/authentication_endpoints.rb'].freeze desc 'Build Documentation' YARD::Rake::YardocTask.new(:documentation) do |t| diff --git a/examples/ruby-api/Gemfile b/examples/ruby-api/Gemfile index beb2aa14..a98b10f6 100644 --- a/examples/ruby-api/Gemfile +++ b/examples/ruby-api/Gemfile @@ -5,4 +5,4 @@ source 'http://rubygems.org' # gem "rails" gem 'sinatra', '~> 1.4' gem 'jwt', '~> 1.5' -gem 'dotenv' \ No newline at end of file +gem 'dotenv' diff --git a/examples/ruby-api/config.ru b/examples/ruby-api/config.ru index b2d135cc..14b2ecfc 100644 --- a/examples/ruby-api/config.ru +++ b/examples/ruby-api/config.ru @@ -1,2 +1,2 @@ require './main' -run Sinatra::Application \ No newline at end of file +run Sinatra::Application diff --git a/examples/ruby-api/main.rb b/examples/ruby-api/main.rb index 2e7caa9d..2d83e680 100644 --- a/examples/ruby-api/main.rb +++ b/examples/ruby-api/main.rb @@ -4,26 +4,20 @@ Dotenv.load '.env' set :show_exceptions, false - -class InvalidTokenError < StandardError; +class InvalidTokenError < StandardError end def validate_token(env) - auth0_client_id = ENV['AUTH0_CLIENT_ID'] - auth0_client_secret = ENV['AUTH0_CLIENT_SECRET'] - authorization = env['HTTP_AUTHORIZATION'] - - raise InvalidTokenError if authorization.nil? - - token = authorization.split(' ').last - decoded_token = JWT.decode(token, - JWT.base64url_decode(auth0_client_secret)) - - raise InvalidTokenError if auth0_client_id != decoded_token[0]['aud'] - 'You get this only if authenticated' - rescue JWT::DecodeError - raise InvalidTokenError - end + auth0_client_id = ENV['AUTH0_CLIENT_ID'] + auth0_client_secret = ENV['AUTH0_CLIENT_SECRET'] + authorization = env['HTTP_AUTHORIZATION'] + fail InvalidTokenError if authorization.nil? + decoded_token = JWT.decode(authorization.split(' ').last, JWT.base64url_decode(auth0_client_secret)) + fail InvalidTokenError if auth0_client_id != decoded_token[0]['aud'] + 'You get this only if authenticated' +rescue JWT::DecodeError + raise InvalidTokenError +end error InvalidTokenError do 'Invalid token' diff --git a/examples/ruby-on-rails-api/Gemfile b/examples/ruby-on-rails-api/Gemfile index 8e96f051..ee80f780 100644 --- a/examples/ruby-on-rails-api/Gemfile +++ b/examples/ruby-on-rails-api/Gemfile @@ -1,10 +1,9 @@ source 'https://rubygems.org' - # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.5.1' # Use sqlite3 as the database for Active Record -gem 'sqlite3', :groups => [:development, :test] +gem 'sqlite3', groups: [:development, :test] gem 'pg' # Use SCSS for stylesheets @@ -23,16 +22,15 @@ gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.4.1' # bundle exec rake doc:rails generates the API under doc/api. -gem 'sdoc', '~> 0.4.1', group: :doc +gem 'sdoc', '~> 0.4.1', group: :doc # knock dependency gem 'knock', '~> 1.4.2' -#Dot env -gem 'dotenv-rails', :groups => [:development, :test] - +# Dot env +gem 'dotenv-rails', groups: [:development, :test] # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring -gem 'spring', group: :development +gem 'spring', group: :development gem 'pry', group: [:development, :test] diff --git a/examples/ruby-on-rails-api/app/controllers/application_controller.rb b/examples/ruby-on-rails-api/app/controllers/application_controller.rb index 9fcc7f0b..a0a35dcb 100644 --- a/examples/ruby-on-rails-api/app/controllers/application_controller.rb +++ b/examples/ruby-on-rails-api/app/controllers/application_controller.rb @@ -1,3 +1,4 @@ +# Application Controller class ApplicationController < ActionController::Base include Knock::Authenticable diff --git a/examples/ruby-on-rails-api/app/controllers/ping_controller.rb b/examples/ruby-on-rails-api/app/controllers/ping_controller.rb index 1b8ac574..674a3e27 100644 --- a/examples/ruby-on-rails-api/app/controllers/ping_controller.rb +++ b/examples/ruby-on-rails-api/app/controllers/ping_controller.rb @@ -1,7 +1,6 @@ +# Ping Controller class PingController < ApplicationController - def ping render text: "All good. You don't need to be authenticated to call this" end - end diff --git a/examples/ruby-on-rails-api/app/controllers/secured_ping_controller.rb b/examples/ruby-on-rails-api/app/controllers/secured_ping_controller.rb index d490540f..d9c2ce95 100644 --- a/examples/ruby-on-rails-api/app/controllers/secured_ping_controller.rb +++ b/examples/ruby-on-rails-api/app/controllers/secured_ping_controller.rb @@ -1,11 +1,11 @@ +# Secured ping Controller class SecuredPingController < ApplicationController before_action :authenticate def ping - render :json => { - :message => "All good. You only get this message if you're authenticated.", - :user => @current_user - } + render json: { + message: "All good. You only get this message if you're authenticated.", + user: @current_user + } end - end diff --git a/examples/ruby-on-rails-api/app/helpers/application_helper.rb b/examples/ruby-on-rails-api/app/helpers/application_helper.rb index de6be794..0b719f88 100644 --- a/examples/ruby-on-rails-api/app/helpers/application_helper.rb +++ b/examples/ruby-on-rails-api/app/helpers/application_helper.rb @@ -1,2 +1,3 @@ +# Application Helper module ApplicationHelper end diff --git a/examples/ruby-on-rails-api/bin/setup b/examples/ruby-on-rails-api/bin/setup index 2d041ee3..4a80f24c 100644 --- a/examples/ruby-on-rails-api/bin/setup +++ b/examples/ruby-on-rails-api/bin/setup @@ -2,15 +2,15 @@ require 'pathname' # path to your application root. -APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) +APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) Dir.chdir APP_ROOT do # This script is a starting point to setup your application. # Add necessary setup steps to this file: - puts "== Installing dependencies ==" - system "gem install bundler --conservative" - system "bundle check || bundle install" + puts '== Installing dependencies ==' + system 'gem install bundler --conservative' + system 'bundle check || bundle install' # puts "\n== Copying sample files ==" # unless File.exist?("config/database.yml") @@ -18,12 +18,12 @@ Dir.chdir APP_ROOT do # end puts "\n== Preparing database ==" - system "bin/rake db:setup" + system 'bin/rake db:setup' puts "\n== Removing old logs and tempfiles ==" - system "rm -f log/*" - system "rm -rf tmp/cache" + system 'rm -f log/*' + system 'rm -rf tmp/cache' puts "\n== Restarting application server ==" - system "touch tmp/restart.txt" + system 'touch tmp/restart.txt' end diff --git a/examples/ruby-on-rails-api/config.ru b/examples/ruby-on-rails-api/config.ru index 5bc2a619..bd83b254 100644 --- a/examples/ruby-on-rails-api/config.ru +++ b/examples/ruby-on-rails-api/config.ru @@ -1,4 +1,4 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) run Rails.application diff --git a/examples/ruby-on-rails-api/config/application.rb b/examples/ruby-on-rails-api/config/application.rb index 7eeb46af..8acbf600 100644 --- a/examples/ruby-on-rails-api/config/application.rb +++ b/examples/ruby-on-rails-api/config/application.rb @@ -8,7 +8,6 @@ module Auth0RorapiSample class Application < Rails::Application - # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. diff --git a/examples/ruby-on-rails-api/config/environments/test.rb b/examples/ruby-on-rails-api/config/environments/test.rb index aa862c1a..2121620d 100644 --- a/examples/ruby-on-rails-api/config/environments/test.rb +++ b/examples/ruby-on-rails-api/config/environments/test.rb @@ -13,7 +13,7 @@ config.eager_load = false # Configure static asset server for tests with Cache-Control for performance. - config.serve_static_files = true + config.serve_static_files = true config.static_cache_control = 'public, max-age=3600' # Show full error reports and disable caching. diff --git a/examples/ruby-on-rails-api/config/initializers/cookies_serializer.rb b/examples/ruby-on-rails-api/config/initializers/cookies_serializer.rb index 7a06a89f..7f70458d 100644 --- a/examples/ruby-on-rails-api/config/initializers/cookies_serializer.rb +++ b/examples/ruby-on-rails-api/config/initializers/cookies_serializer.rb @@ -1,3 +1,3 @@ # Be sure to restart your server when you modify this file. -Rails.application.config.action_dispatch.cookies_serializer = :json \ No newline at end of file +Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/examples/ruby-on-rails-api/config/initializers/knock.rb b/examples/ruby-on-rails-api/config/initializers/knock.rb index 54a7d53f..b84c792c 100644 --- a/examples/ruby-on-rails-api/config/initializers/knock.rb +++ b/examples/ruby-on-rails-api/config/initializers/knock.rb @@ -1,6 +1,5 @@ require 'base64' Knock.setup do |config| - ## Current user retrieval when validating token ## -------------------------------------------- ## @@ -14,7 +13,7 @@ # !!! # This is only to make the example test cases pass, you should use a real # user model in your app instead. - config.current_user_from_token = -> (claims) {{ id: claims['sub'] }} + config.current_user_from_token = -> (claims) { { id: claims['sub'] } } ## Expiration claim ## ---------------- @@ -24,7 +23,6 @@ ## Default: # config.token_lifetime = 1.day - ## Audience claim ## -------------- ## @@ -37,7 +35,6 @@ ## If using Auth0, uncomment the line below config.token_audience = -> { Rails.application.secrets.auth0_client_id } - ## Signature key ## ------------- ## @@ -47,11 +44,10 @@ # config.token_secret_signature_key = -> { Rails.application.secrets.secret_key_base } ## If using Auth0, uncomment the line below - #config.token_secret_signature_key = -> { JWT.base64url_decode Rails.application.secrets.auth0_client_secret } - config.token_secret_signature_key = -> { + # config.token_secret_signature_key = -> { JWT.base64url_decode Rails.application.secrets.auth0_client_secret } + config.token_secret_signature_key = lambda { secret = Rails.application.secrets.auth0_client_secret secret += '=' * (4 - secret.length.modulo(4)) Base64.decode64(secret.tr('-_', '+/')) } - end diff --git a/examples/ruby-on-rails-api/config/routes.rb b/examples/ruby-on-rails-api/config/routes.rb index 52e722b1..c7ac15d9 100644 --- a/examples/ruby-on-rails-api/config/routes.rb +++ b/examples/ruby-on-rails-api/config/routes.rb @@ -1,5 +1,4 @@ Rails.application.routes.draw do - get 'ping' => 'ping#ping' get 'secured/ping' => 'secured_ping#ping' # The priority is based upon order of creation: first created -> highest priority. diff --git a/examples/ruby-on-rails-api/db/schema.rb b/examples/ruby-on-rails-api/db/schema.rb index 4dfbb168..28ac66fd 100644 --- a/examples/ruby-on-rails-api/db/schema.rb +++ b/examples/ruby-on-rails-api/db/schema.rb @@ -12,5 +12,4 @@ # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 0) do - end diff --git a/examples/ruby-on-rails-api/test/ping_controller_test.rb b/examples/ruby-on-rails-api/test/ping_controller_test.rb index e0aa1725..e30b8c8e 100644 --- a/examples/ruby-on-rails-api/test/ping_controller_test.rb +++ b/examples/ruby-on-rails-api/test/ping_controller_test.rb @@ -1,10 +1,8 @@ require 'test_helper' - +# Ping Controller Tests class PingControllerTest < ActionController::TestCase - test 'responds with success' do get :ping assert_response :success end - end diff --git a/examples/ruby-on-rails-api/test/secured_ping_controller_test.rb b/examples/ruby-on-rails-api/test/secured_ping_controller_test.rb index 0c47d14d..dd818e12 100644 --- a/examples/ruby-on-rails-api/test/secured_ping_controller_test.rb +++ b/examples/ruby-on-rails-api/test/secured_ping_controller_test.rb @@ -1,7 +1,6 @@ require 'test_helper' - +# Secure Ping Controller Test class SecuredPingControllerTest < ActionController::TestCase - def with_a_valid_token @user = { id: 1 } @token = Knock::AuthToken.new(payload: { sub: @user[:id] }).token diff --git a/examples/ruby-on-rails-api/test/test_helper.rb b/examples/ruby-on-rails-api/test/test_helper.rb index bf95f818..a8302219 100644 --- a/examples/ruby-on-rails-api/test/test_helper.rb +++ b/examples/ruby-on-rails-api/test/test_helper.rb @@ -1,13 +1,16 @@ ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' +# Active Support +class ActiveSupport + # Test Case + class TestCase + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + # + # Note: You'll currently still have to declare fixtures explicitly in integration tests + # -- they do not yet inherit this setting + fixtures :all -class ActiveSupport::TestCase - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - # - # Note: You'll currently still have to declare fixtures explicitly in integration tests - # -- they do not yet inherit this setting - fixtures :all - - # Add more helper methods to be used by all tests here... + # Add more helper methods to be used by all tests here... + end end diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index f2852e9b..5607ebfd 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -4,8 +4,8 @@ module Api # {https://auth0.com/docs/auth-api} # Methods to use the authentication endpoints module AuthenticationEndpoints - UP_AUTH = 'Username-Password-Authentication' - JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer' + UP_AUTH = 'Username-Password-Authentication'.freeze + JWT_BEARER = 'urn:ietf:params:oauth:grant-type:jwt-bearer'.freeze # Retrives an access token # @see https://auth0.com/docs/auth-api#!#post--oauth-access_token @@ -203,27 +203,14 @@ def delegation(id_token, target, scope = 'openid', api_type = 'app', extra_param # Retrives an impersonation URL to login as another user # @see https://auth0.com/docs/auth-api#!#post--users--user_id--impersonate # @param user_id [string] Impersonate user id - # @param app_client_id [string] Application client id - # @param impersonator_id [string] Impersonator user id id. # @param options [string] Additional Parameters # @return [string] Impersonation URL - def impersonate(user_id, app_client_id, impersonator_id, options) + def impersonate(user_id, options) fail Auth0::InvalidParameter, 'Must supply a valid user_id' if user_id.to_s.empty? fail Auth0::MissingParameter, 'Must supply client_secret' if @client_secret.nil? - set_authorization_header obtain_access_token - request_params = { - protocol: options.fetch(:protocol, 'oauth2'), - impersonator_id: impersonator_id, - client_id: app_client_id, - additionalParameters: { - response_type: options.fetch(:response_type, 'code'), - state: options.fetch(:state, ''), - scope: options.fetch(:scope, 'openid'), - callback_url: options.fetch(:callback_url, '') - } - } - result = post("/users/#{user_id}/impersonate", request_params) - set_authorization_header @token + authorization_header obtain_access_token + result = post("/users/#{user_id}/impersonate", impersonate_request_params(options)) + authorization_header @token result end @@ -306,6 +293,16 @@ def wsfed_url(connection = UP_AUTH) def to_query(hash) hash.map { |k, v| "#{k}=#{URI.escape(v)}" unless v.nil? }.reject(&:nil?).join('&') end + + def impersonate_request_params + { + client_id: @client_id, + response_type: options.fetch(:connection, 'code'), + connection: options.fetch(:connection, nil), + redirect_url: redirect_uri, + state: options.fetch(:state, nil) + }.merge(options.fetch(:additional_parameters, {})) + end end end end diff --git a/lib/auth0/api/v1/clients.rb b/lib/auth0/api/v1/clients.rb index 2eb4a8f4..01457bf4 100644 --- a/lib/auth0/api/v1/clients.rb +++ b/lib/auth0/api/v1/clients.rb @@ -9,7 +9,7 @@ def clients get(path) end - alias_method :get_clients, :clients + alias get_clients clients # {https://auth0.com/docs/api#!#post--api-clients} def create_client(name, callbacks = '') diff --git a/lib/auth0/api/v1/connections.rb b/lib/auth0/api/v1/connections.rb index 6cc82c62..a5af4818 100644 --- a/lib/auth0/api/v1/connections.rb +++ b/lib/auth0/api/v1/connections.rb @@ -7,14 +7,14 @@ module Connections def connections get('/api/connections') end - alias_method :get_connections, :connections + alias get_connections connections # {https://auth0.com/docs/api#!#get--api-connections--connection-name-} def connection(connection_name) path = "/api/connections/#{connection_name}" get(path) end - alias_method :get_connection, :connection + alias get_connection connection # {https://auth0.com/docs/api#!#delete--api-connections--connection-name-} def delete_connection(connection_name) diff --git a/lib/auth0/api/v1/logs.rb b/lib/auth0/api/v1/logs.rb index 67d372a8..d933d244 100644 --- a/lib/auth0/api/v1/logs.rb +++ b/lib/auth0/api/v1/logs.rb @@ -15,7 +15,7 @@ def logs(options = {}) get(path) end - alias_method :search_logs, :logs + alias search_logs logs # {https://auth0.com/docs/api#!#get--api-logs--_id-} def log(id) diff --git a/lib/auth0/api/v1/rules.rb b/lib/auth0/api/v1/rules.rb index 7600c4b5..ba404124 100644 --- a/lib/auth0/api/v1/rules.rb +++ b/lib/auth0/api/v1/rules.rb @@ -9,7 +9,7 @@ def rules get(path) end - alias_method :get_rules, :rules + alias get_rules rules # https://auth0.com/docs/api#!#post--api-rules def create_rule(name, script, order = nil, status = true) diff --git a/lib/auth0/api/v1/users.rb b/lib/auth0/api/v1/users.rb index a8355600..71a76e5a 100644 --- a/lib/auth0/api/v1/users.rb +++ b/lib/auth0/api/v1/users.rb @@ -13,8 +13,8 @@ def users(search = nil) get(path) end - alias_method :users_search, :users - alias_method :get_users, :users + alias users_search users + alias get_users users # {https://auth0.com/docs/api#!#get--api-users--user_id-} def user(user_id) @@ -22,7 +22,7 @@ def user(user_id) get(path) end - alias_method :get_user, :user + alias get_user user # {https://auth0.com/docs/api#!#get--api-users--user_id--devices} def user_devices(user_id) @@ -38,7 +38,7 @@ def connection_users(connection_name, search = nil) get(path) end - alias_method :search_connection_users, :connection_users + alias search_connection_users connection_users # {https://auth0.com/docs/api#!#get--api-enterpriseconnections-users-search--criteria-} def enterpriseconnections_users(search_criteria = nil, per_page = 500) diff --git a/lib/auth0/api/v2/clients.rb b/lib/auth0/api/v2/clients.rb index e2a54b68..cb71d386 100644 --- a/lib/auth0/api/v2/clients.rb +++ b/lib/auth0/api/v2/clients.rb @@ -19,7 +19,7 @@ def clients(fields: nil, include_fields: nil) } get(clients_path, request_params) end - alias_method :get_clients, :clients + alias get_clients clients # Creates a new client application. # @see https://auth0.com/docs/api/v2#!/clients/post_clients diff --git a/lib/auth0/api/v2/connections.rb b/lib/auth0/api/v2/connections.rb index ebd4000c..0081739b 100644 --- a/lib/auth0/api/v2/connections.rb +++ b/lib/auth0/api/v2/connections.rb @@ -21,7 +21,7 @@ def connections(strategy: nil, fields: nil, include_fields: true) } get(connections_path, request_params) end - alias_method :get_connections, :connections + alias get_connections connections # Creates a new connection according to the JSON object received in body. # @see https://auth0.com/docs/api/v2#!/Connections/post_connections diff --git a/lib/auth0/api/v2/rules.rb b/lib/auth0/api/v2/rules.rb index 4f9d377e..87e7984c 100644 --- a/lib/auth0/api/v2/rules.rb +++ b/lib/auth0/api/v2/rules.rb @@ -26,7 +26,7 @@ def rules(enabled: nil, fields: nil, include_fields: nil, stage: nil) get(rules_path, request_params) end - alias_method :get_rules, :rules + alias get_rules rules # Retrieves a rule by its ID. Accepts a list of fields to include or exclude in the result. # @see https://auth0.com/docs/api/v2#!/Rules/get_rules_by_id @@ -45,7 +45,7 @@ def rule(rule_id, fields: nil, include_fields: nil) get(path, request_params) end - alias_method :get_rule, :rule + alias get_rule rule # Creates a new rule according to the JSON object received in body. # @see https://auth0.com/docs/api/v2#!/Rules/post_rules diff --git a/lib/auth0/api/v2/users.rb b/lib/auth0/api/v2/users.rb index a894966f..98fb8d03 100644 --- a/lib/auth0/api/v2/users.rb +++ b/lib/auth0/api/v2/users.rb @@ -32,7 +32,7 @@ def users(options = {}) request_params[:search_engine] = :v2 if request_params[:q] get(users_path, request_params) end - alias_method :get_users, :users + alias get_users users # Creates a new user according to optional parameters received. # The attribute connection is always mandatory but depending on the type of connection you are using there diff --git a/lib/auth0/mixins/httparty_proxy.rb b/lib/auth0/mixins/httparty_proxy.rb index f847c939..8353702d 100644 --- a/lib/auth0/mixins/httparty_proxy.rb +++ b/lib/auth0/mixins/httparty_proxy.rb @@ -8,14 +8,13 @@ module HTTPartyProxy define_method(method) do |path, body = {}| safe_path = URI.escape(path) body = body.delete_if { |_, v| v.nil? } - if method == :get - result = self.class.send(method, safe_path, query: body) - elsif method == :post_file - result = self.class.send(:post, safe_path, body: body, detect_mime_type: true) - else - result = self.class.send(method, safe_path, body: body.to_json) - end - + result = if method == :get + self.class.send(method, safe_path, query: body) + elsif method == :post_file + self.class.send(:post, safe_path, body: body, detect_mime_type: true) + else + self.class.send(method, safe_path, body: body.to_json) + end case result.code when 200...226 then safe_parse_json(result.body) when 400 then fail Auth0::BadRequest, result.body diff --git a/lib/auth0/mixins/initializer.rb b/lib/auth0/mixins/initializer.rb index 138459d5..0d72b011 100644 --- a/lib/auth0/mixins/initializer.rb +++ b/lib/auth0/mixins/initializer.rb @@ -21,7 +21,7 @@ def self.included(klass) klass.send :prepend, Initializer end - def set_authorization_header(token) + def authorization_header(token) self.class.headers 'Authorization' => "Bearer #{token}" end @@ -30,7 +30,7 @@ def set_authorization_header(token) def initialize_api(options) api_v1?(options) ? initialize_v1(options) : initialize_v2(options) fail InvalidCredentials, 'Must supply a valid API token' if @token.nil? - set_authorization_header(@token) + authorization_header(@token) end def base_url(options) diff --git a/lib/auth0/version.rb b/lib/auth0/version.rb index 1a88c30b..73a4bf72 100644 --- a/lib/auth0/version.rb +++ b/lib/auth0/version.rb @@ -1,4 +1,4 @@ # current version of gem module Auth0 - VERSION = '4.0.0' + VERSION = '4.0.0'.freeze end diff --git a/spec/integration/lib/auth0/api/v2/api_email_spec.rb b/spec/integration/lib/auth0/api/v2/api_email_spec.rb index afcbc903..b4aa1d22 100644 --- a/spec/integration/lib/auth0/api/v2/api_email_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_email_spec.rb @@ -13,7 +13,7 @@ let(:name) { 'mandrill' } let(:enabled) { true } let(:credentials) { { 'api_key' => 'api_key' } } - let(:settings) { { 'first_setting' => 'first_setting_set', 'second_setting' => 'second_setting_set' } } + let(:settings) { { 'first_setting' => 'first_setting_set', 'second_setting' => 'second_setting_set' } } let(:body) do { 'name' => name, 'enabled' => enabled, diff --git a/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb b/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb index 0216da56..7734e7dd 100644 --- a/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb @@ -25,9 +25,9 @@ end let(:connection_id) do client.connections - .find do |connection| - connection['name'].include?(Auth0::Api::AuthenticationEndpoints::UP_AUTH) - end['id'] + .find do |connection| + connection['name'].include?(Auth0::Api::AuthenticationEndpoints::UP_AUTH) + end['id'] end let(:imported_users) { client.import_users(users_file, connection_id) } it do diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index a8262a5e..7019fe44 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -215,25 +215,23 @@ end context '.impersonate' do - let(:user_id) { 'some_user_id' } - let(:app_client_id) { 'some_app_client_id' } - let(:impersonator_id) { 'some_impersonator_id' } - + let(:user_id) { 'some_user_id' } it { expect(@instance).to respond_to(:impersonate) } -=begin - it "is expected to make post request to '/users/{user_id}/impersonate'" do - expect(@instance).to receive(:post).with( - "/users/#{user_id}/impersonate", - protocol: 'oauth2', - impersonator_id: impersonator_id, client_id: app_client_id, - additionalParameters: { - response_type: 'code', state: '', - scope: 'openid', callback_url: '' }) - @instance.impersonate(user_id, app_client_id, impersonator_id, {}) + # it "is expected to make post request to '/users/{user_id}/impersonate'" do + # expect(@instance).to receive(:post).with( + # "/users/#{user_id}/impersonate", + # protocol: 'oauth2', + # impersonator_id: impersonator_id, client_id: app_client_id, + # additionalParameters: { + # response_type: 'code', state: '', + # scope: 'openid', callback_url: '' }) + # @instance.impersonate(user_id, app_client_id, impersonator_id, {}) + # end + it do + expect { @instance.impersonate(user_id, {}) }.to raise_error( + 'Must supply client_secret') end -=end - it { expect { @instance.impersonate(user_id, app_client_id, impersonator_id, {}) }.to raise_error 'Must supply client_secret' } - it { expect { @instance.impersonate('', '', '', '') }.to raise_error 'Must supply a valid user_id' } + it { expect { @instance.impersonate('', '') }.to raise_error 'Must supply a valid user_id' } end context '.unlink_user' do diff --git a/spec/lib/auth0/mixins/httparty_proxy_spec.rb b/spec/lib/auth0/mixins/httparty_proxy_spec.rb index d80c8615..e7d71993 100644 --- a/spec/lib/auth0/mixins/httparty_proxy_spec.rb +++ b/spec/lib/auth0/mixins/httparty_proxy_spec.rb @@ -146,14 +146,13 @@ expect { @instance.send(http_method, '/te st') }.not_to raise_error end - it "should give the JSON representation of the error as the error message" do + it 'should give the JSON representation of the error as the error message' do allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - res = JSON.generate({ - "statusCode"=>404, - "error"=>"Bad Request", - "message"=>"Path validation error: 'String does not match pattern ^.+\\|.+$: 3241312' on property id (The user_id of the user to retrieve).", - "errorCode"=>"invalid_uri" - }) + res = JSON.generate('statusCode' => 404, + 'error' => 'Bad Request', + 'message' => "Path validation error: 'String does not match pattern ^.+\\|.+$: + 3241312' on property id (The user_id of the user to retrieve).", + 'errorCode' => 'invalid_uri') expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') .and_return(StubResponse.new(res, false, 404)) expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound, res) diff --git a/spec/spec_helper_full.rb b/spec/spec_helper_full.rb index 55d97164..a1c8b35a 100644 --- a/spec/spec_helper_full.rb +++ b/spec/spec_helper_full.rb @@ -16,8 +16,8 @@ require 'auth0' require 'pry' -Dir[('./lib/**/*.rb')].each { |f| require f } -Dir[('./spec/support/**/*.rb')].each { |f| require f } +Dir['./lib/**/*.rb'].each { |f| require f } +Dir['./spec/support/**/*.rb'].each { |f| require f } def entity_suffix (ENV['TRAVIS_JOB_ID'] || 'local').delete('_') diff --git a/spec/spec_helper_unit.rb b/spec/spec_helper_unit.rb index 4958eb33..f116c33a 100644 --- a/spec/spec_helper_unit.rb +++ b/spec/spec_helper_unit.rb @@ -4,8 +4,8 @@ require 'rack/test' require 'faker' require 'auth0' -Dir[('./lib/**/*.rb')].each { |f| require f } -Dir[('./spec/support/**/*.rb')].each { |f| require f } +Dir['./lib/**/*.rb'].each { |f| require f } +Dir['./spec/support/**/*.rb'].each { |f| require f } RSpec.configure do |config| config.include Rack::Test::Methods config.fail_fast = true From d1b72edb8d477ad5c6b893ac6027c1fd0916254f Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Tue, 7 Jun 2016 15:08:09 -0300 Subject: [PATCH 03/36] Resource Servers Endpoint --- lib/auth0/api/v2.rb | 2 + lib/auth0/api/v2/resource_servers.rb | 57 +++++++++++++++++++ .../auth0/api/v2/api_resource_servers_spec.rb | 47 +++++++++++++++ .../lib/auth0/api/v2/resource_servers_spec.rb | 54 ++++++++++++++++++ 4 files changed, 160 insertions(+) create mode 100644 lib/auth0/api/v2/resource_servers.rb create mode 100644 spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb create mode 100644 spec/lib/auth0/api/v2/resource_servers_spec.rb diff --git a/lib/auth0/api/v2.rb b/lib/auth0/api/v2.rb index 2b8cf192..b66b6767 100644 --- a/lib/auth0/api/v2.rb +++ b/lib/auth0/api/v2.rb @@ -9,6 +9,7 @@ require 'auth0/api/v2/tenants' require 'auth0/api/v2/tickets' require 'auth0/api/v2/logs' +require 'auth0/api/v2/resource_servers' module Auth0 module Api @@ -25,6 +26,7 @@ module V2 include Auth0::Api::V2::Tenants include Auth0::Api::V2::Tickets include Auth0::Api::V2::Logs + include Auth0::Api::V2::ResourceServers end end end diff --git a/lib/auth0/api/v2/resource_servers.rb b/lib/auth0/api/v2/resource_servers.rb new file mode 100644 index 00000000..65e60272 --- /dev/null +++ b/lib/auth0/api/v2/resource_servers.rb @@ -0,0 +1,57 @@ +module Auth0 + module Api + module V2 + # Methods to use the resource servers endpoints + module ResourceServers + attr_reader :resource_servers_path + + # Retrieves a resource server by its ID. + # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/get_resource_servers_by_id + # @param resource_server_id [string] The id of the resource server to retrieve + # + # @return [json] Returns the resource server. + def resource_server(resource_server_id) + fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? + path = "#{resource_servers_path}/#{resource_server_id}" + get(path) + end + + alias get_resource_server resource_server + + # Creates a new resource server according to the JSON object received in body. + # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/post_resource_servers + # @param identifier [string] The identifier of the resource server. + # @param name [string] The name of the resource server. Must contain at least one character. + # Does not allow '<' or '>'. + # @param signing_alg [string] The algorithm used to sign tokens. + # @param signing_secret [string] The secret used to sign tokens when using symmetric algorithms + # @param token_lifetime [integer] The amount of time (in seconds) that the token will be valid after being issued + # @param scopes [array] The scope of the resource server. + # + # @return [json] Returns the resource server. + def create_resource_server(identifier, options = {}) + fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if identifier.to_s.empty? + request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] + request_params[:identifier] = identifier + post(resource_servers_path, request_params) + end + + # Deletes a resource server by its ID. + # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/delete_resource_servers_by_id + # @param resource_server_id [string] The id of the resource server to delete + def delete_resource_server(resource_server_id) + fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? + path = "#{resource_servers_path}/#{resource_server_id}" + delete(path) + end + + private + + # Resource Servers API path + def resource_servers_path + @rules_path ||= '/api/v2/resource-servers' + end + end + end + end +end diff --git a/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb b/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb new file mode 100644 index 00000000..d000e9a9 --- /dev/null +++ b/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb @@ -0,0 +1,47 @@ +require 'spec_helper' +describe Auth0::Api::V2::ResourceServers do + attr_reader :client, :resource_server + + before(:all) do + @client = Auth0Client.new(v2_creds) + identifier = SecureRandom.uuid + @resource_server = client.create_resource_server(identifier) + end + + after(:all) do + client.delete_resource_server(resource_server['id']) + end + + describe '.resource_server' do + it do + expect(client.resource_server(resource_server['id'])).to( + include('identifier' => resource_server['identifier'], 'id' => resource_server['id'], + 'signing_alg' => resource_server['signing_alg'], + 'token_lifetime' => resource_server['token_lifetime'])) + end + end + + describe '.create_resource_server' do + let(:name) { Faker::Lorem.word } + let(:identifier) { SecureRandom.uuid } + let(:signing_alg) { 'HS256' } + let(:signing_secret) { Faker::Lorem.characters(16) } + let(:token_lifetime) { rand(1000..3000) } + let!(:resource_server) do + client.create_resource_server(identifier, 'name' => name, 'signing_alg' => signing_alg, + 'signing_secret' => signing_secret, + 'token_lifetime' => token_lifetime) + end + it do + expect(resource_server).to include('name' => name, 'identifier' => identifier, 'signing_alg' => signing_alg, + 'signing_secret' => signing_secret, + 'token_lifetime' => token_lifetime) + end + it { expect { client.delete_resource_server(resource_server['id']) }.to_not raise_error } + end + + describe '.delete_resource_server' do + it { expect { client.delete_resource_server(resource_server['id']) }.to_not raise_error } + it { expect { client.delete_resource_server '' }.to raise_error(Auth0::InvalidParameter) } + end +end diff --git a/spec/lib/auth0/api/v2/resource_servers_spec.rb b/spec/lib/auth0/api/v2/resource_servers_spec.rb new file mode 100644 index 00000000..6640b8dd --- /dev/null +++ b/spec/lib/auth0/api/v2/resource_servers_spec.rb @@ -0,0 +1,54 @@ +require 'spec_helper' +describe Auth0::Api::V2::ResourceServers do + before :all do + dummy_instance = DummyClass.new + dummy_instance.extend(Auth0::Api::V2::ResourceServers) + dummy_instance.extend(Auth0::Mixins::Initializer) + @instance = dummy_instance + end + + context '.resource_server' do + it { expect(@instance).to respond_to(:resource_server) } + it 'is expected to call get /api/v2/resource-servers/test' do + expect(@instance).to receive(:get).with('/api/v2/resource-servers/test') + expect { @instance.resource_server('test') }.not_to raise_error + end + it 'expect to raise an error when calling with empty resource server id' do + expect { @instance.resource_server(nil) }.to raise_error 'Must supply a valid resource server id' + end + end + + context '.create_resource_server' do + it { expect(@instance).to respond_to(:create_resource_server) } + it 'is expected to call post /api/v2/resource-servers' do + expect(@instance).to receive(:post).with( + '/api/v2/resource-servers', + identifier: 'test', + name: 'name', + signing_alg: 'signing_alg', + signing_secret: 'signing_secret', + token_lifetime: 'token_lifetime', + scopes: 'scopes') + + @instance.create_resource_server('test', name: 'name', + signing_alg: 'signing_alg', + signing_secret: 'signing_secret', + token_lifetime: 'token_lifetime', + scopes: 'scopes') + end + it 'expect to raise an error when calling with empty identifier' do + expect { @instance.create_resource_server(nil) }.to raise_error 'Must supply a valid resource server id' + end + end + + context '.delete_resource_server' do + it { expect(@instance).to respond_to(:delete_resource_server) } + it 'is expected to call delete /api/v2/resource-server/test' do + expect(@instance).to receive(:delete).with('/api/v2/resource-servers/test') + expect { @instance.delete_resource_server('test') }.not_to raise_error + end + it 'expect to raise an error when calling with empty resource server identifier' do + expect { @instance.delete_resource_server(nil) }.to raise_error 'Must supply a valid resource server id' + end + end +end From 71f0e83aee65d5fdc8bd98f3ae0abeb8658dcdf1 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Fri, 10 Jun 2016 13:03:50 -0300 Subject: [PATCH 04/36] Ignore unlink user test --- spec/integration/lib/auth0/api/v2/api_users_spec.rb | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/spec/integration/lib/auth0/api/v2/api_users_spec.rb b/spec/integration/lib/auth0/api/v2/api_users_spec.rb index f9c0fc44..d477a3c3 100644 --- a/spec/integration/lib/auth0/api/v2/api_users_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_users_spec.rb @@ -110,11 +110,12 @@ client.link_user_account(primary_user['user_id'], body_link).first ).to include('provider' => 'auth0', 'user_id' => primary_user['identities'].first['user_id']) end - end - it do - expect( - client.unlink_users_account(primary_user['user_id'], 'auth0', link_user['user_id']).first - ).to include('provider' => 'auth0', 'user_id' => primary_user['identities'].first['user_id']) + + it do + expect( + client.unlink_users_account(primary_user['user_id'], 'auth0', link_user['user_id']).first + ).to include('provider' => 'auth0', 'user_id' => primary_user['identities'].first['user_id']) + end end end end From 2cea1fb7296a454c98d206d7d7ac868518c58184 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Fri, 10 Jun 2016 17:08:02 -0300 Subject: [PATCH 05/36] Add unit test for resource servers name --- lib/auth0/api/v2/resource_servers.rb | 16 ++++++++++------ .../auth0/api/v2/api_resource_servers_spec.rb | 1 - spec/lib/auth0/api/v2/resource_servers_spec.rb | 6 ++++++ 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/lib/auth0/api/v2/resource_servers.rb b/lib/auth0/api/v2/resource_servers.rb index 65e60272..3470323e 100644 --- a/lib/auth0/api/v2/resource_servers.rb +++ b/lib/auth0/api/v2/resource_servers.rb @@ -7,7 +7,7 @@ module ResourceServers # Retrieves a resource server by its ID. # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/get_resource_servers_by_id - # @param resource_server_id [string] The id of the resource server to retrieve + # @param resource_server_id [string] The id of the resource server to retrieve. # # @return [json] Returns the resource server. def resource_server(resource_server_id) @@ -21,16 +21,20 @@ def resource_server(resource_server_id) # Creates a new resource server according to the JSON object received in body. # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/post_resource_servers # @param identifier [string] The identifier of the resource server. - # @param name [string] The name of the resource server. Must contain at least one character. + # @param name [string] The name of the resource server. Must contain at least one character. # Does not allow '<' or '>'. # @param signing_alg [string] The algorithm used to sign tokens. - # @param signing_secret [string] The secret used to sign tokens when using symmetric algorithms - # @param token_lifetime [integer] The amount of time (in seconds) that the token will be valid after being issued + # @param signing_secret [string] The secret used to sign tokens when using symmetric algorithms. + # @param token_lifetime [integer] The amount of time (in seconds) that the token will be valid + # after being issued. # @param scopes [array] The scope of the resource server. # # @return [json] Returns the resource server. def create_resource_server(identifier, options = {}) fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if identifier.to_s.empty? + if ['<', '>'].include?(options.fetch(:name, '')) + fail Auth0::InvalidParameter, 'Name must contain at least one character. Does not allow "<" or ">"' + end request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] request_params[:identifier] = identifier post(resource_servers_path, request_params) @@ -38,7 +42,7 @@ def create_resource_server(identifier, options = {}) # Deletes a resource server by its ID. # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/delete_resource_servers_by_id - # @param resource_server_id [string] The id of the resource server to delete + # @param resource_server_id [string] The id of the resource server to delete. def delete_resource_server(resource_server_id) fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? path = "#{resource_servers_path}/#{resource_server_id}" @@ -49,7 +53,7 @@ def delete_resource_server(resource_server_id) # Resource Servers API path def resource_servers_path - @rules_path ||= '/api/v2/resource-servers' + @resource_servers_path ||= '/api/v2/resource-servers' end end end diff --git a/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb b/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb index d000e9a9..ed08e085 100644 --- a/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb @@ -42,6 +42,5 @@ describe '.delete_resource_server' do it { expect { client.delete_resource_server(resource_server['id']) }.to_not raise_error } - it { expect { client.delete_resource_server '' }.to raise_error(Auth0::InvalidParameter) } end end diff --git a/spec/lib/auth0/api/v2/resource_servers_spec.rb b/spec/lib/auth0/api/v2/resource_servers_spec.rb index 6640b8dd..b1dab2ff 100644 --- a/spec/lib/auth0/api/v2/resource_servers_spec.rb +++ b/spec/lib/auth0/api/v2/resource_servers_spec.rb @@ -39,6 +39,12 @@ it 'expect to raise an error when calling with empty identifier' do expect { @instance.create_resource_server(nil) }.to raise_error 'Must supply a valid resource server id' end + it 'expect to raise an error when name contains < or > characters' do + expect { @instance.create_resource_server('test', name: '<') }.to raise_error( + 'Name must contain at least one character. Does not allow "<" or ">"') + expect { @instance.create_resource_server('test', name: '>') }.to raise_error( + 'Name must contain at least one character. Does not allow "<" or ">"') + end end context '.delete_resource_server' do From 4173eae5ee228b59b004ed8f2cf5f7baa51eb75c Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Thu, 9 Jun 2016 17:35:32 -0300 Subject: [PATCH 06/36] Logs Endpoint Documentation Review --- lib/auth0/api/v2/logs.rb | 38 ++++++++++--- .../lib/auth0/api/v2/api_logs_spec.rb | 55 +++++++++++++++++++ spec/lib/auth0/api/v2/logs_spec.rb | 4 +- 3 files changed, 89 insertions(+), 8 deletions(-) create mode 100644 spec/integration/lib/auth0/api/v2/api_logs_spec.rb diff --git a/lib/auth0/api/v2/logs.rb b/lib/auth0/api/v2/logs.rb index d1132a56..7f2ff831 100644 --- a/lib/auth0/api/v2/logs.rb +++ b/lib/auth0/api/v2/logs.rb @@ -1,9 +1,22 @@ module Auth0 module Api module V2 - # https://auth0.com/docs/api/v2#!/Logs + # Methods to use the logs endpoints module Logs - # https://auth0.com/docs/api/v2#!/Logs/get_logs + + # Retrieves log entries that match the specified search criteria. + # @see https://auth0.com/docs/api/v2#!/Logs/get_logs + # @param q [string] Query in Lucene query string syntax. + # @param page [integer] The page number. Zero based. + # @param per_page [integer] The amount of entries per page. Default: 50. Max value: 100 + # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending + # @param fields [string] A comma separated list of fields to include or exclude from the result. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. + # @param include_totals [string] True if a query summary must be included in the result, false otherwise. + # @param from [string] Log Event Id to start retrieving logs. You can limit the amount of logs using the take parameter. + # @param take [integer] The total amount of entries to retrieve when using the from parameter. Default: 50. Max value: 100. + # + # @return [json] The list of existing log entries. def logs(options = {}) request_params = { q: options.fetch(:q, nil), @@ -16,16 +29,27 @@ def logs(options = {}) from: options.fetch(:from, nil), take: options.fetch(:take, nil) } - - path = '/api/v2/logs' - get(path, request_params) + get(logs_path, request_params) end + alias_method :get_logs, :logs + - # https://auth0.com/docs/api/v2#!/Logs/get_logs_by_id + # Retrieves log entries that match the specified search criteria. + # @see https://auth0.com/docs/api/v2#!/Logs/get_logs_by_id + # @param id [string] The log_id of the log to retrieve. + # + # @return [json] the log with the given id if exists def log(log_id) - path = "/api/v2/logs/#{log_id}" + fail Auth0::MissingParameter, 'Must supply a valid log_id' if log_id.to_s.empty? + path = "#{logs_path}/#{log_id}" get(path) end + alias_method :get_logs_by_id, :log + + # Users API path + def logs_path + @logs_path ||= '/api/v2/logs' + end end end end diff --git a/spec/integration/lib/auth0/api/v2/api_logs_spec.rb b/spec/integration/lib/auth0/api/v2/api_logs_spec.rb new file mode 100644 index 00000000..68ded09c --- /dev/null +++ b/spec/integration/lib/auth0/api/v2/api_logs_spec.rb @@ -0,0 +1,55 @@ +require 'spec_helper' + +describe Auth0::Api::V2::Logs do + attr_reader :client, :user + + before(:all) do + @client = Auth0Client.new(v2_creds) + username = Faker::Internet.user_name + email = "#{entity_suffix}#{Faker::Internet.safe_email(username)}" + password = Faker::Internet.password + @user = client.create_user(username, 'email' => email, + 'password' => password, + 'email_verified' => false, + 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, + 'app_metadata' => {}) + end + + after(:all) do + client.delete_user(user['user_id']) + end + + + describe '.logs' do + let(:logs) { client.logs } + it { expect(logs.size).to be > 0 } + it { expect(logs.find {|log| log['description'] == 'Create a user' && log['type'] == 'sapi' && log['details']['request']['body']['email'] == user['email'] }).to_not be_empty } + + context '#filters' do + it { expect(client.logs(per_page: 1).size).to be 1 } + it do + expect( + client.logs(per_page: 1, fields: [:date, :description, :type].join(','), include_fields: true).first + ).to(include('date', 'description', 'type')) + end + it { expect(client.logs(per_page: 1, fields: [:date].join(',')).first).to_not include('type', 'description') } + it do + expect( + client.logs(per_page: 1, fields: [:date].join(','), include_fields: false).first + ).to include('type', 'description') + end + end + context '#from' do + it { expect(client.logs(from: logs.last['_id'], take: 1).size).to be 1 } + it { expect(client.logs(from: logs.first['_id'], take: 1).size).to be 0 } + end + end + + describe '.log' do + let(:first_log) { client.logs.first } + let(:log) { client.log(first_log['_id']) } + it { expect(log).to_not be_empty } + it { expect(log['_id']).to eq(first_log['_id']) } + it { expect(log['date']).to eq(first_log['date']) } + end +end diff --git a/spec/lib/auth0/api/v2/logs_spec.rb b/spec/lib/auth0/api/v2/logs_spec.rb index 5255f56d..42c956d0 100644 --- a/spec/lib/auth0/api/v2/logs_spec.rb +++ b/spec/lib/auth0/api/v2/logs_spec.rb @@ -8,6 +8,7 @@ context '.logs' do it { expect(@instance).to respond_to(:logs) } + it { expect(@instance).to respond_to(:get_logs) } it 'is expected to call /api/v2/logs' do expect(@instance).to receive(:get).with( '/api/v2/logs', @@ -24,8 +25,9 @@ end end - context '.user' do + context '.log' do it { expect(@instance).to respond_to(:log) } + it { expect(@instance).to respond_to(:get_logs_by_id) } it 'is expected to call get request to /api/v2/logs/LOG_ID' do expect(@instance).to receive(:get).with('/api/v2/logs/LOG_ID') expect { @instance.log('LOG_ID') }.not_to raise_error From 3f717a49cddaaebf712b10dd5d4d0c1ade4c2b25 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Fri, 10 Jun 2016 16:14:04 -0300 Subject: [PATCH 07/36] Add wait helper + Refactor logs unit tests --- lib/auth0/api/v2/logs.rb | 29 +++++++++++-------- .../lib/auth0/api/v2/api_logs_spec.rb | 20 +++++++++++-- spec/lib/auth0/api/v2/logs_spec.rb | 4 +++ spec/spec_helper_full.rb | 8 +++++ 4 files changed, 46 insertions(+), 15 deletions(-) diff --git a/lib/auth0/api/v2/logs.rb b/lib/auth0/api/v2/logs.rb index 7f2ff831..e407a5ae 100644 --- a/lib/auth0/api/v2/logs.rb +++ b/lib/auth0/api/v2/logs.rb @@ -3,20 +3,23 @@ module Api module V2 # Methods to use the logs endpoints module Logs + attr_reader :logs_path # Retrieves log entries that match the specified search criteria. # @see https://auth0.com/docs/api/v2#!/Logs/get_logs # @param q [string] Query in Lucene query string syntax. # @param page [integer] The page number. Zero based. - # @param per_page [integer] The amount of entries per page. Default: 50. Max value: 100 - # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending + # @param per_page [integer] The amount of entries per page. Default: 50. Max value: 100. + # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending. # @param fields [string] A comma separated list of fields to include or exclude from the result. # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. - # @param include_totals [string] True if a query summary must be included in the result, false otherwise. - # @param from [string] Log Event Id to start retrieving logs. You can limit the amount of logs using the take parameter. - # @param take [integer] The total amount of entries to retrieve when using the from parameter. Default: 50. Max value: 100. + # @param include_totals [string] True if a query summary must be included in the result, false otherwise. + # @param from [string] Log Event Id to start retrieving logs. You can limit the amount of logs using the take + # parameter. + # @param take [integer] The total amount of entries to retrieve when using the from parameter. + # Default: 50. Max value: 100. # - # @return [json] The list of existing log entries. + # @return [json] Returns the list of existing log entries. def logs(options = {}) request_params = { q: options.fetch(:q, nil), @@ -29,24 +32,26 @@ def logs(options = {}) from: options.fetch(:from, nil), take: options.fetch(:take, nil) } + if request_params[:take].to_i > 100 + fail Auth0::MissingParameter, 'The total amount of entries should be less than 100' + end get(logs_path, request_params) end - alias_method :get_logs, :logs - + alias get_logs logs # Retrieves log entries that match the specified search criteria. # @see https://auth0.com/docs/api/v2#!/Logs/get_logs_by_id - # @param id [string] The log_id of the log to retrieve. + # @param id [string] The log_id of the log to retrieve. # - # @return [json] the log with the given id if exists + # @return [json] Returns the log with the given id if exists. def log(log_id) fail Auth0::MissingParameter, 'Must supply a valid log_id' if log_id.to_s.empty? path = "#{logs_path}/#{log_id}" get(path) end - alias_method :get_logs_by_id, :log + alias get_logs_by_id log - # Users API path + # Logs API path def logs_path @logs_path ||= '/api/v2/logs' end diff --git a/spec/integration/lib/auth0/api/v2/api_logs_spec.rb b/spec/integration/lib/auth0/api/v2/api_logs_spec.rb index 68ded09c..6502da85 100644 --- a/spec/integration/lib/auth0/api/v2/api_logs_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_logs_spec.rb @@ -19,11 +19,13 @@ client.delete_user(user['user_id']) end - describe '.logs' do let(:logs) { client.logs } - it { expect(logs.size).to be > 0 } - it { expect(logs.find {|log| log['description'] == 'Create a user' && log['type'] == 'sapi' && log['details']['request']['body']['email'] == user['email'] }).to_not be_empty } + it 'is expected to get a log about user creation' do + wait 30 do + expect(find_create_user_log_by_email(user['email'])).to_not be_empty + end + end context '#filters' do it { expect(client.logs(per_page: 1).size).to be 1 } @@ -39,6 +41,7 @@ ).to include('type', 'description') end end + context '#from' do it { expect(client.logs(from: logs.last['_id'], take: 1).size).to be 1 } it { expect(client.logs(from: logs.first['_id'], take: 1).size).to be 0 } @@ -52,4 +55,15 @@ it { expect(log['_id']).to eq(first_log['_id']) } it { expect(log['date']).to eq(first_log['date']) } end + + private + + def find_create_user_log_by_email(email) + logs = client.logs + logs.find do |log| + log['description'] == 'Create a user' && + log['type'] == 'sapi' && + log['details']['request']['body']['email'] == email + end + end end diff --git a/spec/lib/auth0/api/v2/logs_spec.rb b/spec/lib/auth0/api/v2/logs_spec.rb index 42c956d0..f41587c5 100644 --- a/spec/lib/auth0/api/v2/logs_spec.rb +++ b/spec/lib/auth0/api/v2/logs_spec.rb @@ -23,6 +23,10 @@ take: nil) expect { @instance.logs }.not_to raise_error end + it 'is expect to rise an error when take is higher than 100' do + expect(@instance.logs(take: rand(101...1000))).to raise_error( + 'The total amount of entries should be less than 100') + end end context '.log' do diff --git a/spec/spec_helper_full.rb b/spec/spec_helper_full.rb index a1c8b35a..3c27d27b 100644 --- a/spec/spec_helper_full.rb +++ b/spec/spec_helper_full.rb @@ -45,3 +45,11 @@ def entity_suffix puts "Finished cleaning up for #{entity_suffix}" end end + +def wait(time, increment = 5, elapsed_time = 0, &block) + yield +rescue RSpec::Expectations::ExpectationNotMetError => e + raise e if elapsed_time >= time + sleep increment + wait(time, increment, elapsed_time + increment, &block) +end From deb193be493710d1fd4db0a88c608002d4423d5c Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Mon, 13 Jun 2016 17:22:57 -0300 Subject: [PATCH 08/36] Update Rubocop --- .rubocop_todo.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 875f3f2a..ee88529f 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,7 +1,8 @@ -# Configuration parameters: CountComments. Metrics/MethodLength: Max: 15 -# Configuration parameters: AllowURI, URISchemes. Metrics/LineLength: Max: 121 + +Metrics/AbcSize: + Max: 15.5 From 85ceaa37c02c64b490fc866b03a80fa0bb3b5a5d Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Mon, 13 Jun 2016 17:33:19 -0300 Subject: [PATCH 09/36] Add spec for log method to validate the log_id --- .rubocop_todo.yml | 3 --- lib/auth0/api/v2/logs.rb | 6 +++++- spec/lib/auth0/api/v2/logs_spec.rb | 9 +++++++-- 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index ee88529f..02b5e688 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -3,6 +3,3 @@ Metrics/MethodLength: Metrics/LineLength: Max: 121 - -Metrics/AbcSize: - Max: 15.5 diff --git a/lib/auth0/api/v2/logs.rb b/lib/auth0/api/v2/logs.rb index e407a5ae..fbb951ff 100644 --- a/lib/auth0/api/v2/logs.rb +++ b/lib/auth0/api/v2/logs.rb @@ -1,3 +1,4 @@ +# rubocop:disable Metrics/MethodLength, Metrics/AbcSize module Auth0 module Api module V2 @@ -33,7 +34,10 @@ def logs(options = {}) take: options.fetch(:take, nil) } if request_params[:take].to_i > 100 - fail Auth0::MissingParameter, 'The total amount of entries should be less than 100' + fail Auth0::MissingParameter, 'The total amount of entries to retrieve should be less than 100' + end + if request_params[:per_page].to_i > 100 + fail Auth0::MissingParameter, 'The total amount of entries per page should be less than 100' end get(logs_path, request_params) end diff --git a/spec/lib/auth0/api/v2/logs_spec.rb b/spec/lib/auth0/api/v2/logs_spec.rb index f41587c5..6a95c58a 100644 --- a/spec/lib/auth0/api/v2/logs_spec.rb +++ b/spec/lib/auth0/api/v2/logs_spec.rb @@ -24,8 +24,12 @@ expect { @instance.logs }.not_to raise_error end it 'is expect to rise an error when take is higher than 100' do - expect(@instance.logs(take: rand(101...1000))).to raise_error( - 'The total amount of entries should be less than 100') + expect { @instance.logs(take: rand(101..2000)) }.to raise_error( + 'The total amount of entries to retrieve should be less than 100') + end + it 'is expect to rise an error when per_page is higher than 100' do + expect { @instance.logs(per_page: rand(101..2000)) }.to raise_error( + 'The total amount of entries per page should be less than 100') end end @@ -36,5 +40,6 @@ expect(@instance).to receive(:get).with('/api/v2/logs/LOG_ID') expect { @instance.log('LOG_ID') }.not_to raise_error end + it { expect { @instance.log(nil) }.to raise_error('Must supply a valid log_id') } end end From ede23b386704700240d90f643313e4810827bd15 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Tue, 14 Jun 2016 12:37:03 -0300 Subject: [PATCH 10/36] Change exception type to InvalidParameter --- lib/auth0/api/v2/logs.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/auth0/api/v2/logs.rb b/lib/auth0/api/v2/logs.rb index fbb951ff..14c693bf 100644 --- a/lib/auth0/api/v2/logs.rb +++ b/lib/auth0/api/v2/logs.rb @@ -34,10 +34,10 @@ def logs(options = {}) take: options.fetch(:take, nil) } if request_params[:take].to_i > 100 - fail Auth0::MissingParameter, 'The total amount of entries to retrieve should be less than 100' + fail Auth0::InvalidParameter, 'The total amount of entries to retrieve should be less than 100' end if request_params[:per_page].to_i > 100 - fail Auth0::MissingParameter, 'The total amount of entries per page should be less than 100' + fail Auth0::InvalidParameter, 'The total amount of entries per page should be less than 100' end get(logs_path, request_params) end From e70e241b2878af47bf5781173259fc315b8cd4b7 Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Fri, 10 Jun 2016 17:38:06 -0300 Subject: [PATCH 11/36] API endpoints review --- lib/auth0/api/v2/clients.rb | 16 ++++++------- lib/auth0/api/v2/connections.rb | 25 ++++++++++----------- lib/auth0/api/v2/emails.rb | 8 +++---- lib/auth0/api/v2/jobs.rb | 19 +++++++++------- lib/auth0/api/v2/rules.rb | 27 +++++++++++----------- lib/auth0/api/v2/stats.rb | 4 ++-- lib/auth0/api/v2/tenants.rb | 8 ++++--- lib/auth0/api/v2/tickets.rb | 20 +++++++++-------- lib/auth0/api/v2/users.rb | 40 ++++++++++++++++----------------- 9 files changed, 86 insertions(+), 81 deletions(-) diff --git a/lib/auth0/api/v2/clients.rb b/lib/auth0/api/v2/clients.rb index cb71d386..638c4b3c 100644 --- a/lib/auth0/api/v2/clients.rb +++ b/lib/auth0/api/v2/clients.rb @@ -8,7 +8,7 @@ module Clients # Retrieves a list of all client applications. Accepts a list of fields to include or exclude. # @see https://auth0.com/docs/api/v2#!/clients/get_clients # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] if the fields specified are to be included in the result, false otherwise + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # # @return [json] Returns the clients applications. def clients(fields: nil, include_fields: nil) @@ -23,9 +23,9 @@ def clients(fields: nil, include_fields: nil) # Creates a new client application. # @see https://auth0.com/docs/api/v2#!/clients/post_clients - # @param name [string] The name of the client. Must contain at least one character. Does not allow '<' or '>' + # @param name [string] The name of the client. Must contain at least one character. Does not allow '<' or '>'. # @param options [hash] The Hash options used to define the client's properties. - # @return [json] Returns the created client application. + # @return [json] Returns the created client application. def create_client(name, options = {}) fail Auth0::MissingParameter, 'Must specify a valid client name' if name.to_s.empty? request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] @@ -35,10 +35,10 @@ def create_client(name, options = {}) # Retrieves a client by its id. # @see https://auth0.com/docs/api/v2#!/Clients/get_clients_by_id - # @param client_id [string] The id of the client to retrieve + # @param client_id [string] The id of the client to retrieve. # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] If the fields specified are to be included in the result, false otherwise - # @return [json] Returns the requested client application. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. + # @return [json] Returns the requested client application. def client(client_id, fields: nil, include_fields: nil) fail Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? include_fields = true if !fields.nil? && include_fields.nil? @@ -52,7 +52,7 @@ def client(client_id, fields: nil, include_fields: nil) # Deletes a client and all its related assets (like rules, connections, etc) given its id. # @see https://auth0.com/docs/api/v2#!/Clients/delete_clients_by_id - # @param client_id [string] The id of the client to delete + # @param client_id [string] The id of the client to delete. def delete_client(client_id) fail Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? path = "#{clients_path}/#{client_id}" @@ -61,7 +61,7 @@ def delete_client(client_id) # Updates a client. # @see https://auth0.com/docs/api/v2#!/Clients/patch_clients_by_id - # @param client_id [string] The id of the client to update + # @param client_id [string] The id of the client to update. # @param options [hash] The Hash options used to define the client's properties. def patch_client(client_id, options) fail Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? diff --git a/lib/auth0/api/v2/connections.rb b/lib/auth0/api/v2/connections.rb index 0081739b..75ea7854 100644 --- a/lib/auth0/api/v2/connections.rb +++ b/lib/auth0/api/v2/connections.rb @@ -8,9 +8,10 @@ module Connections # Retrieves every connection matching the specified strategy. All connections are retrieved if no strategy is # being specified. Accepts a list of fields to include or exclude in the resulting list of connection objects. # @see https://auth0.com/docs/api/v2#!/Connections/get_connections - # @param strategy [string] Provide a type of strategy to only retrieve connections with that strategy + # @param strategy [string] Provide a type of strategy to only retrieve connections with that strategy (e.g. 'ad', + # 'facebook', 'twitter'). # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] if the fields specified are to be included in the result, false otherwise. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # # @return [json] Returns the existing connections matching the strategy. def connections(strategy: nil, fields: nil, include_fields: true) @@ -27,7 +28,7 @@ def connections(strategy: nil, fields: nil, include_fields: true) # @see https://auth0.com/docs/api/v2#!/Connections/post_connections # @param body [hash] The Hash options used to define the conecctions's properties. # - # @return [json] Returns the created connection. + # @return [json] Returns the created connection. def create_connection(body) fail Auth0::InvalidParameter, 'Must specify a body to create a connection' if body.to_s.empty? request_params = body @@ -36,11 +37,11 @@ def create_connection(body) # Retrieves a connection by its id. # @see https://auth0.com/docs/api/v2#!/Connections/get_connections_by_id - # @param connection_id [string] The id of the connection to retrieve + # @param connection_id [string] The id of the connection to retrieve. # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] if the fields specified are to be included in the result, false otherwise + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # - # @return [json] Returns the matching connection + # @return [json] Returns the matching connection. def connection(connection_id, fields: nil, include_fields: true) fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? path = "#{connections_path}/#{connection_id}" @@ -53,7 +54,7 @@ def connection(connection_id, fields: nil, include_fields: true) # Deletes a connection and all its users. # @see https://auth0.com/docs/api/v2#!/Connections/delete_connections_by_id - # @param connection_id [string] The id of the connection to delete + # @param connection_id [string] The id of the connection to delete. def delete_connection(connection_id) fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? path = "#{connections_path}/#{connection_id}" @@ -63,10 +64,8 @@ def delete_connection(connection_id) # Deletes a specified connection user by its email (currently only database connections are supported and you # cannot delete all users from specific connection). # @see https://auth0.com/docs/api/v2#!/Connections/delete_users - # @param connection_id [string] The id of the connection - # @param user_email [string] The email of the user to delete - # - # @return [json] Returns the updated connection. + # @param connection_id [string] The id of the connection. + # @param user_email [string] The email of the user to delete. def delete_connection_user(connection_id, user_email) fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid user email' if user_email.to_s.empty? @@ -76,10 +75,10 @@ def delete_connection_user(connection_id, user_email) # Updates a connection. Updates the fields specified in the body parameter. # @see https://auth0.com/docs/api/v2#!/Connections/patch_connections_by_id - # @param connection_id [string] The id of the connection to delete + # @param connection_id [string] The id of the connection to delete. # @param body [hash] The Hash options used to update the conecctions's properties. # - # @return [json] Returns the updated connection. + # @return [json] Returns the updated connection. def update_connection(connection_id, body) fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? path = "#{connections_path}/#{connection_id}" diff --git a/lib/auth0/api/v2/emails.rb b/lib/auth0/api/v2/emails.rb index 8d6c8c6f..8e768276 100644 --- a/lib/auth0/api/v2/emails.rb +++ b/lib/auth0/api/v2/emails.rb @@ -8,7 +8,7 @@ module Emails # Get all the email providers. # @see https://auth0.com/docs/api/v2#!/Emails/get_provider # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] if the fields specified are to be included in the result, false otherwise. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # # @return [json] Returns the existing email providers. def get_provider(fields: nil, include_fields: nil) @@ -21,9 +21,7 @@ def get_provider(fields: nil, include_fields: nil) # Configure a new email provider. # @see https://auth0.com/docs/api/v2#!/Emails/post_provider - # @param body [hash] The Hash options used to spcify the email provider's properties. - # - # @return [json] Returns the created email provider. + # @param body [hash] The Hash options used to specify the email provider's properties. def configure_provider(body) fail Auth0::InvalidParameter, 'Must supply a valid body to create an email provider' if body.to_s.empty? post(email_path, body) @@ -39,7 +37,7 @@ def delete_provider # Updates the configured email provider. # @see https://auth0.com/docs/api/v2#!/Emails/patch_provider - # @param body [hash] The Hash options used to spcify the email provider's properties. + # @param body [hash] The Hash options used to specify the email provider's properties. # # @return [json] Returns the updated email provider. def update_provider(body) diff --git a/lib/auth0/api/v2/jobs.rb b/lib/auth0/api/v2/jobs.rb index d00e592a..b384d68e 100644 --- a/lib/auth0/api/v2/jobs.rb +++ b/lib/auth0/api/v2/jobs.rb @@ -7,9 +7,9 @@ module Jobs # Retrieves a job. Useful to check its status. # @see https://auth0.com/docs/api/v2#!/Jobs/get_jobs_by_job_id - # @param job_id [string] The id of the job + # @param job_id [string] The id of the job. # - # @return [json] the job status and properties + # @return [json] Returns the job status and properties. def get_job(job_id) fail Auth0::InvalidParameter, 'Must specify a job id' if job_id.to_s.empty? path = "#{jobs_path}/#{job_id}" @@ -19,10 +19,10 @@ def get_job(job_id) # Imports users to a connection from a file using a long running job. # Important: The documentation for the file format is at https://docs.auth0.com/bulk-import. # @see https://auth0.com/docs/api/v2#!/Jobs/post_users_imports - # @param users_file [file] A file containing the users to import - # @param connection_id [string] The connection id of the connection to which users will be inserted + # @param users_file [file] A file containing the users to import. + # @param connection_id [string] The connection id of the connection to which users will be inserted. # - # @return [json] the job status and properties + # @return [json] Returns the job status and properties. def import_users(users_file, connection_id) fail Auth0::InvalidParameter, 'Must specify a valid file' if users_file.to_s.empty? fail Auth0::InvalidParameter, 'Must specify a connection_id' if connection_id.to_s.empty? @@ -36,13 +36,16 @@ def import_users(users_file, connection_id) # Send an email to the specified user that asks them to click a link to verify their email address. # @see https://auth0.com/docs/api/v2#!/Jobs/post_verification_email - # @param user_id [string] The user_id of the user to whom the email will be sent + # @param user_id [string] The user_id of the user to whom the email will be sent. # - # @return [json] the job status and properties + # @return [json] Returns the job status and properties. def send_verification_email(user_id) fail Auth0::InvalidParameter, 'Must specify a user id' if user_id.to_s.empty? + request_params = { + user_id: user_id + } path = "#{jobs_path}/verification-email" - post(path, user_id) + post(path, request_params) end private diff --git a/lib/auth0/api/v2/rules.rb b/lib/auth0/api/v2/rules.rb index 87e7984c..04e91a4a 100644 --- a/lib/auth0/api/v2/rules.rb +++ b/lib/auth0/api/v2/rules.rb @@ -10,10 +10,10 @@ module Rules # The rule's stage of executing could be set to the following values login_success, # login_failure or pre_authorize # @see https://auth0.com/docs/api/v2#!/Rules/get_rules - # @param enabled [boolean] If provided retrieves rules that match the value, otherwise all rules are retrieved + # @param enabled [boolean] If provided retrieves rules that match the value, otherwise all rules are retrieved. # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] If the fields specified are to be included in the result, false otherwise - # @param stage [string] Retrieves rules that match the execution stage (defaults to login_success) + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. + # @param stage [string] Retrieves rules that match the execution stage (defaults to login_success). # # @return [json] Returns the existing rules. def rules(enabled: nil, fields: nil, include_fields: nil, stage: nil) @@ -30,9 +30,9 @@ def rules(enabled: nil, fields: nil, include_fields: nil, stage: nil) # Retrieves a rule by its ID. Accepts a list of fields to include or exclude in the result. # @see https://auth0.com/docs/api/v2#!/Rules/get_rules_by_id - # @param rule_id [string] The id of the rule to retrieve + # @param rule_id [string] The id of the rule to retrieve. # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] If the fields specified are to be included in the result, false otherwise + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # # @return [json] Returns the rule. def rule(rule_id, fields: nil, include_fields: nil) @@ -49,15 +49,15 @@ def rule(rule_id, fields: nil, include_fields: nil) # Creates a new rule according to the JSON object received in body. # @see https://auth0.com/docs/api/v2#!/Rules/post_rules - # @param name [string] The name of the rule. Can only contain alphanumeric characters, spaces and '-'. - # @param script [string] A script that contains the rule's code + # @param name [string] The name of the rule. Can only contain alphanumeric characters, spaces and '-'. + # @param script [string] A script that contains the rule's code. # @param order [integer] The rule's order in relation to other rules. A rule with a lower order than another rule - # executes first. If no order is provided it will automatically be one greater than the current maximum - # @param enabled [string] true if the rule is enabled, false otherwise + # executes first. If no order is provided it will automatically be one greater than the current maximum. + # @param enabled [string] True if the rule is enabled, false otherwise. # @param stage [string] The rule's execution stage 'login_success' or 'login_failure' or 'pre_authorize' or - # 'user_registration' or 'user_blocked' + # 'user_registration' or 'user_blocked'. # - # @return [json] Returns the rule. + # @return [json] Returns the created rule. def create_rule(name, script, order = nil, enabled = true, stage = 'login_success') fail Auth0::InvalidParameter, 'Must supply a valid name' if name.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid script' if script.to_s.empty? @@ -73,8 +73,9 @@ def create_rule(name, script, order = nil, enabled = true, stage = 'login_succes # Updates a rule. # @see https://auth0.com/docs/api/v2#!/Rules/patch_rules_by_id - # @param rule_id [string] The id of the rule to retrieve + # @param rule_id [string] The id of the rule to retrieve. # @param fields_to_update [hash] The Hash fields_to_update used to define the rule's properties. + # # @return [json] Returns the updated rule. def update_rule(rule_id, fields_to_update = {}) fail Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? @@ -85,7 +86,7 @@ def update_rule(rule_id, fields_to_update = {}) # Deletes a rule. # @see https://auth0.com/docs/api/v2#!/Rules/delete_rules_by_id - # @param rule_id [string] The id of the rule to retrieve + # @param rule_id [string] The id of the rule to delete. def delete_rule(rule_id) fail Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? path = "#{rules_path}/#{rule_id}" diff --git a/lib/auth0/api/v2/stats.rb b/lib/auth0/api/v2/stats.rb index ba797d83..2576fc4f 100644 --- a/lib/auth0/api/v2/stats.rb +++ b/lib/auth0/api/v2/stats.rb @@ -8,7 +8,7 @@ module Stats # Gets the active users count (logged in during the last 30 days). # @see https://auth0.com/docs/api/v2#!/Stats/get_active_users # - # @return [integer] Returns numbers + # @return [integer] Returns the active users count. def active_users path = "#{stats_path}/active-users" get(path) @@ -16,7 +16,7 @@ def active_users # Gets the daily stats for a particular period. # @see https://auth0.com/docs/api/v2#!/Stats/get_daily - # @param from [string] The first day of the period (inclusive) in YYYYMMDD format. + # @param from [string] The first day of the period (inclusive) in YYYYMMDD format. # @param to [string] The last day of the period (inclusive) in YYYYMMDD format. # # @return [json] Returns the daily stats. diff --git a/lib/auth0/api/v2/tenants.rb b/lib/auth0/api/v2/tenants.rb index b2a4a2f6..9dcf3809 100644 --- a/lib/auth0/api/v2/tenants.rb +++ b/lib/auth0/api/v2/tenants.rb @@ -8,7 +8,8 @@ module Tenants # Gets tenants settings. # @see https://auth0.com/docs/api/v2#!/Tenants/get_settings # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] If the fields specified are to be included in the result, false otherwise + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. + # # @return [json] Returns tenants settings. def get_tenant_settings(fields: nil, include_fields: true) request_params = { @@ -20,8 +21,9 @@ def get_tenant_settings(fields: nil, include_fields: true) # Updates tenants settings. # @see https://auth0.com/docs/api/v2#!/Tenants/patch_settings - # @param body [hash] The Hash body used to define the tenants settings's properties. - # @return [json] Returns updated tenants settings. + # @param body [hash] The Hash body used to define the tenant settings' values. + # + # @return [json] Returns the updated tenant settings. def update_tenant_settings(body) fail Auth0::InvalidParameter, 'Must supply a valid body to update tenant settings' if body.to_s.empty? patch(tenant_path, body) diff --git a/lib/auth0/api/v2/tickets.rb b/lib/auth0/api/v2/tickets.rb index 7c734adf..464b438a 100644 --- a/lib/auth0/api/v2/tickets.rb +++ b/lib/auth0/api/v2/tickets.rb @@ -7,9 +7,10 @@ module Tickets # Create an email verification ticket # @see https://auth0.com/docs/api/v2#!/Tickets/post_email_verification - # @param user_id [string] The user_id of for which the ticket is to be created - # @param result_url [string] The user will be redirected to this endpoint once the ticket is used - # @return [json] Returns ticket url + # @param user_id [string] The user_id of for which the ticket is to be created. + # @param result_url [string] The user will be redirected to this endpoint once the ticket is used. + # + # @return [json] Returns the created ticket url. def post_email_verification(user_id, result_url: nil) if user_id.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid user id to post an email verification' @@ -24,13 +25,14 @@ def post_email_verification(user_id, result_url: nil) # Create a password change ticket # @see https://auth0.com/docs/api/v2#!/Tickets/post_password_change - # @param new_password [string] The password to set for the user once the ticket is used - # @param user_id [string] The user_id of for which the ticket is to be created - # @param result_url [string] The user will be redirected to this endpoint once the ticket is used + # @param new_password [string] The password to be set for the user once the ticket is used. + # @param user_id [string] The user_id of for which the ticket is to be created. + # @param result_url [string] The user will be redirected to this endpoint once the ticket is used. # @param connection_id [string] The connection that provides the identity for which the password is to be - # changed. If sending this parameter, the email is also required and the user_id is invalid - # @param email [string] The user's email - # @return [json] Returns ticket url + # changed. If sending this parameter, the email is also required and the user_id is invalid. + # @param email [string] The user's email. + # + # @return [json] Returns the created ticket url. def post_password_change(new_password, user_id: nil, result_url: nil, connection_id: nil, email: nil) if new_password.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid new password to post a password-change' diff --git a/lib/auth0/api/v2/users.rb b/lib/auth0/api/v2/users.rb index 98fb8d03..da729bfc 100644 --- a/lib/auth0/api/v2/users.rb +++ b/lib/auth0/api/v2/users.rb @@ -7,17 +7,17 @@ module Users # Retrieves a list of existing users. # @see https://auth0.com/docs/api/v2#!/Users/get_users - # @param per_page [integer] The amount of entries per page. Default: 50. Max value: 100 - # @param page [integer] The page number. Zero based - # @param include_totals [boolean] true if a query summary must be included in the result - # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending - # @param connection [string] Connection filter + # @param per_page [integer] The amount of entries per page. Default: 50. Max value: 100. + # @param page [integer] The page number. Zero based. + # @param include_totals [boolean] True if a query summary must be included in the result. + # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending. + # @param connection [string] Connection filter. # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] if the fields specified are to be included in the result, false otherwise. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # @param q [string] Query in Lucene query string syntax. Only fields in app_metadata, user_metadata or the # normalized user profile are searchable. # - # @return [json] The list of existing users. + # @return [json] Returns the list of existing users. def users(options = {}) request_params = { per_page: options.fetch(:per_page, nil), @@ -38,10 +38,10 @@ def users(options = {}) # The attribute connection is always mandatory but depending on the type of connection you are using there # could be others too. For instance, Auth0 DB Connections require email and password. # @see https://auth0.com/docs/api/v2#!/Users/post_users - # @param name [string] the user name - # @param connection [string] The connection the user belongs to + # @param name [string] The user name. + # @param connection [string] The connection the user belongs to. # - # @return [json] + # @return [json] Returns the created user. def create_user(name, options = {}) request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] request_params[:name] = name @@ -56,11 +56,11 @@ def delete_users # Retrieves a user given a user_id # @see https://auth0.com/docs/api/v2#!/Users/get_users_by_id - # @param user_id [string] The user_id of the user to retrieve + # @param user_id [string] The user_id of the user to retrieve. # @param fields [string] A comma separated list of fields to include or exclude from the result. - # @param include_fields [boolean] if the fields specified are to be included in the result, false otherwise. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # - # @return [json] the user with the given user_id if exists + # @return [json] Returns the user with the given user_id if it exists. def user(user_id, fields: nil, include_fields: true) fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? path = "#{users_path}/#{user_id}" @@ -73,7 +73,7 @@ def user(user_id, fields: nil, include_fields: true) # Deletes a single user given its id # @see https://auth0.com/docs/api/v2#!/Users/delete_users_by_id - # @param user_id [string] The user_id of the user to delete + # @param user_id [string] The user_id of the user to delete. def delete_user(user_id) fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? path = "#{users_path}/#{user_id}" @@ -93,9 +93,9 @@ def delete_user(user_id) # If your are updating email or phone_number you need to specify the connection and the client_id properties. # @see https://auth0.com/docs/api/v2#!/Users/patch_users_by_id # @param user_id [string] The user_id of the user to update. - # @param body [hash] The optional parametes to update + # @param body [hash] The optional parametes to update. # - # @return [json] the updated user + # @return [json] Returns the updated user. def patch_user(user_id, body) fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty? @@ -105,8 +105,8 @@ def patch_user(user_id, body) # Delete a user's multifactor provider # @see https://auth0.com/docs/api/v2#!/Users/delete_multifactor_by_provider - # @param user_id [string] The user_id of the user to delete - # @param provider_name [string] The multifactor provider. Supported values 'duo' or 'google-authenticator' + # @param user_id [string] The user_id of the user to delete the multifactor provider from. + # @param provider_name [string] The multifactor provider. Supported values 'duo' or 'google-authenticator'. def delete_user_provider(user_id, provider_name) fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid provider name' if provider_name.to_s.empty? @@ -126,7 +126,7 @@ def delete_user_provider(user_id, provider_name) # @param user_id [string] The user_id of the primary identity where you are linking the secondary account to. # @param body [string] the options to link the account to. # - # @return [json] the new array of the primary account identities. + # @return [json] Returns the new array of the primary account identities. def link_user_account(user_id, body) fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? fail Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty? @@ -140,7 +140,7 @@ def link_user_account(user_id, body) # @param provider [string] The type of identity provider. # @param secondary_user_id [string] The unique identifier for the user for the identity. # - # @return [json] the array of the unlinked account identities. + # @return [json] Returns the array of the unlinked account identities. def unlink_users_account(user_id, provider, secondary_user_id) fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? fail Auth0::MissingUserId, 'Must supply a valid secondary user_id' if secondary_user_id.to_s.empty? From a176a0202af8b04e4074f88c0be3deca62c43ec4 Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Mon, 13 Jun 2016 17:14:50 -0300 Subject: [PATCH 12/36] Add user_logs method to users endpoint --- lib/auth0/api/v2/users.rb | 23 +++++++++++++++++ .../lib/auth0/api/v2/api_users_spec.rb | 25 +++++++++++++++++++ spec/lib/auth0/api/v2/users_spec.rb | 17 +++++++++++++ 3 files changed, 65 insertions(+) diff --git a/lib/auth0/api/v2/users.rb b/lib/auth0/api/v2/users.rb index da729bfc..726a894f 100644 --- a/lib/auth0/api/v2/users.rb +++ b/lib/auth0/api/v2/users.rb @@ -149,6 +149,29 @@ def unlink_users_account(user_id, provider, secondary_user_id) delete(path) end + # Retrieve every log event for a specific user id + # @see https://auth0.com/docs/api/management/v2#!/Users/get_logs_by_user + # @param user_id [string] The user_id of the logs to retrieve. + # @param per_page [integer] The amount of entries per page. Default: 50. Max value: 100. + # @param page [integer] The page number. Zero based. + # @param include_totals [boolean] True if a query summary must be included in the result. + # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending. + # + # @return [json] Returns the list of existing log entries for the given user_id. + def user_logs(user_id, options = {}) + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + path = "#{users_path}/#{user_id}/logs" + request_params = { + user_id: user_id, + per_page: options.fetch(:per_page, nil), + page: options.fetch(:page, nil), + include_totals: options.fetch(:include_totals, nil), + sort: options.fetch(:sort, nil) + } + get(path, request_params) + end + alias get_user_log_events user_logs + private # Users API path diff --git a/spec/integration/lib/auth0/api/v2/api_users_spec.rb b/spec/integration/lib/auth0/api/v2/api_users_spec.rb index d477a3c3..0c868077 100644 --- a/spec/integration/lib/auth0/api/v2/api_users_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_users_spec.rb @@ -118,4 +118,29 @@ end end end + + describe '.user_logs' do + it 'is expected that the user logs contain a success signup log entry' do + wait 30 do + user_logs = client.user_logs(user['user_id']) + expect(user_logs.size).to be > 0 + expect(find_success_signup_log_by_email(user['email'], user_logs)).to_not be_empty + end + end + + context '#filters' do + it do + wait 30 do + expect(client.user_logs(user['user_id'], per_page: 1).size).to be 1 + end + end + end + end + + def find_success_signup_log_by_email(email, logs) + logs.find do |log| + log['type'] == 'ss' && + log['details']['body']['email'] == email + end + end end diff --git a/spec/lib/auth0/api/v2/users_spec.rb b/spec/lib/auth0/api/v2/users_spec.rb index 5a941b31..dadf9bb3 100644 --- a/spec/lib/auth0/api/v2/users_spec.rb +++ b/spec/lib/auth0/api/v2/users_spec.rb @@ -131,4 +131,21 @@ end it { expect { @instance.delete_user_provider(nil, 'test') }.to raise_error 'Must supply a valid user_id' } end + + context '.user_logs' do + it { expect(@instance).to respond_to(:user_logs) } + it { expect(@instance).to respond_to(:get_user_log_events) } + it 'is expected to call /api/v2/USER_ID/logs' do + expect(@instance).to receive(:get).with( + '/api/v2/users/USER_ID/logs', + user_id: 'USER_ID', + per_page: nil, + page: nil, + include_totals: nil, + sort: nil + ) + expect { @instance.user_logs('USER_ID') }.not_to raise_error + end + it { expect { @instance.user_logs('') }.to raise_error 'Must supply a valid user_id' } + end end From 79dc00e154deafac87ab135fc96743ce9384eb91 Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Mon, 13 Jun 2016 17:54:45 -0300 Subject: [PATCH 13/36] Fix for send_verification_email issue --- spec/integration/lib/auth0/api/v2/api_jobs_spec.rb | 2 +- spec/lib/auth0/api/v2/jobs_spec.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb b/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb index 7734e7dd..fb0e8f13 100644 --- a/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb @@ -51,7 +51,7 @@ 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, 'app_metadata' => {}) end - let(:email_verification_job) { client.send_verification_email(user_id: user['user_id']) } + let(:email_verification_job) { client.send_verification_email(user['user_id']) } it { expect(email_verification_job).to include('status' => 'pending', 'type' => 'verification_email') } let(:email_job_id) { email_verification_job['id'] } it do diff --git a/spec/lib/auth0/api/v2/jobs_spec.rb b/spec/lib/auth0/api/v2/jobs_spec.rb index 7fd0db72..f224b76a 100644 --- a/spec/lib/auth0/api/v2/jobs_spec.rb +++ b/spec/lib/auth0/api/v2/jobs_spec.rb @@ -28,7 +28,7 @@ it { expect(@instance).to respond_to(:send_verification_email) } it 'expect client to send post to /api/v2/jobs/verification-email' do expect(@instance).to receive(:post).with('/api/v2/jobs/verification-email', user_id: 'user_id') - expect { @instance.send_verification_email(user_id: 'user_id') }.not_to raise_error + expect { @instance.send_verification_email('user_id') }.not_to raise_error end it { expect { @instance.send_verification_email('') }.to raise_error('Must specify a user id') } end From f7e06a14057e377c6f56cd747f93cf9e1bccc18d Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Mon, 13 Jun 2016 18:00:03 -0300 Subject: [PATCH 14/36] Rubocop fixes v0.40.0 --- examples/ruby-api/main.rb | 4 +- lib/auth0/api/authentication_endpoints.rb | 36 +++++----- lib/auth0/api/v1/connections.rb | 3 +- lib/auth0/api/v1/users.rb | 2 +- lib/auth0/api/v2/blacklists.rb | 2 +- lib/auth0/api/v2/clients.rb | 10 +-- lib/auth0/api/v2/connections.rb | 12 ++-- lib/auth0/api/v2/emails.rb | 4 +- lib/auth0/api/v2/jobs.rb | 8 +-- lib/auth0/api/v2/resource_servers.rb | 8 +-- lib/auth0/api/v2/rules.rb | 10 +-- lib/auth0/api/v2/tenants.rb | 2 +- lib/auth0/api/v2/tickets.rb | 4 +- lib/auth0/api/v2/users.rb | 22 +++--- lib/auth0/mixins/httparty_proxy.rb | 12 ++-- lib/auth0/mixins/initializer.rb | 6 +- .../lib/auth0/api/v2/api_clients_spec.rb | 7 +- .../lib/auth0/api/v2/api_connections_spec.rb | 9 ++- .../lib/auth0/api/v2/api_email_spec.rb | 21 ++++-- .../lib/auth0/api/v2/api_jobs_spec.rb | 12 ++-- .../auth0/api/v2/api_resource_servers_spec.rb | 3 +- .../lib/auth0/api/v2/api_rules_spec.rb | 3 +- .../lib/auth0/api/v2/api_users_spec.rb | 3 +- .../lib/auth0/auth0_client_spec.rb | 15 ++-- .../api/authentication_endpoints_spec.rb | 72 ++++++++++++------- spec/lib/auth0/api/v1/connections_spec.rb | 6 +- spec/lib/auth0/api/v1/rules_spec.rb | 3 +- spec/lib/auth0/api/v1/users_spec.rb | 24 ++++--- spec/lib/auth0/api/v2/connections_spec.rb | 3 +- spec/lib/auth0/api/v2/jobs_spec.rb | 3 +- spec/lib/auth0/api/v2/logs_spec.rb | 3 +- .../lib/auth0/api/v2/resource_servers_spec.rb | 9 ++- spec/lib/auth0/api/v2/rules_spec.rb | 12 ++-- spec/lib/auth0/api/v2/tenants_spec.rb | 3 +- spec/lib/auth0/api/v2/tickets_spec.rb | 6 +- spec/lib/auth0/api/v2/users_spec.rb | 18 +++-- spec/lib/auth0/client_spec.rb | 3 +- spec/lib/auth0/mixins/httparty_proxy_spec.rb | 3 +- spec/spec_helper_full.rb | 3 +- 39 files changed, 233 insertions(+), 156 deletions(-) diff --git a/examples/ruby-api/main.rb b/examples/ruby-api/main.rb index 2d83e680..b0fc2bd5 100644 --- a/examples/ruby-api/main.rb +++ b/examples/ruby-api/main.rb @@ -11,9 +11,9 @@ def validate_token(env) auth0_client_id = ENV['AUTH0_CLIENT_ID'] auth0_client_secret = ENV['AUTH0_CLIENT_SECRET'] authorization = env['HTTP_AUTHORIZATION'] - fail InvalidTokenError if authorization.nil? + raise InvalidTokenError if authorization.nil? decoded_token = JWT.decode(authorization.split(' ').last, JWT.base64url_decode(auth0_client_secret)) - fail InvalidTokenError if auth0_client_id != decoded_token[0]['aud'] + raise InvalidTokenError if auth0_client_id != decoded_token[0]['aud'] 'You get this only if authenticated' rescue JWT::DecodeError raise InvalidTokenError diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index 5607ebfd..af01ee88 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -32,8 +32,8 @@ def obtain_access_token(access_token = nil, connection = 'facebook', scope = 'op # Active Directory/LDAP, Windows Azure AD and ADF # @return [json] Returns the access token and id token def login(username, password, id_token = nil, connection_name = UP_AUTH, options = {}) - fail Auth0::InvalidParameter, 'Must supply a valid username' if username.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid password' if password.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid username' if username.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid password' if password.to_s.empty? request_params = { client_id: @client_id, username: username, @@ -54,8 +54,8 @@ def login(username, password, id_token = nil, connection_name = UP_AUTH, options # @param connection_name [string] Connection name. Works for database connections. # @return [json] Returns the created user def signup(email, password, connection_name = UP_AUTH) - fail Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid password' if password.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid password' if password.to_s.empty? request_params = { client_id: @client_id, email: email, @@ -72,7 +72,7 @@ def signup(email, password, connection_name = UP_AUTH) # @param password [string] User's new password # @param connection_name [string] Connection name. Works for database connections. def change_password(email, password, connection_name = UP_AUTH) - fail Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? request_params = { client_id: @client_id, email: email, @@ -88,7 +88,7 @@ def change_password(email, password, connection_name = UP_AUTH) # @param send [string] Defaults to 'link'. Can be 'code'. You can then authenticate with this user opening the link # @param auth_params [hash] Append/override parameters to the link (like scope, redirect_uri, protocol, etc.) def start_passwordless_email_flow(email, send = 'link', auth_params = {}) - fail Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? request_params = { client_id: @client_id, email: email, @@ -102,7 +102,7 @@ def start_passwordless_email_flow(email, send = 'link', auth_params = {}) # @see https://auth0.com/docs/auth-api#!#post--with_sms # @param phone_number [string] User's phone number. def start_passwordless_sms_flow(phone_number) - fail Auth0::InvalidParameter, 'Must supply a valid phone number' if phone_number.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid phone number' if phone_number.to_s.empty? request_params = { client_id: @client_id, connection: 'sms', @@ -117,8 +117,8 @@ def start_passwordless_sms_flow(phone_number) # @param code [string] Verification code. # @return [json] Returns the access token and id token def phone_login(phone_number, code, scope = 'openid') - fail Auth0::InvalidParameter, 'Must supply a valid phone number' if phone_number.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid code' if code.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid phone number' if phone_number.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid code' if code.to_s.empty? request_params = { client_id: @client_id, username: phone_number, @@ -135,7 +135,7 @@ def phone_login(phone_number, code, scope = 'openid') # @param client_id [string] Client id # @return [xml] SAML 2.0 metadata def saml_metadata(client_id) - fail Auth0::InvalidParameter, 'Must supply a valid client_id' if client_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid client_id' if client_id.to_s.empty? get("/samlp/metadata/#{client_id}") end @@ -151,7 +151,7 @@ def wsfed_metadata # @param id_token [string] Token's id. # @return User information associated with the user id (sub property) of the token. def token_info(id_token) - fail Auth0::InvalidParameter, 'Must supply a valid id_token' if id_token.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid id_token' if id_token.to_s.empty? request_params = { id_token: id_token } post('/tokeninfo', request_params) end @@ -166,7 +166,7 @@ def token_info(id_token) # @param extra_parameters [hash] Extra parameters. # @return [json] Returns the refreshed delegation token def refresh_delegation(refresh_token, target, scope = 'openid', api_type = 'app', extra_parameters = {}) - fail Auth0::InvalidParameter, 'Must supply a valid token to refresh' if refresh_token.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid token to refresh' if refresh_token.to_s.empty? request_params = { client_id: @client_id, grant_type: JWT_BEARER, @@ -188,7 +188,7 @@ def refresh_delegation(refresh_token, target, scope = 'openid', api_type = 'app' # @param extra_parameters [hash] Extra parameters. # @return [json] Returns the refreshed delegation token def delegation(id_token, target, scope = 'openid', api_type = 'app', extra_parameters = {}) - fail Auth0::InvalidParameter, 'Must supply a valid id_token' if id_token.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid id_token' if id_token.to_s.empty? request_params = { client_id: @client_id, grant_type: JWT_BEARER, @@ -206,8 +206,8 @@ def delegation(id_token, target, scope = 'openid', api_type = 'app', extra_param # @param options [string] Additional Parameters # @return [string] Impersonation URL def impersonate(user_id, options) - fail Auth0::InvalidParameter, 'Must supply a valid user_id' if user_id.to_s.empty? - fail Auth0::MissingParameter, 'Must supply client_secret' if @client_secret.nil? + raise Auth0::InvalidParameter, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::MissingParameter, 'Must supply client_secret' if @client_secret.nil? authorization_header obtain_access_token result = post("/users/#{user_id}/impersonate", impersonate_request_params(options)) authorization_header @token @@ -219,8 +219,8 @@ def impersonate(user_id, options) # @param access_token [string] Logged-in user access token # @param user_id [string] User Id def unlink_user(access_token, user_id) - fail Auth0::InvalidParameter, 'Must supply a valid access_token' if access_token.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid access_token' if access_token.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid user_id' if user_id.to_s.empty? request_params = { access_token: access_token, user_id: user_id @@ -241,7 +241,7 @@ def user_info # @param options [hash] Can contain response_type, connection, state and additional_parameters. # @return [url] Authorization URL. def authorization_url(redirect_uri, options = {}) - fail Auth0::InvalidParameter, 'Must supply a valid redirect_uri' if redirect_uri.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid redirect_uri' if redirect_uri.to_s.empty? request_params = { client_id: @client_id, response_type: options.fetch(:connection, 'code'), diff --git a/lib/auth0/api/v1/connections.rb b/lib/auth0/api/v1/connections.rb index a5af4818..cdee4395 100644 --- a/lib/auth0/api/v1/connections.rb +++ b/lib/auth0/api/v1/connections.rb @@ -30,7 +30,8 @@ def create_connection(connection_name, strategy, tenant_domain, domain_aliases = strategy: strategy, options: { tenant_domain: tenant_domain, - domain_aliases: domain_aliases } + domain_aliases: domain_aliases + } } post(path, request_params) end diff --git a/lib/auth0/api/v1/users.rb b/lib/auth0/api/v1/users.rb index 71a76e5a..02fc7d8c 100644 --- a/lib/auth0/api/v1/users.rb +++ b/lib/auth0/api/v1/users.rb @@ -142,7 +142,7 @@ def delete_users # {https://auth0.com/docs/api#!#delete--api-users--user_id-} def delete_user(user_id) - fail Auth0::MissingUserId, 'if you want to remove all users use delete_users method' if user_id.to_s.empty? + raise Auth0::MissingUserId, 'if you want to remove all users use delete_users method' if user_id.to_s.empty? path = "/api/users/#{user_id}" delete(path) end diff --git a/lib/auth0/api/v2/blacklists.rb b/lib/auth0/api/v2/blacklists.rb index 32ef51c7..3cadc57b 100644 --- a/lib/auth0/api/v2/blacklists.rb +++ b/lib/auth0/api/v2/blacklists.rb @@ -25,7 +25,7 @@ def blacklisted_tokens(aud = nil) # @return [json] Returns the blacklisted token # def add_token_to_blacklist(jti, aud = nil) - fail Auth0::MissingParameter, 'Must specify a valid JTI' if jti.to_s.empty? + raise Auth0::MissingParameter, 'Must specify a valid JTI' if jti.to_s.empty? request_params = { jti: jti, aud: aud diff --git a/lib/auth0/api/v2/clients.rb b/lib/auth0/api/v2/clients.rb index 638c4b3c..4eb35cce 100644 --- a/lib/auth0/api/v2/clients.rb +++ b/lib/auth0/api/v2/clients.rb @@ -27,7 +27,7 @@ def clients(fields: nil, include_fields: nil) # @param options [hash] The Hash options used to define the client's properties. # @return [json] Returns the created client application. def create_client(name, options = {}) - fail Auth0::MissingParameter, 'Must specify a valid client name' if name.to_s.empty? + raise Auth0::MissingParameter, 'Must specify a valid client name' if name.to_s.empty? request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] request_params[:name] = name post(clients_path, request_params) @@ -40,7 +40,7 @@ def create_client(name, options = {}) # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. # @return [json] Returns the requested client application. def client(client_id, fields: nil, include_fields: nil) - fail Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? + raise Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? include_fields = true if !fields.nil? && include_fields.nil? request_params = { fields: fields, @@ -54,7 +54,7 @@ def client(client_id, fields: nil, include_fields: nil) # @see https://auth0.com/docs/api/v2#!/Clients/delete_clients_by_id # @param client_id [string] The id of the client to delete. def delete_client(client_id) - fail Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? + raise Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? path = "#{clients_path}/#{client_id}" delete(path) end @@ -64,8 +64,8 @@ def delete_client(client_id) # @param client_id [string] The id of the client to update. # @param options [hash] The Hash options used to define the client's properties. def patch_client(client_id, options) - fail Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? - fail Auth0::MissingParameter, 'Must specify a valid body' if options.to_s.empty? + raise Auth0::MissingClientId, 'Must specify a client id' if client_id.to_s.empty? + raise Auth0::MissingParameter, 'Must specify a valid body' if options.to_s.empty? path = "#{clients_path}/#{client_id}" patch(path, options) end diff --git a/lib/auth0/api/v2/connections.rb b/lib/auth0/api/v2/connections.rb index 75ea7854..fb3b57d5 100644 --- a/lib/auth0/api/v2/connections.rb +++ b/lib/auth0/api/v2/connections.rb @@ -30,7 +30,7 @@ def connections(strategy: nil, fields: nil, include_fields: true) # # @return [json] Returns the created connection. def create_connection(body) - fail Auth0::InvalidParameter, 'Must specify a body to create a connection' if body.to_s.empty? + raise Auth0::InvalidParameter, 'Must specify a body to create a connection' if body.to_s.empty? request_params = body post(connections_path, request_params) end @@ -43,7 +43,7 @@ def create_connection(body) # # @return [json] Returns the matching connection. def connection(connection_id, fields: nil, include_fields: true) - fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? path = "#{connections_path}/#{connection_id}" request_params = { fields: fields, @@ -56,7 +56,7 @@ def connection(connection_id, fields: nil, include_fields: true) # @see https://auth0.com/docs/api/v2#!/Connections/delete_connections_by_id # @param connection_id [string] The id of the connection to delete. def delete_connection(connection_id) - fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? path = "#{connections_path}/#{connection_id}" delete(path) end @@ -67,8 +67,8 @@ def delete_connection(connection_id) # @param connection_id [string] The id of the connection. # @param user_email [string] The email of the user to delete. def delete_connection_user(connection_id, user_email) - fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid user email' if user_email.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid user email' if user_email.to_s.empty? path = "#{connections_path}/#{connection_id}/users?email=#{user_email}" delete(path) end @@ -80,7 +80,7 @@ def delete_connection_user(connection_id, user_email) # # @return [json] Returns the updated connection. def update_connection(connection_id, body) - fail Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid connection id' if connection_id.to_s.empty? path = "#{connections_path}/#{connection_id}" patch(path, body) end diff --git a/lib/auth0/api/v2/emails.rb b/lib/auth0/api/v2/emails.rb index 8e768276..2925d886 100644 --- a/lib/auth0/api/v2/emails.rb +++ b/lib/auth0/api/v2/emails.rb @@ -23,7 +23,7 @@ def get_provider(fields: nil, include_fields: nil) # @see https://auth0.com/docs/api/v2#!/Emails/post_provider # @param body [hash] The Hash options used to specify the email provider's properties. def configure_provider(body) - fail Auth0::InvalidParameter, 'Must supply a valid body to create an email provider' if body.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid body to create an email provider' if body.to_s.empty? post(email_path, body) end @@ -41,7 +41,7 @@ def delete_provider # # @return [json] Returns the updated email provider. def update_provider(body) - fail Auth0::InvalidParameter, 'Must supply a valid body to update an email provider' if body.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid body to update an email provider' if body.to_s.empty? patch(email_path, body) end diff --git a/lib/auth0/api/v2/jobs.rb b/lib/auth0/api/v2/jobs.rb index b384d68e..89c698e4 100644 --- a/lib/auth0/api/v2/jobs.rb +++ b/lib/auth0/api/v2/jobs.rb @@ -11,7 +11,7 @@ module Jobs # # @return [json] Returns the job status and properties. def get_job(job_id) - fail Auth0::InvalidParameter, 'Must specify a job id' if job_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must specify a job id' if job_id.to_s.empty? path = "#{jobs_path}/#{job_id}" get(path) end @@ -24,8 +24,8 @@ def get_job(job_id) # # @return [json] Returns the job status and properties. def import_users(users_file, connection_id) - fail Auth0::InvalidParameter, 'Must specify a valid file' if users_file.to_s.empty? - fail Auth0::InvalidParameter, 'Must specify a connection_id' if connection_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must specify a valid file' if users_file.to_s.empty? + raise Auth0::InvalidParameter, 'Must specify a connection_id' if connection_id.to_s.empty? request_params = { users: users_file, connection_id: connection_id @@ -40,7 +40,7 @@ def import_users(users_file, connection_id) # # @return [json] Returns the job status and properties. def send_verification_email(user_id) - fail Auth0::InvalidParameter, 'Must specify a user id' if user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must specify a user id' if user_id.to_s.empty? request_params = { user_id: user_id } diff --git a/lib/auth0/api/v2/resource_servers.rb b/lib/auth0/api/v2/resource_servers.rb index 3470323e..038184cd 100644 --- a/lib/auth0/api/v2/resource_servers.rb +++ b/lib/auth0/api/v2/resource_servers.rb @@ -11,7 +11,7 @@ module ResourceServers # # @return [json] Returns the resource server. def resource_server(resource_server_id) - fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? path = "#{resource_servers_path}/#{resource_server_id}" get(path) end @@ -31,9 +31,9 @@ def resource_server(resource_server_id) # # @return [json] Returns the resource server. def create_resource_server(identifier, options = {}) - fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if identifier.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid resource server id' if identifier.to_s.empty? if ['<', '>'].include?(options.fetch(:name, '')) - fail Auth0::InvalidParameter, 'Name must contain at least one character. Does not allow "<" or ">"' + raise Auth0::InvalidParameter, 'Name must contain at least one character. Does not allow "<" or ">"' end request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] request_params[:identifier] = identifier @@ -44,7 +44,7 @@ def create_resource_server(identifier, options = {}) # @see https://auth0.com/docs/api/management/v2#!/Resource_Servers/delete_resource_servers_by_id # @param resource_server_id [string] The id of the resource server to delete. def delete_resource_server(resource_server_id) - fail Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid resource server id' if resource_server_id.to_s.empty? path = "#{resource_servers_path}/#{resource_server_id}" delete(path) end diff --git a/lib/auth0/api/v2/rules.rb b/lib/auth0/api/v2/rules.rb index 04e91a4a..f14ccbcb 100644 --- a/lib/auth0/api/v2/rules.rb +++ b/lib/auth0/api/v2/rules.rb @@ -36,7 +36,7 @@ def rules(enabled: nil, fields: nil, include_fields: nil, stage: nil) # # @return [json] Returns the rule. def rule(rule_id, fields: nil, include_fields: nil) - fail Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? path = "#{rules_path}/#{rule_id}" request_params = { fields: fields, @@ -59,8 +59,8 @@ def rule(rule_id, fields: nil, include_fields: nil) # # @return [json] Returns the created rule. def create_rule(name, script, order = nil, enabled = true, stage = 'login_success') - fail Auth0::InvalidParameter, 'Must supply a valid name' if name.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid script' if script.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid name' if name.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid script' if script.to_s.empty? request_params = { name: name, enabled: enabled, @@ -78,7 +78,7 @@ def create_rule(name, script, order = nil, enabled = true, stage = 'login_succes # # @return [json] Returns the updated rule. def update_rule(rule_id, fields_to_update = {}) - fail Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? path = "#{rules_path}/#{rule_id}" patch(path, fields_to_update) @@ -88,7 +88,7 @@ def update_rule(rule_id, fields_to_update = {}) # @see https://auth0.com/docs/api/v2#!/Rules/delete_rules_by_id # @param rule_id [string] The id of the rule to delete. def delete_rule(rule_id) - fail Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid rule id' if rule_id.to_s.empty? path = "#{rules_path}/#{rule_id}" delete(path) end diff --git a/lib/auth0/api/v2/tenants.rb b/lib/auth0/api/v2/tenants.rb index 9dcf3809..7c71a7e3 100644 --- a/lib/auth0/api/v2/tenants.rb +++ b/lib/auth0/api/v2/tenants.rb @@ -25,7 +25,7 @@ def get_tenant_settings(fields: nil, include_fields: true) # # @return [json] Returns the updated tenant settings. def update_tenant_settings(body) - fail Auth0::InvalidParameter, 'Must supply a valid body to update tenant settings' if body.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid body to update tenant settings' if body.to_s.empty? patch(tenant_path, body) end diff --git a/lib/auth0/api/v2/tickets.rb b/lib/auth0/api/v2/tickets.rb index 464b438a..6af75117 100644 --- a/lib/auth0/api/v2/tickets.rb +++ b/lib/auth0/api/v2/tickets.rb @@ -13,7 +13,7 @@ module Tickets # @return [json] Returns the created ticket url. def post_email_verification(user_id, result_url: nil) if user_id.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid user id to post an email verification' + raise Auth0::InvalidParameter, 'Must supply a valid user id to post an email verification' end path = "#{tickets_path}/email-verification" request_params = { @@ -35,7 +35,7 @@ def post_email_verification(user_id, result_url: nil) # @return [json] Returns the created ticket url. def post_password_change(new_password, user_id: nil, result_url: nil, connection_id: nil, email: nil) if new_password.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid new password to post a password-change' + raise Auth0::InvalidParameter, 'Must supply a valid new password to post a password-change' end path = "#{tickets_path}/password-change" request_params = { diff --git a/lib/auth0/api/v2/users.rb b/lib/auth0/api/v2/users.rb index 726a894f..5e2dd782 100644 --- a/lib/auth0/api/v2/users.rb +++ b/lib/auth0/api/v2/users.rb @@ -62,7 +62,7 @@ def delete_users # # @return [json] Returns the user with the given user_id if it exists. def user(user_id, fields: nil, include_fields: true) - fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? path = "#{users_path}/#{user_id}" request_params = { fields: fields, @@ -75,7 +75,7 @@ def user(user_id, fields: nil, include_fields: true) # @see https://auth0.com/docs/api/v2#!/Users/delete_users_by_id # @param user_id [string] The user_id of the user to delete. def delete_user(user_id) - fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? path = "#{users_path}/#{user_id}" delete(path) end @@ -97,8 +97,8 @@ def delete_user(user_id) # # @return [json] Returns the updated user. def patch_user(user_id, body) - fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty? path = "#{users_path}/#{user_id}" patch(path, body) end @@ -108,8 +108,8 @@ def patch_user(user_id, body) # @param user_id [string] The user_id of the user to delete the multifactor provider from. # @param provider_name [string] The multifactor provider. Supported values 'duo' or 'google-authenticator'. def delete_user_provider(user_id, provider_name) - fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid provider name' if provider_name.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid provider name' if provider_name.to_s.empty? path = "#{users_path}/#{user_id}/multifactor/#{provider_name}" delete(path) end @@ -128,8 +128,8 @@ def delete_user_provider(user_id, provider_name) # # @return [json] Returns the new array of the primary account identities. def link_user_account(user_id, body) - fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid body' if body.to_s.empty? path = "#{users_path}/#{user_id}/identities" post(path, body) end @@ -142,9 +142,9 @@ def link_user_account(user_id, body) # # @return [json] Returns the array of the unlinked account identities. def unlink_users_account(user_id, provider, secondary_user_id) - fail Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? - fail Auth0::MissingUserId, 'Must supply a valid secondary user_id' if secondary_user_id.to_s.empty? - fail Auth0::InvalidParameter, 'Must supply a valid provider' if provider.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::MissingUserId, 'Must supply a valid secondary user_id' if secondary_user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid provider' if provider.to_s.empty? path = "#{users_path}/#{user_id}/identities/#{provider}/#{secondary_user_id}" delete(path) end diff --git a/lib/auth0/mixins/httparty_proxy.rb b/lib/auth0/mixins/httparty_proxy.rb index 8353702d..0e1aa0ac 100644 --- a/lib/auth0/mixins/httparty_proxy.rb +++ b/lib/auth0/mixins/httparty_proxy.rb @@ -17,12 +17,12 @@ module HTTPartyProxy end case result.code when 200...226 then safe_parse_json(result.body) - when 400 then fail Auth0::BadRequest, result.body - when 401 then fail Auth0::Unauthorized, result.body - when 403 then fail Auth0::AccessDenied, result.body - when 404 then fail Auth0::NotFound, result.body - when 500 then fail Auth0::ServerError, result.body - else fail Auth0::Unsupported, result.body + when 400 then raise Auth0::BadRequest, result.body + when 401 then raise Auth0::Unauthorized, result.body + when 403 then raise Auth0::AccessDenied, result.body + when 404 then raise Auth0::NotFound, result.body + when 500 then raise Auth0::ServerError, result.body + else raise Auth0::Unsupported, result.body end end end diff --git a/lib/auth0/mixins/initializer.rb b/lib/auth0/mixins/initializer.rb index 0d72b011..3b5fa740 100644 --- a/lib/auth0/mixins/initializer.rb +++ b/lib/auth0/mixins/initializer.rb @@ -29,13 +29,13 @@ def authorization_header(token) def initialize_api(options) api_v1?(options) ? initialize_v1(options) : initialize_v2(options) - fail InvalidCredentials, 'Must supply a valid API token' if @token.nil? + raise InvalidCredentials, 'Must supply a valid API token' if @token.nil? authorization_header(@token) end def base_url(options) @domain = options[:domain] || options[:namespace] - fail InvalidApiNamespace, 'Api namespace must supply an API domain' if @domain.to_s.empty? + raise InvalidApiNamespace, 'Api namespace must supply an API domain' if @domain.to_s.empty? "https://#{@domain}" end @@ -63,7 +63,7 @@ def initialize_v2(options) def initialize_v1(options) extend Auth0::Api::V1 @client_secret = options[:client_secret] - fail InvalidCredentials, 'Invalid API v1 client_id and client_secret' if @client_id.nil? || @client_secret.nil? + raise InvalidCredentials, 'Invalid API v1 client_id and client_secret' if @client_id.nil? || @client_secret.nil? @token = obtain_access_token end diff --git a/spec/integration/lib/auth0/api/v2/api_clients_spec.rb b/spec/integration/lib/auth0/api/v2/api_clients_spec.rb index 473be5ea..fac1e409 100644 --- a/spec/integration/lib/auth0/api/v2/api_clients_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_clients_spec.rb @@ -50,7 +50,8 @@ describe '.create_client' do it do expect(client.create_client(client_name, custom_login_page_on: false)).to( - include('name' => client_name, 'custom_login_page_on' => false)) + include('name' => client_name, 'custom_login_page_on' => false) + ) end it { expect { client.create_client('', custom_login_page_on: false) }.to raise_error(Auth0::MissingParameter) } end @@ -61,7 +62,9 @@ client.patch_client( existing_client['client_id'], custom_login_page_on: false, - sso: true)).to(include('custom_login_page_on' => false, 'sso' => true)) + sso: true + ) + ).to(include('custom_login_page_on' => false, 'sso' => true)) end it { expect { client.patch_client('', custom_login_page_on: false) }.to raise_error(Auth0::MissingClientId) } end diff --git a/spec/integration/lib/auth0/api/v2/api_connections_spec.rb b/spec/integration/lib/auth0/api/v2/api_connections_spec.rb index 9a190c98..eeea6002 100644 --- a/spec/integration/lib/auth0/api/v2/api_connections_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_connections_spec.rb @@ -25,7 +25,8 @@ it { expect(client.connections(strategy: strategy, fields: [:name].join(',')).first).to include('name') } it do expect(client.connections(strategy: strategy, fields: [:name].join(','), include_fields: false).first).to_not( - include('name')) + include('name') + ) end end end @@ -39,7 +40,8 @@ it { expect(client.connection(connection['id'], fields: [:name, :id].join(','))).to include('id', 'name') } it do expect(client.connection(connection['id'], fields: [:name, :id].join(','), include_fields: false)).to_not( - include('id', 'name')) + include('id', 'name') + ) end end end @@ -66,7 +68,8 @@ let(:options) { { username: new_name } } it do expect(client.update_connection(connection_to_update['id'], 'options' => options)['options']).to include( - 'username' => new_name) + 'username' => new_name + ) end end diff --git a/spec/integration/lib/auth0/api/v2/api_email_spec.rb b/spec/integration/lib/auth0/api/v2/api_email_spec.rb index b4aa1d22..8eecaf53 100644 --- a/spec/integration/lib/auth0/api/v2/api_email_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_email_spec.rb @@ -25,7 +25,8 @@ let!(:email_provider) { client.configure_provider(body) } it do expect(email_provider).to include( - 'name' => name, 'enabled' => enabled, 'credentials' => credentials, 'settings' => settings) + 'name' => name, 'enabled' => enabled, 'credentials' => credentials, 'settings' => settings + ) end end @@ -37,12 +38,15 @@ context '#filters' do it do expect( - client.get_provider(fields: [:name, :enabled, :credentials].join(','), include_fields: true)).to( - include('name', 'enabled', 'credentials')) + client.get_provider(fields: [:name, :enabled, :credentials].join(','), include_fields: true) + ).to( + include('name', 'enabled', 'credentials') + ) end it do expect( - client.get_provider(fields: [:enabled].join(','), include_fields: false).first).to_not(include('enabled')) + client.get_provider(fields: [:enabled].join(','), include_fields: false).first + ).to_not(include('enabled')) end end end @@ -58,9 +62,12 @@ end it do expect( - client.update_provider(update_body)).to( - include( - 'name' => update_name, 'enabled' => enabled, 'credentials' => credentials, 'settings' => update_settings)) + client.update_provider(update_body) + ).to( + include( + 'name' => update_name, 'enabled' => enabled, 'credentials' => credentials, 'settings' => update_settings + ) + ) end end diff --git a/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb b/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb index fb0e8f13..cdae84ef 100644 --- a/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_jobs_spec.rb @@ -17,8 +17,7 @@ 'user_metadata' => { 'theme' => 'light' } - } - ] + }] end let(:users_file) do File.new('temp.json', 'w+') { |f| f.write(file_content) } @@ -34,12 +33,14 @@ expect(imported_users).to include( 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, 'status' => 'pending', - 'type' => 'users_import') + 'type' => 'users_import' + ) end let(:import_job_id) { imported_users['id'] } it do expect(client.get_job(import_job_id)).to include( - 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, 'type' => 'users_import', 'id' => import_job_id) + 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, 'type' => 'users_import', 'id' => import_job_id + ) end end @@ -56,7 +57,8 @@ let(:email_job_id) { email_verification_job['id'] } it do expect(client.get_job(email_job_id)).to include( - 'status' => 'completed', 'type' => 'verification_email', 'id' => email_job_id) + 'status' => 'completed', 'type' => 'verification_email', 'id' => email_job_id + ) end end diff --git a/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb b/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb index ed08e085..047798b9 100644 --- a/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_resource_servers_spec.rb @@ -17,7 +17,8 @@ expect(client.resource_server(resource_server['id'])).to( include('identifier' => resource_server['identifier'], 'id' => resource_server['id'], 'signing_alg' => resource_server['signing_alg'], - 'token_lifetime' => resource_server['token_lifetime'])) + 'token_lifetime' => resource_server['token_lifetime']) + ) end end diff --git a/spec/integration/lib/auth0/api/v2/api_rules_spec.rb b/spec/integration/lib/auth0/api/v2/api_rules_spec.rb index 38cb66fb..45881079 100644 --- a/spec/integration/lib/auth0/api/v2/api_rules_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_rules_spec.rb @@ -44,7 +44,8 @@ describe '.rule' do it do expect(client.rule(enabled_rule['id'])).to( - include('stage' => enabled_rule['stage'], 'order' => enabled_rule['order'], 'script' => enabled_rule['script'])) + include('stage' => enabled_rule['stage'], 'order' => enabled_rule['order'], 'script' => enabled_rule['script']) + ) end context '#filters' do diff --git a/spec/integration/lib/auth0/api/v2/api_users_spec.rb b/spec/integration/lib/auth0/api/v2/api_users_spec.rb index 0c868077..5f74e653 100644 --- a/spec/integration/lib/auth0/api/v2/api_users_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_users_spec.rb @@ -51,7 +51,8 @@ context '#filters' do it do expect(client.user(user['user_id'], fields: [:picture, :email, :user_id].join(','))).to( - include('email', 'user_id', 'picture')) + include('email', 'user_id', 'picture') + ) end it { expect(client.user(user['user_id'], fields: [:email].join(','))).to_not include('user_id', 'picture') } end diff --git a/spec/integration/lib/auth0/auth0_client_spec.rb b/spec/integration/lib/auth0/auth0_client_spec.rb index 10eb1e19..6c1e9cdf 100644 --- a/spec/integration/lib/auth0/auth0_client_spec.rb +++ b/spec/integration/lib/auth0/auth0_client_spec.rb @@ -12,18 +12,23 @@ it_should_behave_like 'invalid credentials', { namespace: 'samples.auth0.com' }, Auth0::InvalidCredentials it_should_behave_like 'invalid credentials', { - namespace: 'samples.auth0.com', client_id: 'client_id' }, Auth0::InvalidCredentials + namespace: 'samples.auth0.com', client_id: 'client_id' + }, Auth0::InvalidCredentials it_should_behave_like 'invalid credentials', { - namespace: 'samples.auth0.com', client_secret: 'secret' }, Auth0::InvalidCredentials + namespace: 'samples.auth0.com', client_secret: 'secret' + }, Auth0::InvalidCredentials it_should_behave_like 'invalid credentials', { - namespace: 'samples.auth0.com', api_version: 2 }, Auth0::InvalidCredentials + namespace: 'samples.auth0.com', api_version: 2 + }, Auth0::InvalidCredentials it_should_behave_like 'invalid credentials', {} it_should_behave_like 'invalid credentials', api_version: 2 it_should_behave_like 'invalid credentials', api_version: 1 it_should_behave_like 'invalid credentials', { - client_id: 'client_id', client_secret: 'secret' }, Auth0::InvalidApiNamespace + client_id: 'client_id', client_secret: 'secret' + }, Auth0::InvalidApiNamespace it_should_behave_like 'invalid credentials', { - api_version: 2, token: 'token' }, Auth0::InvalidApiNamespace + api_version: 2, token: 'token' + }, Auth0::InvalidApiNamespace let(:valid_v1_credentials) do { client_id: ENV['CLIENT_ID'], diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index 7019fe44..054ee349 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -11,10 +11,12 @@ it { expect(@instance).to respond_to(:obtain_access_token) } it "is expected to make post request to '/oauth/token'" do allow(@instance).to receive(:post).with( - '/oauth/token', client_id: nil, client_secret: nil, grant_type: 'client_credentials') + '/oauth/token', client_id: nil, client_secret: nil, grant_type: 'client_credentials' + ) .and_return('access_token' => 'AccessToken') expect(@instance).to receive(:post).with( - '/oauth/token', client_id: nil, client_secret: nil, grant_type: 'client_credentials') + '/oauth/token', client_id: nil, client_secret: nil, grant_type: 'client_credentials' + ) expect(@instance.obtain_access_token).to eql 'AccessToken' end end @@ -23,10 +25,12 @@ it { expect(@instance).to respond_to(:obtain_access_token) } it "is expected to make post request to '/oauth/access_token'" do allow(@instance).to receive(:post).with( - '/oauth/access_token', client_id: nil, access_token: 'access_token', connection: 'facebook', scope: 'openid') + '/oauth/access_token', client_id: nil, access_token: 'access_token', connection: 'facebook', scope: 'openid' + ) .and_return('access_token' => 'AccessToken') expect(@instance).to receive(:post).with( - '/oauth/access_token', client_id: nil, access_token: 'access_token', connection: 'facebook', scope: 'openid') + '/oauth/access_token', client_id: nil, access_token: 'access_token', connection: 'facebook', scope: 'openid' + ) expect(@instance.obtain_access_token('access_token', 'facebook', 'openid')).to eql 'AccessToken' end end @@ -38,7 +42,8 @@ '/oauth/ro', client_id: nil, username: 'test@test.com', password: 'password', scope: 'openid', connection: 'Username-Password-Authentication', - grant_type: 'password', id_token: nil, device: nil) + grant_type: 'password', id_token: nil, device: nil + ) @instance.login('test@test.com', 'password') end it { expect { @instance.login('', '') }.to raise_error 'Must supply a valid username' } @@ -51,7 +56,8 @@ expect(@instance).to receive(:post).with( '/dbconnections/signup', client_id: nil, email: 'test@test.com', - password: 'password', connection: 'User') + password: 'password', connection: 'User' + ) @instance.signup('test@test.com', 'password', 'User') end it { expect { @instance.signup('', '') }.to raise_error 'Must supply a valid email' } @@ -64,7 +70,8 @@ expect(@instance).to receive(:post).with( '/dbconnections/change_password', client_id: nil, email: 'test@test.com', - password: 'password', connection: 'User') + password: 'password', connection: 'User' + ) @instance.change_password('test@test.com', 'password', 'User') end it { expect { @instance.change_password('', '', '') }.to raise_error 'Must supply a valid email' } @@ -81,7 +88,8 @@ auth_params: { scope: 'scope', protocol: 'protocol' - }) + } + ) @instance.start_passwordless_email_flow('test@test.com', 'link', scope: 'scope', protocol: 'protocol') end it { expect { @instance.start_passwordless_email_flow('', '', '') }.to raise_error 'Must supply a valid email' } @@ -95,7 +103,8 @@ '/passwordless/start', client_id: nil, connection: 'sms', - phone_number: phone_number) + phone_number: phone_number + ) @instance.start_passwordless_sms_flow(phone_number) end it { expect { @instance.start_passwordless_sms_flow('') }.to raise_error 'Must supply a valid phone number' } @@ -110,7 +119,8 @@ '/oauth/ro', client_id: nil, username: phone_number, password: code, connection: 'sms', - scope: 'openid', grant_type: 'password') + scope: 'openid', grant_type: 'password' + ) @instance.phone_login(phone_number, code) end it { expect { @instance.phone_login('', '') }.to raise_error 'Must supply a valid phone number' } @@ -140,17 +150,20 @@ it { expect(@instance).to respond_to(:authorization_url) } it 'is expected to return an authorization url' do expect(@instance.authorization_url(redirect_url).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}") + "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}" + ) end let(:additional_parameters) { { additional_parameters: { aparam1: 'test1' } } } it 'is expected to return an authorization url with additionalParameters' do expect(@instance.authorization_url(redirect_url, additional_parameters).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&aparam1=test1") + "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&aparam1=test1" + ) end let(:state) { { state: 'state1' } } it 'is expected to return an authorization url with additionalParameters' do expect(@instance.authorization_url(redirect_url, state).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&state=state1") + "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&state=state1" + ) end it { expect { @instance.authorization_url('', '') }.to raise_error 'Must supply a valid redirect_uri' } end @@ -171,7 +184,8 @@ client_id: nil, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', refresh_token: 'id_token', target: '', api_type: '', scope: '', - additional_parameter: 'parameter') + additional_parameter: 'parameter' + ) @instance.refresh_delegation('id_token', '', '', '', additional_parameter: 'parameter') end it { expect { @instance.refresh_delegation('', '', '', '') }.to raise_error 'Must supply a valid token to refresh' } @@ -187,7 +201,8 @@ id_token: 'token', target: 'target', scope: '', - api_type: 'app') + api_type: 'app' + ) @instance.delegation('token', 'target', '') end it "is expected to make post request to '/delegation' @@ -197,7 +212,8 @@ client_id: nil, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', id_token: 'id_token', target: '', scope: '', - api_type: 'salesforce_api') + api_type: 'salesforce_api' + ) @instance.delegation('id_token', '', '', 'salesforce_api') end it 'allows to pass extra parameters' do @@ -206,10 +222,12 @@ client_id: nil, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', id_token: 'id_token', target: '', scope: '', api_type: '', - community_name: 'test-community', community_url: 'test-url') + community_name: 'test-community', community_url: 'test-url' + ) @instance.delegation( 'id_token', '', '', '', - community_name: 'test-community', community_url: 'test-url') + community_name: 'test-community', community_url: 'test-url' + ) end it { expect { @instance.delegation('', nil, nil, nil) }.to raise_error 'Must supply a valid id_token' } end @@ -229,7 +247,8 @@ # end it do expect { @instance.impersonate(user_id, {}) }.to raise_error( - 'Must supply client_secret') + 'Must supply client_secret' + ) end it { expect { @instance.impersonate('', '') }.to raise_error 'Must supply a valid user_id' } end @@ -257,7 +276,8 @@ it { expect(@instance).to respond_to(:logout_url) } it 'is expected to return a logout url' do expect(@instance.logout_url(return_to).to_s).to eq( - "https://#{@instance.domain}/logout?returnTo=#{return_to}") + "https://#{@instance.domain}/logout?returnTo=#{return_to}" + ) end end @@ -265,11 +285,13 @@ it { expect(@instance).to respond_to(:samlp_url) } it 'is expected to get the samlp url' do expect(@instance.samlp_url.to_s).to eq( - "https://#{@instance.domain}/samlp/?connection=Username-Password-Authentication") + "https://#{@instance.domain}/samlp/?connection=Username-Password-Authentication" + ) end it 'is expected to get the samlp url with fb connection' do expect(@instance.samlp_url('facebook').to_s).to eq( - "https://#{@instance.domain}/samlp/?connection=facebook") + "https://#{@instance.domain}/samlp/?connection=facebook" + ) end end @@ -277,11 +299,13 @@ it { expect(@instance).to respond_to(:wsfed_url) } it 'is expected to get the wsfed url' do expect(@instance.wsfed_url.to_s).to eq( - "https://#{@instance.domain}/wsfed/?whr=Username-Password-Authentication") + "https://#{@instance.domain}/wsfed/?whr=Username-Password-Authentication" + ) end it 'is expected to get the wsfed url with fb connection' do expect(@instance.wsfed_url('facebook').to_s).to eq( - "https://#{@instance.domain}/wsfed/?whr=facebook") + "https://#{@instance.domain}/wsfed/?whr=facebook" + ) end end end diff --git a/spec/lib/auth0/api/v1/connections_spec.rb b/spec/lib/auth0/api/v1/connections_spec.rb index 850295a8..99ffddd8 100644 --- a/spec/lib/auth0/api/v1/connections_spec.rb +++ b/spec/lib/auth0/api/v1/connections_spec.rb @@ -40,8 +40,7 @@ options: { tenant_domain: 'google.com', domain_aliases: 'test.google.com,auth0.com' - } - } + } } expect(@instance).to receive(:post).with('/api/connections', params) expect do @instance.create_connection( @@ -59,8 +58,7 @@ params = { status: false, options: { tenant_domain: 'google.com' - } - } + } } expect(@instance).to receive(:put).with('/api/connections/TestName', params) expect { @instance.update_connection('TestName', 'google.com', false) }.not_to raise_error end diff --git a/spec/lib/auth0/api/v1/rules_spec.rb b/spec/lib/auth0/api/v1/rules_spec.rb index a1274a82..faa25a6a 100644 --- a/spec/lib/auth0/api/v1/rules_spec.rb +++ b/spec/lib/auth0/api/v1/rules_spec.rb @@ -20,7 +20,8 @@ it 'is expected to call post /api/rules' do expect(@instance).to receive(:post).with( '/api/rules', - name: 'test', script: 'script', order: 'order', status: 'status') + name: 'test', script: 'script', order: 'order', status: 'status' + ) expect { @instance.create_rule('test', 'script', 'order', 'status') }.not_to raise_error end end diff --git a/spec/lib/auth0/api/v1/users_spec.rb b/spec/lib/auth0/api/v1/users_spec.rb index b1fad0db..8c01e7be 100644 --- a/spec/lib/auth0/api/v1/users_spec.rb +++ b/spec/lib/auth0/api/v1/users_spec.rb @@ -101,7 +101,8 @@ '/api/users', email: 'test@test.com', password: 'password', - connection: 'conn') + connection: 'conn' + ) @instance.create_user('test@test.com', 'password', 'conn') end end @@ -120,7 +121,8 @@ password = SecureRandom.hex expect(@instance).to receive(:post).with( '/api/users/USERID/change_password_ticket', - 'newPassword' => password, 'resultUrl' => nil) + 'newPassword' => password, 'resultUrl' => nil + ) @instance.change_password_ticket 'USERID', password end end @@ -130,14 +132,16 @@ it 'is expected to call post to /api/users/userId/verification_ticket if resulturl is set' do expect(@instance).to receive(:post).with( '/api/users/auth0|tdasfasdfasdfa/verification_ticket', - 'resultUrl' => 'google.com') + 'resultUrl' => 'google.com' + ) @instance.verification_ticket('auth0|tdasfasdfasdfa', 'google.com') end it 'is expected to call post to /api/users/userId/verification_ticket if result url is empty' do expect(@instance).to receive(:post).with( '/api/users/auth0|tdasfasdfasdfa/verification_ticket', - 'resultUrl' => nil) + 'resultUrl' => nil + ) @instance.verification_ticket('auth0|tdasfasdfasdfa') end end @@ -147,7 +151,8 @@ it 'is expected to call post to /api/users/userId/public_key' do expect(@instance).to receive(:post).with( '/api/users/auth0|tdasfasdfasdfa/public_key', - device: 'device22', public_key: 'SuperSecurePK') + device: 'device22', public_key: 'SuperSecurePK' + ) @instance.create_public_key('auth0|tdasfasdfasdfa', 'device22', 'SuperSecurePK') end end @@ -174,7 +179,8 @@ expect(@instance).to receive(:put).with( '/api/users/auth0|tdasfasdfasdfa/password', password: 'password', - verify: true) + verify: true + ) @instance.update_user_password('auth0|tdasfasdfasdfa', 'password') end end @@ -187,9 +193,11 @@ email: 'email@email.com', password: 'password', connection: 'Con', - verify: true) + verify: true + ) @instance.update_user_password_using_email( - 'email@email.com', 'password', 'Con') + 'email@email.com', 'password', 'Con' + ) end end diff --git a/spec/lib/auth0/api/v2/connections_spec.rb b/spec/lib/auth0/api/v2/connections_spec.rb index 2e54a5a6..eb6ca950 100644 --- a/spec/lib/auth0/api/v2/connections_spec.rb +++ b/spec/lib/auth0/api/v2/connections_spec.rb @@ -15,7 +15,8 @@ '/api/v2/connections', strategy: nil, fields: nil, - include_fields: true) + include_fields: true + ) expect { @instance.connections }.not_to raise_error end end diff --git a/spec/lib/auth0/api/v2/jobs_spec.rb b/spec/lib/auth0/api/v2/jobs_spec.rb index f224b76a..de3108de 100644 --- a/spec/lib/auth0/api/v2/jobs_spec.rb +++ b/spec/lib/auth0/api/v2/jobs_spec.rb @@ -17,7 +17,8 @@ it { expect(@instance).to respond_to(:import_users) } it 'expect client to send post to /api/v2/jobs/users-imports' do expect(@instance).to receive(:post_file).with( - '/api/v2/jobs/users-imports', users: 'file', connection_id: 'connnection_id') + '/api/v2/jobs/users-imports', users: 'file', connection_id: 'connnection_id' + ) expect { @instance.import_users('file', 'connnection_id') }.not_to raise_error end it { expect { @instance.import_users('', 'connnection_id') }.to raise_error('Must specify a valid file') } diff --git a/spec/lib/auth0/api/v2/logs_spec.rb b/spec/lib/auth0/api/v2/logs_spec.rb index 6a95c58a..d8383a14 100644 --- a/spec/lib/auth0/api/v2/logs_spec.rb +++ b/spec/lib/auth0/api/v2/logs_spec.rb @@ -20,7 +20,8 @@ include_fields: nil, include_totals: nil, from: nil, - take: nil) + take: nil + ) expect { @instance.logs }.not_to raise_error end it 'is expect to rise an error when take is higher than 100' do diff --git a/spec/lib/auth0/api/v2/resource_servers_spec.rb b/spec/lib/auth0/api/v2/resource_servers_spec.rb index b1dab2ff..f3a5116b 100644 --- a/spec/lib/auth0/api/v2/resource_servers_spec.rb +++ b/spec/lib/auth0/api/v2/resource_servers_spec.rb @@ -28,7 +28,8 @@ signing_alg: 'signing_alg', signing_secret: 'signing_secret', token_lifetime: 'token_lifetime', - scopes: 'scopes') + scopes: 'scopes' + ) @instance.create_resource_server('test', name: 'name', signing_alg: 'signing_alg', @@ -41,9 +42,11 @@ end it 'expect to raise an error when name contains < or > characters' do expect { @instance.create_resource_server('test', name: '<') }.to raise_error( - 'Name must contain at least one character. Does not allow "<" or ">"') + 'Name must contain at least one character. Does not allow "<" or ">"' + ) expect { @instance.create_resource_server('test', name: '>') }.to raise_error( - 'Name must contain at least one character. Does not allow "<" or ">"') + 'Name must contain at least one character. Does not allow "<" or ">"' + ) end end diff --git a/spec/lib/auth0/api/v2/rules_spec.rb b/spec/lib/auth0/api/v2/rules_spec.rb index 3148d49b..ba587f67 100644 --- a/spec/lib/auth0/api/v2/rules_spec.rb +++ b/spec/lib/auth0/api/v2/rules_spec.rb @@ -11,7 +11,8 @@ it { expect(@instance).to respond_to(:rules) } it 'is expected to call get /api/v2/rules' do expect(@instance).to receive(:get).with( - '/api/v2/rules', enabled: nil, fields: nil, include_fields: nil, stage: nil) + '/api/v2/rules', enabled: nil, fields: nil, include_fields: nil, stage: nil + ) expect { @instance.rules }.not_to raise_error end end @@ -20,7 +21,8 @@ it { expect(@instance).to respond_to(:rule) } it 'is expected to call get /api/v2/rules/test' do expect(@instance).to receive(:get).with( - '/api/v2/rules/test', fields: nil, include_fields: nil) + '/api/v2/rules/test', fields: nil, include_fields: nil + ) expect { @instance.rule('test') }.not_to raise_error end it 'expect to raise an error when calling with empty rule id' do @@ -33,7 +35,8 @@ it 'is expected to call post /api/v2/rules' do expect(@instance).to receive(:post).with( '/api/v2/rules', - name: 'test', script: 'script', order: 'order', enabled: false, stage: 'login_success') + name: 'test', script: 'script', order: 'order', enabled: false, stage: 'login_success' + ) expect { @instance.create_rule('test', 'script', 'order', false) }.not_to raise_error end it 'expect to raise an error when calling with empty name' do @@ -47,7 +50,8 @@ it { expect(@instance).to respond_to(:update_rule) } it 'is expected to call put /api/v2/rules/test' do expect(@instance).to receive(:patch).with( - '/api/v2/rules/test', script: 'script', order: 'order', enabled: true, stage: 'some_stage') + '/api/v2/rules/test', script: 'script', order: 'order', enabled: true, stage: 'some_stage' + ) expect do @instance.update_rule('test', script: 'script', order: 'order', enabled: true, stage: 'some_stage') end.not_to raise_error diff --git a/spec/lib/auth0/api/v2/tenants_spec.rb b/spec/lib/auth0/api/v2/tenants_spec.rb index 7085b579..55c212e5 100644 --- a/spec/lib/auth0/api/v2/tenants_spec.rb +++ b/spec/lib/auth0/api/v2/tenants_spec.rb @@ -19,7 +19,8 @@ end it 'expect client to rasie error when calling with empty body' do expect { @instance.update_tenant_settings(nil) }.to raise_error( - 'Must supply a valid body to update tenant settings') + 'Must supply a valid body to update tenant settings' + ) end end end diff --git a/spec/lib/auth0/api/v2/tickets_spec.rb b/spec/lib/auth0/api/v2/tickets_spec.rb index e5f93237..3cab1d32 100644 --- a/spec/lib/auth0/api/v2/tickets_spec.rb +++ b/spec/lib/auth0/api/v2/tickets_spec.rb @@ -12,7 +12,8 @@ end it 'expect client to rasie error when calling with empty body' do expect { @instance.post_email_verification(nil) }.to raise_error( - 'Must supply a valid user id to post an email verification') + 'Must supply a valid user id to post an email verification' + ) end end context '.post_password_change' do @@ -25,7 +26,8 @@ end it 'expect client to rasie error when calling with empty body' do expect { @instance.post_password_change(nil) }.to raise_error( - 'Must supply a valid new password to post a password-change') + 'Must supply a valid new password to post a password-change' + ) end end end diff --git a/spec/lib/auth0/api/v2/users_spec.rb b/spec/lib/auth0/api/v2/users_spec.rb index dadf9bb3..9505d141 100644 --- a/spec/lib/auth0/api/v2/users_spec.rb +++ b/spec/lib/auth0/api/v2/users_spec.rb @@ -19,7 +19,8 @@ connection: nil, fields: nil, include_fields: nil, - q: nil) + q: nil + ) expect { @instance.users }.not_to raise_error end end @@ -41,12 +42,14 @@ email: 'test@test.com', password: 'password', connection: 'conn', - name: 'name') + name: 'name' + ) @instance.create_user( 'name', email: 'test@test.com', password: 'password', - connection: 'conn') + connection: 'conn' + ) end end @@ -68,7 +71,8 @@ it 'is expected not to call delete to /api/v2/users if user_id is blank' do expect(@instance).not_to receive(:delete) expect { @instance.delete_user('') }.to raise_exception( - Auth0::MissingUserId) + Auth0::MissingUserId + ) end end @@ -88,13 +92,15 @@ email: 'test@test.com', password: 'password', connection: 'conn', - name: 'name') + name: 'name' + ) @instance.patch_user( 'UserID', email: 'test@test.com', password: 'password', connection: 'conn', - name: 'name') + name: 'name' + ) end it { expect { @instance.patch_user('', 'body') }.to raise_error 'Must supply a valid user_id' } it { expect { @instance.patch_user('UserId', '') }.to raise_error 'Must supply a valid body' } diff --git a/spec/lib/auth0/client_spec.rb b/spec/lib/auth0/client_spec.rb index eb2a11c0..6aa5e667 100644 --- a/spec/lib/auth0/client_spec.rb +++ b/spec/lib/auth0/client_spec.rb @@ -70,7 +70,8 @@ client_id: 'client_id', client_secret: 'client_secret', domain: 'samples.auth0.com', - api_version: 1) + api_version: 1 + ) end it_should_behave_like 'v1 API client' it_should_behave_like 'authentication API client' diff --git a/spec/lib/auth0/mixins/httparty_proxy_spec.rb b/spec/lib/auth0/mixins/httparty_proxy_spec.rb index e7d71993..facd4543 100644 --- a/spec/lib/auth0/mixins/httparty_proxy_spec.rb +++ b/spec/lib/auth0/mixins/httparty_proxy_spec.rb @@ -55,7 +55,8 @@ expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) .and_return(StubResponse.new({}, false, 400)) expect { @instance.send(http_method, '/test') }.to raise_error( - Auth0::BadRequest) + Auth0::BadRequest + ) end it "should raise Auth0::AccessDenied on send http #{http_method} method diff --git a/spec/spec_helper_full.rb b/spec/spec_helper_full.rb index 3c27d27b..33504920 100644 --- a/spec/spec_helper_full.rb +++ b/spec/spec_helper_full.rb @@ -33,7 +33,8 @@ def entity_suffix config.after(:suite) do puts "Cleaning up for #{entity_suffix}" v2_client = Auth0Client.new( - token: ENV['MASTER_JWT'], api_version: 2, domain: ENV['DOMAIN']) + token: ENV['MASTER_JWT'], api_version: 2, domain: ENV['DOMAIN'] + ) v2_client .clients .select { |client| client['name'] != 'DefaultApp' && !client['global'] && client['name'].include?(entity_suffix) } From a017ff70016bdea76a3bee913479616a52e2e654 Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Wed, 15 Jun 2016 12:32:46 -0300 Subject: [PATCH 15/36] Add checks for per_page and sort parameters --- lib/auth0/api/v2/users.rb | 8 ++++++++ spec/lib/auth0/api/v2/users_spec.rb | 10 ++++++++++ 2 files changed, 18 insertions(+) diff --git a/lib/auth0/api/v2/users.rb b/lib/auth0/api/v2/users.rb index 5e2dd782..f43cda0b 100644 --- a/lib/auth0/api/v2/users.rb +++ b/lib/auth0/api/v2/users.rb @@ -158,6 +158,7 @@ def unlink_users_account(user_id, provider, secondary_user_id) # @param sort [string] The field to use for sorting. 1 == ascending and -1 == descending. # # @return [json] Returns the list of existing log entries for the given user_id. + # rubocop:disable Metrics/MethodLength, Metrics/AbcSize def user_logs(user_id, options = {}) raise Auth0::MissingUserId, 'Must supply a valid user_id' if user_id.to_s.empty? path = "#{users_path}/#{user_id}/logs" @@ -168,6 +169,13 @@ def user_logs(user_id, options = {}) include_totals: options.fetch(:include_totals, nil), sort: options.fetch(:sort, nil) } + if request_params[:per_page].to_i > 100 + raise Auth0::InvalidParameter, 'The total amount of entries per page should be less than 100' + end + sort_pattern = /^(([a-zA-Z0-9_\.]+))\:(1|-1)$/ + if !request_params[:sort].nil? && !sort_pattern.match(request_params[:sort]) + raise Auth0::InvalidParameter, 'Sort does not match pattern ^(([a-zA-Z0-9_\\.]+))\\:(1|-1)$' + end get(path, request_params) end alias get_user_log_events user_logs diff --git a/spec/lib/auth0/api/v2/users_spec.rb b/spec/lib/auth0/api/v2/users_spec.rb index 9505d141..cfb1c06e 100644 --- a/spec/lib/auth0/api/v2/users_spec.rb +++ b/spec/lib/auth0/api/v2/users_spec.rb @@ -153,5 +153,15 @@ expect { @instance.user_logs('USER_ID') }.not_to raise_error end it { expect { @instance.user_logs('') }.to raise_error 'Must supply a valid user_id' } + it 'is expected to raise an error when per_page is higher than 100' do + expect { @instance.user_logs('USER_ID', per_page: rand(101..2000)) }.to raise_error( + 'The total amount of entries per page should be less than 100' + ) + end + it 'is expected to raise an error when sort does not match pattern' do + expect { @instance.user_logs('USER_ID', sort: 'no match') }.to raise_error( + 'Sort does not match pattern ^(([a-zA-Z0-9_\\.]+))\\:(1|-1)$' + ) + end end end From b1662be6e2cf63887a48e863a0675a77c4445f79 Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Tue, 14 Jun 2016 17:20:05 -0300 Subject: [PATCH 16/36] Add client grants endpoints with corresponding unit and integration tests --- lib/auth0/api/v2.rb | 2 + lib/auth0/api/v2/client_grants.rb | 57 +++++++++++++++++++ .../auth0/api/v2/api_client_grants_spec.rb | 53 +++++++++++++++++ spec/lib/auth0/api/v2/client_grants_spec.rb | 44 ++++++++++++++ 4 files changed, 156 insertions(+) create mode 100644 lib/auth0/api/v2/client_grants.rb create mode 100644 spec/integration/lib/auth0/api/v2/api_client_grants_spec.rb create mode 100644 spec/lib/auth0/api/v2/client_grants_spec.rb diff --git a/lib/auth0/api/v2.rb b/lib/auth0/api/v2.rb index b66b6767..439a1ab1 100644 --- a/lib/auth0/api/v2.rb +++ b/lib/auth0/api/v2.rb @@ -1,5 +1,6 @@ require 'auth0/api/v2/blacklists' require 'auth0/api/v2/clients' +require 'auth0/api/v2/client_grants' require 'auth0/api/v2/connections' require 'auth0/api/v2/emails' require 'auth0/api/v2/jobs' @@ -17,6 +18,7 @@ module Api module V2 include Auth0::Api::V2::Blacklists include Auth0::Api::V2::Clients + include Auth0::Api::V2::ClientGrants include Auth0::Api::V2::Connections include Auth0::Api::V2::Emails include Auth0::Api::V2::Jobs diff --git a/lib/auth0/api/v2/client_grants.rb b/lib/auth0/api/v2/client_grants.rb new file mode 100644 index 00000000..26f64be4 --- /dev/null +++ b/lib/auth0/api/v2/client_grants.rb @@ -0,0 +1,57 @@ +module Auth0 + module Api + module V2 + # Methods to use the client grants endpoints + module ClientGrants + attr_reader :client_grants_path + + # Retrieves a list of all client grants. + # @see https://auth0.com/docs/api/management/v2#!/client_grants/get_client_grants + # + # @return [json] Returns the client grants. + def client_grants + get(client_grants_path) + end + alias get_all_client_grants client_grants + + # Creates a new client grant. + # @see https://auth0.com/docs/api/management/v2#!/client_grants/post_client_grants + # @param options [hash] The Hash options used to define the client grant's properties. + # + # @return [json] Returns the created client grant. + def create_client_grant(options = {}) + request_params = Hash[options.map { |(k, v)| [k.to_sym, v] }] + post(client_grants_path, request_params) + end + + # Deletes a client grant given its id. + # @see https://auth0.com/docs/api/management/v2#!/client_grants/delete_client_grants_by_id + # @param client_id [string] The id of the client grant to delete. + def delete_client_grant(client_grant_id) + raise Auth0::InvalidParameter, 'Must specify a client grant id' if client_grant_id.to_s.empty? + path = "#{client_grants_path}/#{client_grant_id}" + delete(path) + end + + # Updates a client grant. + # @see https://auth0.com/docs/api/management/v2#!/client_grants/patch_client_grants_by_id + # @param client_id [string] The id of the client grant to update. + # @param options [hash] The Hash options used to define the client grant's properties. + def patch_client_grant(client_grant_id, options) + raise Auth0::InvalidParameter, 'Must specify a client grant id' if client_grant_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must specify a valid body' if options.to_s.empty? + path = "#{client_grants_path}/#{client_grant_id}" + patch(path, options) + end + alias update_client_grant patch_client_grant + + private + + # Client Grants API path + def client_grants_path + @client_grants_path ||= '/api/v2/client-grants' + end + end + end + end +end diff --git a/spec/integration/lib/auth0/api/v2/api_client_grants_spec.rb b/spec/integration/lib/auth0/api/v2/api_client_grants_spec.rb new file mode 100644 index 00000000..2dfd4639 --- /dev/null +++ b/spec/integration/lib/auth0/api/v2/api_client_grants_spec.rb @@ -0,0 +1,53 @@ +require 'spec_helper' +describe Auth0::Api::V2::ClientGrants do + attr_reader :client, :client_id, :audience, :existing_grant, :scope + + before(:all) do + @client = Auth0Client.new(v2_creds) + @client_id = Faker::Lorem.word + @audience = Faker::Internet.url + @scope = [Faker::Lorem.word] + @existing_grant = client.create_client_grant('client_id' => client_id, 'audience' => audience, 'scope' => scope) + end + + after(:all) do + grants = client.client_grants + grants.each do |grant| + client.delete_client_grant(grant['id']) + end + end + + describe '.client_grants' do + let(:client_grants) { client.client_grants } + + it { expect(client_grants.size).to be > 0 } + it { expect(client_grants).to include(existing_grant) } + end + + describe '.create_client_grant' do + let(:new_client) { Faker::Lorem.word } + + it do + expect( + client.create_client_grant('client_id' => new_client, 'audience' => audience, + 'scope' => scope) + ).to(include('client_id' => new_client, 'audience' => audience, 'scope' => scope)) + end + end + + describe '.patch_client_grant' do + let(:new_scope) { [Faker::Lorem.word] } + it do + expect( + client.patch_client_grant( + existing_grant['id'], + 'scope' => new_scope + ) + ).to(include('scope' => new_scope)) + end + end + + describe '.delete_client_grant' do + it { expect { client.delete_client_grant(existing_grant['id']) }.to_not raise_error } + end +end diff --git a/spec/lib/auth0/api/v2/client_grants_spec.rb b/spec/lib/auth0/api/v2/client_grants_spec.rb new file mode 100644 index 00000000..d5f832ef --- /dev/null +++ b/spec/lib/auth0/api/v2/client_grants_spec.rb @@ -0,0 +1,44 @@ +require 'spec_helper' +describe Auth0::Api::V2::ClientGrants do + before :all do + dummy_instance = DummyClass.new + dummy_instance.extend(Auth0::Api::V2::ClientGrants) + @instance = dummy_instance + end + context '.client_grants' do + it { expect(@instance).to respond_to(:client_grants) } + it { expect(@instance).to respond_to(:get_all_client_grants) } + it 'is expected to send get request to /api/v2/client_grants/' do + expect(@instance).to receive(:get).with('/api/v2/client-grants') + expect { @instance.client_grants }.not_to raise_error + end + end + + context '.create_client_grant' do + it { expect(@instance).to respond_to(:create_client_grant) } + it 'is expected to send post to /api/v2/client-grants' do + expect(@instance).to receive(:post).with('/api/v2/client-grants', opt: 'test body') + expect { @instance.create_client_grant(opt: 'test body') }.not_to raise_error + end + end + + context '.delete_client_grant' do + it { expect(@instance).to respond_to(:delete_client_grant) } + it 'is expected to send delete to /api/v2/client-grants/1' do + expect(@instance).to receive(:delete).with('/api/v2/client-grants/1') + expect { @instance.delete_client_grant('1') }.not_to raise_error + end + it { expect { @instance.delete_client_grant('') }.to raise_error 'Must specify a client grant id' } + end + + context '.patch_client_grant' do + it { expect(@instance).to respond_to(:patch_client_grant) } + it { expect(@instance).to respond_to(:update_client_grant) } + it 'is expected to send patch to /api/v2/client-grants/1' do + expect(@instance).to receive(:patch).with('/api/v2/client-grants/1', 'test body') + expect { @instance.patch_client_grant('1', 'test body') }.not_to raise_error + end + it { expect { @instance.patch_client_grant('', nil) }.to raise_error 'Must specify a client grant id' } + it { expect { @instance.patch_client_grant('some', nil) }.to raise_error 'Must specify a valid body' } + end +end From 0d23fd3b8c35e491f6b0b60456f2211d4eab6afc Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Thu, 9 Jun 2016 12:55:08 -0300 Subject: [PATCH 17/36] Add User Blocks endpoints --- lib/auth0/api/v2.rb | 2 + lib/auth0/api/v2/user_blocks.rb | 57 ++++++++++++++++++ .../lib/auth0/api/v2/api_user_blocks_spec.rb | 60 +++++++++++++++++++ spec/lib/auth0/api/v2/user_blocks_spec.rb | 52 ++++++++++++++++ spec/support/credentials.rb | 3 +- 5 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 lib/auth0/api/v2/user_blocks.rb create mode 100644 spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb create mode 100644 spec/lib/auth0/api/v2/user_blocks_spec.rb diff --git a/lib/auth0/api/v2.rb b/lib/auth0/api/v2.rb index 439a1ab1..5e50f0e9 100644 --- a/lib/auth0/api/v2.rb +++ b/lib/auth0/api/v2.rb @@ -7,6 +7,7 @@ require 'auth0/api/v2/rules' require 'auth0/api/v2/stats' require 'auth0/api/v2/users' +require 'auth0/api/v2/user_blocks' require 'auth0/api/v2/tenants' require 'auth0/api/v2/tickets' require 'auth0/api/v2/logs' @@ -25,6 +26,7 @@ module V2 include Auth0::Api::V2::Rules include Auth0::Api::V2::Stats include Auth0::Api::V2::Users + include Auth0::Api::V2::UserBlocks include Auth0::Api::V2::Tenants include Auth0::Api::V2::Tickets include Auth0::Api::V2::Logs diff --git a/lib/auth0/api/v2/user_blocks.rb b/lib/auth0/api/v2/user_blocks.rb new file mode 100644 index 00000000..225ffbad --- /dev/null +++ b/lib/auth0/api/v2/user_blocks.rb @@ -0,0 +1,57 @@ +module Auth0 + module Api + module V2 + # Methods to use the User Blocks endpoints + module UserBlocks + attr_reader :user_blocks_path + + # Retrieves the user blocks + # @see https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks + # @param identifier [string] Should be any of: username, phone_number, email. + # + # @return [json] the user blocks + def user_blocks(identifier) + raise Auth0::InvalidParameter, 'Must specify a valid identifier' if identifier.to_s.empty? + path = "#{user_blocks_path}?identifier=#{identifier}" + get(path) + end + + # Deletes the user blocks + # @see https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks + # @param identifier [string] Should be any of: username, phone_number, email. + def delete_user_blocks(identifier) + raise Auth0::InvalidParameter, 'Must specify a valid identifier' if identifier.to_s.empty? + path = "#{user_blocks_path}?identifier=#{identifier}" + delete(path) + end + + # Retrieves a user's blocks + # @see https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks_by_id + # @param user_id [string] The user_id of the user to retrieve + # + # @return [json] the user blocks + def user_blocks_by_id(user_id) + raise Auth0::InvalidParameter, 'Must specify a valid identifier' if user_id.to_s.empty? + path = "#{user_blocks_path}/#{user_id}" + get(path) + end + + # Deletes a user's blocks + # @see https://auth0.com/docs/api/management/v2#!/User_Blocks/delete_user_blocks_by_id + # @param user_id [string] The user_id of the user to retrieve + def delete_user_blocks_by_id(user_id) + raise Auth0::InvalidParameter, 'Must specify a valid identifier' if user_id.to_s.empty? + path = "#{user_blocks_path}/#{user_id}" + delete(path) + end + + private + + # User Blocks API path + def user_blocks_path + @user_blocks_path ||= '/api/v2/user-blocks' + end + end + end + end +end diff --git a/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb b/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb new file mode 100644 index 00000000..a51b3445 --- /dev/null +++ b/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb @@ -0,0 +1,60 @@ +require 'spec_helper' +describe Auth0::Api::V2::UserBlocks do + attr_reader :client, :user, :email + + skip "User blocks examples are skipped since is #logins exceeds free tenant limits" do + before(:all) do + @client = Auth0Client.new(v2_creds) + username = Faker::Internet.user_name + @email = "#{entity_suffix}#{Faker::Internet.safe_email(username)}" + password = Faker::Internet.password + @user = client.create_user(username, 'email' => email, + 'password' => password, + 'email_verified' => true, + 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, + 'app_metadata' => {}) + 100.times do + begin + client.login(email, 'invalid password') + rescue Auth0::Unauthorized + next + rescue Auth0::Unsupported => e + puts e.message + break + end + end + end + + after(:all) do + client.delete_user(user['user_id']) + end + + describe '.user_blocks' do + let(:user_blocks) { client.user_blocks(email) } + it { expect(user_blocks['blocked_for'].size).to be > 0 } + it { expect(user_blocks['blocked_for'].first['identifier']).to eq email } + end + + describe '.user_blocks_by_id' do + let(:user_blocks) { client.user_blocks_by_id(user['user_id']) } + it { expect(user_blocks['blocked_for'].size).to be > 0 } + it { expect(user_blocks['blocked_for'].first['identifier']).to eq email } + end + + describe '.delete_user_blocks' do + let(:user_blocks) do + client.delete_user_blocks(email) + client.user_blocks(email) + end + it { expect(user_blocks['blocked_for']).to eq [] } + end + + describe '.delete_user_blocks_by_id' do + let(:user_blocks) do + client.delete_user_blocks_by_id(user['user_id']) + client.user_blocks(email) + end + it { expect(user_blocks['blocked_for']).to eq [] } + end + end +end diff --git a/spec/lib/auth0/api/v2/user_blocks_spec.rb b/spec/lib/auth0/api/v2/user_blocks_spec.rb new file mode 100644 index 00000000..54957c51 --- /dev/null +++ b/spec/lib/auth0/api/v2/user_blocks_spec.rb @@ -0,0 +1,52 @@ +require 'spec_helper' +describe Auth0::Api::V2::UserBlocks do + before :all do + dummy_instance = DummyClass.new + dummy_instance.extend(Auth0::Api::V2::UserBlocks) + @instance = dummy_instance + end + + context '.user_blocks' do + it { expect(@instance).to respond_to(:user_blocks) } + it 'is expected to call /api/v2/user-blocks?identifier=Test' do + expect(@instance).to receive(:get).with('/api/v2/user-blocks?identifier=Test') + expect { @instance.user_blocks('Test') }.not_to raise_error + end + it 'expect client to raise an error when calling with empty identifier' do + expect { @instance.user_blocks(nil) }.to raise_error('Must specify a valid identifier') + end + end + + context '.delete_user_blocks' do + it { expect(@instance).to respond_to(:delete_user_blocks) } + it 'is expected to call /api/v2/user-blocks?identifier=Test' do + expect(@instance).to receive(:delete).with('/api/v2/user-blocks?identifier=Test') + expect { @instance.delete_user_blocks('Test') }.not_to raise_error + end + it 'expect client to raise an error when calling with empty identifier' do + expect { @instance.delete_user_blocks(nil) }.to raise_error('Must specify a valid identifier') + end + end + + context '.user_blocks_by_id' do + it { expect(@instance).to respond_to(:user_blocks_by_id) } + it 'is expected to call /api/v2/user-blocks/Test' do + expect(@instance).to receive(:get).with('/api/v2/user-blocks/Test') + expect { @instance.user_blocks_by_id('Test') }.not_to raise_error + end + it 'expect client to raise an error when calling with empty identifier' do + expect { @instance.user_blocks_by_id(nil) }.to raise_error('Must specify a valid identifier') + end + end + + context '.delete_user_blocks_by_id' do + it { expect(@instance).to respond_to(:delete_user_blocks_by_id) } + it 'is expected to call /api/v2/user-blocks/Test' do + expect(@instance).to receive(:delete).with('/api/v2/user-blocks/Test') + expect { @instance.delete_user_blocks_by_id('Test') }.not_to raise_error + end + it 'expect client to raise an error when calling with empty identifier' do + expect { @instance.delete_user_blocks_by_id(nil) }.to raise_error('Must specify a valid identifier') + end + end +end diff --git a/spec/support/credentials.rb b/spec/support/credentials.rb index 30b783a0..36d95be3 100644 --- a/spec/support/credentials.rb +++ b/spec/support/credentials.rb @@ -12,7 +12,8 @@ def v1_global_creds end def v2_creds - { token: ENV['MASTER_JWT'], + { client_id: ENV['CLIENT_ID'], + token: ENV['MASTER_JWT'], api_version: 2, domain: ENV['DOMAIN'] } end From 78a01edeb700823bc2b27b4abd3973c7bfc93852 Mon Sep 17 00:00:00 2001 From: Francisco Alvarisqueta Date: Fri, 17 Jun 2016 12:02:40 -0300 Subject: [PATCH 18/36] Block user before each user_blocks integration test --- .../lib/auth0/api/v2/api_user_blocks_spec.rb | 37 +++++++++++++------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb b/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb index a51b3445..128ddde8 100644 --- a/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb @@ -13,16 +13,6 @@ 'email_verified' => true, 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, 'app_metadata' => {}) - 100.times do - begin - client.login(email, 'invalid password') - rescue Auth0::Unauthorized - next - rescue Auth0::Unsupported => e - puts e.message - break - end - end end after(:all) do @@ -30,19 +20,26 @@ end describe '.user_blocks' do - let(:user_blocks) { client.user_blocks(email) } + let(:user_blocks) do + block_user(email) + client.user_blocks(email) + end it { expect(user_blocks['blocked_for'].size).to be > 0 } it { expect(user_blocks['blocked_for'].first['identifier']).to eq email } end describe '.user_blocks_by_id' do - let(:user_blocks) { client.user_blocks_by_id(user['user_id']) } + let(:user_blocks) do + block_user(email) + client.user_blocks_by_id(user['user_id']) + end it { expect(user_blocks['blocked_for'].size).to be > 0 } it { expect(user_blocks['blocked_for'].first['identifier']).to eq email } end describe '.delete_user_blocks' do let(:user_blocks) do + block_user(email) client.delete_user_blocks(email) client.user_blocks(email) end @@ -51,10 +48,26 @@ describe '.delete_user_blocks_by_id' do let(:user_blocks) do + block_user(email) client.delete_user_blocks_by_id(user['user_id']) client.user_blocks(email) end it { expect(user_blocks['blocked_for']).to eq [] } end end + + private + + def block_user(email) + 100.times do + begin + client.login(email, 'invalid password') + rescue Auth0::Unauthorized + next + rescue Auth0::Unsupported => e + puts e.message + break + end + end + end end From e8ba5dc90d82ba4202a31a707cdd513460d8cc78 Mon Sep 17 00:00:00 2001 From: Francisco Alvarisqueta Date: Tue, 21 Jun 2016 12:02:50 -0300 Subject: [PATCH 19/36] Allow httparty_proxy delete method to support query strings --- lib/auth0/mixins/httparty_proxy.rb | 2 +- spec/lib/auth0/mixins/httparty_proxy_spec.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/auth0/mixins/httparty_proxy.rb b/lib/auth0/mixins/httparty_proxy.rb index 0e1aa0ac..d1af6f69 100644 --- a/lib/auth0/mixins/httparty_proxy.rb +++ b/lib/auth0/mixins/httparty_proxy.rb @@ -8,7 +8,7 @@ module HTTPartyProxy define_method(method) do |path, body = {}| safe_path = URI.escape(path) body = body.delete_if { |_, v| v.nil? } - result = if method == :get + result = if [:get, :delete].include?(method) self.class.send(method, safe_path, query: body) elsif method == :post_file self.class.send(:post, safe_path, body: body, detect_mime_type: true) diff --git a/spec/lib/auth0/mixins/httparty_proxy_spec.rb b/spec/lib/auth0/mixins/httparty_proxy_spec.rb index facd4543..801c46e4 100644 --- a/spec/lib/auth0/mixins/httparty_proxy_spec.rb +++ b/spec/lib/auth0/mixins/httparty_proxy_spec.rb @@ -8,7 +8,7 @@ @instance = dummy_instance end - %i(get).each do |http_method| + %i(get delete).each do |http_method| context ".#{http_method}" do it { expect(@instance).to respond_to(http_method.to_sym) } it "should call send http #{http_method} method to path defined through HTTParty" do @@ -83,7 +83,7 @@ end end - %i(post put patch delete).each do |http_method| + %i(post put patch).each do |http_method| context ".#{http_method}" do it { expect(@instance).to respond_to(http_method.to_sym) } it "should call send http #{http_method} method to path defined through HTTParty" do From 892ad4617b3ad13eaf606dc94fe3ca97d79c6d2e Mon Sep 17 00:00:00 2001 From: Francisco Alvarisqueta Date: Tue, 21 Jun 2016 12:03:37 -0300 Subject: [PATCH 20/36] Refactor user_blocks get and delete to use httproxy methods --- lib/auth0/api/v2/user_blocks.rb | 13 +++++++++---- spec/lib/auth0/api/v2/user_blocks_spec.rb | 4 ++-- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/auth0/api/v2/user_blocks.rb b/lib/auth0/api/v2/user_blocks.rb index 225ffbad..3928ed49 100644 --- a/lib/auth0/api/v2/user_blocks.rb +++ b/lib/auth0/api/v2/user_blocks.rb @@ -12,8 +12,10 @@ module UserBlocks # @return [json] the user blocks def user_blocks(identifier) raise Auth0::InvalidParameter, 'Must specify a valid identifier' if identifier.to_s.empty? - path = "#{user_blocks_path}?identifier=#{identifier}" - get(path) + request_params = { + identifier: identifier + } + get(user_blocks_path, request_params) end # Deletes the user blocks @@ -21,8 +23,11 @@ def user_blocks(identifier) # @param identifier [string] Should be any of: username, phone_number, email. def delete_user_blocks(identifier) raise Auth0::InvalidParameter, 'Must specify a valid identifier' if identifier.to_s.empty? - path = "#{user_blocks_path}?identifier=#{identifier}" - delete(path) + #path = "#{user_blocks_path}?identifier=#{identifier}" + request_params = { + identifier: identifier + } + delete(user_blocks_path, request_params) end # Retrieves a user's blocks diff --git a/spec/lib/auth0/api/v2/user_blocks_spec.rb b/spec/lib/auth0/api/v2/user_blocks_spec.rb index 54957c51..231e0f78 100644 --- a/spec/lib/auth0/api/v2/user_blocks_spec.rb +++ b/spec/lib/auth0/api/v2/user_blocks_spec.rb @@ -9,7 +9,7 @@ context '.user_blocks' do it { expect(@instance).to respond_to(:user_blocks) } it 'is expected to call /api/v2/user-blocks?identifier=Test' do - expect(@instance).to receive(:get).with('/api/v2/user-blocks?identifier=Test') + expect(@instance).to receive(:get).with('/api/v2/user-blocks', identifier: 'Test') expect { @instance.user_blocks('Test') }.not_to raise_error end it 'expect client to raise an error when calling with empty identifier' do @@ -20,7 +20,7 @@ context '.delete_user_blocks' do it { expect(@instance).to respond_to(:delete_user_blocks) } it 'is expected to call /api/v2/user-blocks?identifier=Test' do - expect(@instance).to receive(:delete).with('/api/v2/user-blocks?identifier=Test') + expect(@instance).to receive(:delete).with('/api/v2/user-blocks', identifier:'Test') expect { @instance.delete_user_blocks('Test') }.not_to raise_error end it 'expect client to raise an error when calling with empty identifier' do From 28ff64bbbdc79d4c37d3eaa079ac144c19306309 Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Thu, 16 Jun 2016 18:07:48 -0300 Subject: [PATCH 21/36] Add Device Credentials endpoints and tests --- lib/auth0/api/v2.rb | 2 + lib/auth0/api/v2/device_credentials.rb | 76 +++++++++++++++++++ lib/auth0/api/v2/logs.rb | 6 +- lib/auth0/mixins/initializer.rb | 13 +++- .../api/v2/api_device_credentials_spec.rb | 70 +++++++++++++++++ .../auth0/api/v2/device_credentials_spec.rb | 73 ++++++++++++++++++ spec/lib/auth0/api/v2/logs_spec.rb | 6 +- 7 files changed, 240 insertions(+), 6 deletions(-) create mode 100644 lib/auth0/api/v2/device_credentials.rb create mode 100644 spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb create mode 100644 spec/lib/auth0/api/v2/device_credentials_spec.rb diff --git a/lib/auth0/api/v2.rb b/lib/auth0/api/v2.rb index 5e50f0e9..80aa3b86 100644 --- a/lib/auth0/api/v2.rb +++ b/lib/auth0/api/v2.rb @@ -2,6 +2,7 @@ require 'auth0/api/v2/clients' require 'auth0/api/v2/client_grants' require 'auth0/api/v2/connections' +require 'auth0/api/v2/device_credentials' require 'auth0/api/v2/emails' require 'auth0/api/v2/jobs' require 'auth0/api/v2/rules' @@ -21,6 +22,7 @@ module V2 include Auth0::Api::V2::Clients include Auth0::Api::V2::ClientGrants include Auth0::Api::V2::Connections + include Auth0::Api::V2::DeviceCredentials include Auth0::Api::V2::Emails include Auth0::Api::V2::Jobs include Auth0::Api::V2::Rules diff --git a/lib/auth0/api/v2/device_credentials.rb b/lib/auth0/api/v2/device_credentials.rb new file mode 100644 index 00000000..095d15a8 --- /dev/null +++ b/lib/auth0/api/v2/device_credentials.rb @@ -0,0 +1,76 @@ +module Auth0 + module Api + module V2 + # Methods to use the device crenditials endpoints + module DeviceCredentials + attr_reader :device_credentials_path + + # Retrieves log entries that match the specified search criteria. + # @see https://auth0.com/docs/api/v2#!/device_credentials/get_device_credentials + # @param fields [string] A comma separated list of fields to include or exclude from the result. + # @param include_fields [boolean] True if the fields specified are to be included in the result, false otherwise. + # @param user_id [string] The user_id of the devices to retrieve. + # @param client_id [string] The client_id of the devices to retrieve. + # @param type [string] The type of credentials. Possible values: 'public_key' or 'refresh_token'. + # + # @return [json] Returns the list of existing devices for the specified client_id. + # rubocop:disable Metrics/AbcSize + def device_credentials(client_id, options = {}) + request_params = { + fields: options.fetch(:fields, nil), + include_fields: options.fetch(:include_fields, nil), + user_id: options.fetch(:user_id, nil), + client_id: client_id, + type: options.fetch(:type, nil) + } + raise Auth0::InvalidParameter, 'Must supply a valid client_id' if client_id.to_s.empty? + if !request_params[:type].nil? && !%w(public_key refresh_token).include?(request_params[:type]) + raise Auth0::InvalidParameter, 'Type must be one of \'public_key\', \'refresh_token\'' + end + get(device_credentials_path, request_params) + end + alias list_device_credentials device_credentials + + # Creates a new device public key. + # @see https://auth0.com/docs/api/v2#!/device_credentials/post_device_credentials + # @param device_name [string] The device's name, a value that must be easily recognized by the device's owner. + # @param value [string] A base64 encoded string with the value of the credential. + # @param device_id [string] A unique identifier for the device. + # @param client_id [string] The client_id of the client for which the credential will be created. + # + # @return [json] Returns the created public key. + def create_device_credential(device_name, value, device_id, client_id) + raise Auth0::InvalidParameter, 'Must supply a valid device_name' if device_name.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid value' if value.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid device_id' if device_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid client_id' if client_id.to_s.empty? + request_params = { + device_name: device_name, + type: 'public_key', + value: value, + device_id: device_id, + client_id: client_id + } + post(device_credentials_path, request_params) + end + alias create_device_public_key create_device_credential + + # Deletes a single device credential given its id. + # @see https://auth0.com/docs/api/v2#!/device_credentials/delete_device_credentials_by_id + # @param id [string] The id of the credential to delete. + def delete_device_credential(id) + raise Auth0::InvalidParameter, 'Must supply a valid id' if id.to_s.empty? + path = "#{device_credentials_path}/#{id}" + delete(path) + end + + private + + # Device Credentials API path + def device_credentials_path + @device_credentials_path ||= '/api/v2/device-credentials' + end + end + end + end +end diff --git a/lib/auth0/api/v2/logs.rb b/lib/auth0/api/v2/logs.rb index 14c693bf..6517fdaf 100644 --- a/lib/auth0/api/v2/logs.rb +++ b/lib/auth0/api/v2/logs.rb @@ -34,10 +34,10 @@ def logs(options = {}) take: options.fetch(:take, nil) } if request_params[:take].to_i > 100 - fail Auth0::InvalidParameter, 'The total amount of entries to retrieve should be less than 100' + raise Auth0::InvalidParameter, 'The total amount of entries to retrieve should be less than 100' end if request_params[:per_page].to_i > 100 - fail Auth0::InvalidParameter, 'The total amount of entries per page should be less than 100' + raise Auth0::InvalidParameter, 'The total amount of entries per page should be less than 100' end get(logs_path, request_params) end @@ -49,7 +49,7 @@ def logs(options = {}) # # @return [json] Returns the log with the given id if exists. def log(log_id) - fail Auth0::MissingParameter, 'Must supply a valid log_id' if log_id.to_s.empty? + raise Auth0::MissingParameter, 'Must supply a valid log_id' if log_id.to_s.empty? path = "#{logs_path}/#{log_id}" get(path) end diff --git a/lib/auth0/mixins/initializer.rb b/lib/auth0/mixins/initializer.rb index 3b5fa740..7336dcd6 100644 --- a/lib/auth0/mixins/initializer.rb +++ b/lib/auth0/mixins/initializer.rb @@ -25,12 +25,23 @@ def authorization_header(token) self.class.headers 'Authorization' => "Bearer #{token}" end + def authorization_header_basic(options) + connection_id = options.fetch(:connection_id, Auth0::Api::AuthenticationEndpoints::UP_AUTH) + user = options.fetch(:user, nil) + password = options.fetch(:password, nil) + self.class.headers 'Authorization' => "Basic #{Base64.strict_encode64("#{connection_id}\\#{user}:#{password}")}" + end + private def initialize_api(options) api_v1?(options) ? initialize_v1(options) : initialize_v2(options) raise InvalidCredentials, 'Must supply a valid API token' if @token.nil? - authorization_header(@token) + if options.fetch(:authorization, nil) == 'Basic' + authorization_header_basic(options) + else + authorization_header(@token) + end end def base_url(options) diff --git a/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb b/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb new file mode 100644 index 00000000..09d7e6d6 --- /dev/null +++ b/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb @@ -0,0 +1,70 @@ +require 'spec_helper' +require 'base64' +describe Auth0::Api::V2::DeviceCredentials do + attr_reader :user, :user_client, :basic_client, :existing_device_credentials + + before(:all) do + client = Auth0Client.new(v2_creds) + username = Faker::Internet.user_name + email = "#{entity_suffix}#{Faker::Internet.safe_email(username)}" + password = Faker::Internet.password + @user = client.create_user(username, 'email' => email, + 'password' => password, + 'email_verified' => true, + 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, + 'app_metadata' => {}) + + basic_creds = { connection_id: Auth0::Api::AuthenticationEndpoints::UP_AUTH, + user: email, + password: password, + authorization: 'Basic' } + + @basic_client = Auth0Client.new(v2_creds.merge(basic_creds)) + @existing_device_credentials = basic_client.create_device_credential( + "#{user['name']}_phone_1", + 'dmFsdWU=', + '68753A44-4D6F-1226-9C60-0050E4C00067', + ENV['CLIENT_ID'] + ) + end + + after(:all) do + # Workaround to prevent instance constructor from overwritting class variable (header) + # TODO: fix instance / class isssue from aut0 proxy and remove line below. + client = Auth0Client.new(v2_creds) + client.delete_user(user['user_id']) + end + + describe '.device_credentials' do + let(:device_credentials) { basic_client.device_credentials(ENV['CLIENT_ID']) } + it { expect(device_credentials.size).to be > 0 } + it { expect(device_credentials.find { |cred| cred['id'] == existing_device_credentials['id'] }).to_not be_empty } + context '#filter_by_type' do + let(:filtered_device_credentials) { basic_client.device_credentials(ENV['CLIENT_ID'], type: 'refresh_token') } + it do + expect(filtered_device_credentials.find do |cred| + cred['id'] == existing_device_credentials['id'] + end).to eq nil + end + end + end + + describe '.create_device_credential' do + let!(:new_credentials) do + basic_client.create_device_credential( + "#{user['name']}_phone_2", + 'dmFsdWU=', + '68753A44-4D6F-1226-9C60-0050E4C00067', + ENV['CLIENT_ID'] + ) + end + it do + expect(basic_client.device_credentials(ENV['CLIENT_ID']) + .find { |cred| cred['id'] == new_credentials['id'] }).to_not be_empty + end + end + + describe '.delete_device_credential' do + it { expect { basic_client.delete_device_credential(existing_device_credentials['id']) }.to_not raise_error } + end +end diff --git a/spec/lib/auth0/api/v2/device_credentials_spec.rb b/spec/lib/auth0/api/v2/device_credentials_spec.rb new file mode 100644 index 00000000..5d6b5b13 --- /dev/null +++ b/spec/lib/auth0/api/v2/device_credentials_spec.rb @@ -0,0 +1,73 @@ +require 'spec_helper' +describe Auth0::Api::V2::DeviceCredentials do + attr_reader :client_id + + before :all do + dummy_instance = DummyClass.new + dummy_instance.extend(Auth0::Api::V2::DeviceCredentials) + @instance = dummy_instance + @client_id = Faker::Lorem.word + end + context '.device_credentials' do + it { expect(@instance).to respond_to(:device_credentials) } + it { expect(@instance).to respond_to(:list_device_credentials) } + it 'is expected to send get request to /api/v2/device-credentials' do + expect(@instance).to receive(:get).with( + '/api/v2/device-credentials', + fields: nil, + include_fields: nil, + user_id: nil, + client_id: client_id, + type: nil + ) + expect { @instance.device_credentials(client_id) }.not_to raise_error + end + it 'is expect to raise an error when type is not one of \'public_key\', \'refresh_token\'' do + expect { @instance.device_credentials(client_id, type: 'invalid_type') }.to raise_error( + 'Type must be one of \'public_key\', \'refresh_token\'' + ) + end + end + + context '.create_device_credential' do + it { expect(@instance).to respond_to(:create_device_credential) } + it { expect(@instance).to respond_to(:create_device_public_key) } + it 'is expected to send post to /api/v2/device-credentials' do + expect(@instance).to receive(:post).with( + '/api/v2/device-credentials', + device_name: 'device_name', + value: 'value', + device_id: 'device_id', + client_id: 'client_id', + type: 'public_key' + ) + expect { @instance.create_device_credential('device_name', 'value', 'device_id', 'client_id') } + .not_to raise_error + end + it do + expect { @instance.create_device_credential(nil, 'value', 'device_id', 'client_id') } + .to raise_error('Must supply a valid device_name') + end + it do + expect { @instance.create_device_credential('device_name', nil, 'device_id', 'client_id') } + .to raise_error('Must supply a valid value') + end + it do + expect { @instance.create_device_credential('device_name', 'value', nil, 'client_id') } + .to raise_error('Must supply a valid device_id') + end + it do + expect { @instance.create_device_credential('device_name', 'value', 'device_id', nil) } + .to raise_error('Must supply a valid client_id') + end + end + + context '.delete_device_credential' do + it { expect(@instance).to respond_to(:delete_device_credential) } + it 'is expected to send delete to /api/v2/device-credentials/1' do + expect(@instance).to receive(:delete).with('/api/v2/device-credentials/1') + expect { @instance.delete_device_credential('1') }.not_to raise_error + end + it { expect { @instance.delete_device_credential('') }.to raise_error 'Must supply a valid id' } + end +end diff --git a/spec/lib/auth0/api/v2/logs_spec.rb b/spec/lib/auth0/api/v2/logs_spec.rb index d8383a14..48731322 100644 --- a/spec/lib/auth0/api/v2/logs_spec.rb +++ b/spec/lib/auth0/api/v2/logs_spec.rb @@ -26,11 +26,13 @@ end it 'is expect to rise an error when take is higher than 100' do expect { @instance.logs(take: rand(101..2000)) }.to raise_error( - 'The total amount of entries to retrieve should be less than 100') + 'The total amount of entries to retrieve should be less than 100' + ) end it 'is expect to rise an error when per_page is higher than 100' do expect { @instance.logs(per_page: rand(101..2000)) }.to raise_error( - 'The total amount of entries per page should be less than 100') + 'The total amount of entries per page should be less than 100' + ) end end From 297cc9a27540b302ca8ee187a16d0926884882a0 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Thu, 23 Jun 2016 17:09:08 -0300 Subject: [PATCH 22/36] Fix Rubocop Issues --- lib/auth0/api/v2/user_blocks.rb | 2 +- spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb | 2 +- spec/lib/auth0/api/v2/user_blocks_spec.rb | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/auth0/api/v2/user_blocks.rb b/lib/auth0/api/v2/user_blocks.rb index 3928ed49..ebb1063e 100644 --- a/lib/auth0/api/v2/user_blocks.rb +++ b/lib/auth0/api/v2/user_blocks.rb @@ -23,7 +23,7 @@ def user_blocks(identifier) # @param identifier [string] Should be any of: username, phone_number, email. def delete_user_blocks(identifier) raise Auth0::InvalidParameter, 'Must specify a valid identifier' if identifier.to_s.empty? - #path = "#{user_blocks_path}?identifier=#{identifier}" + # path = "#{user_blocks_path}?identifier=#{identifier}" request_params = { identifier: identifier } diff --git a/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb b/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb index 128ddde8..d331c385 100644 --- a/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_user_blocks_spec.rb @@ -2,7 +2,7 @@ describe Auth0::Api::V2::UserBlocks do attr_reader :client, :user, :email - skip "User blocks examples are skipped since is #logins exceeds free tenant limits" do + skip 'User blocks examples are skipped since is #logins exceeds free tenant limits' do before(:all) do @client = Auth0Client.new(v2_creds) username = Faker::Internet.user_name diff --git a/spec/lib/auth0/api/v2/user_blocks_spec.rb b/spec/lib/auth0/api/v2/user_blocks_spec.rb index 231e0f78..ec845540 100644 --- a/spec/lib/auth0/api/v2/user_blocks_spec.rb +++ b/spec/lib/auth0/api/v2/user_blocks_spec.rb @@ -20,7 +20,7 @@ context '.delete_user_blocks' do it { expect(@instance).to respond_to(:delete_user_blocks) } it 'is expected to call /api/v2/user-blocks?identifier=Test' do - expect(@instance).to receive(:delete).with('/api/v2/user-blocks', identifier:'Test') + expect(@instance).to receive(:delete).with('/api/v2/user-blocks', identifier: 'Test') expect { @instance.delete_user_blocks('Test') }.not_to raise_error end it 'expect client to raise an error when calling with empty identifier' do From 24d278dc9a2d2c3660c0b3936f77634fcfc18655 Mon Sep 17 00:00:00 2001 From: Jon Gelsey Date: Sat, 18 Jun 2016 08:48:01 -0700 Subject: [PATCH 23/36] Updated address --- doc_config/templates/default/layout/html/footer.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc_config/templates/default/layout/html/footer.erb b/doc_config/templates/default/layout/html/footer.erb index 6a347546..dd0e9f03 100644 --- a/doc_config/templates/default/layout/html/footer.erb +++ b/doc_config/templates/default/layout/html/footer.erb @@ -80,7 +80,7 @@ -
10777 Main Street
Suite 204
Bellevue, WA 98004
+
10900 NE 8th St.
Suite 700
Bellevue, WA 98004
Sales
From 6ce9479c2020f1e5809cd46d54ab1e8e573a5d35 Mon Sep 17 00:00:00 2001 From: Leonardo Soubeste Date: Thu, 30 Jun 2016 12:48:54 -0300 Subject: [PATCH 24/36] Migrate from HTTParty to rest-client. --- auth0.gemspec | 2 +- lib/auth0/client.rb | 2 - lib/auth0/mixins.rb | 7 +- lib/auth0/mixins/httparty_proxy.rb | 37 --- lib/auth0/mixins/httpproxy.rb | 55 +++++ lib/auth0/mixins/initializer.rb | 9 +- .../lib/auth0/api/v2/api_blacklist_spec.rb | 2 +- .../lib/auth0/api/v2/api_connections_spec.rb | 4 +- .../lib/auth0/auth0_client_spec.rb | 2 +- spec/lib/auth0/mixins/httparty_proxy_spec.rb | 163 ------------- spec/lib/auth0/mixins/httpproxy_spec.rb | 225 ++++++++++++++++++ spec/lib/auth0/mixins/initializer_spec.rb | 2 +- spec/support/dummy_class_for_proxy.rb | 4 +- spec/support/dummy_class_for_restclient.rb | 2 + 14 files changed, 299 insertions(+), 217 deletions(-) delete mode 100644 lib/auth0/mixins/httparty_proxy.rb create mode 100644 lib/auth0/mixins/httpproxy.rb delete mode 100644 spec/lib/auth0/mixins/httparty_proxy_spec.rb create mode 100644 spec/lib/auth0/mixins/httpproxy_spec.rb create mode 100644 spec/support/dummy_class_for_restclient.rb diff --git a/auth0.gemspec b/auth0.gemspec index 894e03f5..0470e315 100644 --- a/auth0.gemspec +++ b/auth0.gemspec @@ -18,7 +18,7 @@ Gem::Specification.new do |s| s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } s.require_paths = ['lib'] - s.add_runtime_dependency 'httmultiparty', '~> 0.3.16' + s.add_runtime_dependency 'rest-client', '~> 1.8.0' s.add_development_dependency 'rake', '~> 10.4' s.add_development_dependency 'fuubar', '~> 2.0' diff --git a/lib/auth0/client.rb b/lib/auth0/client.rb index 3155fd25..71a8cda2 100644 --- a/lib/auth0/client.rb +++ b/lib/auth0/client.rb @@ -3,7 +3,5 @@ module Auth0 # All Api calls are suposed to return hashes, but delete actions return strings. class Client include Auth0::Mixins - include HTTMultiParty - base_uri 'http://auth0.com' end end diff --git a/lib/auth0/mixins.rb b/lib/auth0/mixins.rb index a0204244..578b5995 100644 --- a/lib/auth0/mixins.rb +++ b/lib/auth0/mixins.rb @@ -1,6 +1,7 @@ -require 'httmultiparty' +require 'base64' +require 'rest-client' require 'uri' -require 'auth0/mixins/httparty_proxy' +require 'auth0/mixins/httpproxy' require 'auth0/mixins/initializer' require 'auth0/api/authentication_endpoints' require 'auth0/api/v1' @@ -8,7 +9,7 @@ module Auth0 # Collecting dependencies here module Mixins - include Auth0::Mixins::HTTPartyProxy + include Auth0::Mixins::HTTPProxy include Auth0::Mixins::Initializer end end diff --git a/lib/auth0/mixins/httparty_proxy.rb b/lib/auth0/mixins/httparty_proxy.rb deleted file mode 100644 index d1af6f69..00000000 --- a/lib/auth0/mixins/httparty_proxy.rb +++ /dev/null @@ -1,37 +0,0 @@ -module Auth0 - module Mixins - # here's the proxy for HTTParty, we're building all request on that gem - # for now, if you want to feel free to use your own http client - module HTTPartyProxy - # proxying requests from instance methods to HTTParty class methods - %i(get post post_file put patch delete).each do |method| - define_method(method) do |path, body = {}| - safe_path = URI.escape(path) - body = body.delete_if { |_, v| v.nil? } - result = if [:get, :delete].include?(method) - self.class.send(method, safe_path, query: body) - elsif method == :post_file - self.class.send(:post, safe_path, body: body, detect_mime_type: true) - else - self.class.send(method, safe_path, body: body.to_json) - end - case result.code - when 200...226 then safe_parse_json(result.body) - when 400 then raise Auth0::BadRequest, result.body - when 401 then raise Auth0::Unauthorized, result.body - when 403 then raise Auth0::AccessDenied, result.body - when 404 then raise Auth0::NotFound, result.body - when 500 then raise Auth0::ServerError, result.body - else raise Auth0::Unsupported, result.body - end - end - end - - def safe_parse_json(body) - JSON.parse(body.to_s) - rescue JSON::ParserError - body - end - end - end -end diff --git a/lib/auth0/mixins/httpproxy.rb b/lib/auth0/mixins/httpproxy.rb new file mode 100644 index 00000000..b5afd54b --- /dev/null +++ b/lib/auth0/mixins/httpproxy.rb @@ -0,0 +1,55 @@ +module Auth0 + module Mixins + # here's the proxy for Rest calls based on rest-client, we're building all request on that gem + # for now, if you want to feel free to use your own http client + module HTTPProxy + attr_accessor :headers, :base_uri, :timeout + + # proxying requests from instance methods to HTTP class methods + %i(get post post_file put patch delete).each do |method| + define_method(method) do |path, body = {}| + safe_path = URI.escape(path) + body = body.delete_if { |_, v| v.nil? } + result = if [:get, :delete].include?(method) + call(method, url(safe_path), timeout, add_headers(params: body)) + elsif method == :post_file + call(:post, url(safe_path), timeout, headers, body) + else + call(method, url(safe_path), timeout, headers, body.to_json) + end + case result.code + when 200...226 then safe_parse_json(result.body) + when 400 then raise Auth0::BadRequest, result.to_s + when 401 then raise Auth0::Unauthorized, result.body + when 403 then raise Auth0::AccessDenied, result.body + when 404 then raise Auth0::NotFound, result.body + when 500 then raise Auth0::ServerError, result.body + else raise Auth0::Unsupported, result.body + end + end + end + + def url(path) + "#{base_uri}#{path}" + end + + def add_headers(h = {}) + raise ArgumentError, 'Headers must be an object which responds to #to_hash' unless h.respond_to?(:to_hash) + @headers ||= {} + @headers.merge!(h.to_hash) + end + + def safe_parse_json(body) + JSON.parse(body.to_s) + rescue JSON::ParserError + body + end + + def call(method, url, timeout, headers, body = nil) + RestClient::Request.execute(method: method, url: url, timeout: timeout, headers: headers, payload: body) + rescue RestClient::Exception => e + e.response + end + end + end +end diff --git a/lib/auth0/mixins/initializer.rb b/lib/auth0/mixins/initializer.rb index 7336dcd6..6481de6a 100644 --- a/lib/auth0/mixins/initializer.rb +++ b/lib/auth0/mixins/initializer.rb @@ -9,8 +9,9 @@ module Initializer # By Default API v2 def initialize(config) options = Hash[config.map { |(k, v)| [k.to_sym, v] }] - self.class.base_uri base_url(options) - self.class.headers client_headers(config) + @base_uri = base_url(options) + @headers = client_headers(config) + @timeout = options[:timeout] || 10 extend Auth0::Api::AuthenticationEndpoints @client_id = options[:client_id] initialize_api(options) @@ -22,14 +23,14 @@ def self.included(klass) end def authorization_header(token) - self.class.headers 'Authorization' => "Bearer #{token}" + add_headers('Authorization' => "Bearer #{token}") end def authorization_header_basic(options) connection_id = options.fetch(:connection_id, Auth0::Api::AuthenticationEndpoints::UP_AUTH) user = options.fetch(:user, nil) password = options.fetch(:password, nil) - self.class.headers 'Authorization' => "Basic #{Base64.strict_encode64("#{connection_id}\\#{user}:#{password}")}" + add_headers('Authorization' => "Basic #{Base64.strict_encode64("#{connection_id}\\#{user}:#{password}")}") end private diff --git a/spec/integration/lib/auth0/api/v2/api_blacklist_spec.rb b/spec/integration/lib/auth0/api/v2/api_blacklist_spec.rb index 0f66bd73..892fd266 100644 --- a/spec/integration/lib/auth0/api/v2/api_blacklist_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_blacklist_spec.rb @@ -4,7 +4,7 @@ let(:token) { 'faketoken' } describe '.add_token_to_blacklist' do - it { expect(client.add_token_to_blacklist(token)).to be_nil } + it { expect(client.add_token_to_blacklist(token)).to be_empty } end describe '.blacklisted_tokens' do diff --git a/spec/integration/lib/auth0/api/v2/api_connections_spec.rb b/spec/integration/lib/auth0/api/v2/api_connections_spec.rb index eeea6002..a3841872 100644 --- a/spec/integration/lib/auth0/api/v2/api_connections_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_connections_spec.rb @@ -18,7 +18,7 @@ let(:connections) { client.connections } it { expect(connections.size).to be > 0 } - it { expect(connections.find { |con| con['name'] == name }).to_not be_nil } + it { expect(connections.find { |con| con['name'] == name }).to_not be_empty } context '#filters' do it { expect(client.connections(strategy: strategy).size).to be > 0 } @@ -88,7 +88,7 @@ client.connections.find { |connection| connection['name'] == Auth0::Api::AuthenticationEndpoints::UP_AUTH } end - it { expect(client.delete_connection_user(connection['id'], email)).to be_nil } + it { expect(client.delete_connection_user(connection['id'], email)).to be_empty } end after(:all) do diff --git a/spec/integration/lib/auth0/auth0_client_spec.rb b/spec/integration/lib/auth0/auth0_client_spec.rb index 6c1e9cdf..b09e4f37 100644 --- a/spec/integration/lib/auth0/auth0_client_spec.rb +++ b/spec/integration/lib/auth0/auth0_client_spec.rb @@ -57,7 +57,7 @@ context 'client headers' do let(:client) { Auth0::Client.new(v2_credentials.merge(access_token: 'abc123', domain: 'myhost.auth0.com')) } - let(:headers) { client.class.headers } + let(:headers) { client.headers } let(:base64_token) do Base64.urlsafe_encode64('{"name":"ruby-auth0","version":"' + Auth0::VERSION + '"}') diff --git a/spec/lib/auth0/mixins/httparty_proxy_spec.rb b/spec/lib/auth0/mixins/httparty_proxy_spec.rb deleted file mode 100644 index 801c46e4..00000000 --- a/spec/lib/auth0/mixins/httparty_proxy_spec.rb +++ /dev/null @@ -1,163 +0,0 @@ -require 'json' -require 'spec_helper' - -describe Auth0::Mixins::HTTPartyProxy do - before :all do - dummy_instance = DummyClassForProxy.new - dummy_instance.extend(Auth0::Mixins::HTTPartyProxy) - @instance = dummy_instance - end - - %i(get delete).each do |http_method| - context ".#{http_method}" do - it { expect(@instance).to respond_to(http_method.to_sym) } - it "should call send http #{http_method} method to path defined through HTTParty" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, true, 200)) - expect { @instance.send(http_method, '/test') }.not_to raise_error - end - - it 'should not raise exception if data returned not in json format (should be fixed in v2)' do - allow(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new('Some random text here', true, 200)) - expect { @instance.send(http_method, '/test') }.not_to raise_error - expect(@instance.send(http_method, '/test')).to eql('Some random text here') - end - - it "should raise Auth0::Unauthorized on send http #{http_method} - method to path defined through HTTParty when 401 status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, false, 401)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unauthorized) - end - - it "should raise Auth0::NotFound on send http #{http_method} method - to path defined through HTTParty when 404 status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, false, 404)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound) - end - - it "should raise Auth0::Unsupported on send http #{http_method} method - to path defined through HTTParty when 418 or other unknown status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, false, 418)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unsupported) - end - - it "should raise Auth0::BadRequest on send http #{http_method} method - to path defined through HTTParty when 400 or other unknown status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, false, 400)) - expect { @instance.send(http_method, '/test') }.to raise_error( - Auth0::BadRequest - ) - end - - it "should raise Auth0::AccessDenied on send http #{http_method} method - to path defined through HTTParty when 403" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, false, 403)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::AccessDenied) - end - it "should raise Auth0::ServerError on send http #{http_method} method - to path defined through HTTParty when 500 received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/test', query: {}) - .and_return(StubResponse.new({}, false, 500)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::ServerError) - end - - it 'should escape path with URI.escape' do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/te%20st', query: {}) - expect(DummyClassForProxy).to receive(http_method).with('/te%20st', query: {}) - .and_return(StubResponse.new({}, true, 200)) - expect { @instance.send(http_method, '/te st') }.not_to raise_error - end - end - end - - %i(post put patch).each do |http_method| - context ".#{http_method}" do - it { expect(@instance).to respond_to(http_method.to_sym) } - it "should call send http #{http_method} method to path defined through HTTParty" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('{}', true, 200)) - expect { @instance.send(http_method, '/test') }.not_to raise_error - end - - it 'should not raise exception if data returned not in json format (should be fixed in v2)' do - allow(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('Some random text here', true, 200)) - expect { @instance.send(http_method, '/test') }.not_to raise_error - expect(@instance.send(http_method, '/test')).to eql('Some random text here') - end - - it "should raise Auth0::Unauthorized on send http #{http_method} method - to path defined through HTTParty when 401 status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('{}', false, 401)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unauthorized) - end - - it "should raise Auth0::NotFound on send http #{http_method} method - to path defined through HTTParty when 404 status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('{}', false, 404)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound) - end - - it "should raise Auth0::Unsupported on send http #{http_method} method - to path defined through HTTParty when 418 or other unknown status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('{}', false, 418)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unsupported) - end - - it "should raise Auth0::BadRequest on send http #{http_method} method - to path defined through HTTParty when 400 or other unknown status received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('{}', false, 400)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::BadRequest) - end - - it "should raise Auth0::ServerError on send http #{http_method} method - to path defined through HTTParty when 500 received" do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new('{}', false, 500)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::ServerError) - end - - it 'should escape path with URI.escape' do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/te%20st', body: '{}') - expect(DummyClassForProxy).to receive(http_method).with('/te%20st', body: '{}') - .and_return(StubResponse.new('{}', true, 200)) - expect { @instance.send(http_method, '/te st') }.not_to raise_error - end - - it 'should give the JSON representation of the error as the error message' do - allow(DummyClassForProxy).to receive(http_method).with('http://login.auth0.com/test', body: '{}') - res = JSON.generate('statusCode' => 404, - 'error' => 'Bad Request', - 'message' => "Path validation error: 'String does not match pattern ^.+\\|.+$: - 3241312' on property id (The user_id of the user to retrieve).", - 'errorCode' => 'invalid_uri') - expect(DummyClassForProxy).to receive(http_method).with('/test', body: '{}') - .and_return(StubResponse.new(res, false, 404)) - expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound, res) - end - end - end -end diff --git a/spec/lib/auth0/mixins/httpproxy_spec.rb b/spec/lib/auth0/mixins/httpproxy_spec.rb new file mode 100644 index 00000000..4909177b --- /dev/null +++ b/spec/lib/auth0/mixins/httpproxy_spec.rb @@ -0,0 +1,225 @@ +require 'json' +require 'spec_helper' + +describe Auth0::Mixins::HTTPProxy do + before :each do + dummy_instance = DummyClassForProxy.new + dummy_instance.extend(Auth0::Mixins::HTTPProxy) + @instance = dummy_instance + @exception = DummyClassForRestClient.new + end + + %i(get delete).each do |http_method| + context ".#{http_method}" do + it { expect(@instance).to respond_to(http_method.to_sym) } + it "should call send http #{http_method} method to path defined through HTTP" do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_return(StubResponse.new({}, true, 200)) + expect { @instance.send(http_method, '/test') }.not_to raise_error + end + + it 'should not raise exception if data returned not in json format (should be fixed in v2)' do + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_return(StubResponse.new('Some random text here', true, 200)) + expect { @instance.send(http_method, '/test') }.not_to raise_error + expect(@instance.send(http_method, '/test')).to eql('Some random text here') + end + + it "should raise Auth0::Unauthorized on send http #{http_method} + method to path defined through HTTP when 401 status received" do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_return(StubResponse.new({}, false, 401)) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unauthorized) + end + + it "should raise Auth0::NotFound on send http #{http_method} method + to path defined through HTTP when 404 status received" do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_return(StubResponse.new({}, false, 404)) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound) + end + + it "should raise Auth0::Unsupported on send http #{http_method} method + to path defined through HTTP when 418 or other unknown status received" do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_return(StubResponse.new({}, false, 418)) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unsupported) + end + + it "should raise Auth0::BadRequest on send http #{http_method} method + to path defined through HTTP when 400 or other unknown status received" do + @exception.response = StubResponse.new({}, false, 400) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::BadRequest) + end + + it "should raise Auth0::AccessDenied on send http #{http_method} method + to path defined through HTTP when 403" do + @exception.response = StubResponse.new({}, false, 403) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::AccessDenied) + end + it "should raise Auth0::ServerError on send http #{http_method} method + to path defined through HTTP when 500 received" do + @exception.response = StubResponse.new({}, false, 500) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::ServerError) + end + + it 'should escape path with URI.escape' do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/te%20st', + timeout: nil, + headers: { params: {} }, + payload: nil) + .and_return(StubResponse.new({}, true, 200)) + expect { @instance.send(http_method, '/te st') }.not_to raise_error + end + end + end + + %i(post put patch).each do |http_method| + context ".#{http_method}" do + it { expect(@instance).to respond_to(http_method.to_sym) } + it "should call send http #{http_method} method to path defined through HTTP" do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_return(StubResponse.new({}, true, 200)) + expect { @instance.send(http_method, '/test') }.not_to raise_error + end + + it 'should not raise exception if data returned not in json format (should be fixed in v2)' do + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_return(StubResponse.new('Some random text here', true, 200)) + expect { @instance.send(http_method, '/test') }.not_to raise_error + expect(@instance.send(http_method, '/test')).to eql('Some random text here') + end + + it "should raise Auth0::Unauthorized on send http #{http_method} method + to path defined through HTTP when 401 status received" do + @exception.response = StubResponse.new({}, false, 401) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unauthorized) + end + + it "should raise Auth0::NotFound on send http #{http_method} method + to path defined through HTTP when 404 status received" do + @exception.response = StubResponse.new({}, false, 404) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound) + end + + it "should raise Auth0::Unsupported on send http #{http_method} method + to path defined through HTTP when 418 or other unknown status received" do + @exception.response = StubResponse.new({}, false, 418) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::Unsupported) + end + + it "should raise Auth0::BadRequest on send http #{http_method} method + to path defined through HTTP when 400 or other unknown status received" do + @exception.response = StubResponse.new({}, false, 400) + allow(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::BadRequest) + end + + it "should raise Auth0::ServerError on send http #{http_method} method + to path defined through HTTP when 500 received" do + @exception.response = StubResponse.new({}, false, 500) + allow(RestClient::Request).to receive(:execute).with(method: http_method, url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_raise(@exception) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::ServerError) + end + + it 'should escape path with URI.escape' do + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/te%20st', + timeout: nil, + headers: nil, + payload: '{}') + .and_return(StubResponse.new({}, true, 200)) + expect { @instance.send(http_method, '/te st') }.not_to raise_error + end + + it 'should give the JSON representation of the error as the error message' do + res = JSON.generate('statusCode' => 404, + 'error' => 'Bad Request', + 'message' => "Path validation error: 'String does not match pattern ^.+\\|.+$: + 3241312' on property id (The user_id of the user to retrieve).", + 'errorCode' => 'invalid_uri') + expect(RestClient::Request).to receive(:execute).with(method: http_method, + url: '/test', + timeout: nil, + headers: nil, + payload: '{}') + .and_return(StubResponse.new(res, true, 404)) + expect { @instance.send(http_method, '/test') }.to raise_error(Auth0::NotFound, res) + end + end + end +end diff --git a/spec/lib/auth0/mixins/initializer_spec.rb b/spec/lib/auth0/mixins/initializer_spec.rb index ab597e8d..2c187000 100644 --- a/spec/lib/auth0/mixins/initializer_spec.rb +++ b/spec/lib/auth0/mixins/initializer_spec.rb @@ -3,7 +3,7 @@ class MockClass attr_reader :token include Auth0::Mixins::Initializer - include HTTMultiParty + include Auth0::Mixins::HTTPProxy end describe Auth0::Mixins::Initializer do diff --git a/spec/support/dummy_class_for_proxy.rb b/spec/support/dummy_class_for_proxy.rb index 7e278d33..7b51afa9 100644 --- a/spec/support/dummy_class_for_proxy.rb +++ b/spec/support/dummy_class_for_proxy.rb @@ -1,4 +1,4 @@ class DummyClassForProxy - include HTTMultiParty - base_uri 'http://auth0.com' + include Auth0::Mixins::HTTPProxy + @base_uri = 'http://auth0.com' end diff --git a/spec/support/dummy_class_for_restclient.rb b/spec/support/dummy_class_for_restclient.rb new file mode 100644 index 00000000..ef81d089 --- /dev/null +++ b/spec/support/dummy_class_for_restclient.rb @@ -0,0 +1,2 @@ +class DummyClassForRestClient < RestClient::Exception +end From 1c4bf7a66f2b7873f5984df2f7b694a9ced47833 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Fri, 1 Jul 2016 17:06:12 -0300 Subject: [PATCH 25/36] Add Rack version to the Gem file --- auth0.gemspec | 1 + 1 file changed, 1 insertion(+) diff --git a/auth0.gemspec b/auth0.gemspec index 0470e315..ada494d9 100644 --- a/auth0.gemspec +++ b/auth0.gemspec @@ -28,6 +28,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'pry-nav', '~> 0.2.4' s.add_development_dependency 'rspec', '~> 3.1', '>= 3.1.0' s.add_development_dependency 'rack-test', '~> 0.6' + s.add_development_dependency 'rack', '~> 1.6.4' s.add_development_dependency 'simplecov', '~> 0.9' s.add_development_dependency 'faker', '~> 1.4' s.add_development_dependency 'yard', '~> 0.8' From aa57e52ab0884ecb11d2b3fa9d6ec3f2daf67b69 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Thu, 30 Jun 2016 12:15:31 -0300 Subject: [PATCH 26/36] Fix Impersonate method --- lib/auth0/api/authentication_endpoints.rb | 34 +++++++++++-------- .../api/authentication_endpoints_spec.rb | 30 +++++++++------- 2 files changed, 38 insertions(+), 26 deletions(-) diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index af01ee88..b9d4ad33 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -203,14 +203,30 @@ def delegation(id_token, target, scope = 'openid', api_type = 'app', extra_param # Retrives an impersonation URL to login as another user # @see https://auth0.com/docs/auth-api#!#post--users--user_id--impersonate # @param user_id [string] Impersonate user id + # @param app_client_id [string] Application client id + # @param impersonator_id [string] Impersonator user id id. # @param options [string] Additional Parameters # @return [string] Impersonation URL - def impersonate(user_id, options) + # rubocop:disable Metrics/MethodLength, Metrics/AbcSize + def impersonate(user_id, app_client_id, impersonator_id, options) raise Auth0::InvalidParameter, 'Must supply a valid user_id' if user_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid app_client_id' if app_client_id.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid impersonator_id' if impersonator_id.to_s.empty? raise Auth0::MissingParameter, 'Must supply client_secret' if @client_secret.nil? - authorization_header obtain_access_token - result = post("/users/#{user_id}/impersonate", impersonate_request_params(options)) - authorization_header @token + set_authorization_header obtain_access_token + request_params = { + protocol: options.fetch(:protocol, 'oauth2'), + impersonator_id: impersonator_id, + client_id: app_client_id, + additionalParameters: { + response_type: options.fetch(:response_type, 'code'), + state: options.fetch(:state, ''), + scope: options.fetch(:scope, 'openid'), + callback_url: options.fetch(:callback_url, '') + } + } + result = post("/users/#{user_id}/impersonate", request_params) + set_authorization_header @token result end @@ -293,16 +309,6 @@ def wsfed_url(connection = UP_AUTH) def to_query(hash) hash.map { |k, v| "#{k}=#{URI.escape(v)}" unless v.nil? }.reject(&:nil?).join('&') end - - def impersonate_request_params - { - client_id: @client_id, - response_type: options.fetch(:connection, 'code'), - connection: options.fetch(:connection, nil), - redirect_url: redirect_uri, - state: options.fetch(:state, nil) - }.merge(options.fetch(:additional_parameters, {})) - end end end end diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index 054ee349..064fae98 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -234,23 +234,29 @@ context '.impersonate' do let(:user_id) { 'some_user_id' } + let(:impersonator_id) { 'some_other_user_id' } + let(:app_client_id) { 'app_client_id' } it { expect(@instance).to respond_to(:impersonate) } - # it "is expected to make post request to '/users/{user_id}/impersonate'" do - # expect(@instance).to receive(:post).with( - # "/users/#{user_id}/impersonate", - # protocol: 'oauth2', - # impersonator_id: impersonator_id, client_id: app_client_id, - # additionalParameters: { - # response_type: 'code', state: '', - # scope: 'openid', callback_url: '' }) - # @instance.impersonate(user_id, app_client_id, impersonator_id, {}) - # end it do - expect { @instance.impersonate(user_id, {}) }.to raise_error( + expect { @instance.impersonate(user_id, app_client_id, impersonator_id, {}) }.to raise_error( 'Must supply client_secret' ) end - it { expect { @instance.impersonate('', '') }.to raise_error 'Must supply a valid user_id' } + it do + expect { @instance.impersonate('', app_client_id, impersonator_id, {}) }.to raise_error( + 'Must supply a valid user_id' + ) + end + it do + expect { @instance.impersonate(user_id, app_client_id, '', {}) }.to raise_error( + 'Must supply a valid impersonator_id' + ) + end + it do + expect { @instance.impersonate(user_id, '', impersonator_id, {}) }.to raise_error( + 'Must supply a valid app_client_id' + ) + end end context '.unlink_user' do From b95b598c79526c279e09f2d2d7f773cc5a4e01f6 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Thu, 30 Jun 2016 17:51:39 -0300 Subject: [PATCH 27/36] Add Integration Test to Authentication Endpoints - Impersonate --- lib/auth0/api/authentication_endpoints.rb | 4 +- .../lib/auth0/api/api_authentication_spec.rb | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 spec/integration/lib/auth0/api/api_authentication_spec.rb diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index b9d4ad33..99c62f26 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -213,7 +213,7 @@ def impersonate(user_id, app_client_id, impersonator_id, options) raise Auth0::InvalidParameter, 'Must supply a valid app_client_id' if app_client_id.to_s.empty? raise Auth0::InvalidParameter, 'Must supply a valid impersonator_id' if impersonator_id.to_s.empty? raise Auth0::MissingParameter, 'Must supply client_secret' if @client_secret.nil? - set_authorization_header obtain_access_token + authorization_header obtain_access_token request_params = { protocol: options.fetch(:protocol, 'oauth2'), impersonator_id: impersonator_id, @@ -226,7 +226,7 @@ def impersonate(user_id, app_client_id, impersonator_id, options) } } result = post("/users/#{user_id}/impersonate", request_params) - set_authorization_header @token + authorization_header @token result end diff --git a/spec/integration/lib/auth0/api/api_authentication_spec.rb b/spec/integration/lib/auth0/api/api_authentication_spec.rb new file mode 100644 index 00000000..5c8ee0e9 --- /dev/null +++ b/spec/integration/lib/auth0/api/api_authentication_spec.rb @@ -0,0 +1,40 @@ +require 'spec_helper' +describe Auth0::Api::AuthenticationEndpoints do + attr_reader :client, :impersonate_user, :impersonator_user + + before(:all) do + client = Auth0Client.new(v2_creds) + impersonate_username = Faker::Internet.user_name + impersonate_email = "#{entity_suffix}#{Faker::Internet.safe_email(impersonate_username)}" + password = Faker::Internet.password + @impersonate_user = client.create_user(impersonate_username, 'email' => impersonate_email, + 'password' => password, + 'email_verified' => true, + 'connection' => + Auth0::Api::AuthenticationEndpoints::UP_AUTH, + 'app_metadata' => {}) + + impersonator_username = Faker::Internet.user_name + impersonator_email = "#{entity_suffix}#{Faker::Internet.safe_email(impersonator_username)}" + @impersonator_user = client.create_user(impersonator_username, 'email' => impersonator_email, + 'password' => password, + 'email_verified' => true, + 'connection' => + Auth0::Api::AuthenticationEndpoints::UP_AUTH, + 'app_metadata' => {}) + end + + after(:all) do + client = Auth0Client.new(v2_creds) + client.delete_user(impersonate_user['user_id']) + client.delete_user(impersonator_user['user_id']) + end + + describe '.impersionation' do + let(:global_client) { Auth0Client.new(v1_global_creds) } + let(:impersonate_url) do + global_client.impersonate(impersonate_user['user_id'], ENV['CLIENT_ID'], impersonator_user['user_id'], {}) + end + it { expect(impersonate_url).to_not be_nil } + end +end From 7c83f7a946352017f727025a62b6b8262382fd42 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Mon, 4 Jul 2016 11:25:12 -0300 Subject: [PATCH 28/36] Refactor tests to use the new proxy --- spec/integration/lib/auth0/api/api_authentication_spec.rb | 1 - .../lib/auth0/api/v2/api_device_credentials_spec.rb | 7 ++----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/spec/integration/lib/auth0/api/api_authentication_spec.rb b/spec/integration/lib/auth0/api/api_authentication_spec.rb index 5c8ee0e9..770366e5 100644 --- a/spec/integration/lib/auth0/api/api_authentication_spec.rb +++ b/spec/integration/lib/auth0/api/api_authentication_spec.rb @@ -25,7 +25,6 @@ end after(:all) do - client = Auth0Client.new(v2_creds) client.delete_user(impersonate_user['user_id']) client.delete_user(impersonator_user['user_id']) end diff --git a/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb b/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb index 09d7e6d6..ee8b91ec 100644 --- a/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_device_credentials_spec.rb @@ -1,10 +1,10 @@ require 'spec_helper' require 'base64' describe Auth0::Api::V2::DeviceCredentials do - attr_reader :user, :user_client, :basic_client, :existing_device_credentials + attr_reader :user, :client, :basic_client, :existing_device_credentials before(:all) do - client = Auth0Client.new(v2_creds) + @client = Auth0Client.new(v2_creds) username = Faker::Internet.user_name email = "#{entity_suffix}#{Faker::Internet.safe_email(username)}" password = Faker::Internet.password @@ -29,9 +29,6 @@ end after(:all) do - # Workaround to prevent instance constructor from overwritting class variable (header) - # TODO: fix instance / class isssue from aut0 proxy and remove line below. - client = Auth0Client.new(v2_creds) client.delete_user(user['user_id']) end From 4ed483d84e3b01387860600a86b82a8026303688 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Mon, 4 Jul 2016 17:30:25 -0300 Subject: [PATCH 29/36] Default API v2 --- README.md | 6 ++++-- lib/auth0/mixins/initializer.rb | 8 ++++---- spec/integration/lib/auth0/auth0_client_spec.rb | 8 +++----- spec/lib/auth0/client_spec.rb | 10 ++++++---- spec/support/credentials.rb | 7 ++++--- 5 files changed, 21 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 9dca54c8..c92a85b0 100644 --- a/README.md +++ b/README.md @@ -25,8 +25,9 @@ Using [APIv2](https://auth0.com/docs/api/v2) require "auth0" auth0 = Auth0Client.new( + :client_id => "YOUR CLIENT ID" :token => "YOUR JWT HERE", - :domain => ".auth0.com" + :domain => ".auth0.com" ) puts auth0.get_users @@ -40,7 +41,8 @@ require "auth0" auth0 = Auth0Client.new( :client_id => "YOUR CLIENT ID", :client_secret => "YOUR CLIENT SECRET", - :domain => ".auth0.com" + :domain => ".auth0.com", + :api_version => "1" ) puts auth0.get_users diff --git a/lib/auth0/mixins/initializer.rb b/lib/auth0/mixins/initializer.rb index 6481de6a..d03707ba 100644 --- a/lib/auth0/mixins/initializer.rb +++ b/lib/auth0/mixins/initializer.rb @@ -36,7 +36,7 @@ def authorization_header_basic(options) private def initialize_api(options) - api_v1?(options) ? initialize_v1(options) : initialize_v2(options) + api_v2?(options) ? initialize_v2(options) : initialize_v1(options) raise InvalidCredentials, 'Must supply a valid API token' if @token.nil? if options.fetch(:authorization, nil) == 'Basic' authorization_header_basic(options) @@ -79,10 +79,10 @@ def initialize_v1(options) @token = obtain_access_token end - def api_v1?(options) - version = options[:api_version] || 1 + def api_v2?(options) + version = options[:api_version] || 2 protocol = options[:protocols].to_s - !protocol.include?('v2') && (protocol.include?('v1') || version == 1) + !protocol.include?('v1') && (protocol.include?('v2') || version == 2) end end end diff --git a/spec/integration/lib/auth0/auth0_client_spec.rb b/spec/integration/lib/auth0/auth0_client_spec.rb index b09e4f37..4317e2e3 100644 --- a/spec/integration/lib/auth0/auth0_client_spec.rb +++ b/spec/integration/lib/auth0/auth0_client_spec.rb @@ -33,10 +33,11 @@ let(:valid_v1_credentials) do { client_id: ENV['CLIENT_ID'], client_secret: ENV['CLIENT_SECRET'], - domain: ENV['DOMAIN'] } + domain: ENV['DOMAIN'], + api_version: 1 } end let(:token) { ENV['MASTER_JWT'] } - let(:v2_credentials) { { domain: ENV['DOMAIN'], api_version: 2 } } + let(:v2_credentials) { { domain: ENV['DOMAIN'] } } shared_examples 'valid credentials' do it { expect { Auth0Client.new(credentials) }.to_not raise_error } @@ -45,9 +46,6 @@ it_should_behave_like 'valid credentials' do let(:credentials) { valid_v1_credentials } end - it_should_behave_like 'valid credentials' do - let(:credentials) { valid_v1_credentials.merge(api_version: 1) } - end it_should_behave_like 'valid credentials' do let(:credentials) { v2_credentials.merge(token: token) } end diff --git a/spec/lib/auth0/client_spec.rb b/spec/lib/auth0/client_spec.rb index 6aa5e667..09ee0b12 100644 --- a/spec/lib/auth0/client_spec.rb +++ b/spec/lib/auth0/client_spec.rb @@ -48,7 +48,8 @@ context 'with namespace' do let(:subject) do - Auth0::Client.new(client_id: 'client_id', client_secret: 'client_secret', namespace: 'samples.auth0.com') + Auth0::Client.new(protocols: 'v1', client_id: 'client_id', client_secret: 'client_secret', + namespace: 'samples.auth0.com') end it_should_behave_like 'v1 API client' @@ -57,7 +58,8 @@ context 'with domain' do let(:subject) do - Auth0::Client.new(client_id: 'client_id', client_secret: 'client_secret', domain: 'samples.auth0.com') + Auth0::Client.new(protocols: 'v1', client_id: 'client_id', client_secret: 'client_secret', + domain: 'samples.auth0.com') end it_should_behave_like 'v1 API client' @@ -84,13 +86,13 @@ end context 'with namespace' do - let(:subject) { Auth0::Client.new(protocols: 'v2', access_token: 'access_token', namespace: 'samples.auth0.com') } + let(:subject) { Auth0::Client.new(access_token: 'access_token', namespace: 'samples.auth0.com') } it_should_behave_like 'v2 API client' it_should_behave_like 'authentication API client' end context 'with domain' do - let(:subject) { Auth0::Client.new(protocols: 'v2', access_token: 'access_token', domain: 'samples.auth0.com') } + let(:subject) { Auth0::Client.new(access_token: 'access_token', domain: 'samples.auth0.com') } it_should_behave_like 'v2 API client' it_should_behave_like 'authentication API client' end diff --git a/spec/support/credentials.rb b/spec/support/credentials.rb index 36d95be3..e9ff7a93 100644 --- a/spec/support/credentials.rb +++ b/spec/support/credentials.rb @@ -2,19 +2,20 @@ module Credentials def v1_creds { client_id: ENV['CLIENT_ID'], client_secret: ENV['CLIENT_SECRET'], - domain: ENV['DOMAIN'] } + domain: ENV['DOMAIN'], + api_version: 1 } end def v1_global_creds { client_id: ENV['GLOBAL_CLIENT_ID'], client_secret: ENV['GLOBAL_CLIENT_SECRET'], - domain: ENV['DOMAIN'] } + domain: ENV['DOMAIN'], + api_version: 1 } end def v2_creds { client_id: ENV['CLIENT_ID'], token: ENV['MASTER_JWT'], - api_version: 2, domain: ENV['DOMAIN'] } end end From 6fbf4d206ff3de16ff1749267600b370caffe6a5 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Tue, 5 Jul 2016 18:06:46 -0300 Subject: [PATCH 30/36] Fix response type in Authorization Endpoints --- lib/auth0/api/authentication_endpoints.rb | 2 +- spec/lib/auth0/api/authentication_endpoints_spec.rb | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index 99c62f26..a4823dae 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -260,7 +260,7 @@ def authorization_url(redirect_uri, options = {}) raise Auth0::InvalidParameter, 'Must supply a valid redirect_uri' if redirect_uri.to_s.empty? request_params = { client_id: @client_id, - response_type: options.fetch(:connection, 'code'), + response_type: options.fetch(:response_type, 'code'), connection: options.fetch(:connection, nil), redirect_url: redirect_uri, state: options.fetch(:state, nil) diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index 064fae98..9db57d3c 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -165,6 +165,12 @@ "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&state=state1" ) end + let(:connection) { { connection: 'connection-1' } } + it 'is expected to return an authorization url with additionalParameters' do + expect(@instance.authorization_url(redirect_url, connection).to_s).to eq( + "https://#{@instance.domain}/authorize?response_type=code&connection=connection-1&redirect_url=#{redirect_url}" + ) + end it { expect { @instance.authorization_url('', '') }.to raise_error 'Must supply a valid redirect_uri' } end context '.token_info' do From 47fc48ba2dda83fcce5c9accf72adeb775b33a95 Mon Sep 17 00:00:00 2001 From: Leonardo Soubeste Date: Thu, 7 Jul 2016 12:46:59 -0300 Subject: [PATCH 31/36] Add authentication integration tests. --- lib/auth0/api/authentication_endpoints.rb | 15 ++- .../lib/auth0/api/api_authentication_spec.rb | 93 ++++++++++++++++++- 2 files changed, 96 insertions(+), 12 deletions(-) diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index a4823dae..46e5d4c4 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -90,10 +90,11 @@ def change_password(email, password, connection_name = UP_AUTH) def start_passwordless_email_flow(email, send = 'link', auth_params = {}) raise Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? request_params = { - client_id: @client_id, - email: email, - send: send, - auth_params: auth_params + client_id: @client_id, + connection: "email", + email: email, + send: send, + authParams: auth_params } post('/passwordless/start', request_params) end @@ -132,11 +133,9 @@ def phone_login(phone_number, code, scope = 'openid') # Retrives the SAML 2.0 metadata # @see https://auth0.com/docs/auth-api#!#get--samlp--client_id- - # @param client_id [string] Client id # @return [xml] SAML 2.0 metadata - def saml_metadata(client_id) - raise Auth0::InvalidParameter, 'Must supply a valid client_id' if client_id.to_s.empty? - get("/samlp/metadata/#{client_id}") + def saml_metadata + get("/samlp/metadata/#{@client_id}") end # Retrives the WS-Federation metadata diff --git a/spec/integration/lib/auth0/api/api_authentication_spec.rb b/spec/integration/lib/auth0/api/api_authentication_spec.rb index 770366e5..c34d8998 100644 --- a/spec/integration/lib/auth0/api/api_authentication_spec.rb +++ b/spec/integration/lib/auth0/api/api_authentication_spec.rb @@ -1,12 +1,12 @@ require 'spec_helper' describe Auth0::Api::AuthenticationEndpoints do - attr_reader :client, :impersonate_user, :impersonator_user + attr_reader :client, :impersonate_user, :impersonator_user, :global_client, :password before(:all) do client = Auth0Client.new(v2_creds) impersonate_username = Faker::Internet.user_name impersonate_email = "#{entity_suffix}#{Faker::Internet.safe_email(impersonate_username)}" - password = Faker::Internet.password + @password = Faker::Internet.password @impersonate_user = client.create_user(impersonate_username, 'email' => impersonate_email, 'password' => password, 'email_verified' => true, @@ -22,6 +22,8 @@ 'connection' => Auth0::Api::AuthenticationEndpoints::UP_AUTH, 'app_metadata' => {}) + + @global_client = Auth0Client.new(v1_global_creds) end after(:all) do @@ -29,11 +31,94 @@ client.delete_user(impersonator_user['user_id']) end - describe '.impersionation' do - let(:global_client) { Auth0Client.new(v1_global_creds) } + describe '.obtain_access_token' do + let(:acces_token) { global_client.obtain_access_token } + it { expect(acces_token).to_not be_nil } + end + + describe '.login' do + let(:login) { global_client.login(impersonate_user['email'], password) } + it { expect(login).to(include('id_token', 'access_token', 'token_type')) } + end + + describe '.signup' do + let(:signup_username) { Faker::Internet.user_name } + let(:signup_email) { "#{entity_suffix}#{Faker::Internet.safe_email(signup_username)}" } + let(:signup) { global_client.signup(signup_email, password) } + it { expect(signup).to(include('_id', 'email')) } + end + + describe '.change_password' do + let(:change_password) do + global_client.change_password(impersonate_user['user_id'], password) + end + it { expect(change_password).to eq '"We\'ve just sent you an email to reset your password."' } + end + + skip '.start_passwordless_email_flow' do + let(:start_passwordless_email_flow) do + global_client.start_passwordless_email_flow(impersonate_user['email']) + end + it { expect(start_passwordless_email_flow).to eq '"We\'ve just sent you an email to reset your password."' } + end + + skip '.start_passwordless_sms_flow' do + let(:phone_number) { '+123456778' } + let(:start_passwordless_sms_flow) { global_client.start_passwordless_sms_flow(phone_number) } + it { expect(start_passwordless_sms_flow).to eq '"We\'ve just sent you an email to reset your password."' } + end + + describe '.saml_metadata' do + let(:saml_metadata) { global_client.saml_metadata } + it { expect(saml_metadata).to(include(' Date: Mon, 11 Jul 2016 17:03:58 -0300 Subject: [PATCH 32/36] Fix Rubocop Issues + Unit Tests --- lib/auth0/api/authentication_endpoints.rb | 2 +- .../lib/auth0/api/api_authentication_spec.rb | 34 +++++------ .../api/authentication_endpoints_spec.rb | 59 ++++++++++--------- spec/lib/auth0/api/v1/users_spec.rb | 2 +- spec/support/dummy_class.rb | 3 +- 5 files changed, 50 insertions(+), 50 deletions(-) diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index 46e5d4c4..28535f57 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -91,7 +91,7 @@ def start_passwordless_email_flow(email, send = 'link', auth_params = {}) raise Auth0::InvalidParameter, 'Must supply a valid email' if email.to_s.empty? request_params = { client_id: @client_id, - connection: "email", + connection: 'email', email: email, send: send, authParams: auth_params diff --git a/spec/integration/lib/auth0/api/api_authentication_spec.rb b/spec/integration/lib/auth0/api/api_authentication_spec.rb index c34d8998..107c12bd 100644 --- a/spec/integration/lib/auth0/api/api_authentication_spec.rb +++ b/spec/integration/lib/auth0/api/api_authentication_spec.rb @@ -3,7 +3,7 @@ attr_reader :client, :impersonate_user, :impersonator_user, :global_client, :password before(:all) do - client = Auth0Client.new(v2_creds) + @client = Auth0Client.new(v2_creds) impersonate_username = Faker::Internet.user_name impersonate_email = "#{entity_suffix}#{Faker::Internet.safe_email(impersonate_username)}" @password = Faker::Internet.password @@ -46,6 +46,7 @@ let(:signup_email) { "#{entity_suffix}#{Faker::Internet.safe_email(signup_username)}" } let(:signup) { global_client.signup(signup_email, password) } it { expect(signup).to(include('_id', 'email')) } + it { expect(signup['email']).to eq signup_email } end describe '.change_password' do @@ -59,13 +60,15 @@ let(:start_passwordless_email_flow) do global_client.start_passwordless_email_flow(impersonate_user['email']) end - it { expect(start_passwordless_email_flow).to eq '"We\'ve just sent you an email to reset your password."' } + it { expect(start_passwordless_email_flow['email']).to eq impersonate_user['email'] } + it { expect(start_passwordless_email_flow).to(include('_id', 'email')) } end skip '.start_passwordless_sms_flow' do - let(:phone_number) { '+123456778' } + let(:phone_number) { '+19143686854' } let(:start_passwordless_sms_flow) { global_client.start_passwordless_sms_flow(phone_number) } - it { expect(start_passwordless_sms_flow).to eq '"We\'ve just sent you an email to reset your password."' } + it { expect(start_passwordless_sms_flow['phone_number']).to eq phone_number } + it { expect(start_passwordless_sms_flow).to(include('_id', 'phone_number', 'request_language')) } end describe '.saml_metadata' do @@ -84,13 +87,6 @@ it { expect(token_info).to(include('email', 'clientID', 'global_client_id')) } end - skip '.refresh_delegation' do - let(:access_token) { global_client.login(impersonate_user['email'], password)['access_token'] } - let(:target) { global_client.clients[0]['clientID'] } - let(:refresh_delegation) { global_client.refresh_delegation(access_token, target) } - it { expect(refresh_delegation).to(include('email', 'clientID', 'global_client_id')) } - end - describe '.delegation' do let(:id_token) { global_client.login(impersonate_user['email'], password)['id_token'] } let(:target) { global_client.clients[0]['clientID'] } @@ -111,14 +107,12 @@ it { expect(unlink_user).to eq 'OK' } end - skip '.user_info' do - let(:user_info) { global_client.user_info } - it { expect(user_info).to eq 'OK' } - end - - skip '.authorization_url' do - let(:uri) { 'new_uri' } - let(:authorization_url) { global_client.authorization_url(uri) } - it { expect(get(authorization_url)).to eq 'OK' } + describe '.user_info' do + let(:access_token) { global_client.login(impersonate_user['email'], password)['access_token'] } + let(:credentials) { { client_id: ENV['CLIENT_ID'], token: access_token, domain: ENV['DOMAIN'] } } + let(:client) { Auth0Client.new(credentials) } + let(:user_info) { client.user_info } + it { expect(user_info['email']).to eq impersonate_user['email'] } + it { expect(user_info).to(include('clientID', 'identities', 'nickname', 'picture')) } end end diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index 9db57d3c..a5e0366b 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -11,11 +11,11 @@ it { expect(@instance).to respond_to(:obtain_access_token) } it "is expected to make post request to '/oauth/token'" do allow(@instance).to receive(:post).with( - '/oauth/token', client_id: nil, client_secret: nil, grant_type: 'client_credentials' + '/oauth/token', client_id: @instance.client_id, client_secret: nil, grant_type: 'client_credentials' ) .and_return('access_token' => 'AccessToken') expect(@instance).to receive(:post).with( - '/oauth/token', client_id: nil, client_secret: nil, grant_type: 'client_credentials' + '/oauth/token', client_id: @instance.client_id, client_secret: nil, grant_type: 'client_credentials' ) expect(@instance.obtain_access_token).to eql 'AccessToken' end @@ -25,11 +25,13 @@ it { expect(@instance).to respond_to(:obtain_access_token) } it "is expected to make post request to '/oauth/access_token'" do allow(@instance).to receive(:post).with( - '/oauth/access_token', client_id: nil, access_token: 'access_token', connection: 'facebook', scope: 'openid' + '/oauth/access_token', client_id: @instance.client_id, access_token: 'access_token', connection: 'facebook', + scope: 'openid' ) .and_return('access_token' => 'AccessToken') expect(@instance).to receive(:post).with( - '/oauth/access_token', client_id: nil, access_token: 'access_token', connection: 'facebook', scope: 'openid' + '/oauth/access_token', client_id: @instance.client_id, access_token: 'access_token', connection: 'facebook', + scope: 'openid' ) expect(@instance.obtain_access_token('access_token', 'facebook', 'openid')).to eql 'AccessToken' end @@ -40,7 +42,7 @@ it 'is expected to make post to /oauth/ro' do expect(@instance).to receive(:post).with( '/oauth/ro', - client_id: nil, username: 'test@test.com', + client_id: @instance.client_id, username: 'test@test.com', password: 'password', scope: 'openid', connection: 'Username-Password-Authentication', grant_type: 'password', id_token: nil, device: nil ) @@ -55,7 +57,7 @@ it 'is expected to make post to /dbconnections/signup' do expect(@instance).to receive(:post).with( '/dbconnections/signup', - client_id: nil, email: 'test@test.com', + client_id: @instance.client_id, email: 'test@test.com', password: 'password', connection: 'User' ) @instance.signup('test@test.com', 'password', 'User') @@ -69,7 +71,7 @@ it 'is expected to make post to /dbconnections/change_password' do expect(@instance).to receive(:post).with( '/dbconnections/change_password', - client_id: nil, email: 'test@test.com', + client_id: @instance.client_id, email: 'test@test.com', password: 'password', connection: 'User' ) @instance.change_password('test@test.com', 'password', 'User') @@ -82,10 +84,11 @@ it 'is expected to make post to /passwordless/start' do expect(@instance).to receive(:post).with( '/passwordless/start', - client_id: nil, + client_id: @instance.client_id, + connection: 'email', email: 'test@test.com', send: 'link', - auth_params: { + authParams: { scope: 'scope', protocol: 'protocol' } @@ -101,7 +104,7 @@ it 'is expected to make post to /passwordless/start' do expect(@instance).to receive(:post).with( '/passwordless/start', - client_id: nil, + client_id: @instance.client_id, connection: 'sms', phone_number: phone_number ) @@ -117,7 +120,7 @@ it 'is expected to make post to /oauth/ro' do expect(@instance).to receive(:post).with( '/oauth/ro', - client_id: nil, username: phone_number, + client_id: @instance.client_id, username: phone_number, password: code, connection: 'sms', scope: 'openid', grant_type: 'password' ) @@ -128,13 +131,11 @@ end context '.saml_metadata' do - let(:client_id) { 'client-id' } it { expect(@instance).to respond_to(:saml_metadata) } it 'is expected to make post to /samlp/metadata/client-id' do - expect(@instance).to receive(:get).with("/samlp/metadata/#{client_id}") - @instance.saml_metadata(client_id) + expect(@instance).to receive(:get).with("/samlp/metadata/#{@instance.client_id}") + @instance.saml_metadata end - it { expect { @instance.saml_metadata('') }.to raise_error 'Must supply a valid client_id' } end context '.wsfed_metadata' do @@ -150,25 +151,29 @@ it { expect(@instance).to respond_to(:authorization_url) } it 'is expected to return an authorization url' do expect(@instance.authorization_url(redirect_url).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}" + "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ + "redirect_url=#{redirect_url}" ) end let(:additional_parameters) { { additional_parameters: { aparam1: 'test1' } } } it 'is expected to return an authorization url with additionalParameters' do expect(@instance.authorization_url(redirect_url, additional_parameters).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&aparam1=test1" + "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ + "redirect_url=#{redirect_url}&aparam1=test1" ) end let(:state) { { state: 'state1' } } it 'is expected to return an authorization url with additionalParameters' do expect(@instance.authorization_url(redirect_url, state).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&redirect_url=#{redirect_url}&state=state1" + "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ + "redirect_url=#{redirect_url}&state=state1" ) end let(:connection) { { connection: 'connection-1' } } it 'is expected to return an authorization url with additionalParameters' do expect(@instance.authorization_url(redirect_url, connection).to_s).to eq( - "https://#{@instance.domain}/authorize?response_type=code&connection=connection-1&redirect_url=#{redirect_url}" + "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ + "connection=connection-1&redirect_url=#{redirect_url}" ) end it { expect { @instance.authorization_url('', '') }.to raise_error 'Must supply a valid redirect_uri' } @@ -187,7 +192,7 @@ it "is expected to make post request to '/delegation'" do expect(@instance).to receive(:post).with( '/delegation', - client_id: nil, + client_id: @instance.client_id, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', refresh_token: 'id_token', target: '', api_type: '', scope: '', additional_parameter: 'parameter' @@ -202,7 +207,7 @@ it "is expected to make post request to '/delegation'" do expect(@instance).to receive(:post).with( '/delegation', - client_id: nil, + client_id: @instance.client_id, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', id_token: 'token', target: 'target', @@ -215,7 +220,7 @@ with specified api_type" do expect(@instance).to receive(:post).with( '/delegation', - client_id: nil, + client_id: @instance.client_id, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', id_token: 'id_token', target: '', scope: '', api_type: 'salesforce_api' @@ -225,7 +230,7 @@ it 'allows to pass extra parameters' do expect(@instance).to receive(:post).with( '/delegation', - client_id: nil, + client_id: @instance.client_id, grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', id_token: 'id_token', target: '', scope: '', api_type: '', community_name: 'test-community', community_url: 'test-url' @@ -297,12 +302,12 @@ it { expect(@instance).to respond_to(:samlp_url) } it 'is expected to get the samlp url' do expect(@instance.samlp_url.to_s).to eq( - "https://#{@instance.domain}/samlp/?connection=Username-Password-Authentication" + "https://#{@instance.domain}/samlp/#{@instance.client_id}?connection=Username-Password-Authentication" ) end it 'is expected to get the samlp url with fb connection' do expect(@instance.samlp_url('facebook').to_s).to eq( - "https://#{@instance.domain}/samlp/?connection=facebook" + "https://#{@instance.domain}/samlp/#{@instance.client_id}?connection=facebook" ) end end @@ -311,12 +316,12 @@ it { expect(@instance).to respond_to(:wsfed_url) } it 'is expected to get the wsfed url' do expect(@instance.wsfed_url.to_s).to eq( - "https://#{@instance.domain}/wsfed/?whr=Username-Password-Authentication" + "https://#{@instance.domain}/wsfed/#{@instance.client_id}?whr=Username-Password-Authentication" ) end it 'is expected to get the wsfed url with fb connection' do expect(@instance.wsfed_url('facebook').to_s).to eq( - "https://#{@instance.domain}/wsfed/?whr=facebook" + "https://#{@instance.domain}/wsfed/#{@instance.client_id}?whr=facebook" ) end end diff --git a/spec/lib/auth0/api/v1/users_spec.rb b/spec/lib/auth0/api/v1/users_spec.rb index 8c01e7be..9f21c18b 100644 --- a/spec/lib/auth0/api/v1/users_spec.rb +++ b/spec/lib/auth0/api/v1/users_spec.rb @@ -89,7 +89,7 @@ @instance.client_users('test_client_id') end it 'is expected to call /api/client//users if no client_id passed' do - expect(@instance).to receive(:get).with('/api/clients//users') + expect(@instance).to receive(:get).with("/api/clients/#{@instance.client_id}/users") expect { @instance.client_users }.not_to raise_error end end diff --git a/spec/support/dummy_class.rb b/spec/support/dummy_class.rb index 1b60bb1c..cf3289be 100644 --- a/spec/support/dummy_class.rb +++ b/spec/support/dummy_class.rb @@ -1,8 +1,9 @@ class DummyClass - attr_reader :domain + attr_reader :domain, :client_id def initialize @domain = 'test.auth0.com' + @client_id = 'NyW50o8Qt8I1VhMVlTlfVwWLGzBIPuxb' end %i(get post put patch delete).each do |method| From fb9be6fe82c15b541886df0d568bdde53933e80a Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Thu, 7 Jul 2016 17:16:47 -0300 Subject: [PATCH 33/36] adds obtain_user_token method to authentication endpoints --- lib/auth0/api/authentication_endpoints.rb | 27 +++++++++++++++++-- .../api/authentication_endpoints_spec.rb | 18 +++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/lib/auth0/api/authentication_endpoints.rb b/lib/auth0/api/authentication_endpoints.rb index 28535f57..1fa4d1ba 100644 --- a/lib/auth0/api/authentication_endpoints.rb +++ b/lib/auth0/api/authentication_endpoints.rb @@ -22,6 +22,28 @@ def obtain_access_token(access_token = nil, connection = 'facebook', scope = 'op end end + # Gets the user tokens using the code obtained through passive authentication in the specified connection + # @see https://auth0.com/docs/auth-api#!#post--oauth-access_token + # @param connection [string] Currently, this endpoint only works for Facebook, Google, Twitter and Weibo + # @param scope [string] Defaults to openid. Can be 'openid name email', 'openid offline_access' + # @param redirect_uri [string] Url to redirect after authorization + # @param redirect_uri [string] The access code obtained through passive authentication + # @return [json] Returns the access_token and id_token + def obtain_user_tokens(code, redirect_uri, connection = 'facebook', scope = 'openid') + raise Auth0::InvalidParameter, 'Must supply a valid code' if code.to_s.empty? + raise Auth0::InvalidParameter, 'Must supply a valid redirect_uri' if redirect_uri.to_s.empty? + request_params = { + client_id: @client_id, + client_secret: @client_secret, + connection: connection, + grant_type: 'authorization_code', + code: code, + scope: scope, + redirect_uri: redirect_uri + } + post('/oauth/token', request_params) + end + # Logins using username/password # @see https://auth0.com/docs/auth-api#!#post--oauth-ro # @param username [string] Username @@ -261,8 +283,9 @@ def authorization_url(redirect_uri, options = {}) client_id: @client_id, response_type: options.fetch(:response_type, 'code'), connection: options.fetch(:connection, nil), - redirect_url: redirect_uri, - state: options.fetch(:state, nil) + redirect_uri: redirect_uri, + state: options.fetch(:state, nil), + scope: options.fetch(:scope, nil) }.merge(options.fetch(:additional_parameters, {})) URI::HTTPS.build(host: @domain, path: '/authorize', query: to_query(request_params)) diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index a5e0366b..b0678a2c 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -37,6 +37,24 @@ end end + context '.obtain_user_tokens' do + it { expect(@instance).to respond_to(:obtain_user_tokens) } + it "is expected to make post request to '/oauth/token'" do + allow(@instance).to receive(:post).with( + '/oauth/token', client_id: @instance.client_id, client_secret: nil, grant_type: 'authorization_code', + connection: 'facebook', code: 'code', scope: 'openid', redirect_uri: 'uri' + ) + .and_return('user_tokens' => 'UserToken') + expect(@instance).to receive(:post).with( + '/oauth/token', client_id: @instance.client_id, client_secret: nil, grant_type: 'authorization_code', + connection: 'facebook', code: 'code', scope: 'openid', redirect_uri: 'uri' + ) + expect(@instance.obtain_user_tokens('code', 'uri')['user_tokens']).to eq 'UserToken' + end + it { expect { @instance.obtain_user_tokens('', '') }.to raise_error 'Must supply a valid code' } + it { expect { @instance.obtain_user_tokens('code', '') }.to raise_error 'Must supply a valid redirect_uri' } + end + context '.login' do it { expect(@instance).to respond_to(:login) } it 'is expected to make post to /oauth/ro' do From 89bb6a4bf79d9dc1ec0900ef8c38994137abe65e Mon Sep 17 00:00:00 2001 From: Ezequiel Aranda Date: Fri, 15 Jul 2016 16:49:36 -0300 Subject: [PATCH 34/36] Fix authorization url parameter name error in unit tests --- .../auth0/api/authentication_endpoints_spec.rb | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/spec/lib/auth0/api/authentication_endpoints_spec.rb b/spec/lib/auth0/api/authentication_endpoints_spec.rb index b0678a2c..17d63536 100644 --- a/spec/lib/auth0/api/authentication_endpoints_spec.rb +++ b/spec/lib/auth0/api/authentication_endpoints_spec.rb @@ -165,33 +165,33 @@ end context '.authorization_url' do - let(:redirect_url) { 'http://redirect.com' } + let(:redirect_uri) { 'http://redirect.com' } it { expect(@instance).to respond_to(:authorization_url) } it 'is expected to return an authorization url' do - expect(@instance.authorization_url(redirect_url).to_s).to eq( + expect(@instance.authorization_url(redirect_uri).to_s).to eq( "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ - "redirect_url=#{redirect_url}" + "redirect_uri=#{redirect_uri}" ) end let(:additional_parameters) { { additional_parameters: { aparam1: 'test1' } } } it 'is expected to return an authorization url with additionalParameters' do - expect(@instance.authorization_url(redirect_url, additional_parameters).to_s).to eq( + expect(@instance.authorization_url(redirect_uri, additional_parameters).to_s).to eq( "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ - "redirect_url=#{redirect_url}&aparam1=test1" + "redirect_uri=#{redirect_uri}&aparam1=test1" ) end let(:state) { { state: 'state1' } } it 'is expected to return an authorization url with additionalParameters' do - expect(@instance.authorization_url(redirect_url, state).to_s).to eq( + expect(@instance.authorization_url(redirect_uri, state).to_s).to eq( "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ - "redirect_url=#{redirect_url}&state=state1" + "redirect_uri=#{redirect_uri}&state=state1" ) end let(:connection) { { connection: 'connection-1' } } it 'is expected to return an authorization url with additionalParameters' do - expect(@instance.authorization_url(redirect_url, connection).to_s).to eq( + expect(@instance.authorization_url(redirect_uri, connection).to_s).to eq( "https://#{@instance.domain}/authorize?client_id=#{@instance.client_id}&response_type=code&"\ - "connection=connection-1&redirect_url=#{redirect_url}" + "connection=connection-1&redirect_uri=#{redirect_uri}" ) end it { expect { @instance.authorization_url('', '') }.to raise_error 'Must supply a valid redirect_uri' } From 7a098537f0bd3ee60525677ae95df3d439a8f14d Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Thu, 21 Jul 2016 09:58:56 -0300 Subject: [PATCH 35/36] Add timeout example to Readme.md --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index c92a85b0..727837e8 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,22 @@ auth0 = Auth0Client.new( puts auth0.get_users ``` +### Timeout +You can setup a custom timeout in the Auth0Client. By default it is set to 10 minutes. + +```ruby +require "auth0" + +auth0 = Auth0Client.new( + :client_id => "YOUR CLIENT ID" + :token => "YOUR JWT HERE", + :domain => ".auth0.com", + :timeout => 15 +) + +puts auth0.get_users +``` + ## What is Auth0? Auth0 helps you to: From 9507df4153fecb2be5809e24f3a6d5a9ad45bf54 Mon Sep 17 00:00:00 2001 From: Ignacio Jonas Date: Thu, 21 Jul 2016 10:30:35 -0300 Subject: [PATCH 36/36] Fix ticket endpoint with mandatory password. --- lib/auth0/api/v2/tickets.rb | 5 +---- spec/integration/lib/auth0/api/v2/api_tickets_spec.rb | 4 ++-- spec/lib/auth0/api/v2/tickets_spec.rb | 9 ++------- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/lib/auth0/api/v2/tickets.rb b/lib/auth0/api/v2/tickets.rb index 6af75117..efede1ee 100644 --- a/lib/auth0/api/v2/tickets.rb +++ b/lib/auth0/api/v2/tickets.rb @@ -33,10 +33,7 @@ def post_email_verification(user_id, result_url: nil) # @param email [string] The user's email. # # @return [json] Returns the created ticket url. - def post_password_change(new_password, user_id: nil, result_url: nil, connection_id: nil, email: nil) - if new_password.to_s.empty? - raise Auth0::InvalidParameter, 'Must supply a valid new password to post a password-change' - end + def post_password_change(new_password: nil, user_id: nil, result_url: nil, connection_id: nil, email: nil) path = "#{tickets_path}/password-change" request_params = { user_id: user_id, diff --git a/spec/integration/lib/auth0/api/v2/api_tickets_spec.rb b/spec/integration/lib/auth0/api/v2/api_tickets_spec.rb index 51fc500a..11e98733 100644 --- a/spec/integration/lib/auth0/api/v2/api_tickets_spec.rb +++ b/spec/integration/lib/auth0/api/v2/api_tickets_spec.rb @@ -25,8 +25,8 @@ describe '.post_password_change' do let(:password_change) do - client.post_password_change('secret', user_id: user['user_id'], - result_url: 'http://myapp.com/callback') + client.post_password_change(new_password: 'secret', user_id: user['user_id'], + result_url: 'http://myapp.com/callback') end it { expect(password_change).to include('ticket') } end diff --git a/spec/lib/auth0/api/v2/tickets_spec.rb b/spec/lib/auth0/api/v2/tickets_spec.rb index 3cab1d32..9389cffc 100644 --- a/spec/lib/auth0/api/v2/tickets_spec.rb +++ b/spec/lib/auth0/api/v2/tickets_spec.rb @@ -20,14 +20,9 @@ it { expect(@instance).to respond_to(:post_password_change) } it 'expect client to send post to /api/v2/tickets/password-change with body' do expect(@instance).to receive(:post).with('/api/v2/tickets/password-change', user_id: nil, result_url: nil, - new_password: 'new_pass', + new_password: nil, connection_id: nil, email: nil) - expect { @instance.post_password_change('new_pass') }.not_to raise_error - end - it 'expect client to rasie error when calling with empty body' do - expect { @instance.post_password_change(nil) }.to raise_error( - 'Must supply a valid new password to post a password-change' - ) + expect { @instance.post_password_change }.not_to raise_error end end end