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