|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +class OmniauthCallbacksController < Devise::OmniauthCallbacksController |
| 4 | + before_action :require_valid_omniauth, only: :shibboleth |
| 5 | + |
| 6 | + def shibboleth |
| 7 | + Rails.logger.info("OmniauthCallbacksController#shibboleth: #{omniauth.inspect}") |
| 8 | + set_user |
| 9 | + if @user.persisted? |
| 10 | + log_in |
| 11 | + else |
| 12 | + redirect_to_login |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + def failure |
| 17 | + redirect_to root_path |
| 18 | + end |
| 19 | + |
| 20 | + private |
| 21 | + |
| 22 | + def redirect_to_login |
| 23 | + Rails.logger.error(find_message(:failure, kind: 'NYU Shibboleth', reason: 'User not persisted')) |
| 24 | + session['devise.shibboleth_data'] = request.env['omniauth.auth'] |
| 25 | + redirect_to root_path |
| 26 | + end |
| 27 | + |
| 28 | + def log_in |
| 29 | + sign_in_and_redirect @user, event: :authentication |
| 30 | + set_flash_message(:notice, :success, kind: 'NYU Shibboleth') |
| 31 | + logger.info(find_message(:success, kind: 'NYU Shibboleth')) |
| 32 | + end |
| 33 | + |
| 34 | + def require_valid_omniauth |
| 35 | + head :bad_request unless valid_omniauth? |
| 36 | + end |
| 37 | + |
| 38 | + def valid_omniauth? |
| 39 | + omniauth.present? |
| 40 | + end |
| 41 | + |
| 42 | + def omniauth |
| 43 | + @omniauth ||= request.env['omniauth.auth'] |
| 44 | + end |
| 45 | + |
| 46 | + def omniauth_provider |
| 47 | + @omniauth_provider ||= omniauth.provider |
| 48 | + end |
| 49 | + |
| 50 | + def attributes_from_omniauth |
| 51 | + { |
| 52 | + provider: omniauth.provider, |
| 53 | + username: omniauth.uid, |
| 54 | + email: omniauth_email, |
| 55 | + firstname: omniauth_firstname, |
| 56 | + lastname: omniauth_lastname |
| 57 | + } |
| 58 | + end |
| 59 | + |
| 60 | + def omniauth_email |
| 61 | + @omniauth_email ||= omniauth.info.email |
| 62 | + end |
| 63 | + |
| 64 | + def omniauth_firstname |
| 65 | + @omniauth_firstname ||= omniauth.info.first_name |
| 66 | + end |
| 67 | + |
| 68 | + def omniauth_lastname |
| 69 | + @omniauth_lastname ||= omniauth.info.last_name |
| 70 | + end |
| 71 | + |
| 72 | + def set_user |
| 73 | + # Find existing or initialize new user, |
| 74 | + # and save new attributes each time |
| 75 | + @user = find_user |
| 76 | + @user.update_attributes(attributes_from_omniauth) |
| 77 | + end |
| 78 | + |
| 79 | + def find_user |
| 80 | + @find_user ||= User.create_from_provider_data(request.env['omniauth.auth']) |
| 81 | + end |
| 82 | +end |
0 commit comments