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
|
|
|
|
|
2023-05-12 13:01:12 +02:00
|
|
|
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }
|
|
|
|
validates :user, presence: true
|
|
|
|
validates :group, presence: true
|
|
|
|
validates :token, presence: true
|
|
|
|
validates :expires_at, presence: true
|
|
|
|
validate :email_not_already_registered, on: :create
|
2011-05-11 11:17:02 +02:00
|
|
|
|
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)
|
2023-05-12 13:01:12 +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
|
2023-05-12 13:01:12 +02:00
|
|
|
return if User.find_by_email(email).nil?
|
|
|
|
|
|
|
|
errors.add(:email, I18n.t('invites.errors.already_member'))
|
2009-01-06 11:49:19 +01:00
|
|
|
end
|
|
|
|
end
|