#345: fixed auntification by token
This commit is contained in:
parent
64f969274d
commit
b85d6c4c2d
|
@ -13,6 +13,24 @@ class Api::V1::BaseController < ApplicationController
|
|||
|
||||
protected
|
||||
|
||||
# For this example, we are simply using token authentication
|
||||
# via parameters. However, anyone could use Rails's token
|
||||
# authentication features to get the token from a header.
|
||||
def authenticate_user!
|
||||
user_token = params[:user_token].presence
|
||||
user = user_token && User.find_by_authentication_token(user_token.to_s)
|
||||
|
||||
if user
|
||||
# Notice we are passing store false, so the user is not
|
||||
# actually stored in the session and a token is needed
|
||||
# for every request. If you want the token to work as a
|
||||
# sign in token, you can simply remove store: false.
|
||||
sign_in user, store: false
|
||||
else
|
||||
super
|
||||
end
|
||||
end
|
||||
|
||||
def set_csv_file_headers(file_name)
|
||||
headers['Content-Type'] = 'text/csv'
|
||||
headers['Content-disposition'] = "attachment; filename=\"#{file_name}.csv\""
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
module TokenAuthenticatable
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
module ClassMethods
|
||||
def find_by_authentication_token(authentication_token = nil)
|
||||
if authentication_token
|
||||
where(authentication_token: authentication_token).first
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def ensure_authentication_token
|
||||
if authentication_token.blank?
|
||||
self.authentication_token = generate_authentication_token
|
||||
end
|
||||
end
|
||||
|
||||
def reset_authentication_token!
|
||||
self.authentication_token = generate_authentication_token
|
||||
save
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def generate_authentication_token
|
||||
loop do
|
||||
token = Devise.friendly_token
|
||||
break token unless self.class.unscoped.where(authentication_token: token).first
|
||||
end
|
||||
end
|
||||
end
|
|
@ -3,6 +3,7 @@ class User < Avatar
|
|||
include ActsLikeMember
|
||||
include Feed::User
|
||||
include EventLoggable
|
||||
include TokenAuthenticatable
|
||||
|
||||
ROLES = ['', 'admin', 'banned', 'tester']
|
||||
EXTENDED_ROLES = ROLES | ['system']
|
||||
|
@ -160,12 +161,6 @@ class User < Avatar
|
|||
end
|
||||
end
|
||||
|
||||
def ensure_authentication_token
|
||||
if authentication_token.blank?
|
||||
self.authentication_token = generate_authentication_token
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
|
||||
def target_roles target
|
||||
|
@ -182,11 +177,4 @@ class User < Avatar
|
|||
roles.map(&:role).uniq
|
||||
end
|
||||
|
||||
def generate_authentication_token
|
||||
loop do
|
||||
token = Devise.friendly_token
|
||||
break token unless User.where(authentication_token: token).first
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
|
Loading…
Reference in New Issue