Merge branch '8784-dir-listings'
[arvados.git] / services / api / script / setup-new-user.rb
1 #!/usr/bin/env ruby
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 abort 'Error: Ruby >= 1.9.3 required.' if RUBY_VERSION < '1.9.3'
7
8 require 'logger'
9 require 'trollop'
10
11 log = Logger.new STDERR
12 log.progname = $0.split('/').last
13
14 opts = Trollop::options do
15   banner ''
16   banner "Usage: #{log.progname} " +
17     "{user_uuid_or_email} {user_and_repo_name} {vm_uuid}"
18   banner ''
19   opt :debug, <<-eos
20 Show debug messages.
21   eos
22   opt :openid_prefix, <<-eos, default: 'https://www.google.com/accounts/o8/id'
23 If creating a new user record, require authentication from an OpenID \
24 with this OpenID prefix *and* a matching email address in order to \
25 claim the account.
26   eos
27   opt :send_notification_email, <<-eos, default: 'true'
28 Send notification email after successfully setting up the user.
29   eos
30 end
31
32 log.level = (ENV['DEBUG'] || opts.debug) ? Logger::DEBUG : Logger::WARN
33
34 if ARGV.count != 3
35   Trollop::die "required arguments are missing"
36 end
37
38 user_arg, user_repo_name, vm_uuid = ARGV
39
40 require 'arvados'
41 arv = Arvados.new(api_version: 'v1')
42
43 # Look up the given user by uuid or, failing that, email address.
44 begin
45   found_user = arv.user.get(uuid: user_arg)
46 rescue Arvados::TransactionFailedError
47   found = arv.user.list(where: {email: user_arg})[:items]
48
49   if found.count == 0
50     if !user_arg.match(/\w\@\w+\.\w+/)
51       abort "About to create new user, but #{user_arg.inspect} " +
52                "does not look like an email address. Stop."
53     end
54   elsif found.count != 1
55     abort "Found #{found.count} users with email. Stop."
56   else
57     found_user = found.first
58   end
59 end
60
61 # Invoke user setup method
62 if (found_user)
63   user = arv.user.setup uuid: found_user[:uuid], repo_name: user_repo_name,
64           vm_uuid: vm_uuid, openid_prefix: opts.openid_prefix,
65           send_notification_email: opts.send_notification_email
66 else
67   user = arv.user.setup user: {email: user_arg}, repo_name: user_repo_name,
68           vm_uuid: vm_uuid, openid_prefix: opts.openid_prefix,
69           send_notification_email: opts.send_notification_email
70 end
71
72 log.info {"user uuid: " + user[:uuid]}
73
74 puts user.inspect