我目前正在为一个朋友建立一个小型网站,我希望他能够更改他的密码,因为他将获得的密码是种子,并且可以从Git存储库中看到(别担心,他很清楚这是他必须更改的第一件事)
一般来说,我习惯于Ruby on Rails,但这是我第一次使用API,而不是Rails的“标准”版本,而且我根本没有使用任何关于令牌之类的东西。
在后台,他可以更改网站的一些元素,我做了一个特定的页面,他可以更改一些细节,如他的传记,他的个人资料图片,他的社交网络链接等。在这个页面上,我添加了一个部分,他可以更改他的密码,字段
current_password
,
password
和
password_confirmation
. 我也开始设置一些验证,但问题是,如果我在字段中键入3次“password”,将得到以下错误:
ActiveRecord::RecordInvalid |验证失败:密码不能为空
困扰我的是两个元素:第一个是错误不是作为JSON返回,而是作为HTML返回(这是我的第一个问题,如何将格式强制为JSON?),并确保将密码发送到API(前面是VueJS,但这不是问题所在),但仍然显示错误。
这是我的代码:
用户控制器.rb
# ...
wrap_parameters :user, include: %i[password password_confirmatioon current_password]
# ...
def profile
if @user.update(user_params)
render json: @user, status: :ok
else
render json: @user.errors, status: :unprocessable_entity
end
@user.reset_password!(user_params[:new_password])
end
用户.rb
class User < ApplicationRecord
mount_base64_uploader :picture, BioFaceUploader
include ActiveModel::Serializers::JSON
has_secure_password
attr_accessor :old_password
attr_accessor :profile
def generate_password_token!
begin
self.reset_password_token = SecureRandom.urlsafe_base64
end while User.exists?(reset_password_token: reset_password_token)
self.reset_password_token_expires_at = 1.day.from_now
save!
end
def reset_password!(password)
self.reset_password_token = nil
self.password = password
save!
end
def clear_password_token!
self.reset_password_token = nil
self.reset_password_token_expires_at = nil
save!
end
end
**编辑:这是我尝试发布新密码时的服务器日志输入**
Started POST "/profile" for 127.0.0.1 at 2018-09-21 13:15:33 +0200
Processing by UsersController#profile as HTML
Parameters: {"id"=>1, "email"=>"email@email.me", "password_digest"=>"[FILTERED]", [some more unrelated datas], "created_at"=>"2018-09-17T11:38:27.464Z", "updated_at"=>"2018-09-21T10:23:50.233Z", "reset_password_token"=>"[FILTERED]", "reset_password_token_expires_at"=>"[FILTERED]", "password"=>"[FILTERED]", "current_password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "user"=>{"password"=>"[FILTERED]", "current_password"=>"[FILTERED]"}}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
â³ app/controllers/users_controller.rb:39
Unpermitted parameters: :password, :current_password
Unpermitted parameters: :password, :current_password
(0.1ms) begin transaction
â³ app/controllers/users_controller.rb:27
(0.1ms) commit transaction
â³ app/controllers/users_controller.rb:27
Unpermitted parameters: :password, :current_password
(0.1ms) begin transaction
â³ app/models/user.rb:21
(0.1ms) rollback transaction
â³ app/models/user.rb:21
Completed 500 Internal Server Error in 32ms (Views: 0.6ms | ActiveRecord: 1.5ms)
如您所见,有两个字段未经授权,我将它们添加到允许的参数中,但现在出现以下错误:
用户的“当前密码”属性未知
我应该把它加到
attr_accessor
的列表?
我该怎么做才能解决这个问题?
提前谢谢你