Class: Bc::RequireGoogleAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/bc/require_google_auth.rb,
lib/bc/require_google_auth/version.rb

Constant Summary collapse

DEFAULT_ALLOWED_PATHS =
[
  "/auth/google_oauth2/callback",
  "/auth/google_oauth2"
].freeze
DEFAULT_SESSION_KEY =
'bc.auth'.freeze
DEFAULT_AFTER_AUTH_PATH =
'/'.freeze
OMNIAUTH_SESSION_KEY =
'omniauth.auth'.freeze
VERSION =
"0.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ RequireGoogleAuth

Returns a new instance of RequireGoogleAuth.



17
18
19
20
21
22
23
# File 'lib/bc/require_google_auth.rb', line 17

def initialize(app, opts={})
  @allowed_paths = opts[:allowed_paths] || DEFAULT_ALLOWED_PATHS
  @session_key = opts[:session_key] || DEFAULT_SESSION_KEY
  @authorized_emails = opts[:authorized_emails]
  @after_auth_path = opts[:after_auth_path] || DEFAULT_AFTER_AUTH_PATH
  @app = app
end

Instance Method Details

#allowed_path?(req) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/bc/require_google_auth.rb', line 32

def allowed_path?(req)
  @allowed_paths.include?(req.path)
end

#auth_callback?(req) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
# File 'lib/bc/require_google_auth.rb', line 25

def auth_callback?(req)
  return false unless req.path == '/auth/google_oauth2/callback'
  return false unless req.env[OMNIAUTH_SESSION_KEY]
  return false unless req.env[OMNIAUTH_SESSION_KEY][:info]
  return true
end

#authorized_email?(req) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/bc/require_google_auth.rb', line 40

def authorized_email?(req)
  @authorized_emails.include?(req.env[OMNIAUTH_SESSION_KEY][:info][:email])
end

#authorized_session?(req) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/bc/require_google_auth.rb', line 36

def authorized_session?(req)
  !!req.session[@session_key]
end

#call(env) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/bc/require_google_auth.rb', line 62

def call(env)
  req = Rack::Request.new(env)

  if auth_callback?(req)
    handle_auth_callback(req)
  elsif authorized_session?(req) || allowed_path?(req)
    @app.call(env)
  else
    handle_unauthorized
  end
end

#handle_auth_callback(req) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bc/require_google_auth.rb', line 50

def handle_auth_callback(req)
  if authorized_email?(req)
    req.session[@session_key] = req.env[OMNIAUTH_SESSION_KEY][:info]
  else
    req.session.delete(@session_key)
  end

  res = Rack::Response.new
  res.redirect @after_auth_path, status=302
  res.finish
end

#handle_unauthorizedObject



44
45
46
47
48
# File 'lib/bc/require_google_auth.rb', line 44

def handle_unauthorized
  res = Rack::Response.new
  res.redirect '/auth/google_oauth2', status=302
  res.finish
end