61 lines
2.1 KiB
Ruby
61 lines
2.1 KiB
Ruby
module JamRuby
|
|
class UserPresence < ActiveRecord::Base
|
|
|
|
PERMISSION_MSG = "You do not have permission to perform this operation."
|
|
|
|
attr_accessible :user_id, :service_type, :username
|
|
belongs_to :user, :class_name => "JamRuby::User", :foreign_key => "user_id"
|
|
|
|
validates :service_type, presence:true, length: {maximum: 100}
|
|
validates :username, presence:true, length: {maximum: 100}
|
|
|
|
validate :username_service_type_unique
|
|
|
|
def username_service_type_unique
|
|
match = UserPresence.exists?(:username => self.username, :service_type => self.service_type)
|
|
raise ConflictError, "Username #{self.username} is already associated with a #{self.service_type} account" if match
|
|
end
|
|
|
|
def self.index(options = {})
|
|
raise StateError, "The user is not specified." if options[:id].blank?
|
|
UserPresence.where("user_id = ?", options[:id])
|
|
end
|
|
|
|
def self.create(current_user, options = {})
|
|
auth_user(current_user, options)
|
|
raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank?
|
|
|
|
up = UserPresence.new({:user_id => current_user.id, :service_type => options[:service_type], :username => options[:username]})
|
|
up.save!
|
|
end
|
|
|
|
def self.update(current_user, options = {})
|
|
auth_user(current_user, options)
|
|
raise StateError, "Missing required information" if options[:service_type].blank? || options[:username].blank? || options[:id].blank?
|
|
|
|
up = UserPresence.find(options[:id])
|
|
up.service_type = options[:service_type]
|
|
up.username = options[:username]
|
|
up.save!
|
|
end
|
|
|
|
def self.delete(current_user, options = {})
|
|
id = options[:id]
|
|
raise StateError, "Missing required information" if id.blank?
|
|
user_presence = UserPresence.find(id)
|
|
|
|
if user_presence.user_id != current_user.id
|
|
raise PermissionError, PERMISSION_MSG
|
|
end
|
|
|
|
unless user_presence.nil?
|
|
UserPresence.destroy(id)
|
|
end
|
|
end
|
|
|
|
private
|
|
def self.auth_user(current_user, options={})
|
|
raise PermissionError, PERMISSION_MSG if current_user.nil? || options[:user_id] != current_user.id
|
|
end
|
|
end
|
|
end |