From 4122ae237abe81fedc8ea9dbb7d85e03e705101f Mon Sep 17 00:00:00 2001 From: ROSPARS Benoit Date: Mon, 26 Apr 2021 10:51:50 +0200 Subject: [PATCH] Fix #32 make authentication based on username only --- lti_authenticator.rb | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/lti_authenticator.rb b/lti_authenticator.rb index ec47654..3cc529f 100644 --- a/lti_authenticator.rb +++ b/lti_authenticator.rb @@ -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.