Last active
August 29, 2015 14:07
-
-
Save aishek/e25d7c73fd0e500e1444 to your computer and use it in GitHub Desktop.
Gape api auth example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/api/v1/base_api.rb | |
class Api::V1::BaseAPI < Grape::API | |
class AccessDenied < ArgumentError; end | |
class InvalidToken < ArgumentError; end | |
Grape::Endpoint.class_eval do | |
def abilities | |
@abilities ||= Six.new | |
end | |
def can?(action, subject) | |
abilities << subject | |
abilities.allowed?(current_user, action, subject) | |
end | |
def authorize!(action, subject = self) | |
raise AccessDenied unless can?(action, subject) | |
end | |
def current_user | |
@current_user | |
end | |
def authenticate_current_user!(access_token) | |
@current_user = ::User.find_by! :single_access_token => access_token | |
rescue ActiveRecord::RecordNotFound | |
raise InvalidToken | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/api/v1/users/friends_api.rb | |
class Api::V1::Users::FriendsAPI < Api::V1::BaseAPI | |
namespace 'users/:user_id' do | |
resource :friends do | |
helpers ::Api::V1::UserHelper | |
params do | |
requires :access_token, :type => String | |
end | |
get '/' do | |
authenticate_current_user! params[:access_token] | |
authorize! :friends, resource_user | |
friends = resource_user.friends | |
present :friends, friends, :with => ::Api::V1::UserEntity | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment