16470: Removes exception deprecated on rails 3.2
[arvados.git] / services / api / db / migrate / 20140423133559_new_scope_format.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 # At the time we introduced scopes everywhere, VirtualMachinesController
6 # recognized scopes that gave the URL for a VM to grant access to that VM's
7 # login list.  This migration converts those VM-specific scopes to the new
8 # general format, and back.
9
10 class NewScopeFormat < ActiveRecord::Migration[4.2]
11   include CurrentApiClient
12
13   VM_PATH_REGEX =
14     %r{(/arvados/v1/virtual_machines/[0-9a-z]{5}-[0-9a-z]{5}-[0-9a-z]{15})}
15   OLD_SCOPE_REGEX = %r{^https?://[^/]+#{VM_PATH_REGEX.source}$}
16   NEW_SCOPE_REGEX = %r{^GET #{VM_PATH_REGEX.source}/logins$}
17
18   def fix_scopes_matching(regex)
19     act_as_system_user
20     ApiClientAuthorization.find_each do |auth|
21       auth.scopes = auth.scopes.map do |scope|
22         if match = regex.match(scope)
23           yield match
24         else
25           scope
26         end
27       end
28       auth.save!
29     end
30   end
31
32   def up
33     fix_scopes_matching(OLD_SCOPE_REGEX) do |match|
34       "GET #{match[1]}/logins"
35     end
36   end
37
38   def down
39     case Rails.env
40     when 'test'
41       hostname = 'www.example.com'
42     else
43       require 'socket'
44       hostname = Socket.gethostname
45     end
46     fix_scopes_matching(NEW_SCOPE_REGEX) do |match|
47       Rails.application.routes.url_for(controller: 'virtual_machines',
48                                        uuid: match[1].split('/').last,
49                                        host: hostname, protocol: 'https')
50     end
51   end
52 end