2009-01-06 11:49:19 +01:00
|
|
|
require 'digest/sha1'
|
|
|
|
|
|
|
|
# Invites are created by foodcoop users to invite a new user into the foodcoop and their order group.
|
2019-01-13 07:05:54 +01:00
|
|
|
class Invite < ApplicationRecord
|
2009-01-06 11:49:19 +01:00
|
|
|
belongs_to :user
|
|
|
|
belongs_to :group
|
|
|
|
|
2014-02-20 15:04:53 +01:00
|
|
|
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
|
2009-01-06 11:49:19 +01:00
|
|
|
validates_presence_of :user
|
|
|
|
validates_presence_of :group
|
|
|
|
validates_presence_of :token
|
|
|
|
validates_presence_of :expires_at
|
2011-05-11 11:17:02 +02:00
|
|
|
validate :email_not_already_registered, :on => :create
|
|
|
|
|
2012-10-08 11:51:56 +02:00
|
|
|
before_validation :set_token_and_expires_at
|
2019-01-13 07:05:54 +01:00
|
|
|
|
2021-03-01 15:27:26 +01:00
|
|
|
protected
|
2019-01-13 07:05:54 +01:00
|
|
|
|
2009-01-06 11:49:19 +01:00
|
|
|
# Before validation, set token and expires_at.
|
2012-10-08 11:51:56 +02:00
|
|
|
def set_token_and_expires_at
|
2009-01-06 11:49:19 +01:00
|
|
|
self.token = Digest::SHA1.hexdigest(Time.now.to_s + rand(100).to_s)
|
2011-05-02 14:53:22 +02:00
|
|
|
self.expires_at = Time.now.advance(:days => 7)
|
2009-01-06 11:49:19 +01:00
|
|
|
end
|
|
|
|
|
2021-03-01 15:27:26 +01:00
|
|
|
private
|
2009-01-06 11:49:19 +01:00
|
|
|
|
|
|
|
# Custom validation: check that email does not already belong to a registered user.
|
2011-05-11 11:17:02 +02:00
|
|
|
def email_not_already_registered
|
2009-01-15 12:14:01 +01:00
|
|
|
unless User.find_by_email(self.email).nil?
|
2013-02-27 11:59:03 +01:00
|
|
|
errors.add(:email, I18n.t('invites.errors.already_member'))
|
2009-01-15 12:14:01 +01:00
|
|
|
end
|
2009-01-06 11:49:19 +01:00
|
|
|
end
|
|
|
|
end
|