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 必須完整。不過在大多數瀏覽器中,兩種形式均可以正常使用。

相關文章
相關標籤/搜索