diff --git a/.travis.yml b/.travis.yml index 03e783e..a22b46b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,9 @@ language: ruby rvm: - 2.0.0 - 2.1.0 +branches: + only: + - master gemfile: - Gemfile script: bundle exec rake spec diff --git a/CHANGELOG.md b/CHANGELOG.md index f256517..f2175ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,35 @@ +## 0.2.0 + +Remake the this library. + +#### Upgrade + +1. Run the following commands. + +``` +$ bundle update passwd +$ bundle exec rails gneratate passwd:config +``` + +2. Migrate your passwd settings to `config/initializers/passwd.rb`. +3. Updates your code! + +#### Changes + +- Add extention to ActiveController. + - Add `current_user`, `signin!` and `signout!` to ActionController. + - Add `require_signin` method for `before_action`. +- Include the `Passwd::ActiveRecord` was no longer needed. +- Rename method `define_column` to `with_authenticate` in your User model. +- Rename method `Passwd.create` to `Passwd.random`. +- Rename method `Passwd.hashing` to `Passwd.digest`. +- Add `passwd` method User class. Create Passwd::Password object from target user attributes. +- Split object password and salt. + ## 0.1.5 -Features: +#### Changes - Can be specified algorithm of hashing - Change default hashing algorithm to SHA512 from SHA1 + diff --git a/LICENSE.txt b/LICENSE.txt index be47849..737eabd 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,4 +1,4 @@ -Copyright (c) 2013 i2bskn +Copyright (c) 2013-2014 i2bskn MIT License @@ -20,3 +20,4 @@ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/README.md b/README.md index 0941d7b..4138747 100644 --- a/README.md +++ b/README.md @@ -1,230 +1,170 @@ # Passwd -[![Gem Version](https://badge.fury.io/rb/passwd.png)](http://badge.fury.io/rb/passwd) -[![Build Status](https://travis-ci.org/i2bskn/passwd.png?branch=master)](https://travis-ci.org/i2bskn/passwd) -[![Coverage Status](https://coveralls.io/repos/i2bskn/passwd/badge.png?branch=master)](https://coveralls.io/r/i2bskn/passwd?branch=master) -[![Code Climate](https://codeclimate.com/github/i2bskn/passwd.png)](https://codeclimate.com/github/i2bskn/passwd) +[![Gem Version](https://badge.fury.io/rb/passwd.svg)](http://badge.fury.io/rb/passwd) +[![Build Status](https://travis-ci.org/i2bskn/passwd.svg?branch=master)](https://travis-ci.org/i2bskn/passwd) +[![Coverage Status](https://img.shields.io/coveralls/i2bskn/passwd.svg)](https://coveralls.io/r/i2bskn/passwd?branch=master) +[![Code Climate](https://codeclimate.com/github/i2bskn/passwd/badges/gpa.svg)](https://codeclimate.com/github/i2bskn/passwd) -Password utilities. +Password utilities and integration to Rails. ## Installation Add this line to your application's Gemfile: ```ruby -gem 'passwd' +gem "passwd" ``` And then execute: $ bundle -Or install it yourself as: - - $ gem install passwd - ## Usage -```ruby -require 'passwd' -``` +### ActiveRecord with Rails -### Create random password +Add authentication to your `User` model. +Model name is `User` by default, but can be changed in configuration file. ```ruby -password = Passwd.create +class User < ActiveRecord::Base + with_authenticate +end ``` -### Hashing password +#### Options -Hashing with SHA1. +User model The following column are required. +Column name can be changed with the specified options. -```ruby -password_hash = Passwd.hashing(password) -``` - -### Password settings +- `:id => :email` Unique value to be used for authentication. +- `:salt => :salt` Column of String to save the salt. +- `:password => :password` Column of String to save the hashed password. -Default config is stored in the class instance variable. -Changing the default configs are as follows: +Use the `name` column as id. ```ruby -Passwd.config # => Get config object. -Passwd.config(length: 10) # => Change to the default length. - -Passwd.configure do |c| - c.algorithm = :sha512 - c.length = 10 +class User < ActiveRecord::Base + with_authenticate id: :name end ``` -Options that can be specified: - -* :algorithm => Hashing algorithm. default is :sha512. -* :length => Number of characters. default is 8. -* :lower => Skip lower case if set false. default is true. -* :upper => Skip upper case if set false. default is true. -* :number => Skip numbers if set false. default is true. -* :letters_lower => Define an array of lower case. default is ("a".."z").to_a -* :letters_upper => Define an array of upper case. default is ("A".."Z").to_a -* :letters_number => Define an array of numbers. default is ("0".."9").to_a +#### Authenticate -### Policy check - -Default policy is 8 more characters and require lower case and require number. +`authenticate` method is available in both instance and class. +Returns user object if the authentication successful. +Returns nil if authentication fails or doesn't exists user. +Instance method is not required `id`. ```ruby -Passwd.policy_check("secret") # => true or false +user = User.authenticate(params[:email], params[:password]) # => return user object or nil. +user.authenticate(params[:password]) ``` -### Policy settings +`set_password` method will be set random password. +To specify password as an argument if you want to specify a password. ```ruby -Passwd.policy_configure do |c| - c.min_length = 10 -end -``` - -Options that can be specified: - -* :min_length => Number of minimum characters. default is 8. -* :require_lower => Require lower case if set true. default is true. -* :require_upper => Require upper case if set true. default is false. -* :require_number => Require number if set true. default is true. +current_user.set_password("secret") # => random password if not specified a argument. +current_user.passwd.plain # => new password +current_user.save -### Password object +new_user = User.new +password = new_user.passwd.plain +UserMailer.register(new_user, password).deliver! +``` -Default password is randomly generated. -Default salt is "#{Time.now.to_s}". +`update_password` method will be set new password if the authentication successful. +But `update_password` method doesn't call `save` method. ```ruby -password = Passwd::Password.new -password.text # return text password. -password.salt_text # return text salt. -password.salt_hash # return hash salt. -password.hash # return hash password. +# update_password(OLD_PASSWORD, NEW_PASSWORD[, POLICY_CHECK=false]) +current_user.update_password(old_pass, new_pass, true) +current_user.save ``` -Options that can be specified: - -* :password => Text password. default is random. -* :salt_text => Text salt. default is #{Time.now.to_s}. +#### Policy check -Password authenticate: +Default policy is 8 more characters and require lower case and require number. +Can be changed in configuration file. ```ruby -password = Passwd::Password.new -Passwd.auth(password.text, password.salt_hash, password.hash) # => true -Passwd.auth("invalid!!", password.salt_hash, password.hash) # => false - -password == password.text # => true -password == "invalid!!" # => false +Passwd.policy_check("secret") # => true or false ``` -## For ActiveRecord +### ActionController -### User model +Already several methods is available in your controller. -Include `Passwd::ActiveRecord` module and define id/salt/password column from `define_column` method. -`id` column is required uniqueness. +If you want to authenticate the application. +Unauthorized access is thrown exception. +Can be specified to redirect in configuration file. ```ruby -class User < ActiveRecord::Base - include Passwd::ActiveRecord - # if not specified arguments for define_column => {id: :email, salt: :salt, password: :password} - define_column id: :id_colname, salt: :salt_colname, password: :password_colname - - ... +class ApplicationController < ActionController::Base + before_action :require_signin end ``` -Available following method by defining id/salt/password column. - -### Authentication - -`authenticate` method is available in both instance and class. -Return the user object if the authentication successful. -Return the nil if authentication fails or doesn't exists user. +If you want to implement the session management. ```ruby -user = User.authenticate(params[:email], params[:password]) # => return user object or nil. - -if user - session[:user] = user.id - redirect_to bar_path, notice: "Hello #{user.name}!" -else - flash.now[:alert] = "Authentication failed" - render action: :new +class SessionsController < ApplicationController + # If you has been enabled `require_signin` in ApplicationController + skip_before_action :require_signin + + # GET /signin + def new; end + + # POST /signin + def create + # Returns nil or user + @user = User.authenticate(params[:email], params[:password]) + + if @user + # Save user_id to session + signin!(@user) + redirect_to some_url, notice: "Signin was successful. Hello #{current_user.name}" + else # Authentication fails + render action: :new + end + end + + # DELETE /signout + def destroy + # Clear session (Only user_id) + signout! + redirect_to some_url + end end ``` -instance method is not required `id`. +`current_user` method available if already signin. ```ruby -current_user = User.find(session[:user]) - -if current_user.authenticate(params[:password]) # => return true or false - # some process - redirect_to bar_path, notice: "Some process is successfully" -else - flash.now[:alert] = "Authentication failed" - render action: :edit +# app/controllers/greet_controller.rb +def greet + render text: "Hello #{current_user.name}!!" end -``` -### Change passowrd +# app/views/greet/greet.html.erb +

Hello <%= current_user.name %>!!

+``` -`set_password` method will be set random password. -Return value is plain text password. -To specify the password as an argument if you want to specify a password. -`salt` also set if salt is nil. +### Generate configuration file -```ruby -current_user = User.find(session[:user]) -password_text = current_user.set_password +Run generator of Rails. +Configuration file created to `config/initializers/passwd.rb`. -if current_user.save - redirect_to bar_path, notice: "Password update successfully" -else - render action: :edit -end ``` - -`update_password` method will be set new password if the authentication successful. -But `update_password` method doesn't call `save` method. - -```ruby -current_user = User.find(session[:user]) - -begin - Passwd.confirm_check(params[:password], params[:password_confirmation]) - # update_password(OLD_PASSWORD, NEW_PASSWORD[, POLICY_CHECK=false]) - current_user.update_password(old_pass, new_pass, true) - current_user.save! - redirect_to bar_path, notice: "Password updated successfully" -rescue Passwd::PasswordNotMatch - # PASSWORD != PASSWORD_CONFIRMATION from Passwd.#confirm_check - flash.now[:alert] = "Password not match" - render action: :edit -rescue Passwd::AuthError - # Authentication failed from #update_password - flash.now[:alert] = "Password is incorrect" - render action: :edit -rescue Passwd::PolicyNotMatch - # Policy not match from #update_password - flash.now[:alert] = "Policy not match" - render action: :edit -rescue - # Other errors - flash.now[:alert] = "Password update failed" - render action: :edit -end +$ bundle exec rails generate passwd:config ``` ## Contributing -1. Fork it +1. Fork it ( https://github.com/i2bskn/passwd/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Added some feature'`) +3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request +5. Create a new Pull Request + diff --git a/Rakefile b/Rakefile index 25e1c41..1724416 100644 --- a/Rakefile +++ b/Rakefile @@ -7,3 +7,4 @@ RSpec::Core::RakeTask.new(:spec) do |t| end task :default => :spec + diff --git a/example/.gitignore b/example/.gitignore new file mode 100644 index 0000000..6a502e9 --- /dev/null +++ b/example/.gitignore @@ -0,0 +1,16 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore the default SQLite database. +/db/*.sqlite3 +/db/*.sqlite3-journal + +# Ignore all logfiles and tempfiles. +/log/*.log +/tmp diff --git a/example/Gemfile b/example/Gemfile new file mode 100644 index 0000000..9471824 --- /dev/null +++ b/example/Gemfile @@ -0,0 +1,25 @@ +source 'https://rubygems.org' + + +# Bundle edge Rails instead: gem 'rails', github: 'rails/rails' +gem 'rails', '4.1.8' +# Use sqlite3 as the database for Active Record +gem 'sqlite3' +# Use SCSS for stylesheets +gem 'sass-rails', '~> 4.0.3' +# Use Uglifier as compressor for JavaScript assets +gem 'uglifier', '>= 1.3.0' +# Use CoffeeScript for .js.coffee assets and views +gem 'coffee-rails', '~> 4.0.0' + +# Use jquery as the JavaScript library +gem 'jquery-rails' +# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder +gem 'jbuilder', '~> 2.0' + +gem 'passwd', path: File.expand_path("../..", __FILE__) + +group :development do + gem 'pry-rails' +end + diff --git a/example/README.rdoc b/example/README.rdoc new file mode 100644 index 0000000..dd4e97e --- /dev/null +++ b/example/README.rdoc @@ -0,0 +1,28 @@ +== README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... + + +Please feel free to use a different markup language if you do not plan to run +rake doc:app. diff --git a/example/Rakefile b/example/Rakefile new file mode 100644 index 0000000..ba6b733 --- /dev/null +++ b/example/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require File.expand_path('../config/application', __FILE__) + +Rails.application.load_tasks diff --git a/example/app/assets/images/.keep b/example/app/assets/images/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/assets/javascripts/application.js b/example/app/assets/javascripts/application.js new file mode 100644 index 0000000..06353a5 --- /dev/null +++ b/example/app/assets/javascripts/application.js @@ -0,0 +1,16 @@ +// This is a manifest file that'll be compiled into application.js, which will include all the files +// listed below. +// +// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, +// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. +// +// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the +// compiled file. +// +// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details +// about supported directives. +// +//= require jquery +//= require jquery_ujs +//= require_tree . + diff --git a/example/app/assets/stylesheets/application.css b/example/app/assets/stylesheets/application.css new file mode 100644 index 0000000..9499f25 --- /dev/null +++ b/example/app/assets/stylesheets/application.css @@ -0,0 +1,16 @@ +/* + * This is a manifest file that'll be compiled into application.css, which will include all the files + * listed below. + * + * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, + * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * + * You're free to add application-wide styles to this file and they'll appear at the bottom of the + * compiled file so the styles you add here take precedence over styles defined in any styles + * defined in the other CSS/SCSS files in this directory. It is generally better to create a new + * file per style scope. + * + *= require_tree . + *= require_self + */ + diff --git a/example/app/controllers/application_controller.rb b/example/app/controllers/application_controller.rb new file mode 100644 index 0000000..1283d1a --- /dev/null +++ b/example/app/controllers/application_controller.rb @@ -0,0 +1,10 @@ +class ApplicationController < ActionController::Base + # Prevent CSRF attacks by raising an exception. + # For APIs, you may want to use :null_session instead. + protect_from_forgery with: :exception + + # Require authentication all access! + # Specified `skil_before_action` if not authenticate + before_action :require_signin +end + diff --git a/example/app/controllers/concerns/.keep b/example/app/controllers/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/controllers/root_controller.rb b/example/app/controllers/root_controller.rb new file mode 100644 index 0000000..7881449 --- /dev/null +++ b/example/app/controllers/root_controller.rb @@ -0,0 +1,5 @@ +class RootController < ApplicationController + # GET / + def index; end +end + diff --git a/example/app/controllers/sessions_controller.rb b/example/app/controllers/sessions_controller.rb new file mode 100644 index 0000000..e9477cc --- /dev/null +++ b/example/app/controllers/sessions_controller.rb @@ -0,0 +1,29 @@ +class SessionsController < ApplicationController + # If you has been enabled `require_signin` in ApplicationController + skip_before_action :require_signin + + # GET /signin + def new; end + + # POST /signin + def create + # Returns nil or user + @user = User.authenticate(params[:email], params[:password]) + + if @user + # Save user_id to session + signin!(@user) + redirect_to root_url + else # Authentication fails + render action: :new + end + end + + # DELETE /signout + def destroy + # Clear session (Only user_id) + signout! + redirect_to signin_url + end +end + diff --git a/example/app/helpers/application_helper.rb b/example/app/helpers/application_helper.rb new file mode 100644 index 0000000..de6be79 --- /dev/null +++ b/example/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/example/app/mailers/.keep b/example/app/mailers/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/models/.keep b/example/app/models/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/models/concerns/.keep b/example/app/models/concerns/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/app/models/user.rb b/example/app/models/user.rb new file mode 100644 index 0000000..564499a --- /dev/null +++ b/example/app/models/user.rb @@ -0,0 +1,4 @@ +class User < ActiveRecord::Base + with_authenticate +end + diff --git a/example/app/views/layouts/application.html.erb b/example/app/views/layouts/application.html.erb new file mode 100644 index 0000000..017c550 --- /dev/null +++ b/example/app/views/layouts/application.html.erb @@ -0,0 +1,15 @@ + + + + Example + <%= stylesheet_link_tag 'application', media: 'all' %> + <%= javascript_include_tag 'application' %> + <%= csrf_meta_tags %> + + + +<%= yield %> + + + + diff --git a/example/app/views/root/index.html.erb b/example/app/views/root/index.html.erb new file mode 100644 index 0000000..ebc17a1 --- /dev/null +++ b/example/app/views/root/index.html.erb @@ -0,0 +1,4 @@ +

Hello <%= current_user.name %>!!

+ +<%= link_to "Signout!", signout_path, method: :delete, data: { confirm: "Are you sure?" } %> + diff --git a/example/app/views/sessions/new.html.erb b/example/app/views/sessions/new.html.erb new file mode 100644 index 0000000..d16a2cf --- /dev/null +++ b/example/app/views/sessions/new.html.erb @@ -0,0 +1,6 @@ +<%= form_tag create_session_path do %> + <%= email_field_tag :email, @email, placeholder: "E-Mail", required: true %> + <%= password_field_tag :password, nil, placeholder: "Password", required: true %> + <%= submit_tag "Signin" %> +<% end %> + diff --git a/example/bin/bundle b/example/bin/bundle new file mode 100755 index 0000000..66e9889 --- /dev/null +++ b/example/bin/bundle @@ -0,0 +1,3 @@ +#!/usr/bin/env ruby +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +load Gem.bin_path('bundler', 'bundle') diff --git a/example/bin/rails b/example/bin/rails new file mode 100755 index 0000000..728cd85 --- /dev/null +++ b/example/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path('../../config/application', __FILE__) +require_relative '../config/boot' +require 'rails/commands' diff --git a/example/bin/rake b/example/bin/rake new file mode 100755 index 0000000..1724048 --- /dev/null +++ b/example/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative '../config/boot' +require 'rake' +Rake.application.run diff --git a/example/config.ru b/example/config.ru new file mode 100644 index 0000000..5bc2a61 --- /dev/null +++ b/example/config.ru @@ -0,0 +1,4 @@ +# This file is used by Rack-based servers to start the application. + +require ::File.expand_path('../config/environment', __FILE__) +run Rails.application diff --git a/example/config/application.rb b/example/config/application.rb new file mode 100644 index 0000000..4159ee9 --- /dev/null +++ b/example/config/application.rb @@ -0,0 +1,40 @@ +require File.expand_path('../boot', __FILE__) + +# Pick the frameworks you want: +require "active_model/railtie" +require "active_record/railtie" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_view/railtie" +require "sprockets/railtie" +# require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module Example + class Application < Rails::Application + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. + # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. + # config.time_zone = 'Central Time (US & Canada)' + config.time_zone = "Tokyo" + config.active_record.default_timezone = :local + + # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. + # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] + # config.i18n.default_locale = :de + I18n.enforce_available_locales = false + config.i18n.default_locale = :ja + + config.generators do |g| + g.stylesheets false + g.javascripts false + g.helper false + end + end +end diff --git a/example/config/boot.rb b/example/config/boot.rb new file mode 100644 index 0000000..5e5f0c1 --- /dev/null +++ b/example/config/boot.rb @@ -0,0 +1,4 @@ +# Set up gems listed in the Gemfile. +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) + +require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) diff --git a/example/config/database.yml b/example/config/database.yml new file mode 100644 index 0000000..84f572e --- /dev/null +++ b/example/config/database.yml @@ -0,0 +1,26 @@ +# SQLite version 3.x +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem 'sqlite3' +# +default: &default + adapter: sqlite3 + pool: 5 + timeout: 5000 + +development: + <<: *default + database: db/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: ":memory:" + +production: + <<: *default + database: db/production.sqlite3 + diff --git a/example/config/environment.rb b/example/config/environment.rb new file mode 100644 index 0000000..ee8d90d --- /dev/null +++ b/example/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require File.expand_path('../application', __FILE__) + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/example/config/environments/development.rb b/example/config/environments/development.rb new file mode 100644 index 0000000..ddf0e90 --- /dev/null +++ b/example/config/environments/development.rb @@ -0,0 +1,37 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded on + # every request. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Debug mode disables concatenation and preprocessing of assets. + # This option may cause significant delays in view rendering with a large + # number of complex assets. + config.assets.debug = true + + # Adds additional error checking when serving assets at runtime. + # Checks for improperly declared sprockets dependencies. + # Raises helpful error messages. + config.assets.raise_runtime_errors = true + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/example/config/environments/production.rb b/example/config/environments/production.rb new file mode 100644 index 0000000..b93a877 --- /dev/null +++ b/example/config/environments/production.rb @@ -0,0 +1,78 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Enable Rack::Cache to put a simple HTTP cache in front of your application + # Add `rack-cache` to your Gemfile before enabling this. + # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. + # config.action_dispatch.rack_cache = true + + # Disable Rails's static asset server (Apache or nginx will already do this). + config.serve_static_assets = false + + # Compress JavaScripts and CSS. + config.assets.js_compressor = :uglifier + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missed. + config.assets.compile = false + + # Generate digests for assets URLs. + config.assets.digest = true + + # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Set to :debug to see everything in the log. + config.log_level = :info + + # Prepend all log lines with the following tags. + # config.log_tags = [ :subdomain, :uuid ] + + # Use a different logger for distributed setups. + # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.action_controller.asset_host = "http://assets.example.com" + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallbacks = true + + # Send deprecation notices to registered listeners. + config.active_support.deprecation = :notify + + # Disable automatic flushing of the log to improve performance. + # config.autoflush_log = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false +end diff --git a/example/config/environments/test.rb b/example/config/environments/test.rb new file mode 100644 index 0000000..053f5b6 --- /dev/null +++ b/example/config/environments/test.rb @@ -0,0 +1,39 @@ +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true + + # Do not eager load code on boot. This avoids loading your whole application + # just for the purpose of running a single test. If you are using a tool that + # preloads Rails for running tests, you may have to set it to true. + config.eager_load = false + + # Configure static asset server for tests with Cache-Control for performance. + config.serve_static_assets = true + config.static_cache_control = 'public, max-age=3600' + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + + # Raise exceptions instead of rendering exception templates. + config.action_dispatch.show_exceptions = false + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations + # config.action_view.raise_on_missing_translations = true +end diff --git a/example/config/initializers/assets.rb b/example/config/initializers/assets.rb new file mode 100644 index 0000000..d2f4ec3 --- /dev/null +++ b/example/config/initializers/assets.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = '1.0' + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in app/assets folder are already added. +# Rails.application.config.assets.precompile += %w( search.js ) diff --git a/example/config/initializers/backtrace_silencers.rb b/example/config/initializers/backtrace_silencers.rb new file mode 100644 index 0000000..59385cd --- /dev/null +++ b/example/config/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# 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 =~ /my_noisy_library/ } + +# 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! diff --git a/example/config/initializers/cookies_serializer.rb b/example/config/initializers/cookies_serializer.rb new file mode 100644 index 0000000..7a06a89 --- /dev/null +++ b/example/config/initializers/cookies_serializer.rb @@ -0,0 +1,3 @@ +# Be sure to restart your server when you modify this file. + +Rails.application.config.action_dispatch.cookies_serializer = :json \ No newline at end of file diff --git a/example/config/initializers/filter_parameter_logging.rb b/example/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000..4a994e1 --- /dev/null +++ b/example/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Configure sensitive parameters which will be filtered from the log file. +Rails.application.config.filter_parameters += [:password] diff --git a/example/config/initializers/inflections.rb b/example/config/initializers/inflections.rb new file mode 100644 index 0000000..ac033bf --- /dev/null +++ b/example/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end diff --git a/example/config/initializers/mime_types.rb b/example/config/initializers/mime_types.rb new file mode 100644 index 0000000..dc18996 --- /dev/null +++ b/example/config/initializers/mime_types.rb @@ -0,0 +1,4 @@ +# Be sure to restart your server when you modify this file. + +# Add new mime types for use in respond_to blocks: +# Mime::Type.register "text/richtext", :rtf diff --git a/example/config/initializers/passwd.rb b/example/config/initializers/passwd.rb new file mode 100644 index 0000000..3951fe1 --- /dev/null +++ b/example/config/initializers/passwd.rb @@ -0,0 +1,41 @@ +Passwd.configure do |c| + # Password settings + # The following settings are all default values. + + # Hashing algorithm + # Supported algorithm is :md5, :rmd160, :sha1, :sha256, :sha384 and :sha512 + # c.algorithm = :sha512 + + # Random generate password length + # c.length = 8 + + # Number of hashed by stretching + # Not stretching if specified nil. + # c.stretching = nil + + # Character type that is used for password + # c.lower = true + # c.upper = true + # c.number = true +end + +Passwd.policy_configure do |c| + # Minimum password length + # c.min_length = 8 + + # Character types to force the use + # c.require_lower = true + # c.require_upper = false + # c.require_number = true +end + +# Session key for authentication +Rails.application.config.passwd.session_key = :user_id + +# Authentication Model Class +Rails.application.config.passwd.authenticate_class = :User + +# Redirect path when not signin +# E.G. :signin_path # Do not specify ***_url +Rails.application.config.passwd.redirect_to = :signin_path + diff --git a/example/config/initializers/session_store.rb b/example/config/initializers/session_store.rb new file mode 100644 index 0000000..a9d774e --- /dev/null +++ b/example/config/initializers/session_store.rb @@ -0,0 +1,3 @@ +# Be sure to restart your server when you modify this file. + +Rails.application.config.session_store :cookie_store, key: '_example_session' diff --git a/example/config/initializers/wrap_parameters.rb b/example/config/initializers/wrap_parameters.rb new file mode 100644 index 0000000..33725e9 --- /dev/null +++ b/example/config/initializers/wrap_parameters.rb @@ -0,0 +1,14 @@ +# Be sure to restart your server when you modify this file. + +# This file contains settings for ActionController::ParamsWrapper which +# is enabled by default. + +# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. +ActiveSupport.on_load(:action_controller) do + wrap_parameters format: [:json] if respond_to?(:wrap_parameters) +end + +# To enable root element in JSON for ActiveRecord objects. +# ActiveSupport.on_load(:active_record) do +# self.include_root_in_json = true +# end diff --git a/example/config/locales/en.yml b/example/config/locales/en.yml new file mode 100644 index 0000000..0653957 --- /dev/null +++ b/example/config/locales/en.yml @@ -0,0 +1,23 @@ +# Files in the config/locales directory are used for internationalization +# and are automatically loaded by Rails. If you want to use locales other +# than English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t 'hello' +# +# In views, this is aliased to just `t`: +# +# <%= t('hello') %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more, please read the Rails Internationalization guide +# available at http://guides.rubyonrails.org/i18n.html. + +en: + hello: "Hello world" diff --git a/example/config/routes.rb b/example/config/routes.rb new file mode 100644 index 0000000..a1181dc --- /dev/null +++ b/example/config/routes.rb @@ -0,0 +1,12 @@ +Rails.application.routes.draw do + controller :sessions do + get :signin, to: :new, as: :signin + post :signin, to: :create, as: :create_session + delete :signout, to: :destroy, as: :signout + end + + controller :root do + root to: :index + end +end + diff --git a/example/config/secrets.yml b/example/config/secrets.yml new file mode 100644 index 0000000..43a9c00 --- /dev/null +++ b/example/config/secrets.yml @@ -0,0 +1,22 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rake secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: a38276b6c841e220a18cfc6f82463c9f7e6fa24093d7a8d525a7c5870c7f4eb082fe62e149153e8b5e1e43fd7b512f01715107ff3e557484301967c536699841 + +test: + secret_key_base: f9fa283d957fae581da09a284674f9ad4a720c8c93dbc662058d60b1b52e5c32ac3d6db5d9022c462311716f7eee002b6cf24dd0b29000aad673f15798364905 + +# Do not keep production secrets in the repository, +# instead read values from the environment. +production: + secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> diff --git a/example/db/migrate/20141122165914_create_users.rb b/example/db/migrate/20141122165914_create_users.rb new file mode 100644 index 0000000..3793187 --- /dev/null +++ b/example/db/migrate/20141122165914_create_users.rb @@ -0,0 +1,13 @@ +class CreateUsers < ActiveRecord::Migration + def change + create_table :users do |t| + t.string :name + t.string :email + t.string :salt + t.string :password + + t.timestamps + end + end +end + diff --git a/example/db/schema.rb b/example/db/schema.rb new file mode 100644 index 0000000..5a5371b --- /dev/null +++ b/example/db/schema.rb @@ -0,0 +1,25 @@ +# encoding: UTF-8 +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations +# you'll amass, the slower it'll run and the greater likelihood for issues). +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema.define(version: 20141122165914) do + + create_table "users", force: true do |t| + t.string "name" + t.string "email" + t.string "salt" + t.string "password" + t.datetime "created_at" + t.datetime "updated_at" + end + +end diff --git a/example/db/seeds.rb b/example/db/seeds.rb new file mode 100644 index 0000000..4edb1e8 --- /dev/null +++ b/example/db/seeds.rb @@ -0,0 +1,7 @@ +# This file should contain all the record creation needed to seed the database with its default values. +# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). +# +# Examples: +# +# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) +# Mayor.create(name: 'Emanuel', city: cities.first) diff --git a/example/lib/assets/.keep b/example/lib/assets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/lib/tasks/.keep b/example/lib/tasks/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/lib/tasks/user.rake b/example/lib/tasks/user.rake new file mode 100644 index 0000000..b39846d --- /dev/null +++ b/example/lib/tasks/user.rake @@ -0,0 +1,12 @@ +namespace :user do + desc "User create for development" + task :create => :environment do + User.find_or_create_by(email: "develop@example.com") do |u| + u.name = "developer" + u.salt = "fdb4bb5a745232d43874088c8edfcbaf5975d0d1e254016015991f1f3c4fc7061fd2f379b7d1f40504ddd1ff2f5feeb2caa0df895af5cb036b39f53f5ca79b04" + # password => "secret" + u.password = "636641d912523d7868614deed094797bfa3e9d504e0e01ab76ee2c7246555b41ff657169ac1ddbba9972fc324bc48c7fe479c0d2858105300ee203df6aeb53cc" + end + end +end + diff --git a/example/log/.keep b/example/log/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/public/404.html b/example/public/404.html new file mode 100644 index 0000000..b612547 --- /dev/null +++ b/example/public/404.html @@ -0,0 +1,67 @@ + + + + The page you were looking for doesn't exist (404) + + + + + + +
+
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/public/422.html b/example/public/422.html new file mode 100644 index 0000000..a21f82b --- /dev/null +++ b/example/public/422.html @@ -0,0 +1,67 @@ + + + + The change you wanted was rejected (422) + + + + + + +
+
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/public/500.html b/example/public/500.html new file mode 100644 index 0000000..061abc5 --- /dev/null +++ b/example/public/500.html @@ -0,0 +1,66 @@ + + + + We're sorry, but something went wrong (500) + + + + + + +
+
+

We're sorry, but something went wrong.

+
+

If you are the application owner check the logs for more information.

+
+ + diff --git a/example/public/favicon.ico b/example/public/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/example/public/robots.txt b/example/public/robots.txt new file mode 100644 index 0000000..3c9c7c0 --- /dev/null +++ b/example/public/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-agent: * +# Disallow: / diff --git a/example/vendor/assets/javascripts/.keep b/example/vendor/assets/javascripts/.keep new file mode 100644 index 0000000..e69de29 diff --git a/example/vendor/assets/stylesheets/.keep b/example/vendor/assets/stylesheets/.keep new file mode 100644 index 0000000..e69de29 diff --git a/lib/generators/passwd/config_generator.rb b/lib/generators/passwd/config_generator.rb new file mode 100644 index 0000000..83a0cfa --- /dev/null +++ b/lib/generators/passwd/config_generator.rb @@ -0,0 +1,13 @@ +module Passwd + module Generators + class ConfigGenerator < ::Rails::Generators::Base + source_root File.expand_path(File.join(File.dirname(__FILE__), "templates")) + + desc "Create Passwd configuration file" + def create_configuration_file + template "passwd_config.rb", "config/initializers/passwd.rb" + end + end + end +end + diff --git a/lib/generators/passwd/templates/passwd_config.rb b/lib/generators/passwd/templates/passwd_config.rb new file mode 100644 index 0000000..160dfc0 --- /dev/null +++ b/lib/generators/passwd/templates/passwd_config.rb @@ -0,0 +1,41 @@ +Passwd.configure do |c| + # Password settings + # The following settings are all default values. + + # Hashing algorithm + # Supported algorithm is :md5, :rmd160, :sha1, :sha256, :sha384 and :sha512 + # c.algorithm = :sha512 + + # Random generate password length + # c.length = 8 + + # Number of hashed by stretching + # Not stretching if specified nil. + # c.stretching = nil + + # Character type that is used for password + # c.lower = true + # c.upper = true + # c.number = true +end + +Passwd.policy_configure do |c| + # Minimum password length + # c.min_length = 8 + + # Character types to force the use + # c.require_lower = true + # c.require_upper = false + # c.require_number = true +end + +# Session key for authentication +Rails.application.config.passwd.session_key = :user_id + +# Authentication Model Class +Rails.application.config.passwd.authenticate_class = :User + +# Redirect path when not signin +# E.G. :signin_path # Do not specify ***_url +Rails.application.config.passwd.redirect_to = nil + diff --git a/lib/passwd.rb b/lib/passwd.rb index 610ab19..3cbc52c 100644 --- a/lib/passwd.rb +++ b/lib/passwd.rb @@ -3,7 +3,23 @@ require "passwd/version" require "passwd/errors" +require "passwd/policy" +require "passwd/configuration" require "passwd/base" +require "passwd/salt" require "passwd/password" -require "passwd/active_record" +require "passwd/railtie" if defined?(Rails) + +module Passwd + extend Base + extend Configuration::Writable + + def self.policy_check(plain) + Password.from_plain(plain).valid? + end + + def self.match?(plain, salt_hash, hash) + Password.from_hash(hash, salt_hash).match?(plain) + end +end diff --git a/lib/passwd/action_controller_ext.rb b/lib/passwd/action_controller_ext.rb new file mode 100644 index 0000000..750c33a --- /dev/null +++ b/lib/passwd/action_controller_ext.rb @@ -0,0 +1,48 @@ +module Passwd + module ActionControllerExt + extend ActiveSupport::Concern + + included do + helper_method :current_user + end + + def current_user + @current_user ||= auth_class.find_by(id: session[auth_key]) + end + + def signin!(user) + @current_user = user + session[auth_key] = user.id + end + + def signout! + @current_user = session[auth_key] = nil + end + + private + def auth_key + Rails.application.config.passwd.session_key || :user_id + end + + def auth_class + @_auth_class ||= + (Rails.application.config.passwd.authenticate_class || :User).to_s.constantize + end + + def _redirect_path + _to = Rails.application.config.passwd.redirect_to + _to ? Rails.application.routes.url_helpers.send(_to) : nil + end + + def require_signin + unless current_user + if _redirect_path + redirect_to _redirect_path + else + raise UnauthorizedAccess + end + end + end + end +end + diff --git a/lib/passwd/active_record.rb b/lib/passwd/active_record.rb deleted file mode 100644 index acbe20d..0000000 --- a/lib/passwd/active_record.rb +++ /dev/null @@ -1,61 +0,0 @@ -module Passwd - module ActiveRecord - module ClassMethods - def define_column(options={}) - id_name = options.fetch(:id, :email) - salt_name = options.fetch(:salt, :salt) - password_name = options.fetch(:password, :password) - - define_singleton_auth(id_name, salt_name, password_name) - define_instance_auth(id_name, salt_name, password_name) - define_set_password(id_name, salt_name, password_name) - define_update_password(salt_name, password_name) - end - - private - def define_singleton_auth(id_name, salt_name, password_name) - define_singleton_method :authenticate do |id, pass| - user = self.where(id_name => id).first - user if user && Passwd.auth(pass, user.send(salt_name), user.send(password_name)) - end - end - - def define_instance_auth(id_name, salt_name, password_name) - define_method :authenticate do |pass| - Passwd.auth(pass, self.send(salt_name), self.send(password_name)) - end - end - - def define_set_password(id_name, salt_name, password_name) - define_method :set_password do |pass=nil| - password = pass || Passwd.create - salt = self.send(salt_name) || Passwd.hashing("#{self.send(id_name)}#{Time.now.to_s}") - self.send("#{salt_name.to_s}=", salt) - self.send("#{password_name.to_s}=", Passwd.hashing("#{salt}#{password}")) - password - end - end - - def define_update_password(salt_name, password_name) - define_method :update_password do |old_pass, new_pass, policy_check=false| - if Passwd.auth(old_pass, self.send(salt_name), self.send(password_name)) - if policy_check - raise Passwd::PolicyNotMatch, "Policy not match" unless Passwd.policy_check(new_pass) - end - - set_password(new_pass) - else - raise Passwd::AuthError - end - end - end - end - - class << self - def included(base) - base.extend ClassMethods - end - end - end -end - diff --git a/lib/passwd/active_record_ext.rb b/lib/passwd/active_record_ext.rb new file mode 100644 index 0000000..8c4e0d9 --- /dev/null +++ b/lib/passwd/active_record_ext.rb @@ -0,0 +1,65 @@ +module Passwd + module ActiveRecordExt + def with_authenticate(options = {}) + _id_key = options.fetch(:id, :email) + _salt_key = options.fetch(:salt, :salt) + _pass_key = options.fetch(:password, :password) + + _define_passwd(_salt_key, _pass_key) + _define_singleton_auth(_id_key) + _define_instance_auth + _define_set_password(_salt_key, _pass_key) + _define_update_password(_salt_key, _pass_key) + end + + private + def _define_passwd(_salt_key, _pass_key) + define_method :passwd do |cache = true| + return @_passwd if cache && @_passwd + self.reload unless self.new_record? + _salt, _pass = self.send(_salt_key), self.send(_pass_key) + if _salt.present? && _pass.present? + @_passwd = Passwd::Password.from_hash(_pass, _salt) + else + self.set_password + end + end + end + + def _define_singleton_auth(_id_key) + define_singleton_method :authenticate do |_id, _pass| + _condition = Array(_id_key).map {|k| "#{k} = :id"}.join(" OR ") + _user = self.find_by(_condition, id: _id) + _user if _user && _user.passwd.match?(_pass) + end + end + + def _define_instance_auth + define_method :authenticate do |_pass| + self.passwd.match?(_pass) + end + end + + def _define_set_password(_salt_key, _pass_key) + define_method :set_password do |_pass = nil| + _options = _pass ? {plain: _pass} : {} + _passwd = Passwd::Password.new(_options) + self.send("#{_salt_key}=", _passwd.salt.hash) + self.send("#{_pass_key}=", _passwd.hash) + self.instance_variable_set(:@_passwd, _passwd) + end + end + + def _define_update_password(_salt_key, _pass_key) + define_method :update_password do |_old, _new, _policy = false| + raise PolicyNotMatch if _policy && !Passwd.policy_check(_new) + if self.passwd.match?(_old) + self.set_password(_new) + else + raise AuthenticationFails + end + end + end + end +end + diff --git a/lib/passwd/base.rb b/lib/passwd/base.rb index 2a0fe83..686ba9f 100644 --- a/lib/passwd/base.rb +++ b/lib/passwd/base.rb @@ -1,75 +1,31 @@ -require "singleton" -require "passwd/configuration/config" -require "passwd/configuration/tmp_config" -require "passwd/configuration/policy" - module Passwd - @config = Config.instance - @policy = Policy.instance - module Base - def create(options={}) - if options.empty? - config = @config - else - config = TmpConfig.new(@config, options) - end - Array.new(config.length){config.letters[rand(config.letters.size)]}.join - end - - def auth(password_text, salt_hash, password_hash) - enc_pass = Passwd.hashing("#{salt_hash}#{password_text}") - password_hash == enc_pass - end - - def hashing(plain, algorithm=nil) - if algorithm.nil? - eval "Digest::#{@config.algorithm.to_s.upcase}.hexdigest \"#{plain}\"" - else - eval "Digest::#{algorithm.to_s.upcase}.hexdigest \"#{plain}\"" - end + def random(options = {}) + c = PwConfig.merge(options) + Array.new(c.length){c.letters[rand(c.letters.size)]}.join end - def confirm_check(password, confirm, with_policy=false) - raise PasswordNotMatch, "Password not match" if password != confirm - return true unless with_policy - Passwd.policy_check(password) - end + def digest(plain, _algorithm = nil) + _algorithm ||= PwConfig.algorithm - def configure(options={}, &block) - if block_given? - @config.configure &block - else - if options.empty? - @config - else - @config.merge options + if PwConfig.stretching + _pass = plain + PwConfig.stretching.times do + _pass = digest_without_stretching(_pass, _algorithm) end - end - end - alias :config :configure - - def policy_configure(&block) - if block_given? - @policy.configure &block else - @policy + digest_without_stretching(plain, _algorithm) end end - def policy_check(password) - @policy.valid?(password, @config) + def digest_without_stretching(plain, _algorithm = nil) + algorithm(_algorithm || PwConfig.algorithm).hexdigest(plain) end - def reset_config - @config.reset - end - - def reset_policy - @policy.reset - end + private + def algorithm(_algorithm) + Digest.const_get(_algorithm.upcase, false) + end end - - extend Base end diff --git a/lib/passwd/configuration.rb b/lib/passwd/configuration.rb new file mode 100644 index 0000000..d745050 --- /dev/null +++ b/lib/passwd/configuration.rb @@ -0,0 +1,82 @@ +module Passwd + class Configuration + KINDS = %i(lower upper number).freeze + LETTERS = KINDS.map {|k| "letters_#{k}".to_sym}.freeze + + VALID_OPTIONS = [ + :algorithm, + :length, + :policy, + :stretching, + ].concat(KINDS).concat(LETTERS).freeze + + attr_accessor *VALID_OPTIONS + + def initialize + reset + end + + def configure + yield self + end + + def merge(params) + self.dup.merge!(params) + end + + def merge!(params) + params.keys.each do |key| + self.send("#{key}=", params[key]) + end + self + end + + KINDS.each do |kind| + define_method "#{kind}_chars" do + self.send("letters_#{kind}") || [] + end + end + + def letters + KINDS.detect {|k| self.send(k)} || (raise ConfigError, "letters is empry.") + LETTERS.zip(KINDS).map {|l, k| + self.send(l) if self.send(k) + }.compact.flatten + end + + def reset + self.algorithm = :sha512 + self.length = 8 + self.policy = Policy.new + self.stretching = nil + self.lower = true + self.upper = true + self.number = true + self.letters_lower = ("a".."z").to_a + self.letters_upper = ("A".."Z").to_a + self.letters_number = ("0".."9").to_a + end + + module Writable + def self.extended(base) + base.send(:include, Accessible) + end + + def configure(options = {}, &block) + PwConfig.merge!(options) unless options.empty? + PwConfig.configure(&block) if block_given? + end + + def policy_configure(&block) + PwConfig.policy.configure(&block) if block_given? + end + end + + module Accessible + def self.included(base) + base.const_set(:PwConfig, Configuration.new) + end + end + end +end + diff --git a/lib/passwd/configuration/abstract_config.rb b/lib/passwd/configuration/abstract_config.rb deleted file mode 100644 index 8233e78..0000000 --- a/lib/passwd/configuration/abstract_config.rb +++ /dev/null @@ -1,36 +0,0 @@ -module Passwd - class AbstractConfig - VALID_OPTIONS_KEYS = [ - :algorithm, - :length, - :lower, - :upper, - :number, - :letters_lower, - :letters_upper, - :letters_number - ].freeze - - attr_accessor *VALID_OPTIONS_KEYS - - def configure - yield self - end - - def merge(configs) - configs.keys.each do |k| - send("#{k}=", configs[k]) - end - end - - def letters - chars = [] - chars.concat(self.letters_lower) if self.lower - chars.concat(self.letters_upper) if self.upper - chars.concat(self.letters_number) if self.number - raise "letters is empty" if chars.empty? - chars - end - end -end - diff --git a/lib/passwd/configuration/config.rb b/lib/passwd/configuration/config.rb deleted file mode 100644 index b04a87b..0000000 --- a/lib/passwd/configuration/config.rb +++ /dev/null @@ -1,23 +0,0 @@ -require "passwd/configuration/abstract_config" - -module Passwd - class Config < AbstractConfig - include Singleton - - def initialize - reset - end - - def reset - self.algorithm = :sha512 - self.length = 8 - self.lower = true - self.upper = true - self.number = true - self.letters_lower = ("a".."z").to_a - self.letters_upper = ("A".."Z").to_a - self.letters_number = ("0".."9").to_a - end - end -end - diff --git a/lib/passwd/configuration/policy.rb b/lib/passwd/configuration/policy.rb deleted file mode 100644 index 8e1472d..0000000 --- a/lib/passwd/configuration/policy.rb +++ /dev/null @@ -1,45 +0,0 @@ -module Passwd - class Policy - include Singleton - - VALID_OPTIONS_KEYS = [ - :min_length, - :require_lower, - :require_upper, - :require_number - ].freeze - - attr_accessor *VALID_OPTIONS_KEYS - - def initialize - reset - end - - def configure - yield self - end - - def valid?(password, config) - return false if self.min_length > password.size - return false if self.require_lower && !include_char?(config.letters_lower, password) - return false if self.require_upper && !include_char?(config.letters_upper, password) - return false if self.require_number && !include_char?(config.letters_number, password) - true - end - - def include_char?(letters, strings) - strings.each_char do |c| - return true if letters.include? c - end - false - end - - def reset - self.min_length = 8 - self.require_lower = true - self.require_upper = false - self.require_number = true - end - end -end - diff --git a/lib/passwd/configuration/tmp_config.rb b/lib/passwd/configuration/tmp_config.rb deleted file mode 100644 index 0031566..0000000 --- a/lib/passwd/configuration/tmp_config.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "passwd/configuration/abstract_config" - -module Passwd - class TmpConfig < AbstractConfig - def initialize(config, options) - config.instance_variables.each do |v| - key = v.to_s.sub(/^@/, "").to_sym - if options.has_key? key - instance_variable_set v, options[key] - else - instance_variable_set v, config.instance_variable_get(v) - end - end - end - end -end - diff --git a/lib/passwd/errors.rb b/lib/passwd/errors.rb index bb8b7da..4e1c0d8 100644 --- a/lib/passwd/errors.rb +++ b/lib/passwd/errors.rb @@ -1,14 +1,8 @@ module Passwd - class PasswdError < StandardError - end - - class AuthError < PasswdError - end - - class PasswordNotMatch < PasswdError - end - - class PolicyNotMatch < PasswdError - end + class PasswdError < StandardError; end + class UnauthorizedAccess < PasswdError; end + class PolicyNotMatch < PasswdError; end + class AuthenticationFails < PasswdError; end + class ConfigError < PasswdError; end end diff --git a/lib/passwd/password.rb b/lib/passwd/password.rb index e62008d..befe046 100644 --- a/lib/passwd/password.rb +++ b/lib/passwd/password.rb @@ -1,40 +1,89 @@ module Passwd class Password - attr_reader :text, :hash, :salt_text, :salt_hash + include Base - def initialize(options={}) - @text = options.fetch(:password, Passwd.create) - @salt_text = options.fetch(:salt_text, Time.now.to_s) - @salt_hash = Passwd.hashing(@salt_text) - @hash = Passwd.hashing("#{@salt_hash}#{@text}") + attr_reader :plain, :hash, :salt + + def initialize(options = {}) + options = default_options.merge(options) + + if options.has_key?(:hash) + raise ArgumentError unless options.has_key?(:salt_hash) + @salt = Salt.from_hash(options[:salt_hash], self) + @hash = options[:hash] + else + @salt = + case + when options.has_key?(:salt_hash) + Salt.from_hash(options[:salt_hash], self) + when options.has_key?(:salt_plain) + Salt.from_plain(options[:salt_plain], self) + else + Salt.new(password: self) + end + self.update_plain(options[:plain]) + end + end + + def update_plain(value) + @plain = value + rehash + end + + def update_hash(value, salt_hash) + @plain = nil + @hash = value + self.salt.update_hash(salt_hash) + end + + def rehash + raise PasswdError unless self.plain + @hash = digest([self.salt.hash, self.plain].join) end - def text=(password) - @hash = Passwd.hashing("#{@salt_hash}#{password}") - @text = password + def match?(value) + self.hash == digest([self.salt.hash, value].join) end - def hash=(password_hash) - @text = nil - @hash = password_hash + def ==(other) + match?(other) end - def salt_text=(salt_text) - @salt_hash = Passwd.hashing(salt_text) - @hash = Passwd.hashing("#{@salt_hash}#{@text}") - @salt_text = salt_text + def to_s + self.plain.to_s end - def salt_hash=(salt_hash) - @salt_text = nil - @hash = Passwd.hashing("#{salt_hash}#{@text}") - @salt_hash = salt_hash + def valid? + raise PasswdError unless self.plain + + return false if PwConfig.policy.min_length > self.plain.size + + Configuration::KINDS.each do |key| + if PwConfig.policy.send("require_#{key}") + return false unless include_char?(PwConfig.send("letters_#{key}")) + end + end + true end - def ==(password) - enc_pass = Passwd.hashing("#{@salt_hash}#{password}") - @hash == enc_pass + def self.from_plain(value, options = {}) + new(options.merge(plain: value)) end + + def self.from_hash(value, salt_hash) + new(hash: value, salt_hash: salt_hash) + end + + private + def default_options + {plain: random} + end + + def include_char?(letters) + raise PasswdError unless self.plain + self.plain.chars.uniq.each {|c| return true if letters.include?(c)} + false + end end end diff --git a/lib/passwd/policy.rb b/lib/passwd/policy.rb new file mode 100644 index 0000000..bcf5643 --- /dev/null +++ b/lib/passwd/policy.rb @@ -0,0 +1,28 @@ +module Passwd + class Policy + VALID_OPTIONS = [ + :min_length, + :require_lower, + :require_upper, + :require_number + ].freeze + + attr_accessor *VALID_OPTIONS + + def initialize + reset + end + + def configure + yield self + end + + def reset + self.min_length = 8 + self.require_lower = true + self.require_upper = false + self.require_number = true + end + end +end + diff --git a/lib/passwd/railtie.rb b/lib/passwd/railtie.rb new file mode 100644 index 0000000..a13deda --- /dev/null +++ b/lib/passwd/railtie.rb @@ -0,0 +1,19 @@ +module Passwd + class Railtie < ::Rails::Railtie + config.passwd = ActiveSupport::OrderedOptions.new + + initializer "passwd" do + require "passwd/action_controller_ext" + require "passwd/active_record_ext" + + ActiveSupport.on_load(:action_controller) do + ::ActionController::Base.send(:include, Passwd::ActionControllerExt) + end + + ActiveSupport.on_load(:active_record) do + ::ActiveRecord::Base.send(:extend, Passwd::ActiveRecordExt) + end + end + end +end + diff --git a/lib/passwd/salt.rb b/lib/passwd/salt.rb new file mode 100644 index 0000000..aa9b886 --- /dev/null +++ b/lib/passwd/salt.rb @@ -0,0 +1,50 @@ +module Passwd + class Salt + include Base + + attr_reader :plain, :hash + + def initialize(options = {}) + options = default_options.merge(options) + + @password = options[:password] + if options.has_key?(:hash) + @plain = nil + @hash = options[:hash] + else + @plain = options[:plain] || (raise ArgumentError) + @hash = digest_without_stretching(@plain) + end + end + + def update_plain(value) + @plain = value + @hash = digest_without_stretching(@plain) + update_password! + end + + def update_hash(value) + @plain = nil + @hash = value + update_password! + end + + def self.from_plain(value, password = nil) + new(plain: value, password: password) + end + + def self.from_hash(value, password = nil) + new(hash: value, password: password) + end + + private + def default_options + {plain: Time.now.to_s} + end + + def update_password! + @password.rehash if @password && @password.plain + end + end +end + diff --git a/passwd.gemspec b/passwd.gemspec index 36191f9..5d23f21 100644 --- a/passwd.gemspec +++ b/passwd.gemspec @@ -17,9 +17,13 @@ Gem::Specification.new do |spec| spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] - spec.add_development_dependency "bundler", "~> 1.3" + spec.add_development_dependency "bundler" spec.add_development_dependency "rake" - spec.add_development_dependency "rspec" spec.add_development_dependency "coveralls" spec.add_development_dependency "simplecov" + spec.add_development_dependency "rails" + spec.add_development_dependency "rspec-rails" + spec.add_development_dependency "sqlite3" + spec.add_development_dependency "database_rewinder" end + diff --git a/spec/passwd/.keep b/spec/passwd/.keep new file mode 100644 index 0000000..e69de29 diff --git a/spec/passwd/active_record_ext_spec.rb b/spec/passwd/active_record_ext_spec.rb new file mode 100644 index 0000000..78a0be0 --- /dev/null +++ b/spec/passwd/active_record_ext_spec.rb @@ -0,0 +1,80 @@ +require "spec_helper" + +describe Passwd::ActiveRecordExt do + describe ".with_authenticate" do + it { expect(ActiveRecord::Base).to respond_to(:with_authenticate) } + + context User do + let(:new_pass) { "NewPassw0rd" } + let(:password) { Passwd::Password.new } + let(:user) { + User.create( + name: "i2bskn", + email: "i2bskn@example.com", + salt: password.salt.hash, + password: password.hash + ) + } + + it { is_expected.to respond_to(:passwd) } + it { is_expected.to respond_to(:authenticate) } + it { expect(User).to respond_to(:authenticate) } + it { is_expected.to respond_to(:set_password) } + it { is_expected.to respond_to(:update_password) } + + context "#passwd" do + after { user.passwd } + + it { expect(user.passwd.is_a?(Passwd::Password)).to be_truthy } + it { expect(user).to receive(:reload) } + it { expect(Passwd::Password).to receive(:from_hash) } + + it { + user = User.new + expect(user).to receive(:set_password) + user.passwd + } + end + + context ".authenticate" do + before { user } + + it { expect(User.authenticate("i2bskn@example.com", password.plain)).not_to be_falsy } + it { expect(User.authenticate("i2bskn@example.com", "invalid")).to be_falsy } + end + + context "#authenticate" do + it { expect(user.authenticate(password.plain)).not_to be_falsy } + it { expect(user.authenticate("invalid")).to be_falsy } + end + + context "#set_password" do + it { expect { user.set_password }.to change { user.password } } + it { expect { user.set_password(new_pass) }.to change { user.password } } + end + + context "#update_password" do + before { user } + + it { + expect { + user.update_password(password.plain, new_pass) + }.to change { user.password } + } + + it { + expect { + user.update_password(password.plain, "secret", true) + }.to raise_error(Passwd::PolicyNotMatch) + } + + it { + expect { + user.update_password("invalid", new_pass) + }.to raise_error(Passwd::AuthenticationFails) + } + end + end + end +end + diff --git a/spec/passwd/active_record_spec.rb b/spec/passwd/active_record_spec.rb deleted file mode 100644 index 135f0be..0000000 --- a/spec/passwd/active_record_spec.rb +++ /dev/null @@ -1,159 +0,0 @@ -require "spec_helper" - -describe Passwd::ActiveRecord do - class User - include Passwd::ActiveRecord - define_column - end - - let(:salt) {Digest::SHA512.hexdigest("salt")} - let(:password_text) {"secret"} - let(:password_hash) {Digest::SHA512.hexdigest("#{salt}#{password_text}")} - - describe ".#included" do - it "define singleton methods" do - expect(User.respond_to? :define_column).to be_truthy - end - end - - describe "extend methods" do - describe ".#define_column" do - let(:user) {User.new} - - it "define singleton methods" do - expect(User.respond_to? :authenticate).to be_truthy - end - - it "define authenticate method" do - expect(user.respond_to? :authenticate).to be_truthy - end - - it "define set_password method" do - expect(user.respond_to? :set_password).to be_truthy - end - - it "define update_password" do - expect(user.respond_to? :update_password).to be_truthy - end - end - end - - describe "defined methods from define_column" do - describe ".#authenticate" do - let!(:record) { - record = double("record mock") - allow(record).to receive_messages(salt: salt, password: password_hash) - response = [record] - allow(User).to receive(:where) {response} - record - } - - it "user should be returned if authentication is successful" do - expect(User).to receive(:where) - expect(User.authenticate("valid_id", password_text)).to eq(record) - end - - it "should return nil if authentication failed" do - expect(User).to receive(:where) - expect(User.authenticate("valid_id", "invalid_secret")).to be_nil - end - - it "should return nil if user not found" do - expect(User).to receive(:where).with(email: "invalid_id") {[]} - expect(User.authenticate("invalid_id", password_text)).to be_nil - end - end - - describe "#authenticate" do - let!(:user) { - user = User.new - allow(user).to receive_messages(salt: salt, password: password_hash) - user - } - - it "should return true if authentication is successful" do - expect(user.authenticate(password_text)).to be_truthy - end - - it "should return false if authentication failed" do - expect(user.authenticate("invalid_pass")).to be_falsey - end - end - - describe "#set_password" do - let!(:user) { - user = User.new - allow(user).to receive(:salt) {salt} - user - } - - it "should return set password" do - expect(user).to receive(:salt=).with(salt) - expect(user).to receive(:password=).with(Passwd.hashing("#{salt}#{password_text}")) - expect(user.set_password(password_text)).to eq(password_text) - end - - it "should set random password if not specified" do - expect(user).to receive(:salt=).with(salt) - random_password = Passwd.create - expect(Passwd).to receive(:create) {random_password} - expect(user).to receive(:password=).with(Passwd.hashing("#{salt}#{random_password}")) - user.set_password - end - - it "should set salt if salt is nil" do - mail_addr = "foo@example.com" - time_now = Time.now - salt2 = Passwd.hashing("#{mail_addr}#{time_now.to_s}") - allow(Time).to receive(:now) {time_now} - allow(user).to receive(:email) {mail_addr} - expect(user).to receive(:salt) {nil} - expect(user).to receive(:salt=).with(salt2) - expect(user).to receive(:password=).with(Passwd.hashing("#{salt2}#{password_text}")) - user.set_password(password_text) - end - end - - describe "#update_password" do - let!(:user) { - user = User.new - allow(user).to receive(:salt) {salt} - allow(user).to receive(:password) {password_hash} - user - } - - context "without policy check" do - it "should return update password" do - pass = "new_password" - expect(user).to receive(:set_password).with(pass) {pass} - expect(user.update_password(password_text, pass)).to eq(pass) - end - - it "should generate exception if authentication failed" do - expect(Passwd).to receive(:auth) {false} - expect(user).not_to receive(:set_password) - expect { - user.update_password("invalid_password", "new_password") - }.to raise_error(Passwd::AuthError) - end - end - - context "with policy check" do - it "should return update password" do - pass = "new_password" - expect(Passwd).to receive(:policy_check) {true} - expect(user).to receive(:set_password).with(pass) {pass} - expect(user.update_password(password_text, pass, true)).to eq(pass) - end - - it "should generate exception if policy not match" do - pass = "new_password" - expect(Passwd).to receive(:policy_check) {false} - expect { - user.update_password(password_text, pass, true) - }.to raise_error(Passwd::PolicyNotMatch) - end - end - end - end -end diff --git a/spec/passwd/base_spec.rb b/spec/passwd/base_spec.rb index d968ea2..30b7694 100644 --- a/spec/passwd/base_spec.rb +++ b/spec/passwd/base_spec.rb @@ -1,234 +1,60 @@ require "spec_helper" -describe Passwd do - describe "extended Base" do - describe "#create" do - context "without arguments" do - let(:password) {Passwd.create} - - it "TmpConfig should not be generated" do - expect(Passwd::TmpConfig).not_to receive(:new) - expect{password}.not_to raise_error - end - - it "created password should be String object" do - expect(password.is_a? String).to be_truthy - end - - it "created password length should be default length" do - expect(password.size).to eq(8) - end - end - - context "with arguments" do - it "TmpConfig should be generated" do - tmp_config = double("tmp_config mock", length: 8, letters: ["a", "b"]) - expect(Passwd::TmpConfig).to receive(:new) {tmp_config} - expect{Passwd.create(length: 10)}.not_to raise_error - end - - it "password was created specified characters" do - expect(Passwd.create(length: 10).size).to eq(10) - end - - it "password create without lower case" do - expect(("a".."z").to_a.include? Passwd.create(lower: false)).to be_falsey - end - - it "password create without upper case" do - expect(("A".."Z").to_a.include? Passwd.create(upper: false)).to be_falsey - end - - it "password create without number" do - expect(("0".."9").to_a.include? Passwd.create(number: false)).to be_falsey - end - end - end - - describe "#auth" do - let!(:password) do - password = Passwd.create - salt_hash = Passwd.hashing(Time.now.to_s) - password_hash = Passwd.hashing("#{salt_hash}#{password}") - {text: password, salt: salt_hash, hash: password_hash} - end - - it "return true with valid password" do - expect(Passwd.auth(password[:text], password[:salt], password[:hash])).to be_truthy - end - - it "return false with invalid password" do - expect(Passwd.auth("invalid", password[:salt], password[:hash])).to be_falsey - end - - it "should create exception if not specified arguments" do - expect(proc{Passwd.auth}).to raise_error - end - end - - describe "#hashing" do - it "should call SHA512.#hexdigest" do - expect(Digest::SHA512).to receive(:hexdigest) - Passwd.hashing("secret") - end - - it "return hashed password" do - hashed = Digest::SHA512.hexdigest "secret" - expect(Passwd.hashing("secret")).to eq(hashed) - end - - it "return hashed password specified algorithm" do - hashed = Digest::SHA256.hexdigest "secret" - expect(Passwd.hashing("secret", :sha256)).to eq(hashed) - end - - it "should create exception if not specified argument" do - expect(proc{Passwd.hashing}).to raise_error - end - end - - describe "#confirm_check" do - context "with out policy check" do - it "should generate exception if password don't match" do - expect{ - Passwd.confirm_check("secret", "invalid") - }.to raise_error(Passwd::PasswordNotMatch) - end - - it "return true if password matches" do - expect(Passwd.confirm_check("secret", "secret")).to be_truthy - end - end - - context "with policy check" do - it "return false if invalid password by policy" do - expect(Passwd.confirm_check("secret", "secret", true)).to be_falsey - end - - it "return true if valid password by policy" do - expect(Passwd.confirm_check("secretpass", "secretpass", true)).to be_falsey - end - end - end - - describe "#configure" do - it "return configuration object" do - expect(Passwd.configure.is_a? Passwd::Config).to be_truthy - end - - it "set config value from block" do - Passwd.configure do |c| - c.length = 10 - end - expect(Passwd.configure.length).not_to eq(8) - expect(Passwd.configure.length).to eq(10) - end - - it "set config value from hash" do - Passwd.configure length: 20 - expect(Passwd.config.length).not_to eq(8) - expect(Passwd.config.length).to eq(20) - end - - it "alias of configure as config" do - expect(Passwd.configure.object_id).to eq(Passwd.config.object_id) - end - end - - describe "#policy_configure" do - it "return policy object" do - expect(Passwd.policy_configure.is_a? Passwd::Policy).to be_truthy - end - - it "set policy value from block" do - Passwd.policy_configure do |c| - c.min_length = 10 - end - expect(Passwd.policy_configure.min_length).not_to eq(8) - expect(Passwd.policy_configure.min_length).to eq(10) - end - end - - describe "#policy_check" do - it "Policy#valid? should be called" do - expect(Passwd::Policy.instance).to receive(:valid?).with("secret1234" ,Passwd::Config.instance) - Passwd.policy_check("secret1234") - end - end - - describe "#reset_policy" do - let(:policy) {Passwd::Policy.instance} - - before { - policy.configure do |c| - c.min_length = 20 - c.require_lower = false - c.require_upper = true - c.require_number = false - end - Passwd.reset_policy - } - - it "min_length should be a default" do - expect(policy.min_length).to eq(8) - end - - it "require_lower should be a default" do - expect(policy.require_lower).to be_truthy - end - - it "upper should be a default" do - expect(policy.require_upper).to be_falsey - end - - it "number should be a default" do - expect(policy.require_number).to be_truthy - end - end - - describe "#reset_config" do - let(:config) {Passwd::Config.instance} - - before { - config.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - Passwd.reset_config - } - - it "length should be a default" do - expect(config.length).to eq(8) - end - - it "lower should be a default" do - expect(config.lower).to be_truthy - end - - it "upper should be a default" do - expect(config.upper).to be_truthy - end - - it "number should be a default" do - expect(config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(config.letters_lower).to eq(("a".."z").to_a) - end +describe Passwd::Base do + let(:plain) { "secret" } + + context "#random" do + it { expect(Passwd).to respond_to(:random) } + it { expect(Passwd.random.is_a?(String)).to be_truthy } + it { expect(Passwd.random.size).to eq(Passwd::PwConfig.length) } + it { expect(Passwd.random(lower: false)).not_to include(*"a".."z") } + it { expect(Passwd.random(upper: false)).not_to include(*"A".."Z") } + it { expect(Passwd.random(number: false)).not_to include(*"0".."9") } + + it { + length = Passwd::PwConfig.length + 1 + expect(Passwd.random(length: length).size).to eq(length) + } + + it { + lower = ["a"] + expect( + Passwd.random(letters_lower: lower, upper: false, number: false) + .chars.uniq + ).to eq(lower) + } + end - it "letters_upper should be a default" do - expect(config.letters_upper).to eq(("A".."Z").to_a) - end + context "#digest" do + it { expect(Passwd.respond_to?(:digest)).to be_truthy } + it { expect(Passwd.digest(plain).is_a?(String)).to be_truthy } + it { expect(Passwd.digest(plain)).not_to eq(plain) } + + it { + hashed = Passwd.send(:algorithm, Passwd::PwConfig.algorithm).hexdigest plain + expect(Passwd.digest(plain)).to eq(hashed) + } + + it { + not_default = :md5 + hashed = Passwd.send(:algorithm, not_default).hexdigest plain + expect(Passwd.digest(plain, not_default)).to eq(hashed) + } + end - it "letters_number should be a default" do - expect(config.letters_number).to eq(("0".."9").to_a) - end - end + context "#algorithm" do + it { expect(Passwd.send(:algorithm, :sha1)).to eq(Digest::SHA1) } + it { expect(Passwd.send(:algorithm, :sha256)).to eq(Digest::SHA256) } + it { expect(Passwd.send(:algorithm, :sha384)).to eq(Digest::SHA384) } + it { expect(Passwd.send(:algorithm, :sha512)).to eq(Digest::SHA512) } + it { expect(Passwd.send(:algorithm, :md5)).to eq(Digest::MD5) } + it { expect(Passwd.send(:algorithm, :rmd160)).to eq(Digest::RMD160) } + + it { + expect { + Passwd.send(:algorithm, :unknowAn) + }.to raise_error + } end end + diff --git a/spec/passwd/configuration/config_spec.rb b/spec/passwd/configuration/config_spec.rb deleted file mode 100644 index 815ced0..0000000 --- a/spec/passwd/configuration/config_spec.rb +++ /dev/null @@ -1,248 +0,0 @@ -require "spec_helper" - -describe Passwd::Config do - let(:config) {Passwd::Config.instance} - - describe "defined accessors" do - it "defined algorithm" do - expect(config.respond_to? :algorithm).to be_truthy - end - - it "defined length" do - expect(config.respond_to? :length).to be_truthy - end - - it "defined lower" do - expect(config.respond_to? :lower).to be_truthy - end - - it "defined upper" do - expect(config.respond_to? :upper).to be_truthy - end - - it "defined number" do - expect(config.respond_to? :number).to be_truthy - end - - it "defined letters_lower" do - expect(config.respond_to? :letters_lower).to be_truthy - end - - it "defined letters_upper" do - expect(config.respond_to? :letters_upper).to be_truthy - end - - it "defined letters_number" do - expect(config.respond_to? :letters_number).to be_truthy - end - end - - describe "#initialize" do - it "algorithm should be a default" do - expect(config.algorithm).to eq(:sha512) - end - - it "length should be a default" do - expect(config.length).to eq(8) - end - - it "lower should be a default" do - expect(config.lower).to be_truthy - end - - it "upper should be a default" do - expect(config.upper).to be_truthy - end - - it "number should be a default" do - expect(config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(config.letters_number).to eq(("0".."9").to_a) - end - end - - describe "#configure" do - before { - config.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - } - - it "set length from block" do - expect(config.length).to eq(20) - end - - it "set lower from block" do - expect(config.lower).to be_falsey - end - - it "set upper from block" do - expect(config.upper).to be_falsey - end - - it "set number from block" do - expect(config.number).to be_falsey - end - - it "set letters_lower from block" do - expect(config.letters_lower).to eq(["a"]) - end - - it "set letters_upper from block" do - expect(config.letters_upper).to eq(["A"]) - end - - it "set letters_number from block" do - expect(config.letters_number).to eq(["0"]) - end - - it "raise error unknown setting" do - expect { - config.configure do |c| - c.unknown = true - end - }.to raise_error - end - end - - describe "#merge" do - it "set length from hash" do - config.merge(length: 10) - expect(config.length).to eq(10) - end - - it "set lower from hash" do - config.merge(lower: false) - expect(config.lower).to be_falsey - end - - it "set upper from hash" do - config.merge(upper: false) - expect(config.upper).to be_falsey - end - - it "set number from hash" do - config.merge(number: false) - expect(config.number).to be_falsey - end - - it "set letters_lower from hash" do - config.merge(letters_lower: ["a"]) - expect(config.letters_lower).to eq(["a"]) - end - - it "set letters_upper from hash" do - config.merge(letters_upper: ["A"]) - expect(config.letters_upper).to eq(["A"]) - end - - it "set letters_number from hash" do - config.merge(letters_number: ["0"]) - expect(config.letters_number).to eq(["0"]) - end - - it "raise error unknown setting" do - expect { - config.merge(unknown: true) - }.to raise_error - end - end - - describe "#letters" do - it "return Array object" do - expect(config.letters.is_a? Array).to be_truthy - end - - it "all elements of the string" do - config.letters.each do |l| - expect(l.is_a? String).to be_truthy - end - end - - it "return all letters" do - all_letters = ("a".."z").to_a.concat(("A".."Z").to_a).concat(("0".."9").to_a) - expect(config.letters).to eq(all_letters) - end - - it "return except for the lower case" do - config.merge(lower: false) - expect(config.letters.include? "a").to be_falsey - end - - it "return except for the upper case" do - config.merge(upper: false) - expect(config.letters.include? "A").to be_falsey - end - - it "return except for the number case" do - config.merge(number: false) - expect(config.letters.include? "0").to be_falsey - end - - it "raise error if letters is empty" do - config.merge(lower: false, upper: false, number: false) - expect { - config.letters - }.to raise_error - end - end - - describe "#reset" do - before { - config.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - config.reset - } - - it "length should be a default" do - expect(config.length).to eq(8) - end - - it "lower should be a default" do - expect(config.lower).to be_truthy - end - - it "upper should be a default" do - expect(config.upper).to be_truthy - end - - it "number should be a default" do - expect(config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(config.letters_number).to eq(("0".."9").to_a) - end - end -end diff --git a/spec/passwd/configuration/policy_spec.rb b/spec/passwd/configuration/policy_spec.rb deleted file mode 100644 index 59acc94..0000000 --- a/spec/passwd/configuration/policy_spec.rb +++ /dev/null @@ -1,132 +0,0 @@ -require "spec_helper" - -describe Passwd::Policy do - let(:policy) {Passwd::Policy.instance} - - describe "defined accessors" do - it "defined min_length" do - expect(policy.respond_to? :min_length).to be_truthy - end - - it "defined require_lower" do - expect(policy.respond_to? :require_lower).to be_truthy - end - - it "defined require_upper" do - expect(policy.respond_to? :require_upper).to be_truthy - end - - it "defined require_number" do - expect(policy.respond_to? :require_number).to be_truthy - end - end - - describe "#initialize" do - it "min_length should be a default" do - expect(policy.min_length).to eq(8) - end - - it "require_lower should be a default" do - expect(policy.require_lower).to be_truthy - end - - it "require_upper should be a default" do - expect(policy.require_upper).to be_falsey - end - - it "require_number should be a default" do - expect(policy.require_number).to be_truthy - end - end - - describe "#configure" do - before { - policy.configure do |c| - c.min_length = 20 - c.require_lower = false - c.require_upper = true - c.require_number = false - end - } - - it "set min_length from block" do - expect(policy.min_length).to eq(20) - end - - it "set require_lower from block" do - expect(policy.require_lower).to be_falsey - end - - it "set require_upper from block" do - expect(policy.require_upper).to be_truthy - end - - it "set require_number from block" do - expect(policy.require_number).to be_falsey - end - end - - describe "#valid?" do - let(:config) {Passwd::Config.instance} - - it "valid password should be valid" do - expect(policy.valid?("secret1234", config)).to be_truthy - end - - it "short password should not valid" do - expect(policy.valid?("short1", config)).to be_falsey - end - - it "password should not valid if not contain lower case" do - expect(policy.valid?("NOTLOWER12", config)).to be_falsey - end - - it "password should not valid if not contain upper case" do - policy.configure {|c| c.require_upper = true} - expect(policy.valid?("notupper12", config)).to be_falsey - end - - it "password should not valid if not contain number" do - expect(policy.valid?("notnumber", config)).to be_falsey - end - end - - describe "#include_char?" do - it "should be return true if contains" do - expect(policy.include_char?(("a".."z").to_a, "contains")).to be_truthy - end - - it "should be return false if not contains" do - expect(policy.include_char?(("a".."z").to_a, "NOTCONTAINS")).to be_falsey - end - end - - describe "#reset" do - before { - policy.configure do |c| - c.min_length = 20 - c.require_lower = false - c.require_upper = true - c.require_number = false - end - policy.reset - } - - it "min_length should be a default" do - expect(policy.min_length).to eq(8) - end - - it "require_lower should be a default" do - expect(policy.require_lower).to be_truthy - end - - it "require_upper should be a default" do - expect(policy.require_upper).to be_falsey - end - - it "require_number should be a default" do - expect(policy.require_number).to be_truthy - end - end -end - diff --git a/spec/passwd/configuration/tmp_config_spec.rb b/spec/passwd/configuration/tmp_config_spec.rb deleted file mode 100644 index 7eba00a..0000000 --- a/spec/passwd/configuration/tmp_config_spec.rb +++ /dev/null @@ -1,264 +0,0 @@ -require "spec_helper" - -describe Passwd::TmpConfig do - let(:config) {Passwd::Config.instance} - - def tmp_config(options={}) - Passwd::TmpConfig.new(Passwd::Config.instance, options) - end - - describe "defined accessors" do - it "defined algorithm" do - expect(config.respond_to? :algorithm).to be_truthy - end - - it "defined length" do - expect(tmp_config.respond_to? :length).to be_truthy - end - - it "defined lower" do - expect(tmp_config.respond_to? :lower).to be_truthy - end - - it "defined upper" do - expect(tmp_config.respond_to? :upper).to be_truthy - end - - it "defined number" do - expect(tmp_config.respond_to? :number).to be_truthy - end - - it "defined letters_lower" do - expect(tmp_config.respond_to? :letters_lower).to be_truthy - end - - it "defined letters_upper" do - expect(tmp_config.respond_to? :letters_upper).to be_truthy - end - - it "defined letters_number" do - expect(tmp_config.respond_to? :letters_number).to be_truthy - end - end - - describe "#initialize" do - context "with empty options" do - it "algorithm should be a default" do - expect(config.algorithm).to eq(:sha512) - end - - it "length should be a default" do - expect(tmp_config.length).to eq(8) - end - - it "lower should be a default" do - expect(tmp_config.lower).to be_truthy - end - - it "upper should be a default" do - expect(tmp_config.upper).to be_truthy - end - - it "number should be a default" do - expect(tmp_config.number).to be_truthy - end - - it "letters_lower should be a default" do - expect(tmp_config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a default" do - expect(tmp_config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a default" do - expect(tmp_config.letters_number).to eq(("0".."9").to_a) - end - end - - context "with options" do - it "length should be a specified params" do - expect(tmp_config(length: 10).length).to eq(10) - expect(config.length).to eq(8) - end - - it "lower should be a specified params" do - expect(tmp_config(lower: false).lower).to be_falsey - expect(config.lower).to be_truthy - end - - it "upper should be a specified params" do - expect(tmp_config(upper: false).upper).to be_falsey - expect(config.upper).to be_truthy - end - - it "number should be a specified params" do - expect(tmp_config(number: false).number).to be_falsey - expect(config.number).to be_truthy - end - - it "letters_lower should be a specified params" do - expect(tmp_config(letters_lower: ["a"]).letters_lower).to eq(["a"]) - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "letters_upper should be a specified params" do - expect(tmp_config(letters_upper: ["A"]).letters_upper).to eq(["A"]) - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "letters_number should be a specified params" do - expect(tmp_config(letters_number: ["0"]).letters_number).to eq(["0"]) - expect(config.letters_number).to eq(("0".."9").to_a) - end - end - end - - describe "#configure" do - let(:changed_tmp_config) do - tconf = tmp_config - tconf.configure do |c| - c.length = 20 - c.lower = false - c.upper = false - c.number = false - c.letters_lower = ["a"] - c.letters_upper = ["A"] - c.letters_number = ["0"] - end - tconf - end - - it "set length from block" do - expect(changed_tmp_config.length).to eq(20) - expect(config.length).to eq(8) - end - - it "set lower from block" do - expect(changed_tmp_config.lower).to be_falsey - expect(config.lower).to be_truthy - end - - it "set upper from block" do - expect(changed_tmp_config.upper).to be_falsey - expect(config.upper).to be_truthy - end - - it "set number from block" do - expect(changed_tmp_config.number).to be_falsey - expect(config.number).to be_truthy - end - - it "set letters_lower from block" do - expect(changed_tmp_config.letters_lower).to eq(["a"]) - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "set letters_upper from block" do - expect(changed_tmp_config.letters_upper).to eq(["A"]) - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "set letters_number from block" do - expect(changed_tmp_config.letters_number).to eq(["0"]) - expect(config.letters_number).to eq(("0".."9").to_a) - end - - it "raise error unknown setting" do - expect { - tmp_config.configure do |c| - c.unknown = true - end - }.to raise_error - end - end - - describe "#merge" do - let(:default_tmp_config) {tmp_config} - - it "set length from hash" do - default_tmp_config.merge(length: 10) - expect(default_tmp_config.length).to eq(10) - expect(config.length).to eq(8) - end - - it "set lower from hash" do - default_tmp_config.merge(lower: false) - expect(default_tmp_config.lower).to be_falsey - expect(config.lower).to be_truthy - end - - it "set upper from hash" do - default_tmp_config.merge(upper: false) - expect(default_tmp_config.upper).to be_falsey - expect(config.upper).to be_truthy - end - - it "set number from hash" do - default_tmp_config.merge(number: false) - expect(default_tmp_config.number).to be_falsey - expect(config.number).to be_truthy - end - - it "set letters_lower from hash" do - default_tmp_config.merge(letters_lower: ["a"]) - expect(default_tmp_config.letters_lower).to eq(["a"]) - expect(config.letters_lower).to eq(("a".."z").to_a) - end - - it "set letters_upper from hash" do - default_tmp_config.merge(letters_upper: ["A"]) - expect(default_tmp_config.letters_upper).to eq(["A"]) - expect(config.letters_upper).to eq(("A".."Z").to_a) - end - - it "set letters_number from hash" do - default_tmp_config.merge(letters_number: ["0"]) - expect(default_tmp_config.letters_number).to eq(["0"]) - expect(config.letters_number).to eq(("0".."9").to_a) - end - - it "raise error unknown setting" do - expect { - tmp_config.merge(unknown: true) - }.to raise_error - end - end - - describe "#letters" do - it "return Array object" do - expect(tmp_config.letters.is_a? Array).to be_truthy - end - - it "all elements of the string" do - tmp_config.letters.each do |l| - expect(l.is_a? String).to be_truthy - end - end - - it "return all letters" do - all_letters = ("a".."z").to_a.concat(("A".."Z").to_a).concat(("0".."9").to_a) - expect(tmp_config.letters).to eq(all_letters) - end - - it "return except for the lower case" do - expect(tmp_config(lower: false).letters.include? "a").to be_falsey - end - - it "return except for the upper case" do - expect(tmp_config(upper: false).letters.include? "A").to be_falsey - end - - it "return except for the number case" do - expect(tmp_config(number: false).letters.include? "0").to be_falsey - end - - it "raise error if letters is empty" do - tconf = tmp_config(lower: false, upper: false, number: false) - expect { - tconf.letters - }.to raise_error - end - end -end - diff --git a/spec/passwd/configuration_spec.rb b/spec/passwd/configuration_spec.rb new file mode 100644 index 0000000..cca2dc4 --- /dev/null +++ b/spec/passwd/configuration_spec.rb @@ -0,0 +1,50 @@ +require "spec_helper" + +describe Passwd::Configuration do + describe "#initialize" do + subject { Passwd::PwConfig } + # defined options + it { is_expected.to respond_to(:algorithm) } + it { is_expected.to respond_to(:length) } + it { is_expected.to respond_to(:policy) } + it { is_expected.to respond_to(:stretching) } + it { is_expected.to respond_to(:lower) } + it { is_expected.to respond_to(:upper) } + it { is_expected.to respond_to(:number) } + it { is_expected.to respond_to(:letters_lower) } + it { is_expected.to respond_to(:letters_upper) } + it { is_expected.to respond_to(:letters_number) } + + # default settings + it { is_expected.to have_attributes(algorithm: :sha512) } + it { is_expected.to have_attributes(length: 8) } + it { is_expected.to satisfy {|v| v.policy.is_a?(Passwd::Policy) } } + it { is_expected.to have_attributes(stretching: nil) } + it { is_expected.to have_attributes(lower: true) } + it { is_expected.to have_attributes(upper: true) } + it { is_expected.to have_attributes(number: true) } + it { is_expected.to have_attributes(letters_lower: [*"a".."z"]) } + it { is_expected.to have_attributes(letters_upper: [*"A".."Z"]) } + it { is_expected.to have_attributes(letters_number: [*"0".."9"]) } + end + + describe "Writable" do + subject { Passwd } + + it { + klass = Class.new { extend Passwd::Configuration::Writable } + expect(defined?(klass::PwConfig)).to be_truthy + } + + it { is_expected.to respond_to(:configure) } + it { is_expected.to respond_to(:policy_configure) } + end + + describe "Accessible" do + it { + klass = Class.new { include Passwd::Configuration::Accessible } + expect(klass::PwConfig.is_a?(Passwd::Configuration)).to be_truthy + } + end +end + diff --git a/spec/passwd/password_spec.rb b/spec/passwd/password_spec.rb index 1007bdb..1b88ff7 100644 --- a/spec/passwd/password_spec.rb +++ b/spec/passwd/password_spec.rb @@ -1,148 +1,156 @@ require "spec_helper" describe Passwd::Password do - let(:password) {Passwd::Password.new} + let!(:pswd) { Passwd::Password.new } describe "#initialize" do - context "with default params" do - let!(:password_text) { - password_text = Passwd.create - expect(Passwd).to receive(:create) {password_text} - password_text - } - - let!(:time_now) { - time_now = Time.now - expect(Time).to receive(:now) {time_now} - time_now - } - - it "@text should be a random password" do - expect(password.text.size).to eq(8) - expect(password.text).to eq(password_text) - end - - it "@salt_text should be a auto created" do - expect(password.salt_text).to eq(time_now.to_s) - end - - it "@salt_hash should be a hashed salt" do - expect(password.salt_hash).to eq(Passwd.hashing(time_now.to_s)) - end - - it "@password_hash should be a hashed password with salt" do - password_hash = Passwd.hashing("#{Passwd.hashing(time_now.to_s)}#{password_text}") - expect(password.hash).to eq(password_hash) - end - end + context "without argument" do + subject { Passwd::Password.new } - context "with custom params" do - let(:password_text) {Passwd.create} - let(:salt_text) {"salt"} - let!(:time_now) { - time_now = Time.now - allow(Time).to receive(:create) {time_now} - time_now - } - - it "@text is specified password" do - password = Passwd::Password.new(password: password_text) - expect(password.text).to eq(password_text) - end - - it "@hash is hash of specified password" do - password = Passwd::Password.new(password: password_text) - password_hash = Passwd.hashing("#{Passwd.hashing(time_now.to_s)}#{password_text}") - expect(password.hash).to eq(password_hash) - end - - it "@salt_text is specified salt" do - password = Passwd::Password.new(salt_text: salt_text) - expect(password.salt_text).to eq(salt_text) - end - - it "@salt_hash is hash of specified salt" do - salt_hash = Passwd.hashing(salt_text) - password = Passwd::Password.new(salt_text: salt_text) - expect(password.salt_hash).to eq(salt_hash) - end + it { is_expected.not_to have_attributes(plain: nil) } + it { is_expected.not_to have_attributes(hash: nil) } + it { is_expected.not_to have_attributes(salt: nil) } + it { is_expected.to satisfy {|v| v.salt.is_a?(Passwd::Salt) } } end - end - describe "#text=" do - it "@text is changed" do - old_password = password.text - password.text = password.text.reverse - expect(password.text).not_to eq(old_password) - end + context "with plain" do + subject { Passwd::Password.new(plain: pswd.plain) } - it "@hash is changed" do - old_hash = password.hash - new_password = password.text = password.text.reverse - expect(password.hash).not_to eq(old_hash) - expect(password.hash).to eq(Passwd.hashing("#{password.salt_hash}#{new_password}")) + it { is_expected.to have_attributes(plain: pswd.plain) } + it { is_expected.not_to have_attributes(hash: nil) } + it { is_expected.not_to have_attributes(salt: nil) } + it { is_expected.to satisfy {|v| v.salt.is_a?(Passwd::Salt) } } end - end - describe "#hash=" do - it "@text is nil" do - password.hash = Passwd.hashing("secret") - expect(password.text).to be_nil - end + context "with plain and salt_plain" do + subject { Passwd::Password.new(plain: pswd.plain, salt_plain: pswd.salt.plain) } - it "@hash is changed" do - old_hash = password.hash - password.hash = Passwd.hashing("secret") - expect(password.hash).not_to eq(old_hash) + it { is_expected.to have_attributes(plain: pswd.plain) } + it { is_expected.to have_attributes(hash: pswd.hash) } + it { is_expected.to satisfy {|v| v.salt.plain == pswd.salt.plain } } + it { is_expected.to satisfy {|v| v.salt.hash == pswd.salt.hash } } end - end - describe "#salt_text=" do - it "@salt_text is changed" do - old_salt = password.salt_text - password.salt_text = "salt" - expect(password.salt_text).not_to eq(old_salt) - end + context "with plain and salt_hash" do + subject { Passwd::Password.new(plain: pswd.plain, salt_hash: pswd.salt.hash) } - it "@salt_hash is changed" do - old_salt = password.salt_hash - password.salt_text = "salt" - expect(password.salt_hash).not_to eq(old_salt) + it { is_expected.to have_attributes(plain: pswd.plain) } + it { is_expected.to have_attributes(hash: pswd.hash) } + it { is_expected.to satisfy {|v| v.salt.plain.nil? } } + it { is_expected.to satisfy {|v| v.salt.hash == pswd.salt.hash } } end - it "@hash is changed" do - old_hash = password.hash - password.salt_text = "salt" - expect(password.hash).not_to eq(old_hash) + context "with hash and salt_hash" do + subject { Passwd::Password.new(hash: pswd.hash, salt_hash: pswd.salt.hash) } + + it { is_expected.to have_attributes(plain: nil) } + it { is_expected.to have_attributes(hash: pswd.hash) } + it { is_expected.to satisfy {|v| v.salt.plain.nil? } } + it { is_expected.to satisfy {|v| v.salt.hash == pswd.salt.hash } } end + + it { + expect { + Passwd::Password.new(hash: pswd.hash) + }.to raise_error(ArgumentError) + } end - describe "#salt_hash=" do - it "@salt_text is nil" do - password.salt_hash = Passwd.hashing("salt") - expect(password.salt_text).to eq(nil) - end + describe "#update_plain" do + it { + expect(pswd).to receive(:rehash) + pswd.update_plain("secret") + expect(pswd).to have_attributes(plain: "secret") + } + + it { + expect { + pswd.update_plain("secret") + }.to change { pswd.plain } + } + end - it "@salt_hash is changed" do - old_salt_hash = password.salt_hash - password.salt_hash = Passwd.hashing("salt") - expect(password.salt_hash).not_to eq(old_salt_hash) - end + describe "#update_hash" do + it { + expect(pswd).not_to receive(:rehash) + pswd.update_hash("hashed", "salt") + expect(pswd).to have_attributes(hash: "hashed") + expect(pswd.salt).to have_attributes(hash: "salt") + } + + it { + expect { + pswd.update_hash("hashed", "salt") + }.to change { pswd.plain } + } + end - it "@hash is changed" do - old_hash = password.hash - password.salt_hash = Passwd.hashing("salt") - expect(password.hash).not_to eq(old_hash) - end + describe "#match?" do + it { expect(pswd.match?(pswd.plain)).to be_truthy } + + it { + invalid = [pswd.plain, "invalid"].join + expect(pswd.match?(invalid)).to be_falsy + } end describe "#==" do - it "return true with valid password" do - expect(password == password.text).to be_truthy - end + it { + expect(pswd).to receive(:match?) + pswd == pswd.plain + } + end - it "return false with invalid password" do - expect(password == "secret").to be_falsey - end + describe "#valid?" do + it { + pswd.update_plain("ValidPassw0rd") + expect(pswd.valid?).to be_truthy + } + + it { + pswd.update_plain("a" * (Passwd::PwConfig.policy.min_length - 1)) + expect(pswd.valid?).to be_falsy + } + + it { + pswd.update_hash("hashed", "salt") + expect { + pswd.valid? + }.to raise_error(Passwd::PasswdError) + } + end + + describe "#default_options" do + it { + expect(pswd.send(:default_options)).to satisfy {|v| v.has_key?(:plain) } + } + end + + describe "#include_char?" do + it { + pswd.update_plain("secret") + expect(pswd.send(:include_char?, ["s"])).to be_truthy + } + + it { + expect { + pswd.update_hash("hashed", "salt") + pswd.send(:include_char?, []) + }.to raise_error(Passwd::PasswdError) + } + end + + describe ".from_plain" do + it { + expect(Passwd::Password).to receive(:new) + Passwd::Password.from_plain("secret") + } + end + + describe ".from_hash" do + it { + expect(Passwd::Password).to receive(:new) + Passwd::Password.from_hash("hashed", "salt") + } end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 832c1a0..627da67 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -10,14 +10,25 @@ SimpleCov.start do add_filter "spec" add_filter ".bundle" + add_filter "example" end +ENV["RAILS_ENV"] ||= "test" +require File.expand_path("../../example/config/environment", __FILE__) require "passwd" +Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} + RSpec.configure do |config| config.order = "random" - config.after do - Passwd::Config.instance.reset - Passwd::Policy.instance.reset + + config.before :all do + require "db/schema" + end + + config.after :each do + Passwd::PwConfig.reset + DataUtil.clear end end + diff --git a/spec/support/data_util.rb b/spec/support/data_util.rb new file mode 100644 index 0000000..3e195f7 --- /dev/null +++ b/spec/support/data_util.rb @@ -0,0 +1,11 @@ +class DataUtil + TARGETS = %w(User) + + def self.clear + models.each(&:delete_all) + end + + def self.models + TARGETS.map(&:constantize) + end +end diff --git a/spec/support/paths.rb b/spec/support/paths.rb new file mode 100644 index 0000000..9d0b730 --- /dev/null +++ b/spec/support/paths.rb @@ -0,0 +1,2 @@ +$:.unshift(Rails.root.to_s) unless $:.include?(Rails.root.to_s) +