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



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

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)



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

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

  auth = Rack::Auth::Basic::Request.new(env)
  if auth.provided? && auth.basic?
    Cloud::Settings.cloud_enabled? ?
        begin
          return unauthenticated_error unless Cloud::Auth::valid_session?(env, auth)
        rescue Exception => e
          env['AUTH_CREDENTIALS'] = nil
          env['p4'] = nil
          return unauthenticated_error
        end :
        begin
          check_and_establish_p4_session(env, auth)
        rescue P4Exception
          env['AUTH_CREDENTIALS'] = nil
          env['p4'] = nil
          return unauthenticated_error
        end

    return @app.call(env)

  end

  unauthenticated_error
end

- (Object) check_and_establish_p4_session(env, auth)



48
49
50
51
52
53
54
55
56
57
# File 'lib/auth/middleware.rb', line 48

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



67
68
69
70
71
72
73
74
75
# File 'lib/auth/middleware.rb', line 67

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)


59
60
61
62
63
64
65
# File 'lib/auth/middleware.rb', line 59

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