Add 'apps/arv-web/' from commit 'f9732ad8460d013c2f28363655d0d1b91894dca5'
[arvados.git] / services / api / app / controllers / user_sessions_controller.rb
1 class UserSessionsController < ApplicationController
2   before_filter :require_auth_scope, :only => [ :destroy ]
3
4   skip_before_filter :set_cors_headers
5   skip_before_filter :find_object_by_uuid
6   skip_before_filter :render_404_if_no_object
7
8   respond_to :html
9
10   # omniauth callback method
11   def create
12     omniauth = env['omniauth.auth']
13
14     identity_url_ok = (omniauth['info']['identity_url'].length > 0) rescue false
15     unless identity_url_ok
16       # Whoa. This should never happen.
17       logger.error "UserSessionsController.create: omniauth object missing/invalid"
18       logger.error "omniauth.pretty_inspect():\n\n#{omniauth.pretty_inspect()}"
19
20       return redirect_to login_failure_url
21     end
22
23     user = User.find_by_identity_url(omniauth['info']['identity_url'])
24     if not user
25       # Check for permission to log in to an existing User record with
26       # a different identity_url
27       Link.where("link_class = ? and name = ? and tail_uuid = ? and head_uuid like ?",
28                  'permission',
29                  'can_login',
30                  omniauth['info']['email'],
31                  User.uuid_like_pattern).each do |link|
32         if prefix = link.properties['identity_url_prefix']
33           if prefix == omniauth['info']['identity_url'][0..prefix.size-1]
34             user = User.find_by_uuid(link.head_uuid)
35             break if user
36           end
37         end
38       end
39     end
40     if not user
41       # New user registration
42       user = User.new(:email => omniauth['info']['email'],
43                       :first_name => omniauth['info']['first_name'],
44                       :last_name => omniauth['info']['last_name'],
45                       :identity_url => omniauth['info']['identity_url'],
46                       :is_active => Rails.configuration.new_users_are_active,
47                       :owner_uuid => system_user_uuid)
48       act_as_system_user do
49         user.save or raise Exception.new(user.errors.messages)
50       end
51     else
52       user.email = omniauth['info']['email']
53       user.first_name = omniauth['info']['first_name']
54       user.last_name = omniauth['info']['last_name']
55       if user.identity_url.nil?
56         # First login to a pre-activated account
57         user.identity_url = omniauth['info']['identity_url']
58       end
59     end
60
61     # For the benefit of functional and integration tests:
62     @user = user
63
64     # prevent ArvadosModel#before_create and _update from throwing
65     # "unauthorized":
66     Thread.current[:user] = user
67
68     user.save or raise Exception.new(user.errors.messages)
69
70     omniauth.delete('extra')
71
72     # Give the authenticated user a cookie for direct API access
73     session[:user_id] = user.id
74     session[:api_client_uuid] = nil
75     session[:api_client_trusted] = true # full permission to see user's secrets
76
77     @redirect_to = root_path
78     if params.has_key?(:return_to)
79       return send_api_token_to(params[:return_to], user)
80     end
81     redirect_to @redirect_to
82   end
83
84   # Omniauth failure callback
85   def failure
86     flash[:notice] = params[:message]
87   end
88
89   # logout - Clear our rack session BUT essentially redirect to the provider
90   # to clean up the Devise session from there too !
91   def logout
92     session[:user_id] = nil
93
94     flash[:notice] = 'You have logged off'
95     return_to = params[:return_to] || root_url
96     redirect_to "#{CUSTOM_PROVIDER_URL}/users/sign_out?redirect_uri=#{CGI.escape return_to}"
97   end
98
99   # login - Just bounce to /auth/joshid. The only purpose of this function is
100   # to save the return_to parameter (if it exists; see the application
101   # controller). /auth/joshid bypasses the application controller.
102   def login
103     auth_provider = if params[:auth_provider] then "auth_provider=#{CGI.escape(params[:auth_provider])}" else "" end
104
105     if current_user and params[:return_to]
106       # Already logged in; just need to send a token to the requesting
107       # API client.
108       #
109       # FIXME: if current_user has never authorized this app before,
110       # ask for confirmation here!
111
112       send_api_token_to(params[:return_to], current_user)
113     elsif params[:return_to]
114       redirect_to "/auth/joshid?return_to=#{CGI.escape(params[:return_to])}&#{auth_provider}"
115     else
116       redirect_to "/auth/joshid?#{auth_provider}"
117     end
118   end
119
120   def send_api_token_to(callback_url, user)
121     # Give the API client a token for making API calls on behalf of
122     # the authenticated user
123
124     # Stub: automatically register all new API clients
125     api_client_url_prefix = callback_url.match(%r{^.*?://[^/]+})[0] + '/'
126     act_as_system_user do
127       @api_client = ApiClient.find_or_create_by_url_prefix api_client_url_prefix
128     end
129
130     api_client_auth = ApiClientAuthorization.
131       new(user: user,
132           api_client: @api_client,
133           created_by_ip_address: remote_ip,
134           scopes: ["all"])
135     api_client_auth.save!
136
137     if callback_url.index('?')
138       callback_url += '&'
139     else
140       callback_url += '?'
141     end
142     callback_url += 'api_token=' + api_client_auth.api_token
143     redirect_to callback_url
144   end
145
146   def cross_origin_forbidden
147     send_error 'Forbidden', status: 403
148   end
149 end