Sha256: c0831bd66f5f253999f949234414419af17953f736551a427f7316b6a06894f9

Contents?: true

Size: 1.25 KB

Versions: 3

Compression:

Stored size: 1.25 KB

Contents

class UserInvitation < ActiveRecord::Base
  validates :email, :email => true, :presence => true
  validate :email_already_used?
  before_save :set_token
  before_create :set_sent_at
  after_create :send_email

  belongs_to :account

  def self.find_by_invitation_token(invitation_token)
    begin
      user_invitation = UserInvitation.find(id = invitation_token.gsub(/.{27}$/, ''))
      if user_invitation.token == invitation_token.gsub(/^#{id}/, '')
        return user_invitation
      else
        return nil
      end
    rescue
      return nil
    end
  end

  def accept(user)
    account = Account.find(account_id)
    if account.account_users.where(:user_id => user.id).empty?
      account.account_users << account_user = AccountUser.create(:user => user)
      account_user.set_roles(roles.split(',')) if roles
      true
    else
      false
    end
  end

  private

  def set_token
    self.token = SecureRandom.urlsafe_base64(20) unless token
  end

  def set_sent_at
    self.sent_at = Time.now
  end

  def send_email
    IuguMailer.invitation(self).deliver
  end

  def email_already_used?
    if !AccountUser.joins(:user).where(:account_id => account_id, 'users.email' => email).empty?
      errors.add(:email, "already used in this account")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
iugusdk-1.0.0.alpha.5 app/models/user_invitation.rb
iugusdk-1.0.0.alpha.4 app/models/user_invitation.rb
iugusdk-1.0.0.alpha.3 app/models/user_invitation.rb