Class: User

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/user.rb

Direct Known Subclasses

Person

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.camelcase_twiki_regexObject

The regular expression matches on twiki usernames. Ie AliceSmithJones re This does not work with numbers or characters in the firstname field rubular.com/



218
219
220
# File 'app/models/user.rb', line 218

def self.camelcase_twiki_regex
  /([A-Z][a-z]*)([A-Z][\w]*)/
end

.expired_users_in_the_last_monthObject



414
415
416
# File 'app/models/user.rb', line 414

def self.expired_users_in_the_last_month
  User.where(is_active: true).where("expires_at >= ? AND expires_at < ?", Date.today - 1.month, Date.today)
end

.find_by_param(param) ⇒ Object



99
100
101
102
103
104
105
# File 'app/models/user.rb', line 99

def self.find_by_param(param)
  if param.to_i == 0 #This is a string
    User.find_by_twiki_name(param)
  else #This is a number
    User.find(param)
  end
end

.find_for_google_apps_oauth(access_token, signed_in_resource = nil) ⇒ Object



128
129
130
131
132
# File 'app/models/user.rb', line 128

def self.find_for_google_apps_oauth(access_token, signed_in_resource=nil)
  data = access_token['info']
  email = switch_west_to_sv(data["email"]).downcase
  User.find_by_email(email)
end

.find_for_google_oauth2(access_token, signed_in_resource = nil) ⇒ Object



134
135
136
137
138
# File 'app/models/user.rb', line 134

def self.find_for_google_oauth2(access_token, signed_in_resource=nil)
  data = access_token.info
  email = switch_west_to_sv(data['email']).downcase
  User.find_by_email(email)
end

.get_all_programsObject



82
83
84
# File 'app/models/user.rb', line 82

def self.get_all_programs
  User.select(:masters_program).map(&:masters_program).uniq.reject { |e| e.blank? }.sort
end

.get_all_yearsObject



86
87
88
# File 'app/models/user.rb', line 86

def self.get_all_years
  User.select(:graduation_year).map(&:graduation_year).uniq.reject { |e| e.blank? }.sort.reverse
end

.new_with_session(params, session) ⇒ Object



140
141
142
143
144
145
146
# File 'app/models/user.rb', line 140

def self.new_with_session(params, session)
  super.tap do |user|
    if data = session["devise.google_apps_data"] && session["devise.google_apps_data"]["extra"]["user_hash"]
      user.email = data["email"]
    end
  end
end

.notify_it_about_expired_accountsObject



418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'app/models/user.rb', line 418

def self.notify_it_about_expired_accounts
  email_list = ""
  self.expired_users_in_the_last_month.each do |user|
    email_list += "-" + Rails.application.routes.url_helpers.user_url(user, :host => "whiteboard.sv.cmu.edu") + "\n"
  end
  if email_list.length > 0
    options = {:to => '[email protected]',
               :subject => "Expired accounts between #{(Date.today - 1.month).to_s} and #{(Date.today - 1.day).to_s}",
               :message => "\n#{email_list} \n\n Please executed the processes defined for expired accounts."
    }
    GenericMailer.email(options).deliver
  end
end

.parse_twiki(username) ⇒ Object



222
223
224
225
226
227
228
229
# File 'app/models/user.rb', line 222

def self.parse_twiki(username)
  match = username.match camelcase_twiki_regex
  if match.nil?
    return nil
  else
    return [match[1], match[2]]
  end
end

.perform_create_accounts(person_id, create_google_email, create_twiki_account, create_active_directory_account) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'app/models/user.rb', line 440

def self.perform_create_accounts(person_id, create_google_email, , )
  person = Person.find(person_id)
  error_message = ''
  if create_google_email && person.google_created.blank?
    password = 'just4now' + Time.now.to_f.to_s[-4,4] # just4now0428
    status = person.create_google_email(password)
    if status.is_a?(String)
      error_message += "Google account not created for #{person.human_name}. " + status + " <br/>The password was " + password + "<br/><br/>"
    else
      # If we immediately send the email, google may say the account doesn't exist
      # Then send grid puts the user account on a black likst
      sleep 10
      PersonMailer.welcome_email(person, password).deliver
    end
  end
  if  && person.twiki_created.blank?
    status = person.
    error_message +=  "TWiki account #{person.twiki_name} was not created.<br/><br/>" unless status
    status = person.reset_twiki_password
    error_message +=  'TWiki account password was not reset.<br/>' unless status
  end
  if  && person..blank?
    status = ActiveDirectory.(person)
    error_message +=  "Active directory account for #{person.human_name} was not created.<br/><br/>" unless status
  end

  if(!error_message.blank?)
    #     Delayed::Worker.logger.debug(error_message)
    puts error_message
    message = error_message
    GenericMailer.email(
        :to => ['[email protected]', '[email protected]'],
        :from => '[email protected]',
        :subject => "PersonJob had an error on person id = #{person.id}",
        :message => message,
        :url_label => 'Show which person',
        :url => "http://whiteboard.sv.cmu.edu/people/#{person.id}" #+ person_path(person)
    ).deliver
  end
  return error_message
end

Instance Method Details

#create_google_email(password) ⇒ Object

Creates a Google Apps for University account for the user. For legacy reasons, the accounts are with the domain west.cmu.edu even though the preferred way of talking about the account is with the domain sv.cmu.edu

Input is a password If this fails, it returns an error message as a string



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'app/models/user.rb', line 268

def create_google_email(password)
  return 'Empty email address' if self.email.blank?
  logger.debug('Attempting to create google email account for ' + self.email)
  west_email = switch_sv_to_west(self.email)
  (username, domain) = west_email.split('@')

  if domain != GOOGLE_DOMAIN
    logger.debug('Domain (' + domain + ') is not the same as the google domain (' + GOOGLE_DOMAIN)
    return 'Domain (' + domain + ') is not the same as the google domain (' + GOOGLE_DOMAIN + ')'
  end

  begin
    user = GoogleWrapper.create_user(west_email,
      self.first_name,
      self.last_name,
      password,
      self.org_unit_path
      )
    return user.data['error']['message'] if user.data['error']
  rescue Error => e
    logger.error e
    return 'Determine error message'
  end
  self.google_created = Time.now()
  self.save
  return(user)
end

#create_twiki_accountObject

Creates a twiki account for the user

You may need to modify mechanize as seen here github.com/eric/mechanize/commit/7fd877c60cbb3855652c390c980df1dedfaed820



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'app/models/user.rb', line 302

def 
  require 'mechanize'
  agent = Mechanize.new
  agent.basic_auth(TWIKI_USERNAME, TWIKI_PASSWORD)
  agent.get(TWIKI_URL + '/do/view/TWiki/TWikiRegistration') do |page|
    registration_result = page.form_with(:action => '/do/register/Main/WebHome') do |registration|
      registration.Twk1FirstName = self.first_name
      registration.Twk1LastName = self.last_name
      registration.Twk1WikiName = self.twiki_name
      registration.Twk1Email = self.email
      registration.Twk0Password = 'just4now'
      registration.Twk0Confirm = 'just4now'
      registration.Twk1Country = 'USA'
      #      registration.action = 'register'
      #      registration.topic = 'TWikiRegistration'
      #      registration.rx = '%BLACKLISTPLUGIN{ action=\"magic\" }%'
    end.submit
    #   #<WWW::Mechanize::Page::Link "AndrewCarnegie" "/do/view/Main/AndrewCarnegie">
    link = registration_result.link_with(:text => self.twiki_name)
    if link.nil?
      #the user probably already exists
      pp registration_result
      return false
    end
    self.twiki_created = Time.now()
    self.save
    return true
  end


end

#emailed_recently(email_type) ⇒ Object



149
150
151
152
153
154
155
156
# File 'app/models/user.rb', line 149

def emailed_recently(email_type)
  case email_type
    when :effort_log
      return self.effort_log_warning_email.nil? || (self.effort_log_warning_email < 1.day.ago) ? false : true
    when :sponsored_project_effort
      return self.sponsored_project_effort_last_emailed.nil? || (self.sponsored_project_effort_last_emailed < 1.day.ago) ? false : true
  end
end

#faculty_teams_map(person_id = self.id) ⇒ Object

This method contributed by Team Juran



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'app/models/user.rb', line 159

def faculty_teams_map(person_id = self.id)
  faculty_teams = Team.find_by_sql(["SELECT t.* FROM  teams t WHERE t.primary_faculty_id = ? OR t.secondary_faculty_id = ?", person_id, person_id])

  teams_map = {}
  teams_students_map = {}
  for team in faculty_teams
    if teams_map[team.course.year].nil?
      teams_map[team.course.year] = {}
      teams_students_map[team.course.year] = {}
    end
    if teams_map[team.course.year][team.course.semester.downcase].nil?
      teams_map[team.course.year][team.course.semester.downcase] = []
      teams_students_map[team.course.year][team.course.semester.downcase] = 0
    end
    teams_map[team.course.year][team.course.semester.downcase].push(team)
    teams_students_map[team.course.year][team.course.semester.downcase] += team.members.count
  end
  # teams_map is a two dimentional hash holding arrays of courses
  # teams_students_map is a two dimentional hash holding an integer count
  # of students that are part of the courses for a given semester
  return [teams_map, teams_students_map]
end

#find_teams_by_semester(year, semester) ⇒ Object



231
232
233
234
235
236
237
# File 'app/models/user.rb', line 231

def find_teams_by_semester(year, semester)
  s_teams = []
  self.teams.each do |team|
    s_teams << team if team.course.year == year and team.course.semester == semester
  end
  return s_teams
end

#formatted_teams(array) ⇒ Object

Given an array of team objects [Awesome, Devils, Alpha Omega] Returns “Awesome, Devils, Alpha Omega”



255
256
257
# File 'app/models/user.rb', line 255

def formatted_teams(array)
  array.map { |team| team.name } * ", "
end

#initialize_human_nameObject



240
241
242
# File 'app/models/user.rb', line 240

def initialize_human_name
  self.human_name = self.first_name + " " + self.last_name if self.human_name.nil?
end

#notify_about_missing_field(attribute, message) ⇒ Object

attribute :github If the user has not set this attribute, then ask the user to do so



390
391
392
393
394
395
396
397
398
399
400
# File 'app/models/user.rb', line 390

def notify_about_missing_field(attribute, message)
  if self.send(attribute).blank?
    options = {:to => self.email,
               :subject => "Your user account needs updating",
               :message => message,
               :url_label => "Modify your profile",
               :url => Rails.application.routes.url_helpers.edit_user_url(self, :host => "whiteboard.sv.cmu.edu")
    }
    GenericMailer.email(options).deliver
  end
end

#past_teamsObject

Todo: This method looks similiar to one in helpers/teams_helper.rb – if so DRY!



249
250
251
# File 'app/models/user.rb', line 249

def past_teams
  Team.find_by_sql(["SELECT t.* FROM  teams t INNER JOIN team_assignments ta ON ( t.id = ta.team_id) INNER JOIN users u ON (ta.user_id = u.id) INNER JOIN courses c ON (t.course_id = c.id) WHERE u.id = ? AND (c.semester <> ? OR c.year <> ?)", self.id, AcademicCalendar.current_semester(), Date.today.year])
end

#permission_level_of(role) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
# File 'app/models/user.rb', line 183

def permission_level_of(role)
  case role
    when :student
      return (self.is_student? || self.is_staff? || self.is_admin?)
    when :staff
      return (self.is_staff? || self.is_admin?)
    when :admin
      return (self.is_admin?)
    else
      return false
  end
end

#registered_for_these_courses_during_current_semesterObject



112
113
114
115
116
117
118
119
120
121
# File 'app/models/user.rb', line 112

def registered_for_these_courses_during_current_semester
  hub_registered_courses = registered_courses.where(:semester => AcademicCalendar.current_semester, :year => Date.today.year).all

  sql_str = "select c.* FROM courses c,teams t
            where t.course_id=c.id and c.year=#{Date.today.year} and c.semester='#{AcademicCalendar.current_semester()}' and t.id in
            (SELECT ta.team_id FROM team_assignments ta, users u where u.id=ta.user_id and u.id=#{self.id})"
  courses_assigned_on_teams = Course.find_by_sql(sql_str)

  @registered_courses = hub_registered_courses | courses_assigned_on_teams
end

#registered_for_these_courses_during_past_semestersObject



123
124
125
# File 'app/models/user.rb', line 123

def registered_for_these_courses_during_past_semesters
  self.registered_courses - self.registered_for_these_courses_during_current_semester
end

#reset_twiki_passwordObject



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'app/models/user.rb', line 334

def reset_twiki_password
  require 'mechanize'
  agent = Mechanize.new
  agent.basic_auth(TWIKI_USERNAME, TWIKI_PASSWORD)
  agent.get(TWIKI_URL + '/do/view/TWiki/ResetPassword') do |page|
    reset_result_page = page.form_with(:action => '/do/resetpasswd/Main/WebHome') do |reset_page|
      reset_page.LoginName = self.twiki_name
    end.submit

    return false if reset_result_page.parser.css('.patternTopic h3').text == " Password reset failed "
    return true if reset_result_page.link_with(:text => 'change password')

    return true
  end
end

#set_new_user_tokenObject



432
433
434
# File 'app/models/user.rb', line 432

def set_new_user_token
  self.new_user_token = SecureRandom.urlsafe_base64
end

#set_password_reset_tokenObject



436
437
438
# File 'app/models/user.rb', line 436

def set_password_reset_token
  self.password_reset_token = SecureRandom.urlsafe_base64
end

#should_be_redirected?Boolean

Returns:

  • (Boolean)


402
403
404
405
406
407
408
409
410
411
412
# File 'app/models/user.rb', line 402

def should_be_redirected?
  if self.people_search_first_accessed_at.nil?
    self.people_search_first_accessed_at = Time.now
    self.save!
  end
  #self.first_access = nil
  #self.save!
  ((Time.now - self.people_search_first_accessed_at)>4.weeks) ? true : false
  #true
  #false
end

#teaching_these_courses_during_current_semesterObject



108
109
110
# File 'app/models/user.rb', line 108

def teaching_these_courses_during_current_semester
  teaching_these_courses.where(:semester => AcademicCalendar.current_semester, :year => Date.today.year)
end

#telephonesObject



197
198
199
200
201
202
203
204
# File 'app/models/user.rb', line 197

def telephones
  phones = []
  phones << "#{self.telephone1_label}: #{self.telephone1}" unless (self.telephone1_label.nil? || self.telephone1_label.empty?)
  phones << "#{self.telephone2_label}: #{self.telephone2}" unless (self.telephone2_label.nil? || self.telephone2_label.empty?)
  phones << "#{self.telephone3_label}: #{self.telephone3}" unless (self.telephone3_label.nil? || self.telephone3_label.empty?)
  phones << "#{self.telephone4_label}: #{self.telephone4}" unless (self.telephone4_label.nil? || self.telephone4_label.empty?)
  return phones
end

#telephones_hashObject



206
207
208
209
210
211
212
213
# File 'app/models/user.rb', line 206

def telephones_hash
  phones = Hash.new
  phones[self.telephone1_label] = self.telephone1 unless (self.telephone1_label.nil? || self.telephone1_label.empty?)
  phones[self.telephone2_label] = self.telephone2 unless (self.telephone2_label.nil? || self.telephone2_label.empty?)
  phones[self.telephone3_label] = self.telephone3 unless (self.telephone3_label.nil? || self.telephone3_label.empty?)
  phones[self.telephone4_label] = self.telephone4 unless (self.telephone4_label.nil? || self.telephone4_label.empty?)
  return phones
end

#to_paramObject



91
92
93
94
95
96
97
# File 'app/models/user.rb', line 91

def to_param
  if twiki_name.blank?
    id.to_s
  else
    twiki_name
  end
end

#update_webiso_accountObject



244
245
246
# File 'app/models/user.rb', line 244

def 
  self. = Time.now.to_f.to_s if self..blank?
end