用户身份验证过程出错

时间:2013-01-30 22:26:04

标签: ruby-on-rails ruby authentication authorization password-encryption

我正在尝试在新应用程序中重新创建用户身份验证过程。我有一个旧的,现有的用户身份验证工作,我真的复制代码(更改当然的名称),期望它是一个很好的起点......但它不起作用!我已经尝试了所有的东西,但由于某种原因我无法登录这个程序...也许我有一些东西可以忽略?

login.html.erb

<div class="login" style="margin-left: 390px;">
  <%= form_tag(:action => 'team_login') do %>
  <table>
    <tr>
      <td><%= label_tag(:username) %></td>
      <td><%= text_field_tag(:username) %></td>
    </tr>
    <tr>
      <td><%= label_tag(:password) %></td>
      <td><%= password_field_tag(:password) %></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td><%= submit_tag("Log In") %></td>
    </tr>
  </table>
  <% end %>
</div>

teams_controller.rb

  def team_login
    authorized_team = Team.authenticate(params[:username], params[:password])
    if authorized_team
      #To Do: mark user as logged in
      session[:team_id] = authorized_team.id
      session[:team_name] = authorized_team.username
      #check!
      flash[:notice] = "You are now logged in."
      redirect_to(:controller => 'show', :id => session[:team_id])
    else
      flash[:notice] = "Invalid username and password combination"
      redirect_to(:action => 'login')
    end
  end

team.rb

  attr_accessible :username, :password

  attr_accessor :password

  before_save :create_hashed_password

  def self.authenticate(username="", password="")
    qTeam = Team.find_by_username(username)
    if qTeam && qTeam.password_match?(password)
      return qTeam
    else
      return false
    end
  end

  def password_match?(password="")
    hashed == Team.salt_hash(salt, password)
  end

  def self.make_salt(username="")
    Digest::SHA1.hexdigest(" #{username} #{Time.now}")
  end

  def self.salt_hash(salt="", password="")
    Digest::SHA1.hexdigest("#{salt} #{password}")
  end

  private

  def create_hashed_password
    unless password.blank?
      self.salt = Team.make_salt(username) if salt.blank?
      self.hashed = Team.salt_hash(password, salt)
    end
  end

我意识到创建用户时发生了错误。如果我手动进入并使用保存到用户的salt,密码并生成哈希密码,则它与保存在数据库中的密码不同。我假设这是发生错误的地方 - 我用来创建用户的模板只是从脚手架生成的标准_form。所有代码都与上面相同 - before_save运行一些方法(create_hashed_pa​​ssword,make_salt和salt_hash)

1 个答案:

答案 0 :(得分:0)

您需要确保拥有:

:action => 'team_login'

指向有效的路线。

我通常使用类似的东西:

<%= form_tag sessions_path do %>
...
<% end %>

使用如下所示的路线:

MyApp::Application.routes.draw do
  get "sessions/new"
  get "login" => "sessions#new", :as => "login"
  resources :sessions
  ...
end

使用看起来像:

的sessions_controller
class SessionsController < ApplicationController

  def create
    user = login(params[:email], params[:password], params[:remember_me])
    if user
      redirect_back_or_to root_url, :notice => "Welcome, #{user.email}."
    else
      flash.now.alert = "Email or password was invalid"
      render :new
    end
  end

  def destroy
    logout
    redirect_to root_url, :notice => "Logged out!"
  end
end

当从一个应用程序复制/粘贴功能(例如身份验证)时,忘记连接路由是一种常见的事故。