Merge branch 'master' into 15558-alternate-email-addresses
[arvados.git] / services / api / app / controllers / user_sessions_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class UserSessionsController < ApplicationController
6   before_action :require_auth_scope, :only => [ :destroy ]
7
8   skip_before_action :set_cors_headers
9   skip_before_action :find_object_by_uuid
10   skip_before_action :render_404_if_no_object
11
12   respond_to :html
13
14   # omniauth callback method
15   def create
16     if !Rails.configuration.Login.LoginCluster.empty? and Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
17       raise "Local login disabled when LoginCluster is set"
18     end
19
20     omniauth = request.env['omniauth.auth']
21
22     begin
23       user = User.register omniauth['info']
24     rescue => e
25       Rails.logger.warn e
26       return redirect_to login_failure_url
27     end
28
29     # For the benefit of functional and integration tests:
30     @user = user
31
32     if user.uuid[0..4] != Rails.configuration.ClusterID
33       # Actually a remote user
34       # Send them to their home cluster's login
35       rh = Rails.configuration.RemoteClusters[user.uuid[0..4]]
36       remote, return_to_url = params[:return_to].split(',', 2)
37       @remotehomeurl = "#{rh.Scheme || "https"}://#{rh.Host}/login?remote=#{Rails.configuration.ClusterID}&return_to=#{return_to_url}"
38       render
39       return
40     end
41
42     # prevent ArvadosModel#before_create and _update from throwing
43     # "unauthorized":
44     Thread.current[:user] = user
45
46     user.save or raise Exception.new(user.errors.messages)
47
48     omniauth.delete('extra')
49
50     # Give the authenticated user a cookie for direct API access
51     session[:user_id] = user.id
52     session[:api_client_uuid] = nil
53     session[:api_client_trusted] = true # full permission to see user's secrets
54
55     @redirect_to = root_path
56     if params.has_key?(:return_to)
57       # return_to param's format is 'remote,return_to_url'. This comes from login()
58       # encoding the remote=zbbbb parameter passed by a client asking for a salted
59       # token.
60       remote, return_to_url = params[:return_to].split(',', 2)
61       if remote !~ /^[0-9a-z]{5}$/ && remote != ""
62         return send_error 'Invalid remote cluster id', status: 400
63       end
64       remote = nil if remote == ''
65       return send_api_token_to(return_to_url, user, remote)
66     end
67     redirect_to @redirect_to
68   end
69
70   # Omniauth failure callback
71   def failure
72     flash[:notice] = params[:message]
73   end
74
75   # logout - Clear our rack session BUT essentially redirect to the provider
76   # to clean up the Devise session from there too !
77   def logout
78     session[:user_id] = nil
79
80     flash[:notice] = 'You have logged off'
81     return_to = params[:return_to] || root_url
82     redirect_to "#{Rails.configuration.Services.SSO.ExternalURL}/users/sign_out?redirect_uri=#{CGI.escape return_to}"
83   end
84
85   # login - Just bounce to /auth/joshid. The only purpose of this function is
86   # to save the return_to parameter (if it exists; see the application
87   # controller). /auth/joshid bypasses the application controller.
88   def login
89     if params[:remote] !~ /^[0-9a-z]{5}$/ && !params[:remote].nil?
90       return send_error 'Invalid remote cluster id', status: 400
91     end
92     if current_user and params[:return_to]
93       # Already logged in; just need to send a token to the requesting
94       # API client.
95       #
96       # FIXME: if current_user has never authorized this app before,
97       # ask for confirmation here!
98
99       return send_api_token_to(params[:return_to], current_user, params[:remote])
100     end
101     p = []
102     p << "auth_provider=#{CGI.escape(params[:auth_provider])}" if params[:auth_provider]
103
104     if !Rails.configuration.Login.LoginCluster.empty? and Rails.configuration.Login.LoginCluster != Rails.configuration.ClusterID
105       host = ApiClientAuthorization.remote_host(uuid_prefix: Rails.configuration.Login.LoginCluster)
106       if not host
107         raise "LoginCluster #{Rails.configuration.Login.LoginCluster} missing from RemoteClusters"
108       end
109       scheme = "https"
110       cluster = Rails.configuration.RemoteClusters[Rails.configuration.Login.LoginCluster]
111       if cluster and cluster['Scheme'] and !cluster['Scheme'].empty?
112         scheme = cluster['Scheme']
113       end
114       login_cluster = "#{scheme}://#{host}"
115       p << "remote=#{CGI.escape(params[:remote])}" if params[:remote]
116       p << "return_to=#{CGI.escape(params[:return_to])}" if params[:return_to]
117       redirect_to "#{login_cluster}/login?#{p.join('&')}"
118     else
119       if params[:return_to]
120         # Encode remote param inside callback's return_to, so that we'll get it on
121         # create() after login.
122         remote_param = params[:remote].nil? ? '' : params[:remote]
123         p << "return_to=#{CGI.escape(remote_param + ',' + params[:return_to])}"
124       end
125       redirect_to "/auth/joshid?#{p.join('&')}"
126     end
127   end
128
129   def send_api_token_to(callback_url, user, remote=nil)
130     # Give the API client a token for making API calls on behalf of
131     # the authenticated user
132
133     # Stub: automatically register all new API clients
134     api_client_url_prefix = callback_url.match(%r{^.*?://[^/]+})[0] + '/'
135     act_as_system_user do
136       @api_client = ApiClient.
137         find_or_create_by(url_prefix: api_client_url_prefix)
138     end
139
140     @api_client_auth = ApiClientAuthorization.
141       new(user: user,
142           api_client: @api_client,
143           created_by_ip_address: remote_ip,
144           scopes: ["all"])
145     @api_client_auth.save!
146
147     if callback_url.index('?')
148       callback_url += '&'
149     else
150       callback_url += '?'
151     end
152     if remote.nil?
153       token = @api_client_auth.token
154     else
155       token = @api_client_auth.salted_token(remote: remote)
156     end
157     callback_url += 'api_token=' + token
158     redirect_to callback_url
159   end
160
161   def cross_origin_forbidden
162     send_error 'Forbidden', status: 403
163   end
164 end