我有一個接受json請求來創建用戶的rails應用程序。一個基本上是GET的sign_up。我不能創建一個用戶,當我通過這個URL http://localhost:3000/sign_up.json?username=chalam&[email protected]&name=chalami&password=chalami
我知道我在開放密碼,但這不是我關心的地方。我檢查了日誌,這是我所看到的無法傳遞參數數據來創建用戶
Started GET "/sign_up.json?username=chalam&[email protected]&name=chalami&password=[FILTERED]" for 127.0.0.1 at 2013-05-28 10:37:37 +0700
Processing by UsersController#create as JSON
Parameters: {"username"=>"chalam", "email"=>"[email protected]", "name"=>"chalami", "password"=>"[FILTERED]"}
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
(0.0ms) rollback transaction
(0.0ms) begin transaction
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
(0.0ms) rollback transaction
Completed 200 OK in 6ms (Views: 0.1ms | ActiveRecord: 0.3ms)
正如你可以看到雖然參數Parameters: {"username"=>"chalam", "email"=>"[email protected]", "name"=>"chalami", "password"=>"[FILTERED]"}
清楚地表明,正在傳遞的參數,他們沒有被輸入到數據庫中CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1 CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
主要問題是從PARAMS數據沒有被「使用」創建用戶
有一點需要注意的是我可以通過終端中的控制檯創建用戶。我會盡量包括所有相關信息 軌版本:3.2.13和 我使用薄的,而不是WEBBRICK
我user.rb
class User < ActiveRecord::Base
attr_accessible :email, :name, :username
attr_accessor :password
before_save :encrypt_password
validates_uniqueness_of :username, :email
validates_presence_of :password, :on => :create
validates_presence_of :email, :username
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
def self.authenticate(username, password)
user = find_by_username(username)
if(user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt))
user
else
nil
end
end
end
我的控制器
class UsersController < ApplicationController
respond_to :json
def new
@user = User.new
end
def create
@user = User.new(params[:user])
@user.save
if @user.save
respond_to do |format|
format.json { render :json => {:status => "200", :message => "Signed up successfully"}}
end
else
respond_to do |format|
puts @user.errors.inspect
format.json { render :json => {:status => "400", :message => "Failed"}}
end
end
end
def index
@user = User.all
render :json =>@user
end
end
1)哪裏是你的控制器代碼? 2)請格式化您的代碼,以便它不是簡單的代碼湯。 3)您正在創建* GET *請求的資源,破壞了Rails爲您設置的環境,幫助您構建RESTful應用程序。 4)你清楚地傳遞了一個密碼,無情地阻止了你自己的安全。見#3。 – coreyward
順便說一下,Rails已經用'has_secure_password'支持安全散列密碼,以確保你不會犯一堆你正在犯的錯誤(比如每次保存時重新對你的密碼進行散列)。 – coreyward
你使用設計寶石嗎? – visnu