Class: Auth::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/auth/middleware.rb

Overview

We setup our middleware to generally require Basic authentication that indicates our Perforce login and ticket.

This should be applied after HWSSettings, since we might not know which server we are connecting to.

Instance Method Summary (collapse)

Constructor Details

- (Middleware) initialize(app, options = {})

Returns a new instance of Middleware



11
12
13
14
15
16
17
# File 'lib/auth/middleware.rb', line 11

def initialize(app, options = {})
  @app = app
  @unauthenticated_paths = []
  if options[:unauthenticated_paths]
    @unauthenticated_paths.concat(options[:unauthenticated_paths])
  end
end

Instance Method Details

- (Object) call(env)



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/auth/middleware.rb', line 19

def call(env)
  return @app.call(env) if unauthenticated_path?(env)

  auth = Rack::Auth::Basic::Request.new(env)
  if auth.provided? && auth.basic?

    if HWSSettings.system.ENABLE_HELIX_CLOUD_AUTH
      # TODO(HelixCloud) - Validate ticket, then check AUTH_CREDENTIALS,
      #                    p4, and p4.user as needed.
    else
      begin
        check_and_establish_p4_session(env, auth)
      rescue P4Exception
        env['AUTH_CREDENTIALS'] = nil
        env['p4'] = nil
        return unauthenticated_error
      end
    end

    return @app.call(env)
  end

  unauthenticated_error
end

- (Object) check_and_establish_p4_session(env, auth)



44
45
46
47
48
49
50
51
52
53
# File 'lib/auth/middleware.rb', line 44

def check_and_establish_p4_session(env, auth)
  env['AUTH_CREDENTIALS'] = auth.credentials
  p4 = P4Util.open_from_env(env)
  p4.connect

  results = p4.run_user('-o')

  env['p4.user'] = results.first
  env['p4'] = p4
end

- (Object) unauthenticated_error



63
64
65
66
67
68
69
70
71
# File 'lib/auth/middleware.rb', line 63

def unauthenticated_error
  [
      403,
      { 'Content-Type' => 'text/plain',
        'Content-Length' => '0',
        'WWW-Authenticate' => 'Basic realm="Perforce Web API"' },
      []
  ]
end

- (Boolean) unauthenticated_path?(env)

Returns:

  • (Boolean)


55
56
57
58
59
60
61
# File 'lib/auth/middleware.rb', line 55

def unauthenticated_path?(env)
  @unauthenticated_paths.any? do |pathspec|
    (env['REQUEST_METHOD'] == pathspec[:method]) &&
        ((pathspec[:path].is_a?(String) && pathspec[:path] == env['PATH_INFO']) ||
            (pathspec[:path].is_a?(Regexp) && pathspec[:path].match(env['PATH_INFO'])))
  end
end