思路:表中保存用户的用户名,密码(处理过),密匙,或者把cookies放在特意的一张表中
密码加密是对用户的输入的密码进行md5加密,我做的是md5加密后,再二次用hash加密,密匙是随机生成给用户的随机string,目的是对它进行加密后作为用户的cookie
自动登陆是在本地电脑保存cookie即可,然后读取保存的cookie的值看在数据库中有没有,有的话,就自动登陆,没有的话就跳出登陆框
核心代码:
model:
class User < ActiveRecord::Base
# sha1 加密
def self.sha1(pass)
Digest::SHA1.hexdigest(pass)
end
# md5 加密
def self.md5(pass)
Digest::MD5.hexdigest(pass)
end
# hash 加密
def self.password_hash(pass)
Digest::SHA256.hexdigest(pass)
end
# 混合二次加密
def self.mix_password(pass1,pass2)
password_hash(md5(pass1.to_s).to_s+pass2.to_s)
end
# 随机产生字符串
def self.random_string(len)
randstring = ""
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
1.upto(len) { |i| randstring << chars[rand(chars.size-1)] }
return randstring
end
# 向user表中添加记录
def self.create(name,password,pwd_salt)
@user = User.new do |f|
f.name = name
f.password = password
f.pwd_salt = pwd_salt
f.save
end
end
#判断登陆信息
def self.try_to_login(login_name,login_password)
transaction do
User.find(:first,:conditions=>["name=? and password=?", login_name, login_password])
end
end # 取得登陆用户的密匙
def self.get_pwdsalt(login_name)
transaction do
User.find(:first,:conditions=>["name=?",login_name]).pwd_salt
end
end
end
controller:
class LoginController < ApplicationController
before_filter :login_from_cookie
def login_from_cookie #自动登陆
# cookies.delete :riskfit_token
user = Cookieauto.find(:first,:conditions=>["pwd_salt=?",cookies[:riskfit_token]])
if user && !user.nil?
render :partial=>'success'
end
end
#向数据库添加记录
def new
name = params[:user][:name]
password = params[:user][:password]
rand_string = User.random_string(30)
mix_password = User.mix_password(password,rand_string)
User.create(name,mix_password ,rand_string)
end
#登陆
def logon
name = params[:user][:name]
password = params[:user][:password]
pwd_salt = User.get_pwdsalt(name)
mix_password = User.mix_password(password,pwd_salt)
login_user = User.try_to_login(name,mix_password)
if params[:auto]
Cookieauto.create(name, pwd_salt)
cookies[:riskfit_token]={:value=>pwd_salt,:expires => Time.now + 7.days}
end
if !login_user.nil?
render :partial => 'success'
puts "render"
end
end
#method:logout
def logout
cookies.delete :riskfit_token
render :action=>'index'
end
end
sql:
DROP TABLE IF EXISTS `cookieautos`;
CREATE TABLE `cookieautos` (
`id` int(20) NOT NULL auto_increment,
`name` varchar(30) default NULL,
`pwd_salt` varchar(128) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) default NULL,
`password` text,
`pwd_salt` varchar(128) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
view部分我就不写了
source:
http://www.namipan.com/d/87f7886a3c0660304c48d2b03385810c084ddb7aabbf0100
ref:
http://onrails.org/articles/2006/02/18/auto-login
http://iceskysl.1sters.com/?action=show&id=22
posted on 2009-03-26 18:31
fl1429 阅读(3190)
评论(0) 编辑 收藏 所属分类:
Rails