Sha256: b6365fac177f795bcd07f17f3f8326cada357960bc1115d68ad46bd551a771e7

Contents?: true

Size: 1.71 KB

Versions: 30

Compression:

Stored size: 1.71 KB

Contents

require 'rbbt/util/misc'

require 'sinatra/base'

module Sinatra
  module RbbtAuth

    module Helpers
      def authorized?
        session[:authorized]
      end

      def authorize!
        return true if authorized?
        target_url = request.env["REQUEST_URI"]
        Log.warn("Unauthorized access to #{target_url}")
        session[:target_url] = target_url
        redirect '/login' 
      end

      def logout!
        session[:authorized] = false
      end

      def user
        session[:user]
      end
    end

    def self.registered(app)
      app.helpers RbbtAuth::Helpers

      if Rbbt.etc.web_users.exists?
        app.set :users, Rbbt.etc.web_users.yaml
      else
        app.set :users, {}
      end

      app.get '/login' do
        "<form class='login' method='POST' action='/login'>" +
          "<label for='login_name'>Name: </label>" +
          "<input id='login_name' type='text' name='user'>" +
          "<label for='login_pass'>Pass: </label>" +
          "<input id 'login_pass' type='password' name='pass'>" +
          "<input type='submit'>" +
        "</form>"
      end

      app.post '/login' do
        user = params[:user]
        pass = params[:pass]

        if settings.users.include?(user) and settings.users[user] == pass
          Log.warn("Successful login #{[user, pass] * ": "}")
          session[:authorized] = true
          session[:user] = user
          if session[:target_url]
            url = session.delete :target_url
            redirect url
          else
            redirect '/'
          end
        else
          Log.warn("Failed login attempt #{[user, pass] * ": "}")
          session[:authorized] = false
          redirect '/login'
        end
      end
    end
  end

end

Version data entries

30 entries across 30 versions & 1 rubygems

Version Path
rbbt-rest-1.2.28 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.27 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.26 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.25 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.24 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.23 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.22 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.21 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.20 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.19 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.18 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.17 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.16 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.15 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.14 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.13 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.12 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.11 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.10 lib/rbbt/rest/common/users.rb
rbbt-rest-1.2.9 lib/rbbt/rest/common/users.rb