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.
Passed
Push — master ( ec4722...b2f2e7 )
by Jesus
04:24 queued 10s
created

User   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 254
rs 7.92
wmc 51

16 Methods

Rating   Name   Duplication   Size   Complexity  
A check_if_email_can_be_blank() 0 9 5
B add_role() 0 17 6
A remove_role() 0 8 3
A new_token() 0 3 1
A with_role() 0 3 1
A all_users_with_roles() 0 4 1
A admins_order() 0 4 1
A admin_of? 0 12 3
A activate() 0 3 1
A digest() 0 4 2
A authenticated? 0 5 2
A admins_search() 0 28 3
A setup_user() 0 13 4
A without_role() 0 3 1
A highest_priority_role() 0 3 1
A from_omniauth() 0 13 2

How to fix   Complexity   

Complex Class

Complex classes like User often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 Deleteable
23
24
  attr_accessor :reset_token
25
  after_create :setup_user
26
27
  before_save { email.try(:downcase!) }
28
29
  before_destroy :destroy_rooms
30
31
  has_many :rooms
32
  belongs_to :main_room, class_name: 'Room', foreign_key: :room_id, required: false
33
34
  has_and_belongs_to_many :roles, -> { includes :role_permissions }, join_table: :users_roles
35
36
  validates :name, length: { maximum: 256 }, presence: true
37
  validates :provider, presence: true
38
  validate :check_if_email_can_be_blank
39
  validates :email, length: { maximum: 256 }, allow_blank: true,
40
                    uniqueness: { case_sensitive: false, scope: :provider },
41
                    format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i }
42
43
  validates :password, length: { minimum: 6 }, confirmation: true, if: :greenlight_account?, on: :create
44
45
  # Bypass validation if omniauth
46
  validates :accepted_terms, acceptance: true,
47
                             unless: -> { !greenlight_account? || !Rails.configuration.terms }
48
49
  # We don't want to require password validations on all accounts.
50
  has_secure_password(validations: false)
51
52
  class << self
53
    include AuthValues
54
55
    # Generates a user from omniauth.
56
    def from_omniauth(auth)
57
      # Provider is the customer name if in loadbalanced config mode
58
      provider = auth['provider'] == "bn_launcher" ? auth['info']['customer'] : auth['provider']
59
      find_or_initialize_by(social_uid: auth['uid'], provider: provider).tap do |u|
60
        u.name = auth_name(auth) unless u.name
61
        u.username = auth_username(auth) unless u.username
62
        u.email = auth_email(auth)
63
        u.image = auth_image(auth) unless u.image
64
        auth_roles(u, auth)
65
        u.email_verified = true
66
        u.save!
67
      end
68
    end
69
  end
70
71
  def self.admins_search(string, role)
72
    active_database = Rails.configuration.database_configuration[Rails.env]["adapter"]
73
    # Postgres requires created_at to be cast to a string
74
    created_at_query = if active_database == "postgresql"
75
      "created_at::text"
76
    else
77
      "created_at"
78
    end
79
80
    search_query = ""
81
    role_search_param = ""
82
    if role.nil?
83
      search_query = "users.name LIKE :search OR email LIKE :search OR username LIKE :search" \
84
                    " OR users.#{created_at_query} LIKE :search OR users.provider LIKE :search" \
85
                    " OR roles.name LIKE :roles_search"
86
      role_search_param = "%#{string}%"
87
    else
88
      search_query = "(users.name LIKE :search OR email LIKE :search OR username LIKE :search" \
89
                    " OR users.#{created_at_query} LIKE :search OR users.provider LIKE :search)" \
90
                    " AND roles.name = :roles_search"
91
      role_search_param = role.name
92
    end
93
94
    search_param = "%#{string}%"
95
    joins("LEFT OUTER JOIN users_roles ON users_roles.user_id = users.id LEFT OUTER JOIN roles " \
96
      "ON roles.id = users_roles.role_id").distinct
97
      .where(search_query, search: search_param, roles_search: role_search_param)
98
  end
99
100
  def self.admins_order(column, direction)
101
    # Arel.sql to avoid sql injection
102
    order(Arel.sql("#{column} #{direction}"))
103
  end
104
105
  # Activates an account and initialize a users main room
106
  def activate
107
    update_attributes(email_verified: true, activated_at: Time.zone.now)
108
  end
109
110
  def activated?
111
    Rails.configuration.enable_email_verification ? email_verified : true
112
  end
113
114
  # Sets the password reset attributes.
115
  def create_reset_digest
116
    self.reset_token = User.new_token
117
    update_attributes(reset_digest: User.digest(reset_token), reset_sent_at: Time.zone.now)
118
  end
119
120
  # Returns true if the given token matches the digest.
121
  def authenticated?(attribute, token)
122
    digest = send("#{attribute}_digest")
123
    return false if digest.nil?
124
    BCrypt::Password.new(digest).is_password?(token)
125
  end
126
127
  # Return true if password reset link expires
128
  def password_reset_expired?
129
    reset_sent_at < 2.hours.ago
130
  end
131
132
  # Retrives a list of all a users rooms that are not the main room, sorted by last session date.
133
  def secondary_rooms
134
    secondary = (rooms - [main_room])
135
    no_session, session = secondary.partition { |r| r.last_session.nil? }
136
    sorted = session.sort_by(&:last_session)
137
    sorted + no_session
138
  end
139
140
  def name_chunk
141
    charset = ("a".."z").to_a - %w(b i l o s) + ("2".."9").to_a - %w(5 8)
142
    chunk = name.parameterize[0...3]
143
    if chunk.empty?
144
      chunk + (0...3).map { charset.to_a[rand(charset.size)] }.join
145
    elsif chunk.length == 1
146
      chunk + (0...2).map { charset.to_a[rand(charset.size)] }.join
147
    elsif chunk.length == 2
148
      chunk + (0...1).map { charset.to_a[rand(charset.size)] }.join
149
    else
150
      chunk
151
    end
152
  end
153
154
  def greenlight_account?
155
    social_uid.nil?
156
  end
157
158
  def activation_token
159
    # Create the token.
160
    create_reset_activation_digest(User.new_token)
161
  end
162
163
  def admin_of?(user)
164
    if Rails.configuration.loadbalanced_configuration
165
      if has_role? :super_admin
166
        id != user.id
167
      else
168
        highest_priority_role.get_permission("can_manage_users") && (id != user.id) && (provider == user.provider) &&
169
          (!user.has_role? :super_admin)
170
      end
171
    else
172
      (highest_priority_role.get_permission("can_manage_users") || (has_role? :super_admin)) && (id != user.id)
173
    end
174
  end
175
176
  def self.digest(string)
177
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
178
    BCrypt::Password.create(string, cost: cost)
179
  end
180
181
  # Returns a random token.
182
  def self.new_token
183
    SecureRandom.urlsafe_base64
184
  end
185
186
  # role functions
187
  def highest_priority_role
188
    roles.by_priority.first
189
  end
190
191
  def add_role(role)
192
    unless has_role?(role)
193
      role_provider = Rails.configuration.loadbalanced_configuration ? provider : "greenlight"
194
195
      new_role = Role.find_by(name: role, provider: role_provider)
196
197
      if new_role.nil?
198
        return if Role.duplicate_name(role, role_provider) || role.strip.empty?
199
200
        new_role = Role.create_new_role(role, role_provider)
201
      end
202
203
      roles << new_role
204
205
      save!
206
    end
207
  end
208
209
  def remove_role(role)
210
    if has_role?(role)
211
      role_provider = Rails.configuration.loadbalanced_configuration ? provider : "greenlight"
212
213
      roles.delete(Role.find_by(name: role, provider: role_provider))
214
      save!
215
    end
216
  end
217
218
  # This rule is disabled as the function name must be has_role?
219
  # rubocop:disable Naming/PredicateName
220
  def has_role?(role)
221
    # rubocop:enable Naming/PredicateName
222
    roles.exists?(name: role)
223
  end
224
225
  def self.with_role(role)
226
    User.all_users_with_roles.where(roles: { name: role })
227
  end
228
229
  def self.without_role(role)
230
    User.where.not(id: with_role(role).pluck(:id))
231
  end
232
233
  def self.all_users_with_roles
234
    User.joins("INNER JOIN users_roles ON users_roles.user_id = users.id INNER JOIN roles " \
235
      "ON roles.id = users_roles.role_id INNER JOIN role_permissions ON roles.id = role_permissions.role_id").distinct
236
  end
237
238
  private
239
240
  def create_reset_activation_digest(token)
241
    # Create the digest and persist it.
242
    update_attribute(:activation_digest, User.digest(token))
243
    token
244
  end
245
246
  # Destory a users rooms when they are removed.
247
  def destroy_rooms
248
    rooms.destroy_all
249
  end
250
251
  def setup_user
252
    # Initializes a room for the user and assign a BigBlueButton user id.
253
    id = "gl-#{(0...12).map { rand(65..90).chr }.join.downcase}"
254
    room = Room.create!(owner: self, name: I18n.t("home_room"))
255
256
    update_attributes(uid: id, main_room: room)
257
258
    # Initialize the user to use the default user role
259
    role_provider = Rails.configuration.loadbalanced_configuration ? provider : "greenlight"
260
261
    Role.create_default_roles(role_provider) if Role.where(provider: role_provider).count.zero?
262
    add_role(:user) if roles.blank?
263
  end
264
265
  def check_if_email_can_be_blank
266
    if email.blank?
267
      if Rails.configuration.loadbalanced_configuration && greenlight_account?
268
        errors.add(:email, I18n.t("errors.messages.blank"))
269
      elsif provider == "greenlight"
270
        errors.add(:email, I18n.t("errors.messages.blank"))
271
      end
272
    end
273
  end
274
end
275