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