devise 小项目(一)

Devise源于Warden,而warden是一个基于Rack的验证权限gem,不过,使用devise实际并不须要任何关于warden的知识。javascript

若是你以前有一些其余相似的维护验证权限功能的gem的使用经验的话,你会发现Devise的和他们的不一样之处在于,提供了从页面到model的实现。相比而言,例如Authlogic就只实现了与model层的实现,这时你就要本身去处理view层实现。而Devise是基于Rails 引擎开发的因此就能够同时提供controllers和view的实现。从功能角度来看,Devise提供了11个方面的在维护和验证权限过程的功能模 块,这些模块都是可配置的。html

Devise is a flexible authentication solution for Rails based on Warden. It:java

  • Is Rack based;
  • Is a complete MVC solution based on Rails engines;
  • Allows you to have multiple models signed in at the same time;
  • Is based on a modularity concept: use only what you really need.

It's composed of 10 modules:jquery

  • Database Authenticatable: encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication.
  • Omniauthable: adds OmniAuth (https://github.com/intridea/omniauth) support.
  • Confirmable: sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in.
  • Recoverable: resets the user password and sends reset instructions.
  • Registerable: handles signing up users through a registration process, also allowing them to edit and destroy their account.
  • Rememberable: manages generating and clearing a token for remembering the user from a saved cookie.
  • Trackable: tracks sign in count, timestamps and IP address.
  • Timeoutable: expires sessions that have not been active in a specified period of time.
  • Validatable: provides validations of email and password. It's optional and can be customized, so you're able to define your own validations.
  • Lockable: locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period.

Devise is guaranteed to be thread-safe on YARV. Thread-safety support on JRuby is in progress.git

1.基于Rackgithub

  2.是一个基于Rails引擎的完整MVC解决方案web

  3.容许多个模块同时登录spring

  4.基于模块化的概念:只使用你须要的sql

它由10个模块组成:数据库

  1.数据库验证:注册信息的同时将密码加密而且储存在数据库中以便于身份验证,不管提交POST请求仍是HTTP基自己份验证的状况下都支持。

  2.Omniauthable验证:添加了OmniAuth(https://github.com/intridea/omniauth)身份验证。

  3.邮件确认:在登录时发送验证邮件确认邮件已被确认。

  4.重获密码:从新设置密码而且发送重设密码邮件

  5.注册:控制已注册用户的功能,已注册用户能够编辑和删除他们的帐户。

  6.记忆cookie功能:管理建立和清楚用户已保存的cookie的记忆令牌。

  7.可追踪的:追踪登录次数,时间以及IP地址。

  8.会话超时管理:在特定的时间内会话到期。

  9.验证信息:提供验证邮件和密码。此功能是可选择和定制的,因此你能够定义你本身须要的验证。

  10.可锁定的:在指定数量的失败登录后锁定帐户,能够经过限定时间或者邮件验证解锁帐户。

Devise在YARV虚拟机上是第三方安全的,在Jruby上第三方安全正在进行中。

1.先建立应用

cd workspace
rails _4.2.0_ new sample_device --skip-bundle(因为会自动检查更新,因此取消更好)
cd sample_device
bundle install --local

 2.若是你以前安装了某个 gem(例如
Rails 自己)的其余版本,和 Gemfile 中指定的版本号不一样,最好再执行 bundle update 命令,更新 gem,确
保安装的版本和指定的一致,运行

bundle update #应该是bundle update会去检查Gemfile里gem的更新,而后对比lock文件,若是Gemfile里没有指定版本或是指定是>=的版本,那有新版本就会去安装新的版本的gem,而后更新lock文件。
        #而bundle install以Lock文件为优先,为本地系统安装Lock文件中指定的版本,而去检查Gemfile中有而Lock中没有的,安装之。Install好像不去管网络中Gem版本的更新。

3.登录bitbucket建立仓库,而后初始化git仓库

git init
git add -A
git commit -m "Init repository"

 将README.rdoc改成README.md(markdown格式)

git mv README.rodc README.md

 提交改动

git commit -am "Improve README"

 把代码推送到bitbucket

git remote add origin git@bitbucket:yz00/sample_devise.git
git push -u origin --all

 使用 Git 时最好在单独的主题分支中完成工做,so创建新的分支

git co master
git co -b devise-init

 4.在Gemfile里面添加,全部gem以下

source 'https://rubygems.org'


# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc

# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
#
gem 'devise'
gem 'omniauth', '1.2.2'
gem 'bootstrap-sass'
# Use Unicorn as the app server
# gem 'unicorn'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug'

  # Use sqlite3 as the database for Active Record
  gem 'sqlite3'

  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'

  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
end
group :production do
  #use postgresql as the database for Active Record
  gem 'pg'
  #Makes running your Rails app easier
  gem 'rails_12factor'
end

 而后安装

bundle install

初始化devise

rails generate devise:install

因为devise用的rails引擎,支持generate

$ rails generate devise User    #注意大写
      invoke  active_record
      create    app/models/user.rb    #生成user模型
      invoke    test_unit        #测试部分
      create      test/unit/user_test.rb
      create      test/fixtures/users.yml
      inject  app/models/user.rb    
      create  db/migrate/20150605114421_devise_create_users.rb       #生成migration
       route  devise_for :users

 而后咱们来看看文件里都有什么

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
   #:lockable
  devise :database_authenticatable, :registerable,   #数据库验证,注册拥有的功能
         :confirmable, :timeoutable,:omniauthable,  #注册邮件验证,登录超时,OmniAuth第三方验证
         :recoverable, :rememberable, :trackable, :validatable  #修改密码发送验证邮件,记忆cookies,追踪功能,登录验证
end

 20150605114421_devise_create_users

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|    #创建user表
      ## Database authenticatable
      t.string :email,              null: false, default: ""    #邮件不能为空,默认为“”
      t.string :encrypted_password, null: false, default: ""    #加密的密码不能为空,默认为“”

      ## Recoverable
      t.string   :reset_password_token                #重置密码的令牌
      t.datetime :reset_password_sent_at               #重置的时间

      ## Rememberable
      t.datetime :remember_created_at                  #记忆令牌创建时间

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false       #登录次数不能为空,默认为0
      t.datetime :current_sign_in_at                  #本次登录时间
      t.datetime :last_sign_in_at                    #上次登录时间
      t.string   :current_sign_in_ip                  #本次登录IP
      t.string   :last_sign_in_ip                    #上次登录IP

      ## Confirmable
       t.string   :confirmation_token            #注册邮件令牌
       t.datetime :confirmed_at                #注册时间
       t.datetime :confirmation_sent_at            #收到邮件验证时间
       t.string   :unconfirmed_email # Only if using reconfirmable    #未验证的邮件,只在再次确认时使用

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false      #时间戳
    end

    add_index :users, :email,                unique: true    #邮件的索引
    add_index :users, :reset_password_token, unique: true    #重置密码的索引
    add_index :users, :confirmation_token,   unique: true    #邮件确认的令牌索引
    # add_index :users, :unlock_token,         unique: true
  end
end

创建数据库

bundel exec rake db:migrate
# bundle exec rake db:rollback  撤销上面的命令
# bundle exec rake db:migrate VERSION=0 回到最初的版本

看看数据库里有什么,users表都创建好了,以后自动添加了id属性

 

再来看看路由里面有啥:

rake routes
                  Prefix Verb     URI Pattern                            Controller#Action
        new_user_session GET      /users/sign_in(.:format)               devise/sessions#new      #获取登录页面
            user_session POST     /users/sign_in(.:format)               devise/sessions#create    #提交登录页面
    destroy_user_session DELETE   /users/sign_out(.:format)              devise/sessions#destroy    #退出登录
 user_omniauth_authorize GET|POST /users/auth/:provider(.:format)        devise/omniauth_callbacks#passthru {:provider=>/(?!)/}    #第三方验证验证
  user_omniauth_callback GET|POST /users/auth/:action/callback(.:format) devise/omniauth_callbacks#:action      #第三方验证回调  
           user_password POST     /users/password(.:format)              devise/passwords#create          #提交密码
       new_user_password GET      /users/password/new(.:format)          devise/passwords#new            #返回页面
      edit_user_password GET      /users/password/edit(.:format)         devise/passwords#edit           #获取修改密码
                         PATCH    /users/password(.:format)              devise/passwords#update          #更新密码
                         PUT      /users/password(.:format)              devise/passwords#update          #替换密码(区别请看http://www.web-tinker.com/article/20707.html)
cancel_user_registration GET      /users/cancel(.:format)                devise/registrations#cancel        #取消注册
       user_registration POST     /users(.:format)                       devise/registrations#create        #提交注册
   new_user_registration GET      /users/sign_up(.:format)               devise/registrations#new          #获取注册
  edit_user_registration GET      /users/edit(.:format)                  devise/registrations#edit          #获取编辑注册信息
                         PATCH    /users(.:format)                       devise/registrations#update        #更新注册此信息
                         PUT      /users(.:format)                       devise/registrations#update        #替换注册信息
                         DELETE   /users(.:format)                       devise/registrations#destroy        #删除帐户
       user_confirmation POST     /users/confirmation(.:format)          devise/confirmations#create        #提交邮件验证
   new_user_confirmation GET      /users/confirmation/new(.:format)      devise/confirmations#new          #建立邮件验证
                         GET      /users/confirmation(.:format)          devise/confirmations#show         #跳转页面
                    root GET      /                                      home#index                  #首页

 建立home,help页面

rails  g controller index help #能够撤销此命令(rails destroy controller Home index help)

 如今启动 rails application

rails s

添加首页内的代码

home/index.html.erb

<% provide(:title, "Home") %>
<h1>Age Home</h1>
<p>Age Time</p>

 修改layouts/application.html.erb

<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
<%= stylesheet_link_tag  'application', media: 'all',
                                       'data-turbolinks-track' => true %>    
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    #引入应用的样式表和 JavaScript 文件,Asset Pipeline 的一部分
<%= csrf_meta_tags %>                                  #Rails 中的 csrf_meta_tags 方法,做用是避免“跨站请求伪造”
</head>
<body>
    <%= yield %>
</body>
</html>

 添加helpers/application_helper.eb,rails会帮助咱们把辅助方法的模块引入其余类中。

module ApplicationHelper
    def full_title(page_title = '')
        base_title = "Age"
        if page_title.empty?
            base_title
        else
            page_title + " | "+ base_title
        end
    end
end

 

添加测试技术

test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'  
require "minitest/reporters"           #利用minitest-reporters技术
Minitest::Reporters.use!        #添加颜色显示
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical
# order.
fixtures :all
# Add more helper methods to be used by all tests here...
end

 调用跟踪静默程序

config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't
# wish to see in your backtraces.
Rails.backtrace_cleaner.add_silencer { |line| line =~ /rvm/ }
# You can also remove all the silencers if you're trying to debug a problem
# that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

 使用 rspec BDD测试

引用解释:

RSpec是一套Ruby的測試DSL(Domain-specific language)框架,它的程式比Test::Unit更好讀,寫的人更容易描述測試目的,能够說是一種可執行的規格文件。也 很是多的Ruby on Rails專案採用RSpec做為測試框架。它又稱為一種BDD(Behavior-driven development)測試框架,相較於TDDtest思維,測試程式的結果。BDD強調的是用spec思維,描述程式應該有什麼行為。

安装rspec

/Gemfile

group :test, :development do
  gem "rspec"
  gem "rspec-rails"
end

gem install rspec
Fetching: rspec-support-3.2.2.gem (100%)
Successfully installed rspec-support-3.2.2
Fetching: rspec-core-3.2.3.gem (100%)
Successfully installed rspec-core-3.2.3
Fetching: rspec-expectations-3.2.1.gem (100%)
Successfully installed rspec-expectations-3.2.1
Fetching: rspec-mocks-3.2.1.gem (100%)
Successfully installed rspec-mocks-3.2.1
Fetching: rspec-3.2.0.gem (100%)
Successfully installed rspec-3.2.0
5 gems installed




$bundle install --binstubs #这会创建一个bin目录包含全部Gemfile里面用的执行档。 安装: $rails generate rspec:install #bin/rspec --init

 如今测试装好了

添加背景图片

 Rails 会使用 Asset Pipeline自动在 app/assets/images/文件夹中寻找图片。

随意打开一个网站选择图片,而后点击邮件,view page source

cd images
wget https://cdn.apstudynotes.org/images/hero/amjed.jpg

修改图片权限

cd ..
chmod -R 777 images

 添加jquery-anystretch

mkdir js
cd js 
wget https://raw.githubusercontent.com/danmillar/jquery-anystretch/master/jquery.anystretch.min.js

 再去jquery.com/download 添加要用的方法

在head标签中添加
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script> <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script src="js/jquery.anystretch.min.js"></script>

 只有重定向使用 _url 形式,其他都使用 _path 形式。(由于 HTTP 标准严格要求重定向的 URL 必须完整。不过在大多数浏览器中,两种形式均可以正常使用。

相关文章
相关标签/搜索