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.
【RIS 辅助的 THz 混合场波束斜视下的信道估计与定位】在混合场波束斜视效应下,利用太赫兹超大可重构智能表面感知用户信道与位置(Matlab代码实现)内容概要:本文围绕“IS 辅助的 THz 混合场波束斜视下的信道估计与定位”展开,重点研究在太赫兹(THz)通信系统中,由于混合近场与远场共存导致的波束斜视效应下,如何利用超大可重构智能表面(RIS)实现对用户信道状态信息和位置的联合感知与精确估计。文中提出了一种基于RIS调控的信道参数估计算法,通过优化RIS相移矩阵提升信道分辨率,并结合信号到达角(AoA)、到达时间(ToA)等信息实现高精度定位。该方法在Matlab平台上进行了仿真验证,复现了SCI一区论文的核心成果,展示了其在下一代高频通信系统中的应用潜力。; 适合人群:具备通信工程、信号处理或电子信息相关背景,熟悉Matlab仿真,从事太赫兹通信、智能反射面或无线定位方向研究的研究生、科研人员及工程师。; 使用场景及目标:① 理解太赫兹通信中混合场域波束斜视问题的成因与影响;② 掌握基于RIS的信道估计与用户定位联合实现的技术路径;③ 学习并复现高水平SCI论文中的算法设计与仿真方法,支撑学术研究或工程原型开发; 阅读建议:此资源以Matlab代码实现为核心,强调理论与实践结合,建议读者在理解波束成形、信道建模和参数估计算法的基础上,动手运行和调试代码,深入掌握RIS在高频通信感知一体化中的关键技术细节。
<think>我们被要求检查SQL查询语句是否存在语法或逻辑错误,并了解如何正确统计特定日期范围内每天活跃用户的去重数量。 用户提供的SQL语句是: Select count(distinct user_id) from user_log where active=1 and login_date between '2025-05-01' and '2025-05-31' group by login_date 分析: 1. 语法检查: - SELECT子句:使用了聚合函数count(distinct user_id)是正确的。 - FROM子句:表名为user_log,假设存在。 - WHERE子句:条件为active=1(表示活跃用户)和login_date在指定日期范围内。注意:日期范围是闭区间,包含两端。 - GROUP BY子句:按login_date分组,即每天一组。 2. 逻辑检查: - 目标:统计每天去重的活跃用户数。 - 使用count(distinct user_id)可以确保对同一天内重复登录的用户只计算一次。 - 但是,这里有一个潜在问题:如果某一天没有用户登录,那么结果中将不会出现该天的记录(因为GROUP BY只会生成有数据的组)。如果希望显示整个日期范围内每一天(包括没有活跃用户的日子),则需要使用日期维度表或者生成日期序列。 3. 日期范围问题: - 用户指定的日期范围是2025-05-01到2025-05-31(5月共31天)。 - 当前查询只会返回在user_log表中有登录记录的那些天。 4. 改进建议: - 如果需要显示所有日期(即使没有活跃用户),则需要连接一个日期表(date_dimension)或者使用递归生成日期序列(在MySQL 8.0+中可以使用递归CTE)。 - 示例(使用日期表): SELECT d.date, COUNT(DISTINCT l.user_id) AS active_users FROM date_dimension d LEFT JOIN user_log l ON d.date = l.login_date AND l.active = 1 AND d.date BETWEEN '2025-05-01' AND '2025-05-31' WHERE d.date BETWEEN '2025-05-01' AND '2025-05-31' GROUP BY d.date ORDER BY d.date; - 如果没有日期表,可以使用递归生成日期序列(MySQL 8.0+): WITH RECURSIVE dates(date) AS ( SELECT '2025-05-01' UNION ALL SELECT date + INTERVAL 1 DAY FROM dates WHERE date < '2025-05-31' ) SELECT d.date, COUNT(DISTINCT l.user_id) AS active_users FROM dates d LEFT JOIN user_log l ON d.date = l.login_date AND l.active = 1 GROUP BY d.date ORDER BY d.date; 5. 原查询的潜在性能问题: - 当数据量很大时,对每天进行distinct计算可能会比较慢。可以考虑在(user_id, login_date)上建立索引,或者使用预聚合(如物化视图)。 6. 关于引用内容的说明: - 引用[1]中提到count(字段)会忽略null值,而这里我们使用的是count(distinct user_id),如果user_id为null,则不会被计数(因为distinct会排除null,且count不计null)。但通常user_id不应为null,所以问题不大。 - 引用[2]中提到的sql_mode=only_full_group_by问题:在原始查询中,我们按login_date分组,并且select子句中只有聚合函数和分组字段(login_date虽然没有直接写出来,但是被隐式包含在group by中,但MySQL允许在group by中直接使用分组字段而不在select中列出,不过这里我们select中只有聚合函数,所以不会出现非聚合列的问题)。但是,如果我们想同时选择login_date,那么需要明确写出分组字段。原查询没有选择login_date,所以结果中每天只有活跃用户数,而没有日期。因此,我们通常会在select中加上分组字段,以便知道是哪一天。 修正后的查询(如果不需要显示所有日期,只显示有数据的日期): SELECT login_date, COUNT(DISTINCT user_id) AS active_users FROM user_log WHERE active=1 AND login_date BETWEEN '2025-05-01' AND '2025-05-31' GROUP BY login_date ORDER BY login_date; 这样修改后,我们就能在结果中看到每天的日期和对应的活跃用户数。 总结: 原查询语法正确,逻辑上也能实现“统计有登录记录的每一天的活跃用户数”,但如果需要覆盖整个日期范围(包括没有登录记录的日子),则需要使用日期表或生成日期序列。 另外,注意原查询没有选择login_date字段,导致结果中只有一列(活跃用户数),而不知道对应的日期。因此,建议在SELECT子句中添加login_date。 关于引用[3]:提到去重后的count,这里我们使用了count(distinct)是正确的。 最终,我们给出两个版本的查询: 版本1(原查询修正,显示日期): SELECT login_date, COUNT(DISTINCT user_id) AS active_users FROM user_log WHERE active=1 AND login_date BETWEEN '2025-05-01' AND '2025-05-31' GROUP BY login_date ORDER BY login_date; 版本2(包含所有日期,使用递归CTE,MySQL 8.0+): WITH RECURSIVE dates (date) AS ( SELECT '2025-05-01' UNION ALL SELECT date + INTERVAL 1 DAY FROM dates WHERE date < '2025-05-31' ) SELECT d.date AS login_date, COUNT(DISTINCT l.user_id) AS active_users FROM dates d LEFT JOIN user_log l ON d.date = l.login_date AND l.active = 1 GROUP BY d.date ORDER BY d.date; 注意:在版本2中,我们使用了LEFT JOIN,所以即使没有登录记录的日期也会显示(活跃用户数为0)。 另外,在版本2中,我们注意在LEFT JOIN的条件中,除了日期匹配,还附加了active=1(这是为了确保只统计活跃用户)。这样处理比在WHERE子句中过滤更合理,因为WHERE子句过滤会排除没有匹配的记录(而LEFT JOIN需要保留这些记录)。 如果使用MySQL 5.7或更低版本,不支持递归CTE,那么可以考虑创建一张日期表,或者用其他方式生成日期序列(如使用一个包含足够多日期的表,或者用UNION ALL手动列出所有日期)。 因此,根据用户的需求(是否要求显示所有日期)和数据库环境,选择不同的查询方式。</think>### SQL查询分析与优化 您的SQL查询语句**语法正确**,但存在逻辑优化空间。以下是分析和优化建议: ```sql -- 优化后的查询 SELECT login_date, COUNT(DISTINCT user_id) AS daily_active_users FROM user_log WHERE active = 1 AND login_date BETWEEN '2025-05-01' AND '2025-05-31' GROUP BY login_date ORDER BY login_date; ``` #### 关键改进点: 1. **添加日期字段显示** 原始查询只返回每天的用户数,未显示具体日期。添加`login_date`字段使结果更清晰[^1]。 2. **结果排序优化** 添加`ORDER BY login_date`确保日期按时间顺序排列,便于分析趋势。 3. **别名增强可读性** 使用`daily_active_users`作为列别名,提高结果可读性。 4. **处理NULL值问题** 如果`user_id`存在NULL值: ```sql COUNT(DISTINCT CASE WHEN user_id IS NOT NULL THEN user_id END) ``` - `COUNT(字段)`忽略NULL值[^1] - 当`user_id`为NULL时不会被计入统计 #### 性能优化建议: 1. **索引优化** 创建复合索引加速查询: ```sql CREATE INDEX idx_active_date ON user_log(active, login_date, user_id); ``` 2. **大数据量分页** 当数据量极大时(>1000万行): ```sql SELECT /*+ MAX_EXECUTION_TIME(3000) */ login_date, COUNT(DISTINCT user_id) FROM ... ``` 3. **日期范围处理** 更精确的日期范围写法: ```sql login_date >= '2025-05-01' AND login_date < '2025-06-01' ``` - 避免BETWEEN可能出现的边界问题 - 兼容不同数据库的日期处理差异 #### 特殊场景处理: 1. **需要包含所有日期(即使无活跃用户)** ```sql WITH RECURSIVE dates(date) AS ( SELECT '2025-05-01' UNION ALL SELECT date + INTERVAL 1 DAY FROM dates WHERE date < '2025-05-31' ) SELECT d.date AS login_date, COUNT(DISTINCT l.user_id) AS daily_active_users FROM dates d LEFT JOIN user_log l ON d.date = l.login_date AND l.active = 1 GROUP BY d.date; ``` 2. **避免ONLY_FULL_GROUP_BY错误**[^2] ```sql -- 临时关闭严格模式 SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'; ``` #### 执行计划验证: 使用`EXPLAIN`分析查询性能: ```sql EXPLAIN FORMAT=JSON SELECT ... -- 您的查询语句 ``` 关注以下指标: - `using_filesort`:是否使用文件排序 - `using_index`:是否使用索引覆盖 - `rows_examined`:扫描行数 ### 最终建议方案 ```sql /* 最优方案 */ SELECT DATE_FORMAT(login_date, '%Y-%m-%d') AS login_date, -- 标准化日期格式 COUNT(DISTINCT user_id) AS active_user_count FROM user_log WHERE active = 1 AND login_date >= '2025-05-01' AND login_date < DATE_ADD('2025-05-01', INTERVAL 1 MONTH) -- 动态计算结束日期 GROUP BY login_date ORDER BY login_date ASC; ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值