Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

added docs for require_login, also added require_login class method

  • Loading branch information...
commit cdf7493690cf62f3964c03314f5b90d2bdce8f63 1 parent 59fa4b9
Cyril David cyx authored

Showing 2 changed files with 56 additions and 0 deletions. Show diff stats Hide diff stats

  1. +27 0 lib/sinatra/security.rb
  2. +29 0 test/test_sinatra-security.rb
27 lib/sinatra/security.rb
@@ -11,6 +11,7 @@ module Security
11 11
12 12 def self.registered(app)
13 13 app.helpers Helpers
  14 +
14 15 app.set :login_error_message, "Wrong Email and/or Password combination."
15 16 app.set :login_url, "/login"
16 17 app.set :login_user_class, :User
@@ -25,6 +26,32 @@ def self.registered(app)
25 26 end
26 27 end
27 28 end
  29 +
  30 + # Allows you to declaratively declare secured locations based on their
  31 + # path prefix.
  32 + #
  33 + # @example
  34 + #
  35 + # require_login '/admin'
  36 + #
  37 + # get '/admin/posts' do
  38 + # # Posts here
  39 + # end
  40 + #
  41 + # get '/admin/users' do
  42 + # # Users here
  43 + # end
  44 + #
  45 + # @param [#to_s] path_prefix a string to match again the start of
  46 + # request.fullpath
  47 + # @return [nil]
  48 + def require_login(path_prefix)
  49 + before do
  50 + if request.fullpath =~ /^#{path_prefix}/
  51 + require_login
  52 + end
  53 + end
  54 + end
28 55 end
29 56
30 57 register Security
29 test/test_sinatra-security.rb
@@ -5,6 +5,8 @@ class BasicApp < Sinatra::Base
5 5
6 6 register Sinatra::Security
7 7
  8 + require_login '/mass'
  9 +
8 10 get '/login' do
9 11 "<h1>Login Page</h1>"
10 12 end
@@ -16,6 +18,14 @@ class BasicApp < Sinatra::Base
16 18 get '/private' do
17 19 require_login
18 20 end
  21 +
  22 + get '/mass/private1' do
  23 + "Private 1"
  24 + end
  25 +
  26 + get '/mass/private2' do
  27 + "Private 2"
  28 + end
19 29
20 30 get '/css/main.css' do
21 31 require_login
@@ -136,4 +146,23 @@ def app
136 146 assert_equal '/login', last_response.headers['Location']
137 147 end
138 148 end
  149 +
  150 + describe "going to /mass/private1" do
  151 + should "redirect to /login" do
  152 + get '/mass/private1'
  153 +
  154 + assert_equal 302, last_response.status
  155 + assert_equal '/login', last_response.headers['Location']
  156 + end
  157 + end
  158 +
  159 + describe "going to /mass/private2" do
  160 + should "redirect to /login" do
  161 + get '/mass/private2'
  162 +
  163 + assert_equal 302, last_response.status
  164 + assert_equal '/login', last_response.headers['Location']
  165 + end
  166 + end
  167 +
139 168 end

0 comments on commit cdf7493

Please sign in to comment.
Something went wrong with that request. Please try again.