ruby on rails api,如何验证用户?

时间:2017-07-17 01:25:14

标签: ruby-on-rails ruby rspec

某个控制器:

source 'https://rubygems.org'

## Rails - Lock project at 4.2.x
gem 'rails', '4.2.6'

## Database and ActiveRecord related
gem 'pg' # use postgres database
gem 'schema_plus_indexes' # adds various convenient capabilities to ActiveRecord's index handling. see: https://github.com/SchemaPlus/schema_plus_indexes
gem 'paranoia' #provides for 'soft' delete functionality using .deleted_at column, see: https://github.com/radar/paranoia
gem 'has_scope', '0.6.0' # Has scope allows you to easily create controller filters based on your resources named scopes. see https://github.com/plataformatec/has_scope
gem 'seedbank', git: "https://github.com/james2m/seedbank.git" #Seedbank allows you to structure your Rails seed data instead of having it all dumped into one large file.
gem 'globalize' # Rails I18n de-facto standard library for ActiveRecord model/data translation.
gem 'ancestry' # Ancestry is a gem/plugin that allows the records of a Ruby on Rails ActiveRecord model to be organised as a tree structure
gem 'delayed_job_active_record' # Delayed::Job (or DJ) encapsulates the common pattern of asynchronously executing longer tasks in the background.
gem 'daemons'

## Routing & Controller related
gem 'friendly_id', '~> 5.0.0' #Provides methods for managing slug-based routes. See this link for docs: http://norman.github.io/friendly_id/4.0/file.Guide.html 4.x version used as 5.x is for Rails 4.x
gem 'versionist' #A plugin for versioning Rails based RESTful APIs. see: https://github.com/bploetz/versionist

## Caching and Performanceg
gem 'dalli' #provides high-performance memcached functionality to Rails apps

## View and Presenter related
gem 'active_model_serializers', '~> 0.10.0' # ActiveModelSerializers brings convention over configuration to your JSON generation. see: https://github.com/rails-api/active_model_serializers
gem 'slim' #provides SLIM templating.

## Authentication, authorization, and user related
gem 'devise_token_auth'
gem 'omniauth', '<=1.3.2'
gem 'omniauth-oauth2'
gem 'pundit' # Roles and permissions handling. see: https://github.com/elabs/pundit

## Security
gem 'rack-cors', :require => 'rack/cors'
#gem 'secure_headers'

## Admin portal
gem 'rails_admin'
gem 'rails_admin_globalize_field'

## Javascript
gem 'gon'# Simple way to make Rails variables available in JS/Coffeescript, see: https://github.com/gazay/gon

## Media and upload/download related
gem 'paperclip'

# Package manager for frontend frameworks, libraries, assets, and utilities
gem "bower-rails", "~> 0.10.0"

# Support for items usually found in the asset pipeline.
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0' # Use Uglifier as compressor for JavaScript assets
gem 'coffee-rails', '~> 4.1.0' # Use CoffeeScript for .coffee assets and views
gem 'turbolinks' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'jbuilder', '~> 2.0'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jquery-rails', '~> 4.1'
gem 'sdoc', '~> 0.4.0', group: :doc # bundle exec rake doc:rails generates the API under doc/api.
gem 'compass-rails'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'faker' #makes it easy to provide fake data for testing, see: https://github.com/stympy/faker

# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Unicorn as the app server
gem 'unicorn'
gem 'ckeditor' # wysiwyg editor
gem 'state_machines'
gem 'twilio-ruby', '~> 4.11.1'
gem 'plivo'

gem 'ruby_dep', '1.3'
gem 'listen', '3.0.0'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
  gem 'rspec-rails', '3.5.2' #required in both dev and test groups
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'
  gem 'mailcatcher'

  # Debugging tools
  gem "better_errors"
  gem "binding_of_caller"
  # Deployment tools
  gem 'capistrano', '3.3.5'
  gem 'capistrano-rails', '1.1.6'
  gem 'capistrano-rvm', '0.1.2'
  gem 'capistrano3-unicorn', '0.2.1'
  gem 'capistrano-secrets-yml', '~> 1.0.0'
  gem 'capistrano-upload-config', '0.7.0'
  gem 'capistrano-faster-assets', '~> 1.0'
  #gem 'capistrano-bower'
  gem 'rspec-collection_matchers'
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
end

group :test do
 gem 'rspec'
 gem 'capybara', '2.7' #simulates how a real-user would interact with the app.
 gem 'poltergeist' #provides headless brower-based testing for Capybara, see: https://github.com/jonleighton/poltergeist
 gem 'guard-rspec' #allows to automatically & intelligently launch specs when files are modified
 gem 'factory_girl',  "~> 4.0" #a replacement for standard fixtures for testing, can be used with faker, see: http://viccode.blogspot.com/2010/12/using-factorygirl-and-faker.html
 gem 'factory_girl_rails',  "~> 4.0" #a fixtures replacement with a straightforward definition syntax, support for multiple build strategies. see https://github.com/thoughtbot/factory_girl_rails
 gem "database_cleaner" #provides database manipulation services for tests, see: https://github.com/bmabey/database_cleaner
 #gem 'mocha' #a ruby library for mocking and stubbing, see: http://gofreerange.com/mocha/docs/
 gem 'launchy'
 gem 'fuubar' # RSpec formatter
 gem "email_spec"
 gem 'shoulda'
end

gemfile:

class API::V1::BaseController < ApplicationController

  before_action :resource_find, only: [ :show, :update, :destroy ]
  before_action :build_resource, only: [ :create ]

  # TODO handle eager loading and parameter scoping
  def index
    @resources = apply_scopes(resource_class_name).all
    render json: @resources, root: false
  end

  def show
    render json: @entity
  end

  def create
    if @entity.save
      render json: @entity
    else
      render json: {success: false, errors: @entity.errors}, status: 422
    end
  end

  def update
    if @entity.update(permitted_params)
      render json: @entity
    else
      render json: {success: false, errors: @entity.errors}, status: 422
    end
  end

  def destroy
    @entity.destroy
    render json: {success: true}, status: 200
  end

  private

  def resource_find
    @entity = resource_class_name.find(params[:id])
  end

  def build_resource
    @entity = resource_class_name.new(permitted_params)
  end

  def permitted_params(parameters = params)
    parameters.permit(self.class::PERMITTED_ATTRIBUTES)
    # TODO test logic with disallowed_attrs
    #allowed = self.class::PERMITTED_ATTRIBUTES - @disallowed_attrs
    #parameters.require(self.class::JSON_CLASSNAME).permit(allowed).tap do |white_listed|
    #  self.class::WHITE_LIST_ATTRIBUTES.each do |attr|
    #    white_listed[attr] = parameters[self.class::JSON_CLASSNAME][attr] unless @disallowed_attrs.include?(attr)
    #  end
    #end
  end

  def authorize_resource
    render json: { message: "You're not authoried to see this page"} unless current_user.has_enough_permissions?(action_name, resource_class_name)
  end

end

我不需要知道如何验证用户,我猜它使用了一些auth_token或者我是ruby的新手,我需要这样我可以继续我的控制器测试,RSpec测试的一些例子对于控制器会很好,谢谢

更新:

filter_

2 个答案:

答案 0 :(得分:0)

点击此处https://github.com/lynndylanhurley/devise_token_auth。 您的Gemfile中提到了gem。如果Rails应用程序正在公开API,那么在您提出的问题中提到的Gemfile和Controller应该是什么情况。然后,这个gem负责与Devise一起验证用户。

您可能还可以使用Auth或Auth2来加载相应的宝石。

答案 1 :(得分:-1)

我怀疑身份验证方法是authenticate_api_v1_user!,我怀疑这位于API::V1::BaseController。按惯例,它应该在api/v1/base_controller.rb上。 关于它如何工作,你应该检查代码。或者向我们展示authenticate_api_v1_user!

的代码