samedi 25 février 2017

How to assign role to user in Registration Controller and its view with Rolify and Devise

I want to have radiobuttongroup to choose role in my view but im not sure how to handle it. I've already setup the gems rolify and devise but Im not sure how to assign roles in view and controller. I've already created roles in console. I want to make sure that there isn't any exploits when choosing role. For example, if the person tries to change role name from browser and assign that to himself(e.g. admin), that would be a big problem.

registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]

  def create
    super
  end

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:firstname, :lastname, :email, :terms_of_service])
  end

user.rb

class User < ApplicationRecord
  rolify

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable
  validates :terms_of_service, :allow_nil => false, :acceptance => true

end

part of view for registration

<%= form_for(resource, as: resource_name, :role => "form", url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>
  <div class="form-group">
    <%= f.label t('label.user.form_content.firstname') %><br/>
    <%= f.text_field :firstname, autofocus: true, :class => "form-control text-center" %>
  </div>
  <div class="form-group">
    <%= f.label t('label.user.form_content.lastname') %><br/>
    <%= f.text_field :lastname, :class => "form-control text-center" %>
  </div>
  <div class="form-group">
    <%= f.label t('label.user.form_content.email') %><br/>
    <%= f.email_field :email, :class => "form-control text-center" %>
  </div>
  <div class="row">
    <div class="col-md-6">
      <div class="form-group">
        <%= f.label t('label.user.form_content.password') %>
        <% if @minimum_password_length %>
            <em>(<%= @minimum_password_length %> characters minimum)</em>
        <% end %><br/>
        <%= f.password_field :password, autocomplete: "off", :class => "form-control text-center" %>
      </div>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <%= f.label t('label.user.form_content.password_confirmation') %>
        <% if @minimum_password_length %>
            <em>(Must be same with password)</em><br/>
        <% end %><br/>
        <%= f.password_field :password_confirmation, autocomplete: "off", :class => "form-control text-center" %>
      </div>
    </div>
  </div>
<% end %>

Aucun commentaire:

Enregistrer un commentaire