15781: Bump API revision number to signal new feature.
[arvados.git] / services / api / app / controllers / arvados / v1 / users_controller.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class Arvados::V1::UsersController < ApplicationController
6   accept_attribute_as_json :prefs, Hash
7   accept_param_as_json :updates
8
9   skip_before_action :find_object_by_uuid, only:
10     [:activate, :current, :system, :setup, :merge, :batch_update]
11   skip_before_action :render_404_if_no_object, only:
12     [:activate, :current, :system, :setup, :merge, :batch_update]
13   before_action :admin_required, only: [:setup, :unsetup, :update_uuid, :batch_update]
14
15   # Internal API used by controller to update local cache of user
16   # records from LoginCluster.
17   def batch_update
18     @objects = []
19     params[:updates].andand.each do |uuid, attrs|
20       begin
21         u = User.find_or_create_by(uuid: uuid)
22       rescue ActiveRecord::RecordNotUnique
23         retry
24       end
25       u.update_attributes!(attrs)
26       @objects << u
27     end
28     @offset = 0
29     @limit = -1
30     render_list
31   end
32
33   def current
34     if current_user
35       @object = current_user
36       show
37     else
38       send_error("Not logged in", status: 401)
39     end
40   end
41
42   def system
43     @object = system_user
44     show
45   end
46
47   def activate
48     if current_user.andand.is_admin && params[:uuid]
49       @object = User.find params[:uuid]
50     else
51       @object = current_user
52     end
53     if not @object.is_active
54       if not (current_user.is_admin or @object.is_invited)
55         logger.warn "User #{@object.uuid} called users.activate " +
56           "but is not invited"
57         raise ArgumentError.new "Cannot activate without being invited."
58       end
59       act_as_system_user do
60         required_uuids = Link.where("owner_uuid = ? and link_class = ? and name = ? and tail_uuid = ? and head_uuid like ?",
61                                     system_user_uuid,
62                                     'signature',
63                                     'require',
64                                     system_user_uuid,
65                                     Collection.uuid_like_pattern).
66           collect(&:head_uuid)
67         signed_uuids = Link.where(owner_uuid: system_user_uuid,
68                                   link_class: 'signature',
69                                   name: 'click',
70                                   tail_uuid: @object.uuid,
71                                   head_uuid: required_uuids).
72           collect(&:head_uuid)
73         todo_uuids = required_uuids - signed_uuids
74         if todo_uuids.empty?
75           @object.update_attributes is_active: true
76           logger.info "User #{@object.uuid} activated"
77         else
78           logger.warn "User #{@object.uuid} called users.activate " +
79             "before signing agreements #{todo_uuids.inspect}"
80           raise ArvadosModel::PermissionDeniedError.new \
81           "Cannot activate without user agreements #{todo_uuids.inspect}."
82         end
83       end
84     end
85     show
86   end
87
88   # create user object and all the needed links
89   def setup
90     if params[:uuid]
91       @object = User.find_by_uuid(params[:uuid])
92       if !@object
93         return render_404_if_no_object
94       end
95     elsif !params[:user] || params[:user].empty?
96       raise ArgumentError.new "Required uuid or user"
97     elsif !params[:user]['email']
98       raise ArgumentError.new "Require user email"
99     else
100       @object = model_class.create! resource_attrs
101     end
102
103     # It's not always possible for the client to know the user's
104     # username when submitting this request: the username might have
105     # been assigned automatically in create!() above. If client
106     # provided a plain repository name, prefix it with the username
107     # now that we know what it is.
108     if params[:repo_name].nil?
109       full_repo_name = nil
110     elsif @object.username.nil?
111       raise ArgumentError.
112         new("cannot setup a repository because user has no username")
113     elsif params[:repo_name].index("/")
114       full_repo_name = params[:repo_name]
115     else
116       full_repo_name = "#{@object.username}/#{params[:repo_name]}"
117     end
118
119     @response = @object.setup(repo_name: full_repo_name,
120                               vm_uuid: params[:vm_uuid])
121
122     # setup succeeded. send email to user
123     if params[:send_notification_email]
124       begin
125         UserNotifier.account_is_setup(@object).deliver_now
126       rescue => e
127         logger.warn "Failed to send email to #{@object.email}: #{e}"
128       end
129     end
130
131     send_json kind: "arvados#HashList", items: @response.as_api_response(nil)
132   end
133
134   # delete user agreements, vm, repository, login links; set state to inactive
135   def unsetup
136     reload_object_before_update
137     @object.unsetup
138     show
139   end
140
141   # Change UUID to a new (unused) uuid and transfer all owned/linked
142   # objects accordingly.
143   def update_uuid
144     @object.update_uuid(new_uuid: params[:new_uuid])
145     show
146   end
147
148   def merge
149     if (params[:old_user_uuid] || params[:new_user_uuid])
150       if !current_user.andand.is_admin
151         return send_error("Must be admin to use old_user_uuid/new_user_uuid", status: 403)
152       end
153       if !params[:old_user_uuid] || !params[:new_user_uuid]
154         return send_error("Must supply both old_user_uuid and new_user_uuid", status: 422)
155       end
156       new_user = User.find_by_uuid(params[:new_user_uuid])
157       if !new_user
158         return send_error("User in new_user_uuid not found", status: 422)
159       end
160       @object = User.find_by_uuid(params[:old_user_uuid])
161       if !@object
162         return send_error("User in old_user_uuid not found", status: 422)
163       end
164     else
165       if !Thread.current[:api_client].andand.is_trusted
166         return send_error("supplied API token is not from a trusted client", status: 403)
167       elsif Thread.current[:api_client_authorization].scopes != ['all']
168         return send_error("cannot merge with a scoped token", status: 403)
169       end
170
171       new_auth = ApiClientAuthorization.validate(token: params[:new_user_token])
172       if !new_auth
173         return send_error("invalid new_user_token", status: 401)
174       end
175
176       if new_auth.user.uuid[0..4] == Rails.configuration.ClusterID
177         if !new_auth.api_client.andand.is_trusted
178           return send_error("supplied new_user_token is not from a trusted client", status: 403)
179         elsif new_auth.scopes != ['all']
180           return send_error("supplied new_user_token has restricted scope", status: 403)
181         end
182       end
183       new_user = new_auth.user
184       @object = current_user
185     end
186
187     if @object.uuid == new_user.uuid
188       return send_error("cannot merge user to self", status: 422)
189     end
190
191     if !params[:new_owner_uuid]
192       return send_error("missing new_owner_uuid", status: 422)
193     end
194
195     if !new_user.can?(write: params[:new_owner_uuid])
196       return send_error("cannot move objects into supplied new_owner_uuid: new user does not have write permission", status: 403)
197     end
198
199     act_as_system_user do
200       @object.merge(new_owner_uuid: params[:new_owner_uuid],
201                     new_user_uuid: new_user.uuid,
202                     redirect_to_new_user: params[:redirect_to_new_user])
203     end
204     show
205   end
206
207   protected
208
209   def self._merge_requires_parameters
210     {
211       new_owner_uuid: {
212         type: 'string', required: true,
213       },
214       new_user_token: {
215         type: 'string', required: false,
216       },
217       redirect_to_new_user: {
218         type: 'boolean', required: false,
219       },
220       old_user_uuid: {
221         type: 'string', required: false,
222       },
223       new_user_uuid: {
224         type: 'string', required: false,
225       }
226     }
227   end
228
229   def self._setup_requires_parameters
230     {
231       uuid: {
232         type: 'string', required: false
233       },
234       user: {
235         type: 'object', required: false
236       },
237       repo_name: {
238         type: 'string', required: false
239       },
240       vm_uuid: {
241         type: 'string', required: false
242       },
243       send_notification_email: {
244         type: 'boolean', required: false, default: false
245       },
246     }
247   end
248
249   def self._update_uuid_requires_parameters
250     {
251       new_uuid: {
252         type: 'string', required: true,
253       },
254     }
255   end
256
257   def apply_filters(model_class=nil)
258     return super if @read_users.any?(&:is_admin)
259     if params[:uuid] != current_user.andand.uuid
260       # Non-admin index/show returns very basic information about readable users.
261       safe_attrs = ["uuid", "is_active", "email", "first_name", "last_name", "username"]
262       if @select
263         @select = @select & safe_attrs
264       else
265         @select = safe_attrs
266       end
267       @filters += [['is_active', '=', true]]
268     end
269     super
270   end
271 end