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