Skip to content
Newer
Older
100644 65 lines (48 sloc) 1.39 KB
e93ce52 @poshboytl Add the PartII in README and the drama of Railscasts china two.
authored
1 (Railscasts China 第二期真实剧本)
2
3 1. rails g model user login:string hashed_password:string salt:string
4
5 2. def password
6 @password
7 end
8
9 def password=(pass)
10 @password = pass
11 return if pass.blank?
12 generate_password(pass)
13 end
14
15 3.def generate_password(pass)
16 salt = Array.new(6){rand(1024).to_s(36)}.join
17 self.usr_password_salt, self.usr_encrypted_password =
18 salt, Digest::SHA256.hexdigest(pass + salt)
19 end
20
21 4.在shell里创建用户
22
23 5.
24 def self.authentication(login, password)
25 user = User.find_by_name(name)
26 if !!user && Digest::SHA256.hexdigest(password + user.salt) == user.hashed_password
27 return user
28 end
29 false
30 end
31
32 6. rails g controller sessions
33
34 7. 添加路由
35
36 8. 添加 new页面
37
38 <h1>Blog Login</h1>
39 <%= form_tag sessions_path do -%>
40 <label for="name">Name</label>
41 <%= text_field_tag :name, params[:name] %>
42 <label for="password">Password</label>
43 <%= password_field_tag :password, params[:password], { :class => "text" } %>
44
45 <%= submit_tag "Login"%>
46 <% end -%>
47
48
49 9. 添加 new action
50
51 10. 添加 create action
52
53 def create
54 @user = User.authentication(params[:name], params[:password])
55 if @user
56 session[:user_id] = @user.id
57 flash[:notice] = "Welcome come #{@user.name}!"
58 redirect_to posts_path
59 else
60 flash[:notice] = "Name or password is not correct."
61 redirect_to new_session_path
62 end
63 end
64
Something went wrong with that request. Please try again.