]> git.openstreetmap.org Git - rails.git/blob - app/models/user_block.rb
Merge remote-tracking branch 'upstream/pull/4654'
[rails.git] / app / models / user_block.rb
1 # == Schema Information
2 #
3 # Table name: user_blocks
4 #
5 #  id            :integer          not null, primary key
6 #  user_id       :bigint(8)        not null
7 #  creator_id    :bigint(8)        not null
8 #  reason        :text             not null
9 #  ends_at       :datetime         not null
10 #  needs_view    :boolean          default(FALSE), not null
11 #  revoker_id    :bigint(8)
12 #  created_at    :datetime
13 #  updated_at    :datetime
14 #  reason_format :enum             default("markdown"), not null
15 #
16 # Indexes
17 #
18 #  index_user_blocks_on_creator_id_and_id  (creator_id,id)
19 #  index_user_blocks_on_user_id            (user_id)
20 #
21 # Foreign Keys
22 #
23 #  user_blocks_moderator_id_fkey  (creator_id => users.id)
24 #  user_blocks_revoker_id_fkey    (revoker_id => users.id)
25 #  user_blocks_user_id_fkey       (user_id => users.id)
26 #
27
28 class UserBlock < ApplicationRecord
29   validate :moderator_permissions
30   validates :reason, :characters => true
31
32   belongs_to :user, :class_name => "User"
33   belongs_to :creator, :class_name => "User"
34   belongs_to :revoker, :class_name => "User", :optional => true
35
36   PERIODS = Settings.user_block_periods
37
38   ##
39   # scope to match active blocks
40   def self.active
41     where("needs_view or ends_at > ?", Time.now.utc)
42   end
43
44   ##
45   # return a renderable version of the reason text.
46   def reason
47     RichText.new(self[:reason_format], self[:reason])
48   end
49
50   ##
51   # returns true if the block is currently active (i.e: the user can't
52   # use the API).
53   def active?
54     needs_view || ends_at > Time.now.utc
55   end
56
57   ##
58   # returns true if the block is a "zero hour" block
59   def zero_hour?
60     # if the times differ more than 1 minute we probably have more important issues
61     needs_view && (ends_at.to_i - updated_at.to_i) < 60
62   end
63
64   ##
65   # revokes the block, allowing the user to use the API again. the argument
66   # is the user object who is revoking the ban.
67   def revoke!(revoker)
68     update(
69       :ends_at => Time.now.utc,
70       :revoker_id => revoker.id,
71       :needs_view => false
72     )
73   end
74
75   private
76
77   ##
78   # validate that only moderators are allowed to change the
79   # block. this should be caught and dealt with in the controller,
80   # but i've also included it here just in case.
81   def moderator_permissions
82     errors.add(:base, I18n.t("user_blocks.model.non_moderator_update")) if creator_id_changed? && !creator.moderator?
83     errors.add(:base, I18n.t("user_blocks.model.non_moderator_revoke")) if revoker_id_changed? && !revoker_id.nil? && !revoker.moderator?
84   end
85 end