Skip to content

Instantly share code, notes, and snippets.

@Bahanix
Last active June 2, 2016 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bahanix/ca75bc0df5488e925accef3c95fa4830 to your computer and use it in GitHub Desktop.
Save Bahanix/ca75bc0df5488e925accef3c95fa4830 to your computer and use it in GitHub Desktop.
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