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 (#496)
by Jesus
03:28
created

User   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 254
rs 8.48
wmc 49

10 Methods

Rating   Name   Duplication   Size   Complexity  
A new_token() 0 3 1
A check_if_email_can_be_blank() 0 9 5
A admins_order() 0 3 1
A admin_of? 0 11 3
A activate() 0 5 1
A digest() 0 4 2
A assign_default_role() 0 3 2
A from_omniauth() 0 12 2
A authenticated? 0 5 2
A admins_search() 0 6 1

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
  rolify
23
  include ::APIConcern
24
  include ::BbbApi
25
26
  attr_accessor :reset_token
27
  after_create :assign_default_role
28
  after_create :initialize_main_room
29
30
  before_save { email.try(:downcase!) }
31
32
  before_destroy :destroy_rooms
33
34
  has_many :rooms
35
  belongs_to :main_room, class_name: 'Room', foreign_key: :room_id, required: false
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
        u.email_verified = true
64
        u.save!
65
      end
66
    end
67
68
    private
69
70
    # Provider attributes.
71
    def auth_name(auth)
72
      case auth['provider']
73
      when :microsoft_office365
74
        auth['info']['display_name']
75
      else
76
        auth['info']['name']
77
      end
78
    end
79
80
    def auth_username(auth)
81
      case auth['provider']
82
      when :google
83
        auth['info']['email'].split('@').first
84
      when :bn_launcher
85
        auth['info']['username']
86
      else
87
        auth['info']['nickname']
88
      end
89
    end
90
91
    def auth_email(auth)
92
      auth['info']['email']
93
    end
94
95
    def auth_image(auth)
96
      case auth['provider']
97
      when :twitter
98
        auth['info']['image'].gsub("http", "https").gsub("_normal", "")
99
      else
100
        auth['info']['image'] unless auth['provider'] == :microsoft_office365
101
      end
102
    end
103
  end
104
105
  def self.admins_search(string)
106
    search_query = "name LIKE :search OR email LIKE :search OR username LIKE :search" \
107
                   " OR created_at LIKE :search OR provider LIKE :search"
108
    search_param = "%#{string}%"
109
    where(search_query, search: search_param)
110
  end
111
112
  def self.admins_order(column, direction)
113
    order("#{column} #{direction}")
114
  end
115
116
  def all_recordings
117
    pag_num = Rails.configuration.pagination_number
118
119
    pag_loops = rooms.length / pag_num - 1
120
121
    res = { recordings: [] }
122
123
    (0..pag_loops).each do |i|
124
      pag_rooms = rooms[pag_num * i, pag_num]
125
126
      # bbb.get_recordings returns an object
127
      # take only the array portion of the object that is returned
128
      full_res = bbb.get_recordings(meetingID: pag_rooms.pluck(:bbb_id))
129
      res[:recordings].push(*full_res[:recordings])
130
    end
131
132
    last_pag_room = rooms[pag_num * (pag_loops + 1), rooms.length % pag_num]
133
134
    full_res = bbb.get_recordings(meetingID: last_pag_room.pluck(:bbb_id))
135
    res[:recordings].push(*full_res[:recordings])
136
137
    format_recordings(res)
138
  end
139
140
  # Activates an account and initialize a users main room
141
  def activate
142
    update_attribute(:email_verified, true)
143
    update_attribute(:activated_at, Time.zone.now)
144
    save
145
  end
146
147
  def activated?
148
    return true unless Rails.configuration.enable_email_verification
149
    email_verified
150
  end
151
152
  def send_activation_email(url)
153
    UserMailer.verify_email(self, url).deliver
154
  end
155
156
  # Sets the password reset attributes.
157
  def create_reset_digest
158
    self.reset_token = User.new_token
159
    update_attribute(:reset_digest,  User.digest(reset_token))
160
    update_attribute(:reset_sent_at, Time.zone.now)
161
  end
162
163
  # Sends password reset email.
164
  def send_password_reset_email(url)
165
    UserMailer.password_reset(self, url).deliver_now
166
  end
167
168
  # Returns true if the given token matches the digest.
169
  def authenticated?(attribute, token)
170
    digest = send("#{attribute}_digest")
171
    return false if digest.nil?
172
    BCrypt::Password.new(digest).is_password?(token)
173
  end
174
175
  # Return true if password reset link expires
176
  def password_reset_expired?
177
    reset_sent_at < 2.hours.ago
178
  end
179
180
  # Retrives a list of all a users rooms that are not the main room, sorted by last session date.
181
  def secondary_rooms
182
    secondary = (rooms - [main_room])
183
    no_session, session = secondary.partition { |r| r.last_session.nil? }
184
    sorted = session.sort_by(&:last_session)
185
    sorted + no_session
186
  end
187
188
  def name_chunk
189
    charset = ("a".."z").to_a - %w(b i l o s) + ("2".."9").to_a - %w(5 8)
190
    chunk = name.parameterize[0...3]
191
    if chunk.empty?
192
      chunk + (0...3).map { charset.to_a[rand(charset.size)] }.join
193
    elsif chunk.length == 1
194
      chunk + (0...2).map { charset.to_a[rand(charset.size)] }.join
195
    elsif chunk.length == 2
196
      chunk + (0...1).map { charset.to_a[rand(charset.size)] }.join
197
    else
198
      chunk
199
    end
200
  end
201
202
  def greenlight_account?
203
    return true unless provider # For testing cases when provider is set to null
204
    return provider == "greenlight" unless Rails.configuration.loadbalanced_configuration
205
    # No need to retrive the provider info if the provider is whitelisted
206
    return true if launcher_allow_user_signup_whitelisted?(provider)
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
        (has_role? :admin) && (id != user.id) && (provider == user.provider) && (!user.has_role? :super_admin)
223
      end
224
    else
225
      ((has_role? :admin) || (has_role? :super_admin)) && (id != user.id)
226
    end
227
  end
228
229
  def self.digest(string)
230
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
231
    BCrypt::Password.create(string, cost: cost)
232
  end
233
234
  # Returns a random token.
235
  def self.new_token
236
    SecureRandom.urlsafe_base64
237
  end
238
239
  private
240
241
  def create_reset_activation_digest(token)
242
    # Create the digest and persist it.
243
    self.activation_digest = User.digest(token)
244
    save
245
    token
246
  end
247
248
  # Destory a users rooms when they are removed.
249
  def destroy_rooms
250
    rooms.destroy_all
251
  end
252
253
  # Initializes a room for the user and assign a BigBlueButton user id.
254
  def initialize_main_room
255
    self.uid = "gl-#{(0...12).map { rand(65..90).chr }.join.downcase}"
256
    self.main_room = Room.create!(owner: self, name: I18n.t("home_room"))
257
    save
258
  end
259
260
  # Initialize the user to use the default user role
261
  def assign_default_role
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