Last active
June 2, 2016 09:21
-
-
Save Bahanix/ca75bc0df5488e925accef3c95fa4830 to your computer and use it in GitHub Desktop.
Ruby on Rails authorization exemple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/views/users/index.html.erb | |
<h1>Liste des utilisateurs</h1> | |
<ul> | |
<% @users.each do |user| %> | |
<li><%= user.id %></li> | |
<% end %> | |
</ul> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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