Skip to content

Commit

Permalink
Fix mit-teaching-systems-lab#32 make authentication based on username…
Browse files Browse the repository at this point in the history
… only
  • Loading branch information
brospars committed Apr 26, 2021
1 parent e96d9c9 commit 4122ae2
Showing 1 changed file with 9 additions and 15 deletions.
24 changes: 9 additions & 15 deletions lti_authenticator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,30 +40,24 @@ def after_authenticate(auth_token)
auth_result.extra_data = omniauth_params.merge(lti_uid: lti_uid)
log :info, "after_authenticate, auth_result: #{auth_result.inspect}"

# Lookup or create a new User record, requiring that both email and username match.
# Lookup or create a new User record
# Discourse's User model patches some Rails methods, so we use their
# methods here rather than reaching into details of how these fields are stored in the DB.
# This appears related to changes in https://github.com/discourse/discourse/pull/4977
user_by_email = User.find_by_email(auth_result.email.downcase)
user_by_username = User.find_by_username(auth_result.username)
both_matches_found = user_by_email.present? && user_by_username.present?
no_matches_found = user_by_email.nil? && user_by_username.nil?
if both_matches_found && user_by_email.id == user_by_username.id
log :info, "after_authenticate, found user records by both username and email and they matched, using existing user..."
user = user_by_email
elsif no_matches_found
log :info, "after_authenticate, no matches found for email or username, creating user record for first-time user..."
#
# Making the assumption that Edx uses username as primary and cannot be changed
# See https://support.edx.org/hc/en-us/articles/115016004448-Can-I-change-my-edX-username-
user = User.find_by_username(auth_result.username)
if user.present?
log :info, "after_authenticate, found user records by username, using existing user..."
elsif user.nil?
log :info, "after_authenticate, no matches found username, creating user record for first-time user..."
user = User.new(email: auth_result.email.downcase, username: auth_result.username)
user.staged = false
user.active = true
user.password = SecureRandom.hex(32)
user.save!
user.reload
else
log :info, "after_authenticate, found user records that did not match by username and email"
log :info, "after_authenticate, user_by_email: #{user_by_email.inspect}"
log :info, "after_authenticate, user_by_username: #{user_by_username.inspect}"
raise ::ActiveRecord::RecordInvalid('LTIAuthenticator: edge case for finding User records where username and email did not match, aborting...')
end

# Return a reference to the User record.
Expand Down

0 comments on commit 4122ae2

Please sign in to comment.