2009年6月17日水曜日

SinatraとSession

SinatraでCookieベースのSessionを使って認証。
sinatra-authorizationを調べる前に、とりあえず目的達成できそうな方法を模索してみた。

study_auth.rb
use Rack::Session::Cookie,
# :key => 'rack.session',
# :domain => 'takumakei.blogspot.com',
# :path => '/',
:expire_after => 3600,
:secret => 'changeme'

helpers do
def auth_ok?(id, pw)
id == 'id' && pw == 'pw'
end

def login
if auth_ok?(params['id'], params['pw'])
session[:login] = 'What should i have to put here ?'
redirect '/'
else
erb :login
end
end

def logout
session.delete(:login)
redirect '/'
end

def need_auth
unless session[:login]
erb :login
else
yield
end
end
end
app.rb
#!ruby
require 'rubygems'
require 'sinatra'
require 'erb'
require 'study_auth'

get '/' do
need_auth do
erb :index
end
end

get '/login' do
login
end

post '/login' do
login
end

get '/logout' do
logout
end

get '/*' do
login
end
index.erb
<html>
<head>
<title>index</title>
</head>
<body>
<%=Time.new.to_s%><br/>
<a href="logout">logout</a>
</body>
</html>
login.erb
<html>
<head>
<title>login</title>
</head>
<body>
<form action="login" method="POST">
<input type="text" name="id" value="<%=params['id']%>">
<input type="password" name="pw">
<input type="submit" value="LOGIN">
</form>
</body>
</html>

0 件のコメント:

コメントを投稿