`
sunchaohui_koko
  • 浏览: 59093 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

login_engine

阅读更多

http://svn.rails-engines.org/plugins/login_engine/README

 

 

= Before we start

This is a Rails Engine version of the Salted Login Generator, a most excellent login system which is sufficient for most simple cases. For the most part, this code has not been altered from its generator form, with the following notable exceptions

* Localization has been removed.
* The 'welcome' page has been changed to the 'home' page
* A few new functions have been thrown in
* It's... uh.... a Rails Engine now ;-)

However, what I'm trying to say is that 99.9999% of the credit for this should go to Joe Hosteny, Tobias Luetke (xal) and the folks that worked on the original Salted Login generator code. I've just wrapped it into something runnable with the Rails Engine system.

Please also bear in mind that this is a work in progress, and things like testing are wildly up in the air... but they will fall into place very soon. And now, on with the show.


= Installation

Installing the Login Engine is fairly simple.

Your options are:
  1.  Install as a rails plugin:
      $ script/plugin install login_engine
  2.  Use svn:externals
      $ svn propedit svn:externals vendor/plugins

      You can choose to use the latest stable release:
          login_engine http://svn.rails-engines.org/plugins/login_engine

      Or a tagged release (recommended for releases of your code):
          login_engine http://svn.rails-engines.org/logine_engine/tags/<TAGGED_RELEASE>

There are a few configuration steps that you'll need to take to get everything running smoothly. Listed below are the changes to your application you will need to make.

=== Setup your Rails application

Edit your <tt>database.yml</tt>, most importantly! You might also want to move <tt>public/index.html</tt> out of the way, and set up some default routes in <tt>config/routes.rb</tt>.

=== Add configuration and start engine

Add the following to the bottom of environment.rb:

  module LoginEngine
    config :salt, "your-salt-here"
  end

  Engines.start :login
  
You'll probably want to change the Salt value to something unique. You can also override any of the configuration values defined at the top of lib/user_system.rb in a similar way. Note that you don't need to start the engine with <tt>Engines.start :login_engine</tt> - instead, <tt>:login</tt> (or any name) is sufficient if the engine is a directory named <some-name>_engine.


=== Add the filters

Next, edit your <tt>app/controllers/application.rb</tt> file. The beginning of your <tt>ApplicationController</tt> should look something like this:

  require 'login_engine'

  class ApplicationController < ActionController::Base
    include LoginEngine
    helper :user
    model :user
    
    before_filter :login_required

If you don't want ALL actions to require a login, you need to read further below to learn how to restrict only certain actions. 

Add the following to your ApplicationHelper:

  module ApplicationHelper
    include LoginEngine
  end

This ensures that the methods to work with users in your views are available

=== Set up ActionMailer

If you want to disable email functions within the Login Engine, simple set the :use_email_notification config flag to false in your environment.rb file:

  module LoginEngine
    
    #  ... other options...
    config :use_email_notification, false

  end

You should note that retrieving forgotten passwords automatically isn't possible when the email functions are disabled. Instead, the user is presented with a message instructing them to contact the system administrator

If you wish you use email notifications and account creation verification, you must properly configure ActionMailer for your mail settings. For example, you could add the following in config/environments/development.rb (for a .Mac account, and with your own username and password, obviously):

ActionMailer::Base.server_settings = {
  :address => "smtp.mac.com",
  :port => 25,
  :domain => "smtp.mac.com",
  :user_name => "<your user name here>",
  :password => "<your password here>",
  :authentication => :login
}

You'll need to configure it properly so that email can be sent. One of the easiest ways to test your configuration is to temporarily reraise exceptions from the signup method (so that you get the actual mailer exception string). In the rescue statement, put a single "raise" statement in. Once you've debugged any setting problems, remove that statement to get the proper flash error handling back.


=== Create the DB schema

After you have done the modifications the the ApplicationController and its helper, you can import the user model into the database. Migration information in login_engine/db/migrate/. 

You *MUST* check that these files aren't going to interfere with anything in your application. 

You can change the table name used by adding

  module LoginEngine
    
    #  ... other options...
    config :user_table, "your_table_name"

  end

...to the LoginEngine configuration in <tt>environment.rb</tt>. Then run from the root of your project:

  rake db:migrate:engines ENGINE=login

to import the schema into your database.


== Include stylesheets

If you want the default stylesheet, add the following line to your layout:

  <%= engine_stylesheet 'login_engine' %>
  
... somewhere in the <head> section of your HTML layout file.

== Integrate flash messages into your layout

LoginEngine does not display any flash messages in the views it contains, and thus you must display them yourself. This allows you to integrate any flash messages into your existing layout. LoginEngine adheres to the emerging flash usage standard, namely:

* :warning - warning (failure) messages
* :notice - success messages
* :message - neutral (reminder, informational) messages

This gives you the flexibility to theme the different message classes separately. In your layout you should check for and display flash[:warning], flash[:notice] and flash[:message]. For example:

  <% for name in [:notice, :warning, :message] %>
    <% if flash[name] %>
      <%= "<div id=\"#{name}\">#{flash[name]}</div>" %>
    <% end %>
  <% end %>

Alternately, you could look at using the flash helper plugin (available from https://opensvn.csie.org/traccgi/flash_helper_plugin/trac.cgi/), which supports the same naming convention.


= How to use the Login Engine 

Now you can go around and happily add "before_filter :login_required" to the controllers which you would like to protect. 

After integrating the login system with your rails application navigate to your new controller's signup method. There you can create a new account. After you are done you should have a look at your DB. Your freshly created user will be there but the password will be a sha1 hashed 40 digit mess. I find this should be the minimum of security which every page offering login & password should give its customers. Now you can move to one of those  controllers which you protected with the before_filter :login_required snippet. You will automatically be re-directed to your freshly created login controller and you are asked for a password. After entering valid account data you will be taken back to the controller which you requested earlier. Simple huh?

=== Protection using <tt>before_filter</tt>

Adding the line <tt>before_filter :login_required</tt> to your <tt>app/controllers/application.rb</tt> file will protect *all* of your applications methods, in every controller. If you only want to control access to specific controllers, remove this line from <tt>application.rb</tt> and add it to the controllers that you want to secure.

Within individual controllers you can restrict which methods the filter runs on in the usual way:

       before_filter :login_required, :only => [:myaccount, :changepassword]
       before_filter :login_required, :except => [:index]

=== Protection using <tt>protect?()</tt>

Alternatively, you can leave the <tt>before_filter</tt> in the global <tt>application.rb</tt> file, and control which actions are restricted in individual controllers by defining a <tt>protect?()</tt> method in that controller.

For instance, in the <tt>UserController</tt> we want to allow everyone access to the 'login', 'signup' and 'forgot_password' methods (otherwise noone would be able to access our site!). So a <tt>protect?()</tt> method is defined in <tt>user_controller.rb</tt> as follows:

  def protect?(action)
    if ['login', 'signup', 'forgot_password'].include?(action)
      return false
    else
      return true
    end
  end

Of course, you can override this Engine behaviour in your application - see below.

== Configuration

The following configuration variables are set in lib/login_engine.rb. If you wish to override them, you should set them BEFORE calling Engines.start (it is possible to set them after, but it's simpler to just do it before. Please refer to the Engine documentation for the #config method for more information).

For example, the following might appear at the bottom of /config/environment.rb:

  module LoginEngine
    config :salt, 'my salt'
    config :app_name, 'My Great App'
    config :app_url, 'http://www.wow-great-domain.com'
  end
  
  Engines.start

=== Configuration Options

+email_from+:: The email from which registration/administration emails will appear to 
               come from. Defaults to 'webmaster@your.company'.
+admin_email+:: The email address users are prompted to contact if passwords cannot
                be emailed. Defaults to 'webmaster@your.company'.
+app_url+:: The URL of the site sent to users for signup/forgotten passwords, etc.
            Defaults to 'http://localhost:3000/'.
+app_name+:: The application title used in emails. Defaults to 'TestApp'.
+mail_charset+:: The charset used in emails. Defaults to 'utf-8'.
+security_token_life_hours+:: The life span of security tokens, in hours. If a security
                              token is older than this when it is used to try and authenticate
                              a user, it will be discarded. In other words, the amount of time
                              new users have between signing up and clicking the link they
                              are sent. Defaults to 24 hours.
+two_column_input+:: If true, forms created with the UserHelper#form_input method will
                     use a two-column table. Defaults to true.
+changeable_fields+:: An array of fields within the user model which the user
                      is allowed to edit. The Salted Hash Login generator documentation
                      states that you should NOT include the email field in this
                      array, although I am not sure why. Defaults to +[ 'firstname', 'lastname' ]+.
+delayed_delete+::  Set to true to allow delayed deletes (i.e., delete of record
                    doesn't happen immediately after user selects delete account,
                    but rather after some expiration of time to allow this action
                    to be reverted). Defaults to false.
+delayed_delete_days+:: The time delay used for the 'delayed_delete' feature. Defaults to
                        7 days.
+user_table+:: The table to store User objects in. Defaults to "users" (or "user" if
               ActiveRecord pluralization is disabled).
+use_email_notification+:: If false, no emails will be sent to the user. As a consequence,
                           users who signup are immediately verified, and they cannot request
                           forgotten passwords. Defaults to true.
+confirm_account+:: An overriding flag to control whether or not user accounts must be
                    verified by email. This overrides the +user_email_notification+ flag.
                    Defaults to true.

== Overriding controllers and views

The standard home page is almost certainly not what you want to present to your users. Because this login system is a Rails Engine, overriding the default behaviour couldn't be simpler. To change the RHTML template shown for the <tt>home</tt> action, simple create a new file in <tt>RAILS_ROOT/app/views/user/home.rhtml</tt> (you'll probably need to create the directory <tt>user</tt> at the same time). This new view file will be used instead of the one provided in the Login Engine. Easy!


== Tips & Tricks

How do I...

  ... access the user who is currently logged in

  A: You can get the user object from the session using session[:user]
     Example: 
       Welcome <%= session[:user].name %>

    You can also use the 'current_user' method provided by UserHelper:
    Example:
      Welcome <%= current_user.name %>


  ... restrict access to only a few methods? 
  
  A: Use before_filters build in scoping. 
     Example: 
       before_filter :login_required, :only => [:myaccount, :changepassword]
       before_filter :login_required, :except => [:index]
     
  ... check if a user is logged-in in my views?
  
  A: session[:user] will tell you. Here is an example helper which you can use to make this more pretty:
     Example: 
       def user?
         !session[:user].nil?
       end

  ... return a user to the page they came from before logging in?

  A: The user will be send back to the last url which called the method "store_location"
     Example:
       User was at /articles/show/1, wants to log in.
       in articles_controller.rb, add store_location to the show function and
       send the user to the login form. 
       After he logs in he will be send back to /articles/show/1

You can find more help at http://wiki.rubyonrails.com/rails/show/SaltedLoginGenerator

== Troubleshooting

One of the more common problems people have seen is that after verifying an account by following the emailed URL, they are unable to login via the normal login method since the verified field is not properly set in the user model's row in the DB.

The most common cause of this problem is that the DB and session get out of sync. In particular, it always happens for me after recreating the DB if I have run the server previously. To fix the problem, remove the /tmp/ruby* session files (from wherever they are for your installation) while the server is stopped, and then restart. This usually is the cause of the problem.

= Notes

=== Database Schemas & Testing

Currently, since not all databases appear to support structure cloning, the tests will load the entire schema into your test database, potentially blowing away any other test structures you might have. If this presents an issue for your application, comment out the line in test/test_helper.rb


= Database Schema Details

You need a database table corresponding to the User model. This is provided as a Rails Schema file, but the schema is presented below for information. Note the table type for MySQL. Whatever DB you use, it must support transactions. If it does not, the functional tests will not work properly, nor will the application in the face of failures during certain DB creates and updates.

  mysql syntax:
  CREATE TABLE users (
    id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    login VARCHAR(80) NOT NULL,
    salted_password VARCHAR(40) NOT NULL,
    email VARCHAR(60) NOT NULL,
    firstname VARCHAR(40),
    lastname VARCHAR(40),
    salt CHAR(40) NOT NULL,
    verified INT default 0,
    role VARCHAR(40) default NULL,
    security_token CHAR(40) default NULL,
    token_expiry DATETIME default NULL,
    deleted INT default 0,
    delete_after DATETIME default NULL
  ) TYPE=InnoDB DEFAULT CHARSET=utf8;

  postgres:
  CREATE TABLE "users" (
    id SERIAL PRIMARY KEY
    login VARCHAR(80) NOT NULL,
    salted_password VARCHAR(40) NOT NULL,
    email VARCHAR(60) NOT NULL,
    firstname VARCHAR(40),
    lastname VARCHAR(40),
    salt CHAR(40) NOT NULL,
    verified INT default 0,
    role VARCHAR(40) default NULL,
    security_token CHAR(40) default NULL,
    token_expiry TIMESTAMP default NULL,
    deleted INT default 0,
    delete_after TIMESTAMP default NULL
  ) WITH OIDS;

  sqlite:
  CREATE TABLE 'users' (
    id INTEGER PRIMARY KEY,
    login VARCHAR(80) NOT NULL,
    salted_password VARCHAR(40) NOT NULL,
    email VARCHAR(60) NOT NULL,
    firstname VARCHAR(40),
    lastname VARCHAR(40),
    salt CHAR(40) NOT NULL,
    verified INT default 0,
    role VARCHAR(40) default NULL,
    security_token CHAR(40) default NULL,
    token_expiry DATETIME default NULL,
    deleted INT default 0,
    delete_after DATETIME default NULL
  );

Of course your user model can have any amount of extra fields. This is just a starting point.
分享到:
评论

相关推荐

    库快科技p2p sdk说明书.docx

    使用库快科技P2P SDK,开发者需要先初始化引擎(使用kkp2p_engine_init,传入kkp2p_engine_conf_t配置),然后创建连接(可以选择同步或异步接口,异步接口需要提供kkp2p_connect_cb回调函数)。一旦连接建立,就...

    Login_delphi_ThisIsHow_源码

    Delphi提供了多种方式与数据源交互,如ADO(ActiveX Data Objects)或BDE(Borland Database Engine)。在这个例子中,可能使用简单的文本文件或更安全的加密数据库来存储用户信息。 4. **密码安全性**:为了保护...

    ruby on rails 常用插件下载

    在这个特定的压缩包文件“login_engine”中,我们似乎有一个用于用户登录功能的插件。这个插件可以帮助开发者快速实现用户认证和授权,避免重复编写常见的登陆验证逻辑。 在Ruby on Rails中,插件通常是一组自包含...

    Delphi+Access做的一个程序登录对话框.rar_access_delphi access_delphi login_d

    1. **数据库连接**:使用 ADO (ActiveX Data Objects) 或 BDE (Borland Database Engine) 连接组件,开发者可以将 Delphi 应用程序与 Access 数据库连接起来,读取和写入数据。 2. **SQL 查询**:在用户提交登录...

    mysql数据库

    CREATE TABLE IF NOT EXISTS `deep_admin` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `nickname` varchar(100) COLLATE ...) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ;

    Flask框架Flask-Login用法分析

    **Flask-Login是Flask框架的一个扩展,用于处理用户登录和身份验证。它提供了一套简单而强大的机制,帮助开发者轻松地管理用户会话。本文将深入探讨Flask-Login的基本用法、核心概念以及如何集成到Flask应用中。** ...

    Codeigniter-login-auth-admin

    DEFAULT NULL, reg_time int(10) DEFAULT NULL, last_login_time int(10) DEFAULT NULL, last_login_ip varchar(15) DEFAULT NULL, login_count int(11) DEFAULT NULL, update_time int(10) DEFAULT NULL, status ...

    Flask-Blogging(Python)

    blogging_engine = BloggingEngine(app, storage) ``` ### 4. 使用Flask-Blogging 创建文章: ```python from flask_blogging import Post new_post = Post(title="我的第一篇博客", content="欢迎来到我的博客!...

    django学习常见错误

    Django学习常见错误解决方案 Django是一个流行的Python Web框架...@login_required(login_url='/bookmarks/login/') def bookmarks(request): # 视图函数代码 ``` 这样,如果用户没有登录,系统就会跳转到登录页面。

    ArcEngine三维开发

    5. **用户交互与登录机制**:login.Designer.cs可能涉及到用户登录界面的设计,这在GIS应用中用于权限控制和个性化设置。TableForm则可能用于显示和编辑表格数据,例如属性信息。 6. **自定义控件与组件**:Table...

    文档围绕企业中关系相关技术展开,讲述了关系统的基本知识,常用建表和查询语言以及优化,还有索引的知识。

    ) ENGINE = InnoDB AUTO_INCREMENT = 2 COMMENT = '用户信息表'; ``` 查询表数据是日常操作的一部分,例如,我们可以根据条件查询`sys_user`表: ```sql SELECT user_id,dept_id,login_name,user_name,user_type,...

    PHP+jQuery+Ajax实现用户登录与退出

    ) ENGINE=MyISAM DEFAULT CHARSET=utf8; ``` 然后,向`user`表中插入一条示例用户数据: ```sql INSERT INTO `user` (`id`, `username`, `password`, `login_time`, `login_ip`, `login_counts`) VALUES(1, 'demo'...

    juniper OS upgradation of dual routing engine.pdf

    &gt;request routing-engine login other-routing-engine &gt;request routing-engine login re1. &gt;request routing-engine login backup. ``` 然后,可以查看版本信息,确认OS升级前的状态: ```shell &gt;show version ``` ...

    iconly:用于管理Web图标字体的Rails引擎

    偶像地 Ruby on Rails 5引擎,用于存储SVG并生成您的Web字体图标。 安装 Iconly使用 ,因此您需要按照他们的安装它和FontForge。 安装Fontcustom之后,将此行添加到应用程序的Gemfile中: ... login_path应

    若依平台-数据库表(完整).doc

    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户和角色关联表'; ``` ### 二、`sys_user_post` 用户与岗位关联表 #### 表格说明: 该表记录了用户与其所担任岗位之间的关联关系,以便于进行更精细化的权限管理...

    frontity-in-atlas:WP Engine中的前端(节点和WP)

    WordPress和Frontity都在WP Engine中运行: WordPress在管理的托管服务中运行。 Frontity在WP Engine的新无头WordPress平台中运行。 安装 如果要在Atlas中运行Frontity,请按照以下步骤操作: 1.安装CLI 首先,...

    IBM Websphere Portal 5 customizing portal login

    - `command.path=com.ibm.wps.engine.commands` 默认的登录命令执行流程如下: 1. **WebSphere 应用服务器登录**:应用服务器验证用户名/密码与用户注册表(通常是LDAP)中的数据是否一致,并构建一个凭据令牌,该...

    brunt-api:Brunt的非官方api(Blind Engine等)

    布朗特·阿皮Brunt的非官方api(Blind Engine等)安装yarn add brunt-api或npm install brunt-api用法这是一个示例类,您可以使用它来按名称打开/关闭Brunt Blind Engine设备 class Blinds { private api = new ...

    pivotal_auth

    关键身份验证 设置 要安装,请将这两行添加到您的 Gemfile 中: gem "pivotal_auth", github: "pivotal/pivotal_auth" gem "okta_saml", github: ...gem 需要两个环境变量: OKTA_LOGIN_URL和OKTA_CERT_FINGERPRINT

Global site tag (gtag.js) - Google Analytics