Created
June 30, 2011 14:40
-
-
Save bensie/1056354 to your computer and use it in GitHub Desktop.
Sinatra authentication helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def auth | |
| @auth ||= Rack::Auth::Basic::Request.new(request.env) | |
| end | |
| def current_user | |
| @current_user | |
| end | |
| def authenticated? | |
| request.env['REMOTE_USER'] | |
| end | |
| def authenticate(email, password) | |
| if @current_user = User.find_by_email(email) | |
| @current_user.valid_password?(password) | |
| end | |
| end | |
| def authenticate! | |
| return if authenticated? | |
| halt_with_401_authorization_required unless auth.provided? | |
| handle_authentication_credentials | |
| end | |
| def permit_authentication | |
| return if authenticated? | |
| handle_authentication_credentials if auth.provided? | |
| end | |
| def handle_authentication_credentials | |
| halt_with_400_bad_request unless auth.basic? && auth.credentials | |
| halt_with_401_authorization_required("Bad credentials") unless authenticate(*auth.credentials) | |
| request.env['REMOTE_USER'] = auth.username | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment