diff --git a/app/controllers/concerns/account_credentials_form.rb b/app/controllers/concerns/account_credentials_form.rb new file mode 100644 index 000000000..9adc43b18 --- /dev/null +++ b/app/controllers/concerns/account_credentials_form.rb @@ -0,0 +1,72 @@ +# typed: strict +# frozen_string_literal: true + +# The email and password fields of the account form, which both the user's own account page and +# the participant settings page submit. +module AccountCredentialsForm + extend T::Sig + extend ActiveSupport::Concern + extend T::Helpers + requires_ancestor { ApplicationController } + + CREDENTIAL_FIELDS = T.let(%w[email email_repeat old_password password password_repeat].freeze, T::Array[String]) + + private + # Applies the submitted email and password fields to an existing account and returns whether + # a password change was requested. + sig { params(user: User, user_params: T.untyped).returns(T::Boolean) } + def apply_credentials(user, user_params) + if user.managed_externally? + refuse_managed_credential_changes(user, user_params) + return false + end + + set_email(user, user_params) + maybe_update_password(user, user_params) + end + + sig { params(user: User, user_params: T.untyped).void } + def set_email(user, user_params) + return if !user.new_record? && user_params[:email_repeat].blank? + + if user_params[:email].blank? + user.errors.add(:email, 'needed') + elsif user_params[:email] != user_params[:email_repeat] + user.errors.add(:email_repeat, 'did not match') + else + user.email = user_params[:email].strip + end + end + + # A managed account's form has no credential fields, so any submitted come from a stale page. + sig { params(user: User, user_params: T.untyped).void } + def refuse_managed_credential_changes(user, user_params) + return if CREDENTIAL_FIELDS.none? { |field| user_params[field].present? } + + user.errors.add(:base, User::MANAGED_CREDENTIALS_MESSAGE) + end + + sig { params(user: User, user_params: T.untyped).returns(T::Boolean) } + def maybe_update_password(user, user_params) + if user_params[:old_password].present? || user_params[:password].present? + if user.externally_managed_without_target? + user.errors.add(:base, 'This account is being migrated; password changes are temporarily unavailable.') + return false + end + if !user.has_password?(user_params[:old_password]) + user.errors.add(:old_password, 'incorrect') + elsif user_params[:password] != user_params[:password_repeat] + user.errors.add(:password_repeat, 'did not match') + elsif user_params[:password].blank? + user.errors.add(:password, 'cannot be empty') + elsif user_params[:password].length > 1000 + user.errors.add(:password, 'cannot be over 1000 characters') + else + user.password = user_params[:password] + end + true + else + false + end + end +end diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index c8fa5ac1c..c564194d9 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -3,6 +3,7 @@ class SettingsController < ApplicationController extend T::Sig + include AccountCredentialsForm skip_authorization_check before_action :set_user @@ -20,13 +21,12 @@ def update User.transaction do email_before = user.email @email_before = T.let(email_before, T.nilable(String)) - set_email - password_changed = maybe_update_password(user, params[:user]) + password_changed = apply_credentials(user, params.fetch(:user, {})) set_user_fields if user.errors.empty? && user.save # Password changed locally: migrate the user to courses.mooc.fi - user.post_new_user_to_courses_mooc_fi(params[:user][:password]) if password_changed && !user.managed_externally? + user.post_new_user_to_courses_mooc_fi(params[:user][:password]) if password_changed RecentlyChangedUserDetail.email_changed.create!(old_value: email_before, new_value: user.email, username: user.login, user_id: user.id) unless T.must(email_before.casecmp(user.email)).zero? flash[:notice] = if password_changed 'Changes saved and password changed' @@ -84,52 +84,6 @@ def set_user @user = T.let(User.find(params[:participant_id]), T.nilable(User)) end - sig { void } - def set_email - user = T.must(@user) - user_params = params[:user] - - return if !user.new_record? && user_params[:email_repeat].blank? - - if user_params[:email].blank? - user.errors.add(:email, 'needed') - elsif user_params[:email] != user_params[:email_repeat] - user.errors.add(:email_repeat, 'did not match') - else - user.email = user_params[:email].strip - end - end - - sig { params(user: User, user_params: T.untyped).returns(T::Boolean) } - def maybe_update_password(user, user_params) - if user_params[:old_password].present? || user_params[:password].present? - if user.managed_externally? - unless user.update_password_via_courses_mooc_fi(user_params[:old_password], user_params[:password]) - user.errors.add(:password, 'could not be changed. Please check your current password and try again.') - return false - end - return true - elsif user.externally_managed_without_target? - user.errors.add(:base, 'This account is being migrated; password changes are temporarily unavailable.') - return false - end - if !user.has_password?(user_params[:old_password]) - user.errors.add(:old_password, 'incorrect') - elsif user_params[:password] != user_params[:password_repeat] - user.errors.add(:password_repeat, 'did not match') - elsif user_params[:password].blank? - user.errors.add(:password, 'cannot be empty') - elsif user_params[:password].length > 1000 - user.errors.add(:password, 'cannot be over 1000 characters') - else - user.password = user_params[:password] - end - true - else - false - end - end - sig { returns(T.nilable(T::Hash[T.untyped, T.untyped])) } def set_user_fields return if params[:user_field].nil? diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 9f6da3a90..5a2a2d202 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -4,6 +4,7 @@ # Presents the "register user" and "edit profile" views. class UsersController < ApplicationController extend T::Sig + include AccountCredentialsForm skip_authorization_check # Stale legacy deletion forms must still redirect, whatever the forgery protection strategy. skip_forgery_protection only: :redirect_to_account_deletion @@ -51,7 +52,7 @@ def create @user.login = SecureRandom.uuid - set_email + set_email(@user, params[:user]) set_password set_user_fields @@ -87,13 +88,12 @@ def update email_before = @user.email @email_before = T.let(email_before, T.nilable(String)) - set_email - password_changed = maybe_update_password(@user, params[:user]) + password_changed = apply_credentials(@user, params.fetch(:user, {})) set_user_fields if @user.errors.empty? && @user.save # Password changed locally: migrate the user to courses.mooc.fi - @user.post_new_user_to_courses_mooc_fi(params[:user][:password]) if password_changed && !@user.managed_externally? + @user.post_new_user_to_courses_mooc_fi(params[:user][:password]) if password_changed RecentlyChangedUserDetail.email_changed.create!(old_value: email_before, new_value: @user.email, username: @user.login, user_id: @user.id) unless T.must(email_before.casecmp(@user.email)).zero? flash[:notice] = if password_changed 'Changes saved and password changed' @@ -140,22 +140,6 @@ def redirect_to_account_deletion end private - sig { void } - def set_email - user = T.must(@user) - user_params = params[:user] - - return if !user.new_record? && user_params[:email_repeat].blank? - - if user_params[:email].blank? - user.errors.add(:email, 'needed') - elsif user_params[:email] != user_params[:email_repeat] - user.errors.add(:email_repeat, 'did not match') - else - user.email = user_params[:email].strip - end - end - sig { void } def set_password user = T.must(@user) @@ -171,36 +155,6 @@ def set_password end end - sig { params(user: User, user_params: T.untyped).returns(T::Boolean) } - def maybe_update_password(user, user_params) - if user_params[:old_password].present? || user_params[:password].present? - if user.managed_externally? - unless user.update_password_via_courses_mooc_fi(user_params[:old_password], user_params[:password]) - user.errors.add(:password, 'could not be changed. Please check your current password and try again.') - return false - end - return true - elsif user.externally_managed_without_target? - user.errors.add(:base, 'This account is being migrated; password changes are temporarily unavailable.') - return false - end - if !user.has_password?(user_params[:old_password]) - user.errors.add(:old_password, 'incorrect') - elsif user_params[:password] != user_params[:password_repeat] - user.errors.add(:password_repeat, 'did not match') - elsif user_params[:password].blank? - user.errors.add(:password, 'cannot be empty') - elsif user_params[:password].length > 1000 - user.errors.add(:password, 'cannot be over 1000 characters') - else - user.password = user_params[:password] - end - true - else - false - end - end - sig { returns(T.nilable(T::Hash[T.untyped, T.untyped])) } def set_user_fields return if params[:user_field].nil? diff --git a/app/models/ability.rb b/app/models/ability.rb index 1c4729572..2c03806d3 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -53,6 +53,8 @@ def initialize(user, auth_source: nil) can :update, User do |u| u == user end + # Its owner changes a managed account's email and password on courses.mooc.fi. + cannot :update_credentials, User, &:managed_externally? cannot :read, Course can :read, Course do |c| diff --git a/app/models/user.rb b/app/models/user.rb index 1c0ce0ca6..e2252aee5 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -53,6 +53,8 @@ class User < ApplicationRecord COURSES_MOOC_FI_USER_ID_FORMAT = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/ + MANAGED_CREDENTIALS_MESSAGE = 'The email address and password of this account are changed on courses.mooc.fi.' + # Lookups by courses.mooc.fi id (token authentication) match exactly, so store the canonical form. normalizes :courses_mooc_fi_user_id, with: ->(id) { id.strip.downcase } @@ -501,10 +503,36 @@ def courses_mooc_fi_profile_url courses_mooc_fi_url("/manage/users/#{courses_mooc_fi_user_id}") end + # This user's summary page in the mooc.fi admin tools. Nil when mooc.fi isn't configured. + sig { returns(T.nilable(String)) } + def moocfi_admin_url + base_url = User.moocfi_base_url + "#{base_url}/admin/users/#{id}/summary" if base_url + end + # courses.mooc.fi's root URL without a trailing slash. Nil when it isn't configured. sig { returns(T.nilable(String)) } def self.courses_mooc_fi_base_url - SiteSetting.value('courses_mooc_fi_base_url').to_s.chomp('/').presence + site_base_url('courses_mooc_fi_base_url') + end + + # mooc.fi's root URL without a trailing slash. Nil when it isn't configured. + sig { returns(T.nilable(String)) } + def self.moocfi_base_url + site_base_url('moocfi_base_url') + end + + # The site setting `key` as a root URL without a trailing slash. Nil when it isn't configured. + sig { params(key: String).returns(T.nilable(String)) } + private_class_method def self.site_base_url(key) + SiteSetting.value(key).to_s.strip.chomp('/').presence + end + + # Where users of a managed account change its email and password. Nil when courses.mooc.fi isn't configured. + sig { returns(T.nilable(String)) } + def self.courses_mooc_fi_account_settings_url + base_url = courses_mooc_fi_base_url + "#{base_url}/user-settings/account" if base_url end # Where users delete their account, which also deletes it here. Nil when courses.mooc.fi isn't configured. diff --git a/app/views/participants/show.html.erb b/app/views/participants/show.html.erb index f88e9938a..d69c0cc17 100644 --- a/app/views/participants/show.html.erb +++ b/app/views/participants/show.html.erb @@ -45,8 +45,15 @@ end %>
+ This user's email address and password are changed on courses.mooc.fi, where admins can also edit them. + <% if profile_url && current_user.administrator? %> + <%= link_to 'Open this user on courses.mooc.fi', profile_url, target: '_blank', rel: 'noopener' %>. + <% end %> +
+<% end %> diff --git a/config/site.defaults.yml b/config/site.defaults.yml index 69e50b6f4..3546a1e31 100644 --- a/config/site.defaults.yml +++ b/config/site.defaults.yml @@ -144,3 +144,6 @@ teacher_manual_url: http://testmycode.github.io/tmc-server/usermanual/ # Base URL for password management, admin lookups and access-token introspection via courses.mooc.fi, # e.g. https://courses.mooc.fi courses_mooc_fi_base_url: + +# Base URL for the mooc.fi admin tools linked from participant pages, e.g. https://www.mooc.fi +moocfi_base_url: diff --git a/spec/controllers/api/v8/users_controller_spec.rb b/spec/controllers/api/v8/users_controller_spec.rb index c4f7cd57e..7ee44eda7 100644 --- a/spec/controllers/api/v8/users_controller_spec.rb +++ b/spec/controllers/api/v8/users_controller_spec.rb @@ -167,15 +167,69 @@ def do_update(old_password) expect(response).to have_http_status(400) expect(user.reload).to have_password('oldpassword') end + end - it 'delegates to courses.mooc.fi without migrating for an already managed user' do + describe 'PUT update credentials of an account managed by courses.mooc.fi' do + before :each do user.update!(password_managed_by_courses_mooc_fi: true, courses_mooc_fi_user_id: SecureRandom.uuid) - expect_any_instance_of(User).to receive(:update_password_via_courses_mooc_fi).with('oldpassword', 'newpassword').and_return(true) - expect_any_instance_of(User).not_to receive(:post_new_user_to_courses_mooc_fi) + end - do_update('oldpassword') + context "with the user's own token" do + let!(:token) { Doorkeeper::AccessToken.create!(resource_owner_id: user.id, scopes: 'public') } - expect(response).to have_http_status(200) + it 'refuses an email change' do + put :update, params: { id: 'current', user: { email: 'changed@example.com' } } + + expect(response).to have_http_status(403) + expect(user.reload.email).not_to eq('changed@example.com') + end + + it 'refuses a password change' do + expect_any_instance_of(User).not_to receive(:update_password_via_courses_mooc_fi) + expect_any_instance_of(User).not_to receive(:post_new_user_to_courses_mooc_fi) + + put :update, params: { id: 'current', user: { email: user.email }, + old_password: 'oldpassword', password: 'newpassword', password_repeat: 'newpassword' } + + expect(response).to have_http_status(403) + end + + it 'still saves other details with the unchanged email' do + put :update, params: { id: 'current', user: { email: user.email } } + + expect(response).to have_http_status(200) + end + end + + context 'with an admin token, as courses.mooc.fi writes them' do + let!(:token) { Doorkeeper::AccessToken.create!(resource_owner_id: admin.id, scopes: 'public') } + + it 'changes the email' do + put :update, params: { id: user.id, user: { email: 'changed@example.com' } }, as: :json + + expect(response).to have_http_status(200) + expect(user.reload.email).to eq('changed@example.com') + end + + it 'changes the password through courses.mooc.fi' do + expect_any_instance_of(User).to receive(:update_password_via_courses_mooc_fi).with('oldpassword', 'newpassword').and_return(true) + + put :update, params: { id: user.id, user: { email: user.email }, + old_password: 'oldpassword', password: 'newpassword', password_repeat: 'newpassword' }, as: :json + + expect(response).to have_http_status(200) + end + + it 'changes the name' do + first_name = UserField.new(name: 'first_name', field_type: 'text') + allow(UserField).to receive_messages(all: [first_name]) + allow(ExtraField).to receive(:by_kind).with(:user).and_return([first_name]) + + put :update, params: { id: user.id, user_field: { 'first_name' => 'Changed' } }, as: :json + + expect(response).to have_http_status(200) + expect(user.reload.field_value_record(first_name).value).to eq('Changed') + end end end diff --git a/spec/controllers/settings_controller_spec.rb b/spec/controllers/settings_controller_spec.rb index 624c76730..865fc7e72 100644 --- a/spec/controllers/settings_controller_spec.rb +++ b/spec/controllers/settings_controller_spec.rb @@ -29,4 +29,51 @@ expect(response.body).not_to include(deletion_url) expect(response.body).to include('Dangerously destroy account') end + + describe 'for an account managed by courses.mooc.fi' do + before :each do + user.update!(password_managed_by_courses_mooc_fi: true, courses_mooc_fi_user_id: SecureRandom.uuid) + controller.current_user = user + end + + it 'links to courses.mooc.fi instead of offering the email and password fields' do + get :show, params: { participant_id: user.id } + + expect(response.body).to include(%(href="https://courses.mooc.fi/user-settings/account")) + expect(response.body).not_to include('user[email_repeat]') + expect(response.body).not_to include('user[old_password]') + end + + it 'refuses submitted email and password changes' do + expect_any_instance_of(User).not_to receive(:update_password_via_courses_mooc_fi) + + put :update, params: { + participant_id: user.id, + user: { email: 'changed@example.com', email_repeat: 'changed@example.com', old_password: 'xooxer', password: 'newpassword', password_repeat: 'newpassword' } + } + + expect(user.reload.email).not_to eq('changed@example.com') + expect(response).to have_http_status(:forbidden) + expect(response.body).to include('changed on courses.mooc.fi') + expect(flash[:notice]).to be_nil + end + + it 'offers no Save button when there is nothing to edit' do + allow(UserField).to receive_messages(all: []) + + get :show, params: { participant_id: user.id } + + expect(response.body).not_to include('value="Save"') + end + + it "points an admin to the user's page on courses.mooc.fi" do + controller.current_user = FactoryBot.create(:admin) + + get :show, params: { participant_id: user.id } + + expect(response.body).to include(%(href="https://courses.mooc.fi/manage/users/#{user.courses_mooc_fi_user_id}")) + expect(response.body).not_to include('user[email_repeat]') + expect(response.body).not_to include('user[old_password]') + end + end end diff --git a/spec/controllers/users_controller_spec.rb b/spec/controllers/users_controller_spec.rb index 15aba1b75..fdca9e28a 100644 --- a/spec/controllers/users_controller_spec.rb +++ b/spec/controllers/users_controller_spec.rb @@ -208,14 +208,17 @@ expect(response.status).to eq(403) end - it 'should delegate to courses.mooc.fi without migrating for an already managed user' do + it 'should refuse email and password changes for a user managed by courses.mooc.fi' do @user.update!(password_managed_by_courses_mooc_fi: true, courses_mooc_fi_user_id: SecureRandom.uuid) - expect_any_instance_of(User).to receive(:update_password_via_courses_mooc_fi).with('oldpassword', 'newpassword').and_return(true) + expect_any_instance_of(User).not_to receive(:update_password_via_courses_mooc_fi) expect_any_instance_of(User).not_to receive(:post_new_user_to_courses_mooc_fi) - put :update, params: { user: params.merge(old_password: 'oldpassword', + put :update, params: { user: params.merge(email_repeat: 'newemail@valid.com', + old_password: 'oldpassword', password: 'newpassword', password_repeat: 'newpassword') } - expect(response).to redirect_to(user_path) + expect(response.status).to eq(403) + expect(flash[:notice]).to be_nil + expect(@user.reload.email).not_to eq('newemail@valid.com') end it 'should not change the password if the old password was wrong' do diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 3f4f70e9e..5b4024560 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -311,6 +311,20 @@ end end + describe 'moocfi_admin_url' do + it 'is nil when moocfi_base_url is not configured' do + user = User.create!(login: 'localuser', password: 'secret123', email: 'localuser@example.com') + SiteSetting.all_settings['moocfi_base_url'] = nil + expect(user.moocfi_admin_url).to be_nil + end + + it "builds the summary url from the configured base url and the user's id" do + user = User.create!(login: 'localuser', password: 'secret123', email: 'localuser@example.com') + SiteSetting.all_settings['moocfi_base_url'] = 'https://www.mooc.fi/' + expect(user.moocfi_admin_url).to eq("https://www.mooc.fi/admin/users/#{user.id}/summary") + end + end + describe 'migrating to courses.mooc.fi on login' do it 'posts a locally-managed user on successful authentication' do user = User.create!(login: 'localuser', password: 'secret123', email: 'localuser@example.com')