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

User.from_omniauth()   A

Complexity

Conditions 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
c 2
b 0
f 0
dl 0
loc 14
rs 9.7
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)
60
        u.username = auth_username(auth)
61
        u.email = auth_email(auth)
62
        u.image = auth_image(auth)
63
        u.email_verified = true
64
        roles = auth_roles(auth)
65
        roles.each { |r| u.add_role r }
66
        u.save!
67
      end
68
    end
69
70
    private
71
72
    # Provider attributes.
73
    def auth_name(auth)
74
      case auth['provider']
75
      when :office365
76
        auth['info']['display_name']
77
      else
78
        auth['info']['name']
79
      end
80
    end
81
82
    def auth_username(auth)
83
      case auth['provider']
84
      when :google
85
        auth['info']['email'].split('@').first
86
      when :bn_launcher
87
        auth['info']['username']
88
      else
89
        auth['info']['nickname']
90
      end
91
    end
92
93
    def auth_roles(auth)
94
      return [] unless Rails.application.config.respond_to? :role_claim
95
      role_claim = Rails.application.config.role_claim
96
      auth[role_claim] || auth['info'][role_claim] || auth['extra']['raw_info'][role_claim] || []
97
    end
98
99
    def auth_email(auth)
100
      auth['info']['email']
101
    end
102
103
    def auth_image(auth)
104
      case auth['provider']
105
      when :twitter
106
        auth['info']['image'].gsub("http", "https").gsub("_normal", "")
107
      else
108
        auth['info']['image']
109
      end
110
    end
111
  end
112
113
  def self.admins_search(string)
114
    active_database = Rails.configuration.database_configuration[Rails.env]["adapter"]
115
    # Postgres requires created_at to be cast to a string
116
    created_at_query = if active_database == "postgresql"
117
      "created_at::text"
118
    else
119
      "created_at"
120
    end
121
122
    search_query = "users.name LIKE :search OR email LIKE :search OR username LIKE :search" \
123
                   " OR users.#{created_at_query} LIKE :search OR provider LIKE :search"
124
    search_param = "%#{string}%"
125
    where(search_query, search: search_param)
126
  end
127
128
  def self.admins_order(column, direction)
129
    order("#{column} #{direction}")
130
  end
131
132
  def all_recordings(search_params = {}, ret_search_params = false)
133
    pag_num = Rails.configuration.pagination_number
134
135
    pag_loops = rooms.length / pag_num - 1
136
137
    res = { recordings: [] }
138
139
    (0..pag_loops).each do |i|
140
      pag_rooms = rooms[pag_num * i, pag_num]
141
142
      # bbb.get_recordings returns an object
143
      # take only the array portion of the object that is returned
144
      full_res = bbb.get_recordings(meetingID: pag_rooms.pluck(:bbb_id))
145
      res[:recordings].push(*full_res[:recordings])
146
    end
147
148
    last_pag_room = rooms[pag_num * (pag_loops + 1), rooms.length % pag_num]
149
150
    full_res = bbb.get_recordings(meetingID: last_pag_room.pluck(:bbb_id))
151
    res[:recordings].push(*full_res[:recordings])
152
153
    format_recordings(res, search_params, ret_search_params)
154
  end
155
156
  # Activates an account and initialize a users main room
157
  def activate
158
    update_attribute(:email_verified, true)
159
    update_attribute(:activated_at, Time.zone.now)
160
    save
161
  end
162
163
  def activated?
164
    return true unless Rails.configuration.enable_email_verification
165
    email_verified
166
  end
167
168
  # Sets the password reset attributes.
169
  def create_reset_digest
170
    self.reset_token = User.new_token
171
    update_attribute(:reset_digest,  User.digest(reset_token))
172
    update_attribute(:reset_sent_at, Time.zone.now)
173
  end
174
175
  # Returns true if the given token matches the digest.
176
  def authenticated?(attribute, token)
177
    digest = send("#{attribute}_digest")
178
    return false if digest.nil?
179
    BCrypt::Password.new(digest).is_password?(token)
180
  end
181
182
  # Return true if password reset link expires
183
  def password_reset_expired?
184
    reset_sent_at < 2.hours.ago
185
  end
186
187
  # Retrives a list of all a users rooms that are not the main room, sorted by last session date.
188
  def secondary_rooms
189
    secondary = (rooms - [main_room])
190
    no_session, session = secondary.partition { |r| r.last_session.nil? }
191
    sorted = session.sort_by(&:last_session)
192
    sorted + no_session
193
  end
194
195
  def name_chunk
196
    charset = ("a".."z").to_a - %w(b i l o s) + ("2".."9").to_a - %w(5 8)
197
    chunk = name.parameterize[0...3]
198
    if chunk.empty?
199
      chunk + (0...3).map { charset.to_a[rand(charset.size)] }.join
200
    elsif chunk.length == 1
201
      chunk + (0...2).map { charset.to_a[rand(charset.size)] }.join
202
    elsif chunk.length == 2
203
      chunk + (0...1).map { charset.to_a[rand(charset.size)] }.join
204
    else
205
      chunk
206
    end
207
  end
208
209
  def greenlight_account?
210
    return true unless provider # For testing cases when provider is set to null
211
    return true if provider == "greenlight"
212
    return false unless Rails.configuration.loadbalanced_configuration
213
    # Proceed with fetching the provider info
214
    provider_info = retrieve_provider_info(provider, 'api2', 'getUserGreenlightCredentials')
215
    provider_info['provider'] == 'greenlight'
216
  end
217
218
  def activation_token
219
    # Create the token.
220
    create_reset_activation_digest(User.new_token)
221
  end
222
223
  def admin_of?(user)
224
    if Rails.configuration.loadbalanced_configuration
225
      if has_role? :super_admin
226
        id != user.id
227
      else
228
        (has_role? :admin) && (id != user.id) && (provider == user.provider) && (!user.has_role? :super_admin)
229
      end
230
    else
231
      ((has_role? :admin) || (has_role? :super_admin)) && (id != user.id)
232
    end
233
  end
234
235
  def self.digest(string)
236
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
237
    BCrypt::Password.create(string, cost: cost)
238
  end
239
240
  # Returns a random token.
241
  def self.new_token
242
    SecureRandom.urlsafe_base64
243
  end
244
245
  private
246
247
  def create_reset_activation_digest(token)
248
    # Create the digest and persist it.
249
    self.activation_digest = User.digest(token)
250
    save
251
    token
252
  end
253
254
  # Destory a users rooms when they are removed.
255
  def destroy_rooms
256
    rooms.destroy_all
257
  end
258
259
  # Initializes a room for the user and assign a BigBlueButton user id.
260
  def initialize_main_room
261
    self.uid = "gl-#{(0...12).map { rand(65..90).chr }.join.downcase}"
262
    self.main_room = Room.create!(owner: self, name: I18n.t("home_room"))
263
    save
264
  end
265
266
  # Initialize the user to use the default user role
267
  def assign_default_role
268
    add_role(:user) if roles.blank?
269
  end
270
271
  def check_if_email_can_be_blank
272
    if email.blank?
273
      if Rails.configuration.loadbalanced_configuration && greenlight_account?
274
        errors.add(:email, I18n.t("errors.messages.blank"))
275
      elsif provider == "greenlight"
276
        errors.add(:email, I18n.t("errors.messages.blank"))
277
      end
278
    end
279
  end
280
end
281