Skip to content

Instantly share code, notes, and snippets.

@Bahanix Bahanix/index.html.erb
Last active Jun 2, 2016

Embed
What would you like to do?
Ruby on Rails authorization exemple
# app/views/users/index.html.erb
<h1>Liste des utilisateurs</h1>
<ul>
<% @users.each do |user| %>
<li><%= user.id %></li>
<% end %>
</ul>
# config/routes.rb
Rails.application.routes.draw do
get 'users' => 'users#index'
get 'users/home' => 'users#home'
get 'users/login' => 'users#login'
delete 'users/login' => 'users#logout'
post 'users/login' => 'users#check'
end
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
if @current_user.try(:role) != "admin"
flash[:error] = "Accès interdit"
return redirect_to request.referrer || "/users/home"
end
@users = User.all
end
def home
end
def login
end
def check
@current_user = User.where(name: params[:name], password: params[:password]).first
if @current_user
session[:user_id] = @current_user.id
flash[:info] = "Vous êtes maintenant connecté"
redirect_to "/users/home"
else
session[:user_id] = nil
flash[:info] = "Échec de la connexion"
redirect_to "/users/login"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.