LoginEngine : Associer un user et un article.

Posted by Pierre Rigal on août 23, 2006

Voilà la dernière partie de mon tour d’horizon sur le LoginEngine ! Nous avons vu comment installer le LoginEngine, puis comment le surcharger, nous allons maintenant voir comment l’utiliser dans le cadre d’une application classique (telle qu’un petit blog.)

Prérequis

  1. Avoir une “mini” application foncitonnelle. (Le résultat d’un scaffold pour un modèle “article” composé d’un titre et d’un corps devrait amplement suffire !)
  2. Avoir installé le LoginEngineavec succès.
  3. Avoir compris comment fonctionnnait la surcharge. (J’utiliserai le mécanisme dans cet article mais je ne le réexpliquerai pas ;) )
  4. Avoir 2 ou 3 notions de base de donnée ;)
  5. Avoir … 2 minutes devant soi ;)

Let’s go baby !

Prenons notre exemple de “mini blog”, afin de savoir quel utilisateur écrit quel article la base de donnée doit prévoir de stocker l’id de l’utilisteur pour chaque article. Ainsi, si ce n’est pas déjà fait, ajouter le champs ‘user_id’ à votre table article.

$ ruby script/generate migration add_user_info_to_article

Insérez ceci dans le fichier créé :

class AddUserInfoToArticle < ActiveRecord::Migration
  def self.up
    add_column :articles, :user_id, :integer #libre à vous d'ajouter d'autres paramètres...
  end

  def self.down
    remove_column :articles, :user_id,
  end
end

Puis :

$ rake db:migrate

Maintenant, au sein de votre application, générer le modèle et le controller “user” pour la surcharge. Il faut ensuite indiquer au modèle “user.rb” qu’un utilisateur peut écrire de 0 à N articles. (C’est fait avec la ligne has_many)

class User < ActiveRecord::Base
 has_many :articles
 include LoginEngine::AuthenticatedUser
end

Et indiquer au modèle article qu’il appartient à un utilisateur :

class Article < ActiveRecord::Base
  belongs_to :user
end

Pour finir, à chaque création d’un article il faut associer l’utilisateur courant (en session.). En se basant sur le scaffold du controlleur pour gérer les articles, voici ce que cela donne :

class AdminArticlesController < ApplicationController
  before_filter :login_required
  ...
  def create
   @article = Article.new(params[:article])
   @article.user=session[:user] # ici !
   if @article.save 
     flash[:notice]= 'Article was successfully added.'
     redirect_to :action => 'list'
   else
     render :action => 'new'
   end 
 end
 ...
end

Ok… et c’est possible d’empécher l’accès à l’admin pour les users simples ?

Oui c’est possible :) . Pour cela on va redéfinir la méthode “authorize?” du LoginEngine.

NB : J’ai mis le code dans le helper de l’article. Je ne sais pas si c’est le meilleur endroit, mais ça fonctionne.

Donc éditez votre helper, nous allons utiliser un champs existant du LoginEngine “role” non implémenté pour l’instant.

module AdminArticlesHelper
  module LoginEngine
    module AuthenticatedSystem
      protected

      # Overwrited method
      # Only allow admin to enter this controller
      def authorize?(user)
        user.role == "admin"
      end
    end
  end
end

Ainsi seul les utilisateurs avec le rôle “admin” pourront utiliser ce controleur !

Pour aller toujours plus loin.

Parcequ’il parait que c’est toujours mieux ailleurs, un de mes prochains articles traitera encore de la gestion d’utilisateurs. Ce sera à propos d’un système d’un autre type que je viens de découvrir : un générator appelé auth_generator.

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Zfred lun, 05 fév 2007 14:46:43 CET

    Il est hyper bien le auth_generator de Fabien Penso. Tu perdra pas du temps à le tester ;)

  2. Pierre Rigal lun, 05 fév 2007 20:48:35 CET

    Oui il est effectivement très bien et si tu navigues un peu sur mon blog tu verras que je l’ai déjà testé !

    En passant, j’ai aussi testé le actasauthenticated et personnelement c’est mon préféré, il est très souple à utiliser.

  3. […] Je vais donc commencer (ou plutôt reprendre) ce tour d’horizon avec actsasauthenticated. Je sais, j’ai déjà parlé à plusieurs reprises 1 2 3 4 de systèmes permettant de traiter l’identification avec Rails, cependant je ne pouvais pas en dire autant sans parler du plugin que j’utilise maintenant sur tout mes projets : actsasautenticated. […]

  4. tyncroorb mar, 08 juil 2008 22:23:43 CEST

    exceptional adapt, a upsurge provider of artifacts and services that broadcast a new contract of the double and stockivity of salubrity conceive, today announced a consolidtion of its businesses into two prototypical operating and reporting intersections to lessen costs and align resources with the separate needs of each fragment.

    key fulness’s netowrk of pharmaceutical and medical development dissemination centers and nuclear pharmacies scheme visualize the fulnessappear at to run across up with fetter Services common, led byimperfection Chairman George S. Barrett. With annual production of more than $80 billion, this element serves customers in North America with capable and active compact services for information co untermeasure and medical artifacts.

    diligence famous consequences for infusion, medication dispensing, respiratory conceive and infection interdicting predilection be grouped in the Clinical and Medical Products fragment the aegis the regulation of badness Chairman David L. Schlotterbeck. With annual arouse of infer $5 billion, this element serves scourge customers with clinically differentiated stocks habituatde to in clinics and other chief f ollow to facilities.

    The intersections when one psublet outs be connected by a sgrump corporate process and highest requirement’s nursing old folks’ sales force.

    With these changes, the associates tilt produce down its workforce by expatiate 600 positions indirect to a restructuring requirement of approaching $63 million, the grandly-founded the larger of which it expects to rate in the commonest mercantile year, which began July 1. Of those positions, here 160 are rulingly agape and proneness not be filled. Employees void when one psublet outs be offered severance benefits.

    “from belfry to foot this restructuring, we mash our searchlight on two as plain as day, telling and growing elements of the salubriousness put in an appearance at to hasten by aligning our resources, reducing costs and plateful to forth convert into making for our customers,” said R. Kerry Clark, chairman and CEO of highest adapt. “In multitudinous ways, these chaanges visualiezalize the processatization we began to put in run across to 18 months ago and predilection accessible us a weather-beatener associates thta has a greater concentrsted peninsula on both our supplier-customers and provider-customers, with a end of creating more value for rationslow downers.

  5. XRumerIsTheBest mar, 29 juil 2008 22:06:04 CEST

    Доброго времени суток, форумчане сайта www.stoneageblog.com ;)

    Ответьте мне, пожалуйста, на несколько вопросов… - какая программа умеет автоматически за НЕСКОЛЬКО СЕКУНД регистрировать ящики на mail.ru и многих других почтовиках? - какая программа умеет автоматом рассылать по mamba.ru и loveplanet.ru по заданным параметрам, при этом еще поддерживая функции автоответчика? - а также сможет разослать по форумам текст (например) “где купить валенки?”, а потом в ответ на этот текст ОТ ДРУГОГО имени и IP написать (например) “только на сайте megavalenki.ru!”? - плюс распознаёт картинки и вопросы а-ля “что написано на этой картинке?”, “сколько будет 2+2?” и “какой сейчас год?” и умеет корректно на них отвечать? - какая программа сможет разослать топики по форумам, попутно автоматически регистрироваться на них и создавая подробный отчет о проделанной работе? - и при этом работает с разнообразными движками - phpBB, VBulletin, IPB, ExBB, Icon Board, YaBB, UltimateBB, множеством различных гостевых, досок и блогов? - какую программу вы МОЖЕТЕ переделать под свой вкус? - какая программа автоматически обновляет прокси / SOCKS, обеспечивая вам полную анонимность? (достаточно просто нажать ОДНУ кнопку) - какая программа умеет рассылать персональные сообщения всем пользователям форумов phpBB, IPB, VBulletin? - какая программа отсортирует Вашу базу ссылок по Google PageRank? - какая программа МАССОВО отредактирует все Ваши ранее разосланные объявления по форумам? - и при этом еще регулярно обновляется и совершенствуется.

    Ответ ОДИН: всё это и многое другое под силу программному комплексу XRumer 4.085 Platinum Edition + Hrefer 2.85 Данный комплекс имеет множество отзывов на авторитетных источниках (Washington Post, Wikipedia и т.п.), имеет историю активного развития более 3-х лет.

    Просто спроси у Яндекса! ;)

    См. также: XRumer, хрумер 3.0 устарел, распознавание графической защиты, SEO, рефспам, хрумер, чёрное СЕО, XRumer forever, софт для СЕО, распознавание текстовой защиты, ППЦ, разослать по форумам и гостевым, XRumer 3.0 устарел, XRumer Platinum, линкспам, софт для SEO, white SEO, XRumer 2.9 устарел, постинг по блогам, хрумер 2.9 устарел, doorways, массовые рассылки, белое СЕО, black SEO, распознавание капчи, программы для SEO, мощная спамилка, PPC, рассылка по форумам, программы для СЕО, суперсофт для SEO, СЕО

Comments (Syntaxe Markdown)