fuyi
fuyi

Reputation: 2639

rails 4 hide a model attribute before rendering

I have a user model using Rails 4 activerecord, it has a accesstoken attribute which store personal access token to authenticate this user as a alternative authentication mechanism.

As rails rendern by json render all fields of a model, access token field is also rendered. This is dangerous to leak credential information.

How could I filter the accesstoken field before rendering and also mark it as 'FILTERED' whenever it shows in server log, just like 'password' field does?

Upvotes: 1

Views: 335

Answers (1)

deefour
deefour

Reputation: 35360

For the JSON you can override as_json on the model:

def as_json(options={})
  options.reverse_merge! except: :accesstoken
  super(options)
end

For the logging, in config/application.rb you can add the attribute to the filter list

config.filter_parameters << :accesstoken

Upvotes: 1

Related Questions