rails用户认证

反正自己也是新手,生怕学来的东西给忘了……
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,否则还要自己实现一些其他功能。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值