Guest User

Untitled

a guest
Feb 20th, 2018
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. =begin
  2.  
  3. Easy Basic Authentication for Sinatra actions.
  4.  
  5. USAGE
  6.  
  7. require 'rubygems'
  8. require 'sinatra'
  9. require 'sinatra-auth'
  10.  
  11. get '/' do
  12. protect! :username => 'admin', :password => 'sekret'
  13. "This is protected by basic auth"
  14. end
  15.  
  16. =end
  17. module Sinatra
  18. module Authorization
  19. class ProtectedAction
  20. attr_reader :credentials, :context
  21.  
  22. def initialize(context, credentials={})
  23. @credentials, @context = credentials, context
  24. end
  25.  
  26. def check!
  27. unauthorized! unless auth.provided?
  28. bad_request! unless auth.basic?
  29. unauthorized! unless authorize(*auth.credentials)
  30. end
  31.  
  32. def remote_user
  33. auth.username
  34. end
  35.  
  36. private
  37.  
  38. def authorize(username, password)
  39. credentials[:username] == username and credentials[:password] == password
  40. end
  41.  
  42. def unauthorized!
  43. context.header 'WWW-Authenticate' => %(Basic realm="#{credentials[:realm]}")
  44. throw :halt, [ 401, 'Authorization Required' ]
  45. end
  46.  
  47. def bad_request!
  48. throw :halt, [ 400, 'Bad Request' ]
  49. end
  50.  
  51. def auth
  52. @auth ||= Rack::Auth::Basic::Request.new(context.request.env)
  53. end
  54. end
  55.  
  56. module Helpers
  57. def protect!(credentials={})
  58. return if authorized?
  59. guard = ProtectedAction.new(self, credentials)
  60. guard.check!
  61. request.env['REMOTE_USER'] = guard.remote_user
  62. end
  63.  
  64. def authorized?
  65. request.env['REMOTE_USER']
  66. end
  67. end
  68. end
  69. end
  70.  
  71. helpers do
  72. include Sinatra::Authorization::Helpers
  73. end
Add Comment
Please, Sign In to add comment