在Sinatra简单身份验证中将家乡路由设置为直达



我正在尝试使用Sinatra简单身份验证来强制用户在能够访问站点之前登录。因此,主页将是登录,然后应该能够在不提示的情况下使用该站点。目前我无法找到登录后重定向到主页的方法。设置:家庭正在正常工作。

# -*- coding: utf-8 -*-
# Required gems
require 'sinatra'
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
require 'sinatra/simple-authentication'
require 'rack-flash'
# Required models and database
require './models/note'
class Index < Sinatra::Base
  DataMapper::Logger.new($stdout, :debug)
    DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/recall.db")

  use Rack::Flash, :sweep => true
  register Sinatra::SimpleAuthentication
    enable :sessions
    set :home, '/'
    # ** SHOW **
    # Root to the index page
    # Pull all notes from the DB into an instance varible to access from the index page in descends order.
    get '/' do
        login_required
      @notes = Note.all :order => :id.desc
      haml :index
    end
    # ** SAVE **
    # Retrieves note contents from :contents on the index view and save them into the DB.
    # Redirects back to the index page.
    post '/' do
      n = Note.new
      n.content = params[:content]
      n.created_at = Time.now
      n.updated_at = Time.now
      n.save
        redirect '/'
    end

    # ** EDIT **
    # Retrieves notes ID to edit the note
    # Title varible is to display the note ID to the user to be able to edit/delete a specific note.
    get '/:id' do
        @note = Note.get params[:id]
        @title = "Edit note ##{params[:id]}"
        haml :edit
    end
    # Edit
    # Retrieves the saved note for the user to edit then save it with the same ID and new timestamp
    put '/:id' do
        n = Note.get params[:id]
        n.content = params[:content]
        n.complete = params[:complete] ? 1 : 0
        n.updated_at = Time.now
        n.save
        redirect '/'
    end
    # ** DESTROY **
    # Delete note by the ID
    # Retrun the note ID to the view page to confirm the deletion of the right note.
    get '/:id/delete' do
        @note = Note.get params[:id]
        @title = "Confirm deletion of note ##{params[:id]}"
        haml :delete
    end
    # Delte note by ID
    delete '/:id' do
        n = Note.get params[:id]
        n.destroy
        redirect '/'
    end
    # Check the completion of note (still not working)
    get '/:id/complete' do
        n = Note.get params[:id]
        n.complete = n.complete ? 0 : 1 # flip it
        n.updated_at = Time.now
        n.save
        redirect '/'
    end
    # To resturn the "Page not found" insted of the default Sinatra error page.
    not_found do
      halt 404, "Page not found 404"
    end
end
**strong text** 

如果要检查用户是否在除"/"以外的任何路由之前登录,则可以使用以下命令:

before do
    if request.path != "/"
        if # statement which returns false if a user is logged in
            redirect "/"
        end
    end
end

最新更新