-
Notifications
You must be signed in to change notification settings - Fork 10
/
sessions_controller.rb
85 lines (63 loc) · 2.72 KB
/
sessions_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class SessionsController < ApplicationController
# some omniauth callbacks (like developer) are sent using a post request,
# need to disable this otherwise session will be clobbered by rails
# https://github.com/omniauth/omniauth/wiki/FAQ#rails-session-is-clobbered-after-callback-on-openid-providers
# TODO just limit this to development mode? since this doesnt effect saml?
skip_before_action :verify_authenticity_token, only: [:create, :system_login]
skip_after_action :verify_authorized
def create
auth_hash = request.env['omniauth.auth']
# Do we have an existing user already?
identity = Identity.find_by(provider: auth_hash.provider, uid: auth_hash.uid)
# Attempt to grab the user if we do have an identity already
user = identity.try(:user)
# Couldn't grab a user, so must be a new user/identity, so lets create them
if user.blank? && auth_hash.info.email.present? && auth_hash.info.name.present?
user = User.find_by(email: auth_hash.info.email)
if user.nil?
user = User.create(email: auth_hash.info.email,
name: auth_hash.info.name)
end
user.identities.create(provider: auth_hash.provider, uid: auth_hash.uid)
end
# System user accounts should not be able to access application through
# omniauth authentication
return redirect_to root_path, alert: t('login.error') if user&.system?
return redirect_to root_path, alert: t('login.user_suspended') if user&.suspended?
# Sign the user in, if they exist
sign_in(user)
if current_user.present?
# Was signed in successfully, redirect them back to where they came from or to the homepage
flash[:notice] = t('login.success')
redirect_back_to
else
# Else something went wrong along the way with omniauth
redirect_to root_path, alert: t('login.error')
end
end
def destroy
log_off_user
redirect_to root_url, notice: t('.signed_out')
end
def failure
redirect_to root_path, alert: t('login.error')
end
def logout_as_user
admin_user = User.find(session[:admin_id])
raise Pundit::NotAuthorizedError if !admin_user.admin? || admin_user.suspended?
original_user = current_user
sign_in(admin_user)
logger.info("Admin '#{admin_user.name}' has now logged out as '#{original_user.name}'")
session[:admin_id] = nil
redirect_to admin_user_path(original_user), notice: t('.flash', original_user: original_user.name)
end
def system_login
email = params[:email]
api_key = params[:api_key]
user = User.find_by(email:)
return head :ok if user.present? &&
user.authenticate_api_key(api_key) &&
sign_in(user)
head :unauthorized
end
end