GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#709)
by
unknown
05:14
created

User.admins_order()   A

Complexity

Conditions 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 4
rs 10
1
# frozen_string_literal: true
2
3
# BigBlueButton open source conferencing system - http://www.bigbluebutton.org/.
4
#
5
# Copyright (c) 2018 BigBlueButton Inc. and by respective authors (see below).
6
#
7
# This program is free software; you can redistribute it and/or modify it under the
8
# terms of the GNU Lesser General Public License as published by the Free Software
9
# Foundation; either version 3.0 of the License, or (at your option) any later
10
# version.
11
#
12
# BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY
13
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
14
# PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
15
#
16
# You should have received a copy of the GNU Lesser General Public License along
17
# with BigBlueButton; if not, see <http://www.gnu.org/licenses/>.
18
19
require 'bbb_api'
20
21
class User < ApplicationRecord
22
  include ::BbbApi
23
24
  attr_accessor :reset_token
25
  after_create :assign_default_role
26
  after_create :initialize_main_room
27
28
  before_save { email.try(:downcase!) }
29
30
  before_destroy :destroy_rooms
31
32
  has_many :rooms
33
  belongs_to :main_room, class_name: 'Room', foreign_key: :room_id, required: false
34
35
  has_and_belongs_to_many :roles, join_table: :users_roles
36
37
  validates :name, length: { maximum: 256 }, presence: true
38
  validates :provider, presence: true
39
  validate :check_if_email_can_be_blank
40
  validates :email, length: { maximum: 256 }, allow_blank: true,
41
                    uniqueness: { case_sensitive: false, scope: :provider },
42
                    format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
43
44
  validates :password, length: { minimum: 6 }, confirmation: true, if: :greenlight_account?, on: :create
45
46
  # Bypass validation if omniauth
47
  validates :accepted_terms, acceptance: true,
48
                             unless: -> { !greenlight_account? || !Rails.configuration.terms }
49
50
  # We don't want to require password validations on all accounts.
51
  has_secure_password(validations: false)
52
53
  class << self
54
    # Generates a user from omniauth.
55
    def from_omniauth(auth)
56
      # Provider is the customer name if in loadbalanced config mode
57
      provider = auth['provider'] == "bn_launcher" ? auth['info']['customer'] : auth['provider']
58
      find_or_initialize_by(social_uid: auth['uid'], provider: provider).tap do |u|
59
        u.name = auth_name(auth) unless u.name
60
        u.username = auth_username(auth) unless u.username
61
        u.email = auth_email(auth)
62
        u.image = auth_image(auth)
63
        auth_roles(u, auth)
64
        u.email_verified = true
65
        u.save!
66
      end
67
    end
68
69
    private
70
71
    # Provider attributes.
72
    def auth_name(auth)
73
      case auth['provider']
74
      when :office365
75
        auth['info']['display_name']
76
      else
77
        auth['info']['name']
78
      end
79
    end
80
81
    def auth_username(auth)
82
      case auth['provider']
83
      when :google
84
        auth['info']['email'].split('@').first
85
      when :bn_launcher
86
        auth['info']['username']
87
      else
88
        auth['info']['nickname']
89
      end
90
    end
91
92
    def auth_email(auth)
93
      auth['info']['email']
94
    end
95
96
    def auth_image(auth)
97
      case auth['provider']
98
      when :twitter
99
        auth['info']['image'].gsub("http", "https").gsub("_normal", "")
100
      else
101
        auth['info']['image']
102
      end
103
    end
104
105
    def auth_roles(user, auth)
106
      roles = auth['info']['roles'].split(',')
107
108
      role_provider = auth['provider'] == "bn_launcher" ? auth['info']['customer'] : "greenlight"
109
      roles.each do |role_name|
110
        role = Role.where(provider: role_provider, name: role_name).first
111
        user.roles << role unless role.nil?
112
      end
113
    end
114
  end
115
116
  def self.admins_search(string, role)
117
    active_database = Rails.configuration.database_configuration[Rails.env]["adapter"]
118
    # Postgres requires created_at to be cast to a string
119
    created_at_query = if active_database == "postgresql"
120
      "created_at::text"
121
    else
122
      "created_at"
123
    end
124
125
    search_query = ""
126
    role_search_param = ""
127
    if role.nil?
128
      search_query = "users.name LIKE :search OR email LIKE :search OR username LIKE :search" \
129
                    " OR users.#{created_at_query} LIKE :search OR users.provider LIKE :search" \
130
                    " OR roles.name LIKE :roles_search"
131
      role_search_param = "%#{string}%"
132
    else
133
      search_query = "(users.name LIKE :search OR email LIKE :search OR username LIKE :search" \
134
                    " OR users.#{created_at_query} LIKE :search OR users.provider LIKE :search)" \
135
                    " AND roles.name = :roles_search"
136
      role_search_param = role.name
137
    end
138
139
    search_param = "%#{string}%"
140
    joins("LEFT OUTER JOIN users_roles ON users_roles.user_id = users.id LEFT OUTER JOIN roles " \
141
      "ON roles.id = users_roles.role_id").distinct
142
      .where(search_query, search: search_param, roles_search: role_search_param)
143
  end
144
145
  def self.admins_order(column, direction)
146
    # Arel.sql to avoid sql injection
147
    order(Arel.sql("#{column} #{direction}"))
148
  end
149
150
  # Activates an account and initialize a users main room
151
  def activate
152
    update_attribute(:email_verified, true)
153
    update_attribute(:activated_at, Time.zone.now)
154
    save
155
  end
156
157
  def activated?
158
    return true unless Rails.configuration.enable_email_verification
159
    email_verified
160
  end
161
162
  # Sets the password reset attributes.
163
  def create_reset_digest
164
    self.reset_token = User.new_token
165
    update_attribute(:reset_digest,  User.digest(reset_token))
166
    update_attribute(:reset_sent_at, Time.zone.now)
167
  end
168
169
  # Returns true if the given token matches the digest.
170
  def authenticated?(attribute, token)
171
    digest = send("#{attribute}_digest")
172
    return false if digest.nil?
173
    BCrypt::Password.new(digest).is_password?(token)
174
  end
175
176
  # Return true if password reset link expires
177
  def password_reset_expired?
178
    reset_sent_at < 2.hours.ago
179
  end
180
181
  # Retrives a list of all a users rooms that are not the main room, sorted by last session date.
182
  def secondary_rooms
183
    secondary = (rooms - [main_room])
184
    no_session, session = secondary.partition { |r| r.last_session.nil? }
185
    sorted = session.sort_by(&:last_session)
186
    sorted + no_session
187
  end
188
189
  def name_chunk
190
    charset = ("a".."z").to_a - %w(b i l o s) + ("2".."9").to_a - %w(5 8)
191
    chunk = name.parameterize[0...3]
192
    if chunk.empty?
193
      chunk + (0...3).map { charset.to_a[rand(charset.size)] }.join
194
    elsif chunk.length == 1
195
      chunk + (0...2).map { charset.to_a[rand(charset.size)] }.join
196
    elsif chunk.length == 2
197
      chunk + (0...1).map { charset.to_a[rand(charset.size)] }.join
198
    else
199
      chunk
200
    end
201
  end
202
203
  def greenlight_account?
204
    return true unless provider # For testing cases when provider is set to null
205
    return true if provider == "greenlight"
206
    return false unless Rails.configuration.loadbalanced_configuration
207
    # Proceed with fetching the provider info
208
    provider_info = retrieve_provider_info(provider, 'api2', 'getUserGreenlightCredentials')
209
    provider_info['provider'] == 'greenlight'
210
  end
211
212
  def activation_token
213
    # Create the token.
214
    create_reset_activation_digest(User.new_token)
215
  end
216
217
  def admin_of?(user)
218
    if Rails.configuration.loadbalanced_configuration
219
      if has_role? :super_admin
220
        id != user.id
221
      else
222
        highest_priority_role.can_manage_users && (id != user.id) && (provider == user.provider) &&
223
          (!user.has_role? :super_admin)
224
      end
225
    else
226
      (highest_priority_role.can_manage_users || (has_role? :super_admin)) && (id != user.id)
227
    end
228
  end
229
230
  def self.digest(string)
231
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
232
    BCrypt::Password.create(string, cost: cost)
233
  end
234
235
  # Returns a random token.
236
  def self.new_token
237
    SecureRandom.urlsafe_base64
238
  end
239
240
  # role functions
241
  def highest_priority_role
242
    roles.by_priority.first
243
  end
244
245
  def add_role(role)
246
    unless has_role?(role)
247
      role_provider = "greenlight"
248
249
      role_provider = provider if Rails.configuration.loadbalanced_configuration
250
251
      roles << Role.find_or_create_by(name: role, provider: role_provider)
252
253
      save!
254
    end
255
  end
256
257
  def remove_role(role)
258
    if has_role?(role)
259
      role_provider = "greenlight"
260
261
      role_provider = provider if Rails.configuration.loadbalanced_configuration
262
      roles.delete(Role.find_by(name: role, provider: role_provider))
263
      save!
264
    end
265
  end
266
267
  # This rule is disabled as the function name must be has_role?
268
  # rubocop:disable Naming/PredicateName
269
  def has_role?(role)
270
    # rubocop:enable Naming/PredicateName
271
    roles.exists?(name: role)
272
  end
273
274
  def self.with_role(role)
275
    User.all_users_with_roles.where(roles: { name: role })
276
  end
277
278
  def self.without_role(role)
279
    User.where.not(id: with_role(role).pluck(:id))
280
  end
281
282
  def self.all_users_with_roles
283
    User.joins("INNER JOIN users_roles ON users_roles.user_id = users.id INNER JOIN roles " \
284
      "ON roles.id = users_roles.role_id")
285
  end
286
287
  private
288
289
  def create_reset_activation_digest(token)
290
    # Create the digest and persist it.
291
    self.activation_digest = User.digest(token)
292
    save
293
    token
294
  end
295
296
  # Destory a users rooms when they are removed.
297
  def destroy_rooms
298
    rooms.destroy_all
299
  end
300
301
  # Initializes a room for the user and assign a BigBlueButton user id.
302
  def initialize_main_room
303
    self.uid = "gl-#{(0...12).map { rand(65..90).chr }.join.downcase}"
304
    self.main_room = Room.create!(owner: self, name: I18n.t("home_room"))
305
    save
306
  end
307
308
  # Initialize the user to use the default user role
309
  def assign_default_role
310
    role_provider = "greenlight"
311
312
    role_provider = provider if Rails.configuration.loadbalanced_configuration
313
314
    Role.create_default_roles(role_provider) if Role.where(provider: role_provider).count.zero?
315
316
    add_role(:user) if roles.blank?
317
  end
318
319
  def check_if_email_can_be_blank
320
    if email.blank?
321
      if Rails.configuration.loadbalanced_configuration && greenlight_account?
322
        errors.add(:email, I18n.t("errors.messages.blank"))
323
      elsif provider == "greenlight"
324
        errors.add(:email, I18n.t("errors.messages.blank"))
325
      end
326
    end
327
  end
328
end
329