Commit 9e9658eb by liyijie

Add code session controller module

parent b2fa073d
......@@ -2,6 +2,7 @@ require "rails_api_authentication/version"
require "rails_api_authentication/configuration"
require "rails_api_authentication/auth_action"
require "rails_api_authentication/auth_session"
require "rails_api_authentication/code_session"
require "rails_api_authentication/auth_password"
require "rails_api_authentication/auth_token"
require "rails_api_authentication/authable"
......
......@@ -18,5 +18,12 @@ module RailsApiAuthentication
auth_action klass_sym, only: [:update]
auth_password klass_sym
end
def acts_as_code_session(klass_sym)
include RailsApiAuthentication::AuthAction
include RailsApiAuthentication::CodeSession
auth_action klass_sym, only: [:destroy]
code_session klass_sym
end
end
end
......@@ -50,7 +50,7 @@ module RailsApiAuthentication
end
def code_login name, code
raise(UserError.new(401, '-1', "The authorization need password")) if @auth_password.present
raise(UserError.new(401, '-1', "The authorization need password")) if @auth_password.present?
valid! name, code
user = self.find_or_create_by(@auth_key => name)
raise(UserError.new(401, '-1', 'Unauthorized')) if user.nil?
......@@ -76,7 +76,9 @@ module RailsApiAuthentication
def register(name, password, attrs={})
raise(UserError.new(401, '-1', 'password is blank')) if password.blank?
valid! name, attrs.delete(@valid_key)
self.create!({@auth_key => name, @auth_password => generate_password(password)}.merge attrs)
user = self.create!({@auth_key => name, @auth_password => generate_password(password)}.merge attrs)
user.token = AuthToken.create(self, { oid: user.id }).token
user
rescue ActiveRecord::RecordInvalid => e
raise UserError.new(401, '-1', e.message)
end
......
module RailsApiAuthentication
module CodeSession
extend ActiveSupport::Concern
included do
end
def create
auth_key = self.class.klass.auth_key
valid_key = self.class.klass.valid_key
@auth_token = self.class.klass.code_login(session_params[auth_key], session_params[valid_key])
render json: { token: @auth_token.token }, status: 200
rescue UserError => e
render json: { error: e.message }, status: e.status
end
def destroy
self.send("current_#{self.class.klass_sym}")&.logout
render json: { message: "logout successful" }, status: 200
end
private
def session_params
auth_key = self.class.klass.auth_key
valid_key = self.class.klass.valid_key
params.require(self.class.klass_sym).permit(auth_key, valid_key)
end
module ClassMethods
attr_reader :klass, :klass_sym
def code_session klass_sym
@klass = klass_sym.to_s.camelize.constantize
@klass_sym = klass_sym
end
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment