0

我正在尝试设置一个简单的 iOS/Rails 应用程序,我可以在其中创建用户并随后使用 BCrypt 对其进行身份验证。我尝试按照 BCrypt 的说明进行操作,但我的身份验证过程不起作用。对rails非常陌生,所以我确定我搞砸了一些简单的事情!

创建新用户:

在 users_controller.rb

# POST /users
# POST /users.json
def create
  @user = User.new(user_params)
  @user.password = user_params[:password]

 respond_to do |format|
  if @user.save
    format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render :show, status: :created, location: @user }
  else
    format.html { render :new }
    format.json { render json: @user.errors, status: :unprocessable_entity }
  end
 end
end

def user_params
    params.require(:user).permit(:username, :password)
end

在用户.rb

def password
   @password ||= Password.new(password_hash)
end

def password=(new_password)
   @password = Password.create(new_password)
   self.password_hash = @password
end

在服务器上:

在 2014-08-21 19:32:05 -0500 开始 POST "/users.json" for 192.168.2.6 由 UsersController#create as JSON 参数处理:{"username"=>"testtest", "password"=>" [FILTERED]", "user"=>{"username"=>"testtest"}} (0.1ms) 开始事务用户存在 (20.8ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = 'testtest' LIMIT 1 为string列上的类型插入二进制数据password_hash SQL (0.8ms) INSERT INTO "users" ("created_at", "password_hash", "updated_at", "username") VALUES (?, ?, ?, ?) [["created_at", "2014-08-22 00 :32:05.960378"], ["password_hash", "$2a$10$UzLdD7ytQXKRDU5MhAawJuFQ3R4oQlPyXh/V4GehNP692fsSpK6wK"], ["updated_at", "2014-08-22 00:32:05.960378"], ["用户名" ]] (1.3ms) 提交事务 Rendered users/show.json.jbuilder (0.3ms) Completed 201 Created in 136ms (Views: 31.9ms | ActiveRecord: 23.5ms)

验证用户:

在 session_controller.rb 中

def create
    if @user = User.authenticate(params[:username], params[:password])
        session[:user_id] = @user.id
        render :show
    else
        flash.now[:alert] = "Invalid login/password combination"
        render :action => 'fail'
    end
end

在用户.rb

def self.authenticate(username,password)
 @user = User.find_by_username(username)
 return @user.password == password
end

服务器:

*开始 POST "/session" for 192.168.2.6 at 2014-08-21 19:38:26 -0500 由 SessionsController#create as / 参数处理:{"username"=>"testtest", "password"=>"[ FILTERED]", "session"=>{"username"=>"testtest", "password"=>"[FILTERED]"}} 用户负载 (0.2ms) SELECT "users".* FROM "users" WHERE "users "."username" = 'testtest' LIMIT 1 Rendered sessions/fail.json.jbuilder (0.2ms) Completed 200 OK in 105ms (Views: 23.3ms | ActiveRecord: 0.2ms)*

非常感谢您的任何见解!

4

1 回答 1

2

基本上 Bcrypt 用于加密密码。

您可以在模型中使用以下方法user.rb来加密密码和验证用户。

before_save :encrypt_password
def self.authenticate(name, password)
  user = find_by_user_name(name)
  if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
    user
  else
    nil
  end
end

def encrypt_password
  if password.present?
    self.password_salt = BCrypt::Engine.generate_salt
    self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
  end
end 
于 2014-08-22T07:33:26.807 回答