diff --git a/app/controllers/api/v1/base_controller.rb b/app/controllers/api/v1/base_controller.rb index f06fb29ee..98503257a 100644 --- a/app/controllers/api/v1/base_controller.rb +++ b/app/controllers/api/v1/base_controller.rb @@ -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\"" diff --git a/app/models/concerns/token_authenticatable.rb b/app/models/concerns/token_authenticatable.rb new file mode 100644 index 000000000..54bba7fdd --- /dev/null +++ b/app/models/concerns/token_authenticatable.rb @@ -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 \ No newline at end of file diff --git a/app/models/user.rb b/app/models/user.rb index 1a2ddf08c..3e84c89ec 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -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