Sha256: 45168314832e52395d3c0a954db8196660f28edc9b791e1288ef711855112662

Contents?: true

Size: 1.67 KB

Versions: 2

Compression:

Stored size: 1.67 KB

Contents

module Challah
  module Authorization
    def challah_authorization
      unless included_modules.include?(InstanceMethods)
        include InstanceMethods
        extend ClassMethods
      end
    end

    module InstanceMethods
      def user
        return nil unless self.user_id
        @user ||= ::User.where(id: self.user_id).first
      end
    end

    module ClassMethods
      def hashable_attributes
        @hashable_attributes ||= self.columns.map(&:name) - %w( user_id provider last_session_at last_session_ip session_count created_at updated_at )
      end

      # Remove an authorization
      def del(options = {})
        provider  = options.fetch(:provider)
        user_id   = options.fetch(:user_id)

        where(provider: provider, user_id: user_id).delete_all
      end

      # Grab the user/provider record
      def get(options = {})
        provider  = options.fetch(:provider)
        user_id   = options.fetch(:user_id)

        where(provider: provider, user_id: user_id).first
      end

      # Create a new authorization record for the given user
      def set(options = {})
        provider    = options.delete(:provider)
        user_id     = options.delete(:user_id).to_i
        uid         = options.delete(:uid)
        token       = options.delete(:token)
        expires_at  = options.delete(:expires_at) || nil

        del(provider: provider, user_id: user_id)

        record = self.new()
        record.provider = provider
        record.user_id = user_id
        record.uid = uid
        record.token = token
        record.expires_at = expires_at

        record.attributes = options if options.any?

        record.save!
        record
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
challah-1.0.0 lib/challah/authorization.rb
challah-1.0.0.beta3 lib/challah/authorization.rb