反正自己也是新手,生怕学来的东西给忘了……
ruby1.9.3-p194 rails3.2.8
rails new authen --skip-bundle
cd authen
rails g model user name:string salt:string
hashed_pswd:string
rake db:migrate
编辑app/models/user.rb
class User < ActiveRecord::Base
attr_accessor :password, :pswd_confirmation
attr_accessible :password, :name
validates_presence_of :name
validates_uniqueness_of :name
before_create :generate_hashed
def self.authentication(name, ps)
user = User.find_by_name(name)
return user if user && user.hashed_pswd == Digest::SHA256.hexdigest(user.salt + ps)
end
private
def generate_hashed
self.salt = Array.new(10){ rand(1024).to_s(36) }.join
self.hashed_pswd = Digest::SHA256.hexdigest(self.salt + @password)
end
end
rails g
controller sessions
编辑app/controllers/sessions_controller.rb
# encoding: utf-8
class SessionsController < ApplicationController
def new
end
def create
@user = User.authentication(params[:name], params[:password])
if @user
session[:user_id] = @user.id
flash[:notice] = "热烈欢迎#{@user.name}莅临"
#root_path为主页路径
redirect_to root_path
else
flash[:notice] = "The username or password is not correct!!!"
redirect_to new_session_path
end
end
def logout
session[:user_id] = nil
flash[:notice] = "你已经退出登录"
redirect_to new_session_path
end
end
编辑app/controllers/application_controller.rb,添加
def current_user
if session[:user_id]
cur_user = User.find(session[:user_id])
return cur_user
end
end
创建app/views/sessions/new.html.erb
<h2>Sign in</h2>
<%= form_tag :sessions do %>
<p>
<%= label :name, "登录名:" %>
<%= text_field_tag :name, params[:name] %>
</p>
<p>
<%= label :password, "密码: " %>
<%= password_field_tag :password, params[:password] %>
</p>
<%= submit_tag "登录" %>
<% end %>
在主页相关的controller中index方法(或者等价的方法中)添加:
@current_user = current_user
在主页中适当位置添加
<% if @current_user %>
<p>当前用户是:<%= @current_user.name %></p>
<%= link_to "Logout", logout_path %>
<% end %>
编辑config/routes.rb
添加:
match '/logout' => 'sessions#logout', :as => "logout"
resources :sessions
rails s
浏览器进入http://localhost:3000/sessions/new进行登录
最后,在实际运用中最好还是使用成熟的gem,比如devise,否则还要自己实现一些其他功能。