Sha256: 3b910e927baa60433dc80d5bbe109aba61f1b85334762ef16803181bdba8cd10

Contents?: true

Size: 1000 Bytes

Versions: 1

Compression:

Stored size: 1000 Bytes

Contents

require 'securerandom'

module AssetHostCore
  class ApiUser < ActiveRecord::Base
    has_many :api_user_permissions
    has_many :permissions, through: :api_user_permissions

    validates_uniqueness_of :auth_token
    validates :name, :email, presence: true

    before_create :generate_auth_token, if: -> {
      self.auth_token.blank?
    }

    attr_accessible :name, :email, :is_active, :permission_ids

    class << self
      def authenticate(auth_token)
        if user = self.where(is_active: true, auth_token: auth_token).first
          user.update_column(:last_authenticated, Time.now)
          user
        else
          false
        end
      end
    end


    def may?(ability, resource)
      !!self.permissions.find do |p|
        p.resource == resource.to_s && p.ability == ability.to_s
      end
    end


    def generate_auth_token
      self.auth_token = SecureRandom.urlsafe_base64
    end

    def generate_auth_token!
      generate_auth_token and save
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
asset_host_core-2.0.0.beta app/models/asset_host_core/api_user.rb