16314: Merge branch 'master'
[arvados.git] / services / api / lib / tasks / manage_long_lived_tokens.rake
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # Tasks that can be useful when changing token expiration policies by assigning
6 # a non-zero value to Login.TokenLifetime config.
7
8 require 'set'
9 require 'current_api_client'
10
11 namespace :db do
12   desc "Apply expiration policy on long lived tokens"
13   task fix_long_lived_tokens: :environment do
14     if Rails.configuration.Login.TokenLifetime == 0
15       puts("No expiration policy set on Login.TokenLifetime.")
16     else
17       exp_date = Time.now + Rails.configuration.Login.TokenLifetime
18       puts("Setting token expiration to: #{exp_date}")
19       token_count = 0
20       ll_tokens.each do |auth|
21         if (auth.user.uuid =~ /-tpzed-000000000000000/).nil?
22           CurrentApiClientHelper.act_as_system_user do
23             auth.update_attributes!(expires_at: exp_date)
24           end
25           token_count += 1
26         end
27       end
28       puts("#{token_count} tokens updated.")
29     end
30   end
31
32   desc "Show users with long lived tokens"
33   task check_long_lived_tokens: :environment do
34     user_ids = Set.new()
35     token_count = 0
36     ll_tokens.each do |auth|
37       if (auth.user.uuid =~ /-tpzed-000000000000000/).nil?
38         user_ids.add(auth.user_id)
39         token_count += 1
40       end
41     end
42
43     if user_ids.size > 0
44       puts("Found #{token_count} long-lived tokens from users:")
45       user_ids.each do |uid|
46         u = User.find(uid)
47         puts("#{u.username},#{u.email},#{u.uuid}") if !u.nil?
48       end
49     else
50       puts("No long-lived tokens found.")
51     end
52   end
53
54   def ll_tokens
55     query = ApiClientAuthorization.where(expires_at: nil)
56     if Rails.configuration.Login.TokenLifetime > 0
57       query = query.or(ApiClientAuthorization.where("expires_at > ?", Time.now + Rails.configuration.Login.TokenLifetime))
58     end
59     query
60   end
61 end