我正在尝试使用Sinatra simple auth强制用户登录,然后才能访问该站点。所以主页将是登录,然后应该能够使用该网站而不被提示它。目前我无法找到一种在登录后重定向到主页面的方法。 set:home正在按预期工作。
# -*- 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**
答案 0 :(得分:1)
如果您要做的是检查用户是否在除&#34; /&#34;之外的任何路线之前登录;你可以用这个:
before do
if request.path != "/"
if # statement which returns false if a user is logged in
redirect "/"
end
end
end