Search code examples
rubysinatrawarden

How to set authentication in Sinatra?


I need simple authentication for blog. For a single person. Just login to the website

Can't configure sinatra_warden. Write the line

require 'rubygems'
require 'sinatra'
require 'pry-byebug'
require "sinatra/activerecord"
require "carrierwave"
require "carrierwave/orm/activerecord"
require 'sinatra_warden'
require 'warden'

register Sinatra::Warden

use Rack::Session::Pool

in app.rb, but I get an error

NoMethodError: undefined method `register' for main:Object

the gem sinatra_warden has installed. as well written require "warden" & require "sinatra_warden"

sinatra_warden 0.3.2

warden 1.2.6

When I add the authorize! method in controller, I get an error

undefined method `authorize!'

Solution

  • Because you didn't use the sinatra/base you should add sinatra/namespace. Add to your app.rb this require require "sinatra/namespace".

    Sinatra::Namespace is an extension that adds namespaces to an application. This namespaces will allow you to share a path prefix for the routes within the namespace, and define filters, conditions and error handlers exclusively for them. Besides that, you can also register helpers and extensions that will be used only within the namespace.

    Or change your application to the modular style:

    require "sinatra/base"
    
    class MyApp < Sinatra::Base
      register Sinatra::Warden
    
      # The rest of your modular application code goes here...
    end