devise-3.5.6/0000755000004100000410000000000012663066463013050 5ustar www-datawww-datadevise-3.5.6/Rakefile0000644000004100000410000000174412663066463014523 0ustar www-datawww-data# encoding: UTF-8 require 'bundler/gem_tasks' require 'rake/testtask' require 'rdoc/task' desc 'Default: run tests for all ORMs.' task default: :test desc 'Run Devise tests for all ORMs.' task :pre_commit do Dir[File.join(File.dirname(__FILE__), 'test', 'orm', '*.rb')].each do |file| orm = File.basename(file).split(".").first # "Some day, my son, rake's inner wisdom will reveal itself. Until then, # take this `system` -- may its brute force protect you well." exit 1 unless system "rake test DEVISE_ORM=#{orm}" end end desc 'Run Devise unit tests.' Rake::TestTask.new(:test) do |t| t.libs << 'lib' t.libs << 'test' t.pattern = 'test/**/*_test.rb' t.verbose = true t.warning = false end desc 'Generate documentation for Devise.' Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'Devise' rdoc.options << '--line-numbers' << '--inline-source' rdoc.rdoc_files.include('README.md') rdoc.rdoc_files.include('lib/**/*.rb') end devise-3.5.6/Gemfile.lock0000644000004100000410000001035512663066463015276 0ustar www-datawww-dataPATH remote: . specs: devise (3.5.6) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 3.2.6, < 5) responders thread_safe (~> 0.1) warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: actionmailer (4.2.2) actionpack (= 4.2.2) actionview (= 4.2.2) activejob (= 4.2.2) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 1.0, >= 1.0.5) actionpack (4.2.2) actionview (= 4.2.2) activesupport (= 4.2.2) rack (~> 1.6) rack-test (~> 0.6.2) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.1) actionview (4.2.2) activesupport (= 4.2.2) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.1) activejob (4.2.2) activesupport (= 4.2.2) globalid (>= 0.3.0) activemodel (4.2.2) activesupport (= 4.2.2) builder (~> 3.1) activerecord (4.2.2) activemodel (= 4.2.2) activesupport (= 4.2.2) arel (~> 6.0) activesupport (4.2.2) i18n (~> 0.7) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) arel (6.0.0) bcrypt (3.1.10) bson (3.1.2) builder (3.2.2) connection_pool (2.2.0) erubis (2.7.0) faraday (0.9.1) multipart-post (>= 1.2, < 3) globalid (0.3.5) activesupport (>= 4.1.0) hashie (3.4.0) i18n (0.7.0) json (1.8.3) jwt (1.4.1) loofah (2.0.2) nokogiri (>= 1.5.9) mail (2.6.3) mime-types (>= 1.16, < 3) metaclass (0.0.4) mime-types (2.6.1) mini_portile (0.6.2) minitest (5.7.0) mocha (1.1.0) metaclass (~> 0.0.1) mongoid (4.0.2) activemodel (~> 4.0) moped (~> 2.0.0) origin (~> 2.1) tzinfo (>= 0.3.37) moped (2.0.6) bson (~> 3.0) connection_pool (~> 2.0) optionable (~> 0.2.0) multi_json (1.11.1) multi_xml (0.5.5) multipart-post (2.0.0) nokogiri (1.6.6.2) mini_portile (~> 0.6.0) oauth2 (0.9.4) faraday (>= 0.8, < 0.10) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (~> 1.2) omniauth (1.2.2) hashie (>= 1.2, < 4) rack (~> 1.0) omniauth-facebook (1.6.0) omniauth-oauth2 (~> 1.1) omniauth-oauth2 (1.1.2) faraday (>= 0.8, < 0.10) multi_json (~> 1.3) oauth2 (~> 0.9.3) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) optionable (0.2.0) origin (2.1.1) orm_adapter (0.5.0) rack (1.6.2) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.6.3) rack (>= 1.0) rails (4.2.2) actionmailer (= 4.2.2) actionpack (= 4.2.2) actionview (= 4.2.2) activejob (= 4.2.2) activemodel (= 4.2.2) activerecord (= 4.2.2) activesupport (= 4.2.2) bundler (>= 1.3.0, < 2.0) railties (= 4.2.2) sprockets-rails rails-deprecated_sanitizer (1.0.3) activesupport (>= 4.2.0.alpha) rails-dom-testing (1.0.6) activesupport (>= 4.2.0.beta, < 5.0) nokogiri (~> 1.6.0) rails-deprecated_sanitizer (>= 1.0.1) rails-html-sanitizer (1.0.2) loofah (~> 2.0) railties (4.2.2) actionpack (= 4.2.2) activesupport (= 4.2.2) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (10.4.2) rdoc (4.2.0) responders (2.1.1) railties (>= 4.2.0, < 5.1) ruby-openid (2.7.0) sprockets (3.2.0) rack (~> 1.0) sprockets-rails (2.3.1) actionpack (>= 3.0) activesupport (>= 3.0) sprockets (>= 2.8, < 4.0) sqlite3 (1.3.10) thor (0.19.1) thread_safe (0.3.5) tzinfo (1.2.2) thread_safe (~> 0.1) warden (1.2.6) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES activerecord-jdbc-adapter activerecord-jdbcsqlite3-adapter devise! jruby-openssl mocha (~> 1.1) mongoid (~> 4.0) omniauth (~> 1.2.0) omniauth-facebook omniauth-oauth2 (~> 1.1.0) omniauth-openid (~> 1.0.1) rails (= 4.2.2) rdoc sqlite3 webrat (= 0.7.3) BUNDLED WITH 1.11.2 devise-3.5.6/Gemfile0000644000004100000410000000077212663066463014351 0ustar www-datawww-datasource "https://rubygems.org" gemspec gem "rails", "4.2.2" gem "omniauth", "~> 1.2.0" gem "omniauth-oauth2", "~> 1.1.0" gem "rdoc" group :test do gem "omniauth-facebook" gem "omniauth-openid", "~> 1.0.1" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false end platforms :jruby do gem "activerecord-jdbc-adapter" gem "activerecord-jdbcsqlite3-adapter" gem "jruby-openssl" end platforms :ruby do gem "sqlite3" end group :mongoid do gem "mongoid", "~> 4.0" end devise-3.5.6/devise.gemspec0000644000004100000410000000174412663066463015702 0ustar www-datawww-data# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "devise/version" Gem::Specification.new do |s| s.name = "devise" s.version = Devise::VERSION.dup s.platform = Gem::Platform::RUBY s.licenses = ["MIT"] s.summary = "Flexible authentication solution for Rails with Warden" s.email = "contact@plataformatec.com.br" s.homepage = "https://github.com/plataformatec/devise" s.description = "Flexible authentication solution for Rails with Warden" s.authors = ['José Valim', 'Carlos Antônio'] s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- test/*`.split("\n") s.require_paths = ["lib"] s.required_ruby_version = '>= 1.9.3' s.add_dependency("warden", "~> 1.2.3") s.add_dependency("orm_adapter", "~> 0.1") s.add_dependency("bcrypt", "~> 3.0") s.add_dependency("thread_safe", "~> 0.1") s.add_dependency("railties", ">= 3.2.6", "< 5") s.add_dependency("responders") end devise-3.5.6/script/0000755000004100000410000000000012663066463014354 5ustar www-datawww-datadevise-3.5.6/script/s3-put0000755000004100000410000000247512663066463015445 0ustar www-datawww-data#!/usr/bin/env bash # Usage: s3-put [:] [] # # Uploads a file to the Amazon S3 service. # Outputs the URL for the newly uploaded file. # # Requirements: # - AMAZON_ACCESS_KEY_ID # - AMAZON_SECRET_ACCESS_KEY # - openssl # - curl # # Author: Mislav Marohnić set -e authorization() { local signature="$(string_to_sign | hmac_sha1 | base64)" echo "AWS ${AMAZON_ACCESS_KEY_ID?}:${signature}" } hmac_sha1() { openssl dgst -binary -sha1 -hmac "${AMAZON_SECRET_ACCESS_KEY?}" } base64() { openssl enc -base64 } bin_md5() { openssl dgst -binary -md5 } string_to_sign() { echo "$http_method" echo "$content_md5" echo "$content_type" echo "$date" echo "x-amz-acl:$acl" printf "/$bucket/$remote_path" } date_string() { LC_TIME=C date "+%a, %d %h %Y %T %z" } file="$1" bucket="${2%%:*}" remote_path="${2#*:}" content_type="$3" if [ -z "$remote_path" ] || [ "$remote_path" = "$bucket" ]; then remote_path="${file##*/}" fi http_method=PUT acl="public-read" content_md5="$(bin_md5 < "$file" | base64)" date="$(date_string)" url="https://$bucket.s3.amazonaws.com/$remote_path" curl -qsSf -T "$file" \ -H "Authorization: $(authorization)" \ -H "x-amz-acl: $acl" \ -H "Date: $date" \ -H "Content-MD5: $content_md5" \ -H "Content-Type: $content_type" \ "$url" echo "$url" devise-3.5.6/script/cached-bundle0000755000004100000410000000236112663066463016762 0ustar www-datawww-data#!/usr/bin/env bash # Usage: cached-bundle install --deployment # # After running `bundle`, caches the `vendor/bundle` directory to S3. # On the next run, restores the cached directory before running `bundle`. # When `Gemfile.lock` changes, the cache gets rebuilt. # # Requirements: # - Gemfile.lock # - TRAVIS_REPO_SLUG # - TRAVIS_RUBY_VERSION # - AMAZON_S3_BUCKET # - script/s3-put # - bundle # - curl # # Author: Mislav Marohnić set -e compute_md5() { local output="$(openssl md5)" echo "${output##* }" } download() { curl --tcp-nodelay -qsfL "$1" -o "$2" } gemfile="${BUNDLE_GEMFILE:-Gemfile}" bundle_fullpath="$(dirname $gemfile)/vendor/bundle" bundle_path=${bundle_fullpath#$PWD/} gemfile_hash="$(compute_md5 <"${gemfile}.lock")" cache_name="${TRAVIS_RUBY_VERSION}-${gemfile_hash}.tgz" fetch_url="http://${AMAZON_S3_BUCKET}.s3.amazonaws.com/${TRAVIS_REPO_SLUG}/${cache_name}" if download "$fetch_url" "$cache_name"; then echo "Reusing cached bundle ${cache_name}" tar xzf "$cache_name" fi bundle "$@" if [ ! -f "$cache_name" ] && [ -n "$AMAZON_SECRET_ACCESS_KEY" ]; then echo "Caching \`${bundle_path}' to S3" tar czf "$cache_name" "$bundle_path" script/s3-put "$cache_name" "${AMAZON_S3_BUCKET}:${TRAVIS_REPO_SLUG}/${cache_name}" fi devise-3.5.6/devise.png0000644000004100000410000003201212663066463015033 0ustar www-datawww-dataPNG  IHDR,}^3IDATx]E{jPhEZA`)4x;Ń^Xpš[~$d{sd&{=gfgg''' 9`9999`՛,XT@$Q0ծ? _uxÔ)SG6y:u*U_Œ3P8qbdM /2LPK͛ƍ(*ݻwK.d}XNNX!C=RϞ="$Ga{UW]U_No߾]tqrrrj?#<R޽CSSSCXNNXv|ohhprrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrBS@TR帿=R:s]S9xw^A]uvS˂bg@1O7߄{/̚5+)gϦ$z0w$-`+`Ya_{Lxzx~[g%Vs۫_T^˱~-|aA:?sD?3A:ӥ:qڌcG'{!_~ex饗w>p'?lFaUW Æ Ç ÇO~5*lv᠃ vZ83e]{o$@fPį}?⫯p&?Yg7qv w\rW_}Zv*z`>< :裏lMXc5j*?pgn!L6WT*&ޜ=Gx͉o4'~' 3gĪSZ ӧ'vw +2QQ]z{äISO=~=䓩a_|qs=\Y<0 c9&r-ᣏ>wW\_grE1@]7K.$\y啴M7݄ת dъW uPXڌ:æn<҃VX!lXzKjeu [aE-Z+~%y#^AT n/f5W^7B*OOKf\JsY-RX&xo_5,/? AZl~~i#?99axLVXwwLXy<}elof4e=(o"=`Jn#_=D=9O~zUsCB7+MY8g%H߭{: w}n@\^{0M ~" ֭0ohlzҩS'^JP8;*AsnM_ypZm(%?-"dJ5AȠ!tORV3fު6D~i2DDXe\sLz9&HT&L@,ʔ c]9n.&hTR;v CR'jBAX_bhL)G@#~c! `O q{?J_d-B 5X_= u܃'o);[SWbD9#W ڊo=,<T P|I|- 8ɌVImꫯ>C5VY%&Eq.@wԩaʔ) .;2.:%&dxe}~uׅƆF=|ɀct~܉sG:Sp)S X=sI M)Hᚺ68AsL?p!iopYguTL"`\ڈRQz cǎe*I,m'^{> ˪i|-ߥ𞥰ހ~`@ hA`Rǯ{ =f]sŀ%=`*:n8'FC]LLD^Q+"B 8UcWY?o_bE L.Cz]wSO=pM%nJVGu =,Ih6f\we 1P"`ʾ{SjX%ꭶJgFĉ`:e,x%cgV#OĪ(LC7J5PԽ8&sJ%w,qVcY*s{P'HAo-6}i >:&YWrR6?x}ԃFM3[P{U8Yäk<)0qPԔ7Sܝ%IHi\sMTl-i%ࢳL*XXii(`js{N|wO5-+ z1(,O *+=PCUݒAy?j+imHr!&Ζ.`aTFKcw0H$>t}0+"K`!Q SFT^SDGVЊS(X&V[P( W:Xr&"Q2){$v& oǏ7ZA_}Hɨ>m<݁M=UN7a㢄]X4j5yʃMa4(:aTˡBAaS#ΧMegөONk X3ـf/ Mlekbi!hǐi5y0M T3(XqkJǣ_ 3 6)qMP{E^+qK"3*پ R j\F'ζ-7Z{DˌW@<`vٟXA礠/z~wy(վAmFz~HO `wPUMP<kcS0J1liQZ@(Kl$"GBMò}lyxX8mʂ]ų#'%M"V;ßf)mA..6FN◪VvyS[P,%s$@R`̺w= o[cr|渞4bPZZ;jkO@6yІ2( 3b ʪ224e_yH-;r@Y!6Ʀ-X^OŊȣi rX<;Y5JP;l^+mɓ9[>2p<g=@$J%vT;FR_Rk)m9f$2ݶu;UJ\:v0@&)R+hRhd<ٷ^n$|I.|Zgu ˍmLܤ_vjQz͇92v%)" "?ɲ֞ (t@GL[-赥AT)lӢ.j{hG 8 qC2o?>p (,G>l{cD %n),eQQUs23)t >"dS5 3t*.T_&I͋"l( Dj:EVM;Cy&70ϖ/[n.MQKc<YK_ [Mhh2zh< |8zr?@+J֍/nv(bE6Cy%s!sGM^Y"SbU1 إլ٩M>'rp#Hl( nH+T~%Rf(r3@s+I]H*6N9b x9p5 8hCwT#T!0H<*hSXKщ XxF?KwP`jR匩 EXTsf˽Y+]Si3l6\)2BBN5Kcbg̘@@Tv՛QXQ61{F"bd' Ql #QZx)pe2,I}ǂUI1Ţ;0Ri; ~Tğy.Za׫Фc"VTz`. ,N0Az2yE`͆ EIX87 1^`'@',}& ".eIgdnowƗݜGfc.b@T΍gˌ7/MX=N6ZZÍudž:&GBc34~$|A.u9ej ) K * %Šs)mфQ5 XXh'si%Wsh*[T6^j^ʊPb*I:IrutTMFGyai<<%,æ+UY| kH8`<ϕ0dQVBRsy2ƻy 09z'?Y(To>BV]-bIz(Z.#X)V0UV!]4R֣˸5ep0{{w_z12&(n >&%+z5,lB'L5Oۺuk#̙3=Z*!^ =@z=~SXC UpT㮦5(c'rq G})=z9T*o|(: =L v@/8!BM X&!4 X,@D`߉Hn"i-ewq|kv pE,C=cvV{zGjx]YkijCС ڵk-мp#Bq(B4|${1vCrPoc18z|{ܠR ݕ"%m *fS%?̀UO3?eޕDR!rTcdD~?`%,svbװҕX޸k #)5ԾzÀ<aCx 1>lWY6@ QckKWV+c{г4V{B{58z4NB^v(uGfuŻ{Vkv?~#@73!X,B1<ì\YUN59EtTm;<͓6k~8z:e@Kݡu!LޙDezK?\m&Er2r(,cR}ѴZ 8WJM(~seLOމ .Xӽ[\Qڐԏ_ӃKT*^cWS6Jŋr_Rv:'CD+Ust{l&Tt>%Im[b=Ǽ{{&H wJm֬Yxm9姗y՟"1"Đg ٜIhcFQ]TBTa,$4vd LI(F!K4-ꨍ5,l,8+ꄡMn)$4CRr _rO@ڼ sVi~S4Z3czTx8=;XzECzu$H_W^ye xMӄ6O>zV?`:wt߉:;wWB;X,_Jh0Y&IKCe3::0c@WTfwGW TӉ5X\sc8vhO 'MR|{<*.pњXAg dHA]o04 cfS]jUEH aC:+" IiiiYoם7T --]ަM zS੧}UQyI ֗.r0w h~N]M=UPtxV("ZG&)SU^p ' (io j8;lM&DŕA;Y_@h"7-Twd[w嬊yV940^Ur%ʣHCfRO]Lb%?wUlx©%"P>sH{"*KK}Pgrk4Q#{VZ6G>͕*JUPQ)4{jƅ˕<@^CexOo>ㄅiZV{_1D0>:BI|6}o3/ |bW@3lG;j[&AQI=~I%Ӱ2򚂖Z)J.#>xcWk~3k"%,ʪ}bA60iϑiKOf$ 4~e;Wt8UYNBc[\^p:Y)|$Q6~b#FY EtX|)YzStm]4.- M ~&'$g<.@ӗ[zrR$J2jUxdA޾};T^f#2`xh0۸0"o… +U'p zQZH$U=HvDGFr솘;0:bj%S?)AZ%V`bP> G 4α XgKRKF;EشxUENU1'@ؼ^M0|ci\j4$JxY?IN@c,R%|$%S]!`|Yg-n>_rFHB n Hj&߽r 䄹1GF*6y2-`92T](9}b1HL+~Ԃx^G*xgb\A# sx~a&~}m> xކhE"DnuX ZP w~O߯]hn7UJgy^/|Mw|fZ_߯S*6}V$բVUv<ܬf}z>(naջzW Xw5W;AYHDg_ZGB詃ޒ//Ag b)UQJ gG#XOªH;p9X>z7G?y5R9J춶Į/ko. Co{{_ڞ^wo_CG~r:2zw쾗_g[!:c^]弻39o&h{y|VYK?wp(B:;{u_uxzpgo_.Z6~1"[!e> $F]c/4/1_c,lߓAc Vn:&ocYݷo|]D6ivL\xsȦ,ӢmIG˸Fƪ;M1={RGv>ي/nqo>V<|koYXBù/ז?JdC?c9d.\;XaXy$6}8eɺ~x on_̫⟟Q:`wǦD6azdg{ߓINΪ|?"{Md 4a _R7ߎ6ܖӒ';sv8DQؓO ^/bx|6>d=wb(0~X~wWdͿwm<1mU,o^?T`9wǼȧϏl}Nq΂wI\?o/<[7oc.c/ټks~SO :7F F{Q>kaf}vvԋo1n>͌A.]Iz~^ߌlԘ0gq8f]oPKXܵ-kc"#s;4wGx}]e#[p]\^$Bk9=Ș4iy|y?nȦ̎/ V:`d3Vno:ޖ#;OXƈ/! Hv!S/c?x6Iň%yrȲ46*p XuwEv/!9 tAǧ܀"&xn ͡ȜwŹĔkGX oaO^)Ė9%ԩv2y倵{JXVv`2AÎ5]Xy1|LtkѺy X>v N+ę=2<uօ7i}C gs?֐s.XzV5{'aX=Vz`X=Vzkb88Oƨ&Z+*jy((ZC4 RcRkZjKLVD ⽦Mj-ؗD}k/1jj4[4^%hjlY`٥{N`Yet_r2 r`,E"X`,E"X`,E"X`,E"X`,E"X`,E"X`,E"X`,E"X+W&`E5N; gdtHe5;Xr-ol-`kF4X OQ{ ViJ+_ﰊ a;Xcr p -(G>u̴4kTɘT{4V86{#EMɊ;뤎/F4yZ9똯BsV| ft&{̙ Ov̘,׃-0S>ńeZھY|)ALО^0޿ƌAH#}043 1_VˍQT L^Ȓ.>Os1$FIiqDDl:v;V~V/: Sa)Z og\=Hu~I5)EΗ4'8~ζx>yw&<:duq,i`@ 5!Z瞚%0 .sw{M`ynf/w4GDNԄ7ZvI޺~jPQ߆M(鱶Z8{z]XWmmAY_a@r3jPYy6Əuurk vcacnvط?C51ocsA%Y`wXZk6nZ#^Q׈͸}ng]h O`'Rܶp}!AbB\W0^n]ڍ!Pm :Sm?DJ2ouCޣ]kWw...W,ݒ';5^ec_<ݾz`/؟G"$?EK IENDB`devise-3.5.6/MIT-LICENSE0000644000004100000410000000207712663066463014512 0ustar www-datawww-dataCopyright 2009-2015 Plataformatec. http://plataformatec.com.br Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 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. devise-3.5.6/CODE_OF_CONDUCT.md0000644000004100000410000000377512663066463015663 0ustar www-datawww-data# Contributor Code of Conduct As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by sending an email to [conduct@plataformatec.com.br](conduct@plataformatec.com.br) or contacting one or more of the project maintainers. This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/) devise-3.5.6/.travis.yml0000644000004100000410000000146412663066463015166 0ustar www-datawww-datalanguage: ruby rvm: - 1.9.3 - 2.0.0 - 2.1 - 2.2 gemfile: - gemfiles/Gemfile.rails-4.2-stable - gemfiles/Gemfile.rails-4.1-stable - gemfiles/Gemfile.rails-4.0-stable - gemfiles/Gemfile.rails-3.2-stable - Gemfile matrix: exclude: - rvm: 2.2 gemfile: gemfiles/Gemfile.rails-3.2-stable services: - mongodb sudo: false cache: bundler env: matrix: - DEVISE_ORM=mongoid - DEVISE_ORM=active_record before_install: "rm ${BUNDLE_GEMFILE}.lock" before_script: "bundle update" script: "bundle exec rake test" notifications: email: false slack: on_success: change on_failure: always secure: Q3M+kmude3FjisibEeeGe0wSMXgvwLH+vL7Zrx9//q4QtkfnrQ/BBMvY9KXxPEsNF+eys4YopYjTkJ8uRmeboUATW/oQ4Jrv3+u3zkIHK2sFn/Q2cQWpK5w+CbgEnHPjKYnUu34b09njXTgDlr/mqtbPqrKeZ1dLlpKXCB/q4GY= devise-3.5.6/lib/0000755000004100000410000000000012663066463013616 5ustar www-datawww-datadevise-3.5.6/lib/generators/0000755000004100000410000000000012663066463015767 5ustar www-datawww-datadevise-3.5.6/lib/generators/mongoid/0000755000004100000410000000000012663066463017423 5ustar www-datawww-datadevise-3.5.6/lib/generators/mongoid/devise_generator.rb0000644000004100000410000000325312663066463023300 0ustar www-datawww-datarequire 'rails/generators/named_base' require 'generators/devise/orm_helpers' module Mongoid module Generators class DeviseGenerator < Rails::Generators::NamedBase include Devise::Generators::OrmHelpers def generate_model invoke "mongoid:model", [name] unless model_exists? && behavior == :invoke end def inject_field_types inject_into_file model_path, migration_data, after: "include Mongoid::Document\n" if model_exists? end def inject_devise_content inject_into_file model_path, model_contents, after: "include Mongoid::Document\n" if model_exists? end def migration_data <Hello <%= @resource.email %>!

We're contacting you to notify you that your password has been changed.

devise-3.5.6/lib/generators/templates/markerb/confirmation_instructions.markerb0000644000004100000410000000024312663066463030270 0ustar www-datawww-dataWelcome <%= @email %>! You can confirm your account through the link below: [Confirm my account](<%= confirmation_url(@resource, confirmation_token: @token) %>) devise-3.5.6/lib/generators/templates/markerb/reset_password_instructions.markerb0000644000004100000410000000054212663066463030646 0ustar www-datawww-dataHello <%= @resource.email %>! Someone has requested a link to change your password, and you can do this through the link below. [Change my password](<%= edit_password_url(@resource, reset_password_token: @token) %>) If you didn't request this, please ignore this email. Your password won't change until you access the link above and create a new one. devise-3.5.6/lib/generators/templates/markerb/unlock_instructions.markerb0000644000004100000410000000036012663066463027073 0ustar www-datawww-dataHello <%= @resource.email %>! Your account has been locked due to an excessive number of unsuccessful sign in attempts. Click the link below to unlock your account: [Unlock my account](<%= unlock_url(@resource, unlock_token: @token) %>) devise-3.5.6/lib/generators/templates/controllers/0000755000004100000410000000000012663066463022333 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/controllers/unlocks_controller.rb0000644000004100000410000000106412663066463026602 0ustar www-datawww-dataclass <%= @scope_prefix %>UnlocksController < Devise::UnlocksController # GET /resource/unlock/new # def new # super # end # POST /resource/unlock # def create # super # end # GET /resource/unlock?unlock_token=abcdef # def show # super # end # protected # The path used after sending unlock password instructions # def after_sending_unlock_instructions_path_for(resource) # super(resource) # end # The path used after unlocking the resource # def after_unlock_path_for(resource) # super(resource) # end end devise-3.5.6/lib/generators/templates/controllers/registrations_controller.rb0000644000004100000410000000256512663066463030030 0ustar www-datawww-dataclass <%= @scope_prefix %>RegistrationsController < Devise::RegistrationsController # before_filter :configure_sign_up_params, only: [:create] # before_filter :configure_account_update_params, only: [:update] # GET /resource/sign_up # def new # super # end # POST /resource # def create # super # end # GET /resource/edit # def edit # super # end # PUT /resource # def update # super # end # DELETE /resource # def destroy # super # end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. # def cancel # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_up_params # devise_parameter_sanitizer.for(:sign_up) << :attribute # end # If you have extra params to permit, append them to the sanitizer. # def configure_account_update_params # devise_parameter_sanitizer.for(:account_update) << :attribute # end # The path used after sign up. # def after_sign_up_path_for(resource) # super(resource) # end # The path used after sign up for inactive accounts. # def after_inactive_sign_up_path_for(resource) # super(resource) # end end devise-3.5.6/lib/generators/templates/controllers/README0000644000004100000410000000067012663066463023216 0ustar www-datawww-data=============================================================================== Some setup you must do manually if you haven't yet: Ensure you have overridden routes for generated controllers in your routes.rb. For example: Rails.application.routes.draw do devise_for :users, controllers: { sessions: 'users/sessions' } end =============================================================================== devise-3.5.6/lib/generators/templates/controllers/sessions_controller.rb0000644000004100000410000000100212663066463026762 0ustar www-datawww-dataclass <%= @scope_prefix %>SessionsController < Devise::SessionsController # before_filter :configure_sign_in_params, only: [:create] # GET /resource/sign_in # def new # super # end # POST /resource/sign_in # def create # super # end # DELETE /resource/sign_out # def destroy # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_in_params # devise_parameter_sanitizer.for(:sign_in) << :attribute # end end devise-3.5.6/lib/generators/templates/controllers/omniauth_callbacks_controller.rb0000644000004100000410000000121412663066463030744 0ustar www-datawww-dataclass <%= @scope_prefix %>OmniauthCallbacksController < Devise::OmniauthCallbacksController # You should configure your model like this: # devise :omniauthable, omniauth_providers: [:twitter] # You should also create an action method in this controller like this: # def twitter # end # More info at: # https://github.com/plataformatec/devise#omniauth # GET|POST /resource/auth/twitter # def passthru # super # end # GET|POST /users/auth/twitter/callback # def failure # super # end # protected # The path used when OmniAuth fails # def after_omniauth_failure_path_for(scope) # super(scope) # end end devise-3.5.6/lib/generators/templates/controllers/confirmations_controller.rb0000644000004100000410000000120512663066463027774 0ustar www-datawww-dataclass <%= @scope_prefix %>ConfirmationsController < Devise::ConfirmationsController # GET /resource/confirmation/new # def new # super # end # POST /resource/confirmation # def create # super # end # GET /resource/confirmation?confirmation_token=abcdef # def show # super # end # protected # The path used after resending confirmation instructions. # def after_resending_confirmation_instructions_path_for(resource_name) # super(resource_name) # end # The path used after confirmation. # def after_confirmation_path_for(resource_name, resource) # super(resource_name, resource) # end end devise-3.5.6/lib/generators/templates/controllers/passwords_controller.rb0000644000004100000410000000117012663066463027147 0ustar www-datawww-dataclass <%= @scope_prefix %>PasswordsController < Devise::PasswordsController # GET /resource/password/new # def new # super # end # POST /resource/password # def create # super # end # GET /resource/password/edit?reset_password_token=abcdef # def edit # super # end # PUT /resource/password # def update # super # end # protected # def after_resetting_password_path_for(resource) # super(resource) # end # The path used after sending reset password instructions # def after_sending_reset_password_instructions_path_for(resource_name) # super(resource_name) # end end devise-3.5.6/lib/generators/templates/README0000644000004100000410000000236512663066463020653 0ustar www-datawww-data=============================================================================== Some setup you must do manually if you haven't yet: 1. Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment in config/environments/development.rb: config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } In production, :host should be set to the actual host of your application. 2. Ensure you have defined root_url to *something* in your config/routes.rb. For example: root to: "home#index" 3. Ensure you have flash messages in app/views/layouts/application.html.erb. For example:

<%= notice %>

<%= alert %>

4. If you are deploying on Heroku with Rails 3.2 only, you may want to set: config.assets.initialize_on_precompile = false On config/application.rb forcing your application to not access the DB or load models when precompiling your assets. 5. You can copy Devise views (for customization) to your app by running: rails g devise:views =============================================================================== devise-3.5.6/lib/generators/templates/simple_form_for/0000755000004100000410000000000012663066463023147 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/simple_form_for/sessions/0000755000004100000410000000000012663066463025015 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/simple_form_for/sessions/new.html.erb0000644000004100000410000000070712663066463027247 0ustar www-datawww-data

Log in

<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.input :email, required: false, autofocus: true %> <%= f.input :password, required: false %> <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
<%= f.button :submit, "Log in" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/lib/generators/templates/simple_form_for/registrations/0000755000004100000410000000000012663066463026044 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/simple_form_for/registrations/new.html.erb0000644000004100000410000000105512663066463030273 0ustar www-datawww-data

Sign up

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= f.error_notification %>
<%= f.input :email, required: true, autofocus: true %> <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %> <%= f.input :password_confirmation, required: true %>
<%= f.button :submit, "Sign up" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/lib/generators/templates/simple_form_for/registrations/edit.html.erb0000644000004100000410000000204012663066463030422 0ustar www-datawww-data

Edit <%= resource_name.to_s.humanize %>

<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> <%= f.error_notification %>
<%= f.input :email, required: true, autofocus: true %> <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>

Currently waiting confirmation for: <%= resource.unconfirmed_email %>

<% end %> <%= f.input :password, autocomplete: "off", hint: "leave it blank if you don't want to change it", required: false %> <%= f.input :password_confirmation, required: false %> <%= f.input :current_password, hint: "we need your current password to confirm your changes", required: true %>
<%= f.button :submit, "Update" %>
<% end %>

Cancel my account

Unhappy? <%= link_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

<%= link_to "Back", :back %> devise-3.5.6/lib/generators/templates/simple_form_for/unlocks/0000755000004100000410000000000012663066463024625 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/simple_form_for/unlocks/new.html.erb0000644000004100000410000000071512663066463027056 0ustar www-datawww-data

Resend unlock instructions

<%= simple_form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %> <%= f.full_error :unlock_token %>
<%= f.input :email, required: true, autofocus: true %>
<%= f.button :submit, "Resend unlock instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/lib/generators/templates/simple_form_for/passwords/0000755000004100000410000000000012663066463025174 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/simple_form_for/passwords/new.html.erb0000644000004100000410000000065712663066463027432 0ustar www-datawww-data

Forgot your password?

<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %>
<%= f.input :email, required: true, autofocus: true %>
<%= f.button :submit, "Send me reset password instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/lib/generators/templates/simple_form_for/passwords/edit.html.erb0000644000004100000410000000131312663066463027554 0ustar www-datawww-data

Change your password

<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> <%= f.error_notification %> <%= f.input :reset_password_token, as: :hidden %> <%= f.full_error :reset_password_token %>
<%= f.input :password, label: "New password", required: true, autofocus: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %> <%= f.input :password_confirmation, label: "Confirm your new password", required: true %>
<%= f.button :submit, "Change my password" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/lib/generators/templates/simple_form_for/confirmations/0000755000004100000410000000000012663066463026022 5ustar www-datawww-datadevise-3.5.6/lib/generators/templates/simple_form_for/confirmations/new.html.erb0000644000004100000410000000074512663066463030256 0ustar www-datawww-data

Resend confirmation instructions

<%= simple_form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> <%= f.error_notification %> <%= f.full_error :confirmation_token %>
<%= f.input :email, required: true, autofocus: true %>
<%= f.button :submit, "Resend confirmation instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/lib/generators/templates/devise.rb0000644000004100000410000003134412663066463021576 0ustar www-datawww-data# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` # by default. You can change it below and use your own secret key. <% if rails_4? -%> # config.secret_key = '<%= SecureRandom.hex(64) %>' <% else -%> config.secret_key = '<%= SecureRandom.hex(64) %>' <% end -%> # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/<%= options[:orm] %>' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '<%= SecureRandom.hex(64) %>' # Send a notification email when the user's password is changed # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 8..72 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end devise-3.5.6/lib/generators/active_record/0000755000004100000410000000000012663066463020600 5ustar www-datawww-datadevise-3.5.6/lib/generators/active_record/templates/0000755000004100000410000000000012663066463022576 5ustar www-datawww-datadevise-3.5.6/lib/generators/active_record/templates/migration_existing.rb0000644000004100000410000000166012663066463027031 0ustar www-datawww-dataclass AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration def self.up change_table(:<%= table_name %>) do |t| <%= migration_data -%> <% attributes.each do |attribute| -%> t.<%= attribute.type %> :<%= attribute.name %> <% end -%> # Uncomment below if timestamps were not included in your original model. # t.timestamps null: false end add_index :<%= table_name %>, :email, unique: true add_index :<%= table_name %>, :reset_password_token, unique: true # add_index :<%= table_name %>, :confirmation_token, unique: true # add_index :<%= table_name %>, :unlock_token, unique: true end def self.down # By default, we don't want to make any assumption about how to roll back a migration when your # model already existed. Please edit below which fields you would like to remove in this migration. raise ActiveRecord::IrreversibleMigration end end devise-3.5.6/lib/generators/active_record/templates/migration.rb0000644000004100000410000000111512663066463025112 0ustar www-datawww-dataclass DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration def change create_table(:<%= table_name %>) do |t| <%= migration_data -%> <% attributes.each do |attribute| -%> t.<%= attribute.type %> :<%= attribute.name %> <% end -%> t.timestamps null: false end add_index :<%= table_name %>, :email, unique: true add_index :<%= table_name %>, :reset_password_token, unique: true # add_index :<%= table_name %>, :confirmation_token, unique: true # add_index :<%= table_name %>, :unlock_token, unique: true end end devise-3.5.6/lib/generators/active_record/devise_generator.rb0000644000004100000410000000533412663066463024457 0ustar www-datawww-datarequire 'rails/generators/active_record' require 'generators/devise/orm_helpers' module ActiveRecord module Generators class DeviseGenerator < ActiveRecord::Generators::Base argument :attributes, type: :array, default: [], banner: "field:type field:type" include Devise::Generators::OrmHelpers source_root File.expand_path("../templates", __FILE__) def copy_devise_migration if (behavior == :invoke && model_exists?) || (behavior == :revoke && migration_exists?(table_name)) migration_template "migration_existing.rb", "db/migrate/add_devise_to_#{table_name}.rb" else migration_template "migration.rb", "db/migrate/devise_create_#{table_name}.rb" end end def generate_model invoke "active_record:model", [name], migration: false unless model_exists? && behavior == :invoke end def inject_devise_content content = model_contents class_path = if namespaced? class_name.to_s.split("::") else [class_name] end indent_depth = class_path.size - 1 content = content.split("\n").map { |line| " " * indent_depth + line } .join("\n") << "\n" inject_into_class(model_path, class_path.last, content) if model_exists? end def migration_data <= 4) && (Rails::VERSION::MINOR >= 2) opts[:script_name] = (config.relative_url_root if config.respond_to?(:relative_url_root)) else if config.respond_to?(:relative_url_root) && config.relative_url_root.present? opts[:script_name] = config.relative_url_root end end router_name = Devise.mappings[scope].router_name || Devise.available_router_name context = send(router_name) if context.respond_to?(route) context.send(route, opts) elsif respond_to?(:root_url) root_url(opts) else "/" end end def skip_format? %w(html */*).include? request_format.to_s end # Choose whether we should respond in a http authentication fashion, # including 401 and optional headers. # # This method allows the user to explicitly disable http authentication # on ajax requests in case they want to redirect on failures instead of # handling the errors on their own. This is useful in case your ajax API # is the same as your public API and uses a format like JSON (so you # cannot mark JSON as a navigational format). def http_auth? if request.xhr? Devise.http_authenticatable_on_xhr else !(request_format && is_navigational_format?) end end # It does not make sense to send authenticate headers in ajax requests # or if the user disabled them. def http_auth_header? scope_class.http_authenticatable && !request.xhr? end def http_auth_body return i18n_message unless request_format method = "to_#{request_format}" if method == "to_xml" { error: i18n_message }.to_xml(root: "errors") elsif {}.respond_to?(method) { error: i18n_message }.send(method) else i18n_message end end def recall_app(app) controller, action = app.split("#") controller_name = ActiveSupport::Inflector.camelize(controller) controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller") controller_klass.action(action) end def warden env['warden'] end def warden_options env['warden.options'] end def warden_message @message ||= warden.message || warden_options[:message] end def scope @scope ||= warden_options[:scope] || Devise.default_scope end def scope_class @scope_class ||= Devise.mappings[scope].to end def attempted_path warden_options[:attempted_path] end # Stores requested uri to redirect the user after signing in. We cannot use # scoped session provided by warden here, since the user is not authenticated # yet, but we still need to store the uri based on scope, so different scopes # would never use the same uri to redirect. def store_location! store_location_for(scope, attempted_path) if request.get? && !http_auth? end def is_navigational_format? Devise.navigational_formats.include?(request_format) end # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? is_navigational_format? end def request_format @request_format ||= request.format.try(:ref) end end end devise-3.5.6/lib/devise/controllers/0000755000004100000410000000000012663066463017443 5ustar www-datawww-datadevise-3.5.6/lib/devise/controllers/store_location.rb0000644000004100000410000000330212663066463023012 0ustar www-datawww-datarequire "uri" module Devise module Controllers # Provide the ability to store a location. # Used to redirect back to a desired path after sign in. # Included by default in all controllers. module StoreLocation # Returns and delete (if it's navigational format) the url stored in the session for # the given scope. Useful for giving redirect backs after sign up: # # Example: # # redirect_to stored_location_for(:user) || root_path # def stored_location_for(resource_or_scope) session_key = stored_location_key_for(resource_or_scope) if is_navigational_format? session.delete(session_key) else session[session_key] end end # Stores the provided location to redirect the user after signing in. # Useful in combination with the `stored_location_for` helper. # # Example: # # store_location_for(:user, dashboard_path) # redirect_to user_omniauth_authorize_path(:facebook) # def store_location_for(resource_or_scope, location) session_key = stored_location_key_for(resource_or_scope) uri = parse_uri(location) if uri path = [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?') path = [path, uri.fragment].compact.join('#') session[session_key] = path end end private def parse_uri(location) location && URI.parse(location) rescue URI::InvalidURIError nil end def stored_location_key_for(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) "#{scope}_return_to" end end end end devise-3.5.6/lib/devise/controllers/rememberable.rb0000644000004100000410000000357512663066463022424 0ustar www-datawww-datamodule Devise module Controllers # A module that may be optionally included in a controller in order # to provide remember me behavior. Useful when signing in is done # through a callback, like in OmniAuth. module Rememberable # Return default cookie values retrieved from session options. def self.cookie_values Rails.configuration.session_options.slice(:path, :domain, :secure) end def remember_me_is_active?(resource) return false unless resource.respond_to?(:remember_me) scope = Devise::Mapping.find_scope!(resource) _, token, generated_at = cookies.signed[remember_key(resource, scope)] resource.remember_me?(token, generated_at) end # Remembers the given resource by setting up a cookie def remember_me(resource) return if env["devise.skip_storage"] scope = Devise::Mapping.find_scope!(resource) resource.remember_me! cookies.signed[remember_key(resource, scope)] = remember_cookie_values(resource) end # Forgets the given resource by deleting a cookie def forget_me(resource) scope = Devise::Mapping.find_scope!(resource) resource.forget_me! cookies.delete(remember_key(resource, scope), forget_cookie_values(resource)) end protected def forget_cookie_values(resource) Devise::Controllers::Rememberable.cookie_values.merge!(resource.rememberable_options) end def remember_cookie_values(resource) options = { httponly: true } options.merge!(forget_cookie_values(resource)) options.merge!( value: resource.class.serialize_into_cookie(resource), expires: resource.remember_expires_at ) end def remember_key(resource, scope) resource.rememberable_options.fetch(:key, "remember_#{scope}_token") end end end end devise-3.5.6/lib/devise/controllers/scoped_views.rb0000644000004100000410000000052112663066463022460 0ustar www-datawww-datamodule Devise module Controllers module ScopedViews extend ActiveSupport::Concern module ClassMethods def scoped_views? defined?(@scoped_views) ? @scoped_views : Devise.scoped_views end def scoped_views=(value) @scoped_views = value end end end end end devise-3.5.6/lib/devise/controllers/url_helpers.rb0000644000004100000410000000463412663066463022323 0ustar www-datawww-datamodule Devise module Controllers # Create url helpers to be used with resource/scope configuration. Acts as # proxies to the generated routes created by devise. # Resource param can be a string or symbol, a class, or an instance object. # Example using a :user resource: # # new_session_path(:user) => new_user_session_path # session_path(:user) => user_session_path # destroy_session_path(:user) => destroy_user_session_path # # new_password_path(:user) => new_user_password_path # password_path(:user) => user_password_path # edit_password_path(:user) => edit_user_password_path # # new_confirmation_path(:user) => new_user_confirmation_path # confirmation_path(:user) => user_confirmation_path # # Those helpers are included by default to ActionController::Base. # # In case you want to add such helpers to another class, you can do # that as long as this new class includes both url_helpers and # mounted_helpers. Example: # # include Rails.application.routes.url_helpers # include Rails.application.routes.mounted_helpers # module UrlHelpers def self.remove_helpers! self.instance_methods.map(&:to_s).grep(/_(url|path)$/).each do |method| remove_method method end end def self.generate_helpers!(routes=nil) routes ||= begin mappings = Devise.mappings.values.map(&:used_helpers).flatten.uniq Devise::URL_HELPERS.slice(*mappings) end routes.each do |module_name, actions| [:path, :url].each do |path_or_url| actions.each do |action| action = action ? "#{action}_" : "" method = :"#{action}#{module_name}_#{path_or_url}" define_method method do |resource_or_scope, *args| scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name context = router_name ? send(router_name) : _devise_route_context context.send("#{action}#{scope}_#{module_name}_#{path_or_url}", *args) end end end end end generate_helpers!(Devise::URL_HELPERS) private def _devise_route_context @_devise_route_context ||= send(Devise.available_router_name) end end end end devise-3.5.6/lib/devise/controllers/helpers.rb0000644000004100000410000002602512663066463021437 0ustar www-datawww-datamodule Devise module Controllers # Those helpers are convenience methods added to ApplicationController. module Helpers extend ActiveSupport::Concern include Devise::Controllers::SignInOut include Devise::Controllers::StoreLocation included do if respond_to?(:helper_method) helper_method :warden, :signed_in?, :devise_controller? end end module ClassMethods # Define authentication filters and accessor helpers for a group of mappings. # These methods are useful when you are working with multiple mappings that # share some functionality. They are pretty much the same as the ones # defined for normal mappings. # # Example: # # inside BlogsController (or any other controller, it doesn't matter which): # devise_group :blogger, contains: [:user, :admin] # # Generated methods: # authenticate_blogger! # Redirects unless user or admin are signed in # blogger_signed_in? # Checks whether there is either a user or an admin signed in # current_blogger # Currently signed in user or admin # current_bloggers # Currently signed in user and admin # # Use: # before_filter :authenticate_blogger! # Redirects unless either a user or an admin are authenticated # before_filter ->{ authenticate_blogger! :admin } # Redirects to the admin login page # current_blogger :user # Preferably returns a User if one is signed in # def devise_group(group_name, opts={}) mappings = "[#{ opts[:contains].map { |m| ":#{m}" }.join(',') }]" class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{group_name}!(favourite=nil, opts={}) unless #{group_name}_signed_in? mappings = #{mappings} mappings.unshift mappings.delete(favourite.to_sym) if favourite mappings.each do |mapping| opts[:scope] = mapping warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end end end def #{group_name}_signed_in? #{mappings}.any? do |mapping| warden.authenticate?(scope: mapping) end end def current_#{group_name}(favourite=nil) mappings = #{mappings} mappings.unshift mappings.delete(favourite.to_sym) if favourite mappings.each do |mapping| current = warden.authenticate(scope: mapping) return current if current end nil end def current_#{group_name.to_s.pluralize} #{mappings}.map do |mapping| warden.authenticate(scope: mapping) end.compact end if respond_to?(:helper_method) helper_method "current_#{group_name}", "current_#{group_name.to_s.pluralize}", "#{group_name}_signed_in?" end METHODS end def log_process_action(payload) payload[:status] ||= 401 unless payload[:exception] super end end # Define authentication filters and accessor helpers based on mappings. # These filters should be used inside the controllers as before_filters, # so you can control the scope of the user who should be signed in to # access that specific controller/action. # Example: # # Roles: # User # Admin # # Generated methods: # authenticate_user! # Signs user in or redirect # authenticate_admin! # Signs admin in or redirect # user_signed_in? # Checks whether there is a user signed in or not # admin_signed_in? # Checks whether there is an admin signed in or not # current_user # Current signed in user # current_admin # Current signed in admin # user_session # Session data available only to the user scope # admin_session # Session data available only to the admin scope # # Use: # before_filter :authenticate_user! # Tell devise to use :user map # before_filter :authenticate_admin! # Tell devise to use :admin map # def self.define_helpers(mapping) #:nodoc: mapping = mapping.name class_eval <<-METHODS, __FILE__, __LINE__ + 1 def authenticate_#{mapping}!(opts={}) opts[:scope] = :#{mapping} warden.authenticate!(opts) if !devise_controller? || opts.delete(:force) end def #{mapping}_signed_in? !!current_#{mapping} end def current_#{mapping} @current_#{mapping} ||= warden.authenticate(scope: :#{mapping}) end def #{mapping}_session current_#{mapping} && warden.session(:#{mapping}) end METHODS ActiveSupport.on_load(:action_controller) do if respond_to?(:helper_method) helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session" end end end # The main accessor for the warden proxy instance def warden request.env['warden'] end # Return true if it's a devise_controller. false to all controllers unless # the controllers defined inside devise. Useful if you want to apply a before # filter to all controllers, except the ones in devise: # # before_filter :my_filter, unless: :devise_controller? def devise_controller? is_a?(::DeviseController) end # Setup a param sanitizer to filter parameters using strong_parameters. See # lib/devise/parameter_sanitizer.rb for more info. Override this # method in your application controller to use your own parameter sanitizer. def devise_parameter_sanitizer @devise_parameter_sanitizer ||= if defined?(ActionController::StrongParameters) Devise::ParameterSanitizer.new(resource_class, resource_name, params) else Devise::BaseSanitizer.new(resource_class, resource_name, params) end end # Tell warden that params authentication is allowed for that specific page. def allow_params_authentication! request.env["devise.allow_params_authentication"] = true end # The scope root url to be used when they're signed in. By default, it first # tries to find a resource_root_path, otherwise it uses the root_path. def signed_in_root_path(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name home_path = "#{scope}_root_path" context = router_name ? send(router_name) : self if context.respond_to?(home_path, true) context.send(home_path) elsif context.respond_to?(:root_path) context.root_path elsif respond_to?(:root_path) root_path else "/" end end # The default url to be used after signing in. This is used by all Devise # controllers and you can overwrite it in your ApplicationController to # provide a custom hook for a custom resource. # # By default, it first tries to find a valid resource_return_to key in the # session, then it fallbacks to resource_root_path, otherwise it uses the # root path. For a user scope, you can define the default url in # the following way: # # get '/users' => 'users#index', as: :user_root # creates user_root_path # # namespace :user do # root 'users#index' # creates user_root_path # end # # If the resource root path is not defined, root_path is used. However, # if this default is not enough, you can customize it, for example: # # def after_sign_in_path_for(resource) # stored_location_for(resource) || # if resource.is_a?(User) && resource.can_publish? # publisher_url # else # super # end # end # def after_sign_in_path_for(resource_or_scope) stored_location_for(resource_or_scope) || signed_in_root_path(resource_or_scope) end # Method used by sessions controller to sign out a user. You can overwrite # it in your ApplicationController to provide a custom hook for a custom # scope. Notice that differently from +after_sign_in_path_for+ this method # receives a symbol with the scope, and not the resource. # # By default it is the root_path. def after_sign_out_path_for(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) router_name = Devise.mappings[scope].router_name context = router_name ? send(router_name) : self context.respond_to?(:root_path) ? context.root_path : "/" end # Sign in a user and tries to redirect first to the stored location and # then to the url specified by after_sign_in_path_for. It accepts the same # parameters as the sign_in method. def sign_in_and_redirect(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope sign_in(scope, resource, options) redirect_to after_sign_in_path_for(resource) end # Sign out a user and tries to redirect to the url specified by # after_sign_out_path_for. def sign_out_and_redirect(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) redirect_path = after_sign_out_path_for(scope) Devise.sign_out_all_scopes ? sign_out : sign_out(scope) redirect_to redirect_path end # Overwrite Rails' handle unverified request to sign out all scopes, # clear run strategies and remove cached variables. def handle_unverified_request super # call the default behaviour which resets/nullifies/raises request.env["devise.skip_storage"] = true sign_out_all_scopes(false) end def request_format @request_format ||= request.format.try(:ref) end def is_navigational_format? Devise.navigational_formats.include?(request_format) end # Check if flash messages should be emitted. Default is to do it on # navigational formats def is_flashing_format? is_navigational_format? end private def expire_session_data_after_sign_in! ActiveSupport::Deprecation.warn "expire_session_data_after_sign_in! is deprecated " \ "in favor of expire_data_after_sign_in!" expire_data_after_sign_in! end def expire_data_after_sign_out! Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) } super end end end end devise-3.5.6/lib/devise/controllers/sign_in_out.rb0000644000004100000410000000736012663066463022313 0ustar www-datawww-datamodule Devise module Controllers # Provide sign in and sign out functionality. # Included by default in all controllers. module SignInOut # Return true if the given scope is signed in session. If no scope given, return # true if any scope is signed in. Does not run authentication hooks. def signed_in?(scope=nil) [scope || Devise.mappings.keys].flatten.any? do |_scope| warden.authenticate?(scope: _scope) end end # Sign in a user that already was authenticated. This helper is useful for logging # users in after sign up. # # All options given to sign_in is passed forward to the set_user method in warden. # The only exception is the :bypass option, which bypass warden callbacks and stores # the user straight in session. This option is useful in cases the user is already # signed in, but we want to refresh the credentials in session. # # Examples: # # sign_in :user, @user # sign_in(scope, resource) # sign_in @user # sign_in(resource) # sign_in @user, event: :authentication # sign_in(resource, options) # sign_in @user, store: false # sign_in(resource, options) # sign_in @user, bypass: true # sign_in(resource, options) # def sign_in(resource_or_scope, *args) options = args.extract_options! scope = Devise::Mapping.find_scope!(resource_or_scope) resource = args.last || resource_or_scope expire_data_after_sign_in! if options[:bypass] warden.session_serializer.store(resource, scope) elsif warden.user(scope) == resource && !options.delete(:force) # Do nothing. User already signed in and we are not forcing it. true else warden.set_user(resource, options.merge!(scope: scope)) end end # Sign out a given user or scope. This helper is useful for signing out a user # after deleting accounts. Returns true if there was a logout and false if there # is no user logged in on the referred scope # # Examples: # # sign_out :user # sign_out(scope) # sign_out @user # sign_out(resource) # def sign_out(resource_or_scope=nil) return sign_out_all_scopes unless resource_or_scope scope = Devise::Mapping.find_scope!(resource_or_scope) user = warden.user(scope: scope, run_callbacks: false) # If there is no user warden.raw_session.inspect # Without this inspect here. The session does not clear. warden.logout(scope) warden.clear_strategies_cache!(scope: scope) instance_variable_set(:"@current_#{scope}", nil) !!user end # Sign out all active users or scopes. This helper is useful for signing out all roles # in one click. This signs out ALL scopes in warden. Returns true if there was at least one logout # and false if there was no user logged in on all scopes. def sign_out_all_scopes(lock=true) users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) } warden.logout expire_data_after_sign_out! warden.clear_strategies_cache! warden.lock! if lock users.any? end private def expire_data_after_sign_in! # session.keys will return an empty array if the session is not yet loaded. # This is a bug in both Rack and Rails. # A call to #empty? forces the session to be loaded. session.empty? session.keys.grep(/^devise\./).each { |k| session.delete(k) } end alias :expire_data_after_sign_out! :expire_data_after_sign_in! end end end devise-3.5.6/lib/devise/mailers/0000755000004100000410000000000012663066463016531 5ustar www-datawww-datadevise-3.5.6/lib/devise/mailers/helpers.rb0000644000004100000410000000470012663066463020521 0ustar www-datawww-datamodule Devise module Mailers module Helpers extend ActiveSupport::Concern included do include Devise::Controllers::ScopedViews attr_reader :scope_name, :resource end protected # Configure default email options def devise_mail(record, action, opts={}) initialize_from_record(record) mail headers_for(action, opts) end def initialize_from_record(record) @scope_name = Devise::Mapping.find_scope!(record) @resource = instance_variable_set("@#{devise_mapping.name}", record) end def devise_mapping @devise_mapping ||= Devise.mappings[scope_name] end def headers_for(action, opts) headers = { subject: subject_for(action), to: resource.email, from: mailer_sender(devise_mapping), reply_to: mailer_reply_to(devise_mapping), template_path: template_paths, template_name: action }.merge(opts) @email = headers[:to] headers end def mailer_reply_to(mapping) mailer_sender(mapping, :reply_to) end def mailer_from(mapping) mailer_sender(mapping, :from) end def mailer_sender(mapping, sender = :from) default_sender = default_params[sender] if default_sender.present? default_sender.respond_to?(:to_proc) ? instance_eval(&default_sender) : default_sender elsif Devise.mailer_sender.is_a?(Proc) Devise.mailer_sender.call(mapping.name) else Devise.mailer_sender end end def template_paths template_path = _prefixes.dup template_path.unshift "#{@devise_mapping.scoped_path}/mailer" if self.class.scoped_views? template_path end # Setup a subject doing an I18n lookup. At first, it attempts to set a subject # based on the current mapping: # # en: # devise: # mailer: # confirmation_instructions: # user_subject: '...' # # If one does not exist, it fallbacks to ActionMailer default: # # en: # devise: # mailer: # confirmation_instructions: # subject: '...' # def subject_for(key) I18n.t(:"#{devise_mapping.name}_subject", scope: [:devise, :mailer, key], default: [:subject, key.to_s.humanize]) end end end end devise-3.5.6/lib/devise/time_inflector.rb0000644000004100000410000000041412663066463020424 0ustar www-datawww-datarequire "active_support/core_ext/module/delegation" module Devise class TimeInflector include ActionView::Helpers::DateHelper class << self attr_reader :instance delegate :time_ago_in_words, to: :instance end @instance = new end end devise-3.5.6/lib/devise/omniauth.rb0000644000004100000410000000175112663066463017252 0ustar www-datawww-databegin require "omniauth" require "omniauth/version" rescue LoadError warn "Could not load 'omniauth'. Please ensure you have the omniauth gem >= 1.0.0 installed and listed in your Gemfile." raise end unless OmniAuth::VERSION =~ /^1\./ raise "You are using an old OmniAuth version, please ensure you have 1.0.0.pr2 version or later installed." end # Clean up the default path_prefix. It will be automatically set by Devise. OmniAuth.config.path_prefix = nil OmniAuth.config.on_failure = Proc.new do |env| env['devise.mapping'] = Devise::Mapping.find_by_path!(env['PATH_INFO'], :path) controller_name = ActiveSupport::Inflector.camelize(env['devise.mapping'].controllers[:omniauth_callbacks]) controller_klass = ActiveSupport::Inflector.constantize("#{controller_name}Controller") controller_klass.action(:failure).call(env) end module Devise module OmniAuth autoload :Config, "devise/omniauth/config" autoload :UrlHelpers, "devise/omniauth/url_helpers" end end devise-3.5.6/lib/devise/parameter_filter.rb0000644000004100000410000000226112663066463020750 0ustar www-datawww-datamodule Devise class ParameterFilter def initialize(case_insensitive_keys, strip_whitespace_keys) @case_insensitive_keys = case_insensitive_keys || [] @strip_whitespace_keys = strip_whitespace_keys || [] end def filter(conditions) conditions = stringify_params(conditions.dup) conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :downcase, @case_insensitive_keys)) conditions.merge!(filtered_hash_by_method_for_given_keys(conditions.dup, :strip, @strip_whitespace_keys)) conditions end def filtered_hash_by_method_for_given_keys(conditions, method, condition_keys) condition_keys.each do |k| value = conditions[k] conditions[k] = value.send(method) if value.respond_to?(method) end conditions end # Force keys to be string to avoid injection on mongoid related database. def stringify_params(conditions) return conditions unless conditions.is_a?(Hash) conditions.each do |k, v| conditions[k] = v.to_s if param_requires_string_conversion?(v) end end private def param_requires_string_conversion?(value) true end end end devise-3.5.6/lib/devise/test_helpers.rb0000644000004100000410000001111112663066463020116 0ustar www-datawww-datamodule Devise # Devise::TestHelpers provides a facility to test controllers in isolation # when using ActionController::TestCase allowing you to quickly sign_in or # sign_out a user. Do not use Devise::TestHelpers in integration tests. # # Notice you should not test Warden specific behavior (like Warden callbacks) # using Devise::TestHelpers since it is a stub of the actual behavior. Such # callbacks should be tested in your integration suite instead. module TestHelpers def self.included(base) base.class_eval do setup :setup_controller_for_warden, :warden if respond_to?(:setup) end end # Override process to consider warden. def process(*) # Make sure we always return @response, a la ActionController::TestCase::Behaviour#process, even if warden interrupts _catch_warden { super } || @response end # We need to setup the environment variables and the response in the controller. def setup_controller_for_warden #:nodoc: @request.env['action_controller.instance'] = @controller end # Quick access to Warden::Proxy. def warden #:nodoc: @request.env['warden'] ||= begin manager = Warden::Manager.new(nil) do |config| config.merge! Devise.warden_config end Warden::Proxy.new(@request.env, manager) end end # sign_in a given resource by storing its keys in the session. # This method bypass any warden authentication callback. # # Examples: # # sign_in :user, @user # sign_in(scope, resource) # sign_in @user # sign_in(resource) # def sign_in(resource_or_scope, resource=nil) scope ||= Devise::Mapping.find_scope!(resource_or_scope) resource ||= resource_or_scope warden.instance_variable_get(:@users).delete(scope) warden.session_serializer.store(resource, scope) end # Sign out a given resource or scope by calling logout on Warden. # This method bypass any warden logout callback. # # Examples: # # sign_out :user # sign_out(scope) # sign_out @user # sign_out(resource) # def sign_out(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) @controller.instance_variable_set(:"@current_#{scope}", nil) user = warden.instance_variable_get(:@users).delete(scope) warden.session_serializer.delete(scope, user) end protected # Catch warden continuations and handle like the middleware would. # Returns nil when interrupted, otherwise the normal result of the block. def _catch_warden(&block) result = catch(:warden, &block) env = @controller.request.env result ||= {} # Set the response. In production, the rack result is returned # from Warden::Manager#call, which the following is modelled on. case result when Array if result.first == 401 && intercept_401?(env) # does this happen during testing? _process_unauthenticated(env) else result end when Hash _process_unauthenticated(env, result) else result end end def _process_unauthenticated(env, options = {}) options[:action] ||= :unauthenticated proxy = env['warden'] result = options[:result] || proxy.result ret = case result when :redirect body = proxy.message || "You are being redirected to #{proxy.headers['Location']}" [proxy.status, proxy.headers, [body]] when :custom proxy.custom_response else env["PATH_INFO"] = "/#{options[:action]}" env["warden.options"] = options Warden::Manager._run_callbacks(:before_failure, env, options) status, headers, response = Devise.warden_config[:failure_app].call(env).to_a @controller.response.headers.merge!(headers) @controller.send :render, status: status, text: response.body, content_type: headers["Content-Type"], location: headers["Location"] nil # causes process return @response end # ensure that the controller response is set up. In production, this is # not necessary since warden returns the results to rack. However, at # testing time, we want the response to be available to the testing # framework to verify what would be returned to rack. if ret.is_a?(Array) # ensure the controller response is set to our response. @controller.response ||= @response @response.status = ret.first @response.headers = ret.second @response.body = ret.third end ret end end end devise-3.5.6/lib/devise/encryptor.rb0000644000004100000410000000122012663066463017442 0ustar www-datawww-datarequire 'bcrypt' module Devise module Encryptor def self.digest(klass, password) if klass.pepper.present? password = "#{password}#{klass.pepper}" end ::BCrypt::Password.create(password, cost: klass.stretches).to_s end def self.compare(klass, encrypted_password, password) return false if encrypted_password.blank? bcrypt = ::BCrypt::Password.new(encrypted_password) if klass.pepper.present? password = "#{password}#{klass.pepper}" end password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt) Devise.secure_compare(password, encrypted_password) end end end devise-3.5.6/lib/devise/strategies/0000755000004100000410000000000012663066463017247 5ustar www-datawww-datadevise-3.5.6/lib/devise/strategies/rememberable.rb0000644000004100000410000000374412663066463022226 0ustar www-datawww-datarequire 'devise/strategies/authenticatable' module Devise module Strategies # Remember the user through the remember token. This strategy is responsible # to verify whether there is a cookie with the remember token, and to # recreate the user from this cookie if it exists. Must be called *before* # authenticatable. class Rememberable < Authenticatable # A valid strategy for rememberable needs a remember token in the cookies. def valid? @remember_cookie = nil remember_cookie.present? end # To authenticate a user we deserialize the cookie and attempt finding # the record in the database. If the attempt fails, we pass to another # strategy handle the authentication. def authenticate! resource = mapping.to.serialize_from_cookie(*remember_cookie) unless resource cookies.delete(remember_key) return pass end if validate(resource) remember_me(resource) extend_remember_me_period(resource) resource.after_remembered success!(resource) end end # No need to clean up the CSRF when using rememberable. # In fact, cleaning it up here would be a bug because # rememberable is triggered on GET requests which means # we would render a page on first access with all csrf # tokens expired. def clean_up_csrf? false end private def extend_remember_me_period(resource) if resource.respond_to?(:extend_remember_period=) resource.extend_remember_period = mapping.to.extend_remember_period end end def remember_me? true end def remember_key mapping.to.rememberable_options.fetch(:key, "remember_#{scope}_token") end def remember_cookie @remember_cookie ||= cookies.signed[remember_key] end end end end Warden::Strategies.add(:rememberable, Devise::Strategies::Rememberable) devise-3.5.6/lib/devise/strategies/database_authenticatable.rb0000644000004100000410000000151712663066463024561 0ustar www-datawww-datarequire 'devise/strategies/authenticatable' module Devise module Strategies # Default strategy for signing in a user, based on their email and password in the database. class DatabaseAuthenticatable < Authenticatable def authenticate! resource = password.present? && mapping.to.find_for_database_authentication(authentication_hash) encrypted = false if validate(resource){ encrypted = true; resource.valid_password?(password) } remember_me(resource) resource.after_database_authentication success!(resource) end mapping.to.new.password = password if !encrypted && Devise.paranoid fail(:not_found_in_database) unless resource end end end end Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable) devise-3.5.6/lib/devise/strategies/authenticatable.rb0000644000004100000410000001411412663066463022732 0ustar www-datawww-datarequire 'devise/strategies/base' module Devise module Strategies # This strategy should be used as basis for authentication strategies. It retrieves # parameters both from params or from http authorization headers. See database_authenticatable # for an example. class Authenticatable < Base attr_accessor :authentication_hash, :authentication_type, :password def store? super && !mapping.to.skip_session_storage.include?(authentication_type) end def valid? valid_for_params_auth? || valid_for_http_auth? end # Override and set to false for things like OmniAuth that technically # run through Authentication (user_set) very often, which would normally # reset CSRF data in the session def clean_up_csrf? true end private # Receives a resource and check if it is valid by calling valid_for_authentication? # An optional block that will be triggered while validating can be optionally # given as parameter. Check Devise::Models::Authenticatable.valid_for_authentication? # for more information. # # In case the resource can't be validated, it will fail with the given # unauthenticated_message. def validate(resource, &block) result = resource && resource.valid_for_authentication?(&block) if result true else if resource fail!(resource.unauthenticated_message) end false end end # Get values from params and set in the resource. def remember_me(resource) resource.remember_me = remember_me? if resource.respond_to?(:remember_me=) end # Should this resource be marked to be remembered? def remember_me? valid_params? && Devise::TRUE_VALUES.include?(params_auth_hash[:remember_me]) end # Check if this is a valid strategy for http authentication by: # # * Validating if the model allows http authentication; # * If any of the authorization headers were sent; # * If all authentication keys are present; # def valid_for_http_auth? http_authenticatable? && request.authorization && with_authentication_hash(:http_auth, http_auth_hash) end # Check if this is a valid strategy for params authentication by: # # * Validating if the model allows params authentication; # * If the request hits the sessions controller through POST; # * If the params[scope] returns a hash with credentials; # * If all authentication keys are present; # def valid_for_params_auth? params_authenticatable? && valid_params_request? && valid_params? && with_authentication_hash(:params_auth, params_auth_hash) end # Check if the model accepts this strategy as http authenticatable. def http_authenticatable? mapping.to.http_authenticatable?(authenticatable_name) end # Check if the model accepts this strategy as params authenticatable. def params_authenticatable? mapping.to.params_authenticatable?(authenticatable_name) end # Extract the appropriate subhash for authentication from params. def params_auth_hash params[scope] end # Extract a hash with attributes:values from the http params. def http_auth_hash keys = [http_authentication_key, :password] Hash[*keys.zip(decode_credentials).flatten] end # By default, a request is valid if the controller set the proper env variable. def valid_params_request? !!env["devise.allow_params_authentication"] end # If the request is valid, finally check if params_auth_hash returns a hash. def valid_params? params_auth_hash.is_a?(Hash) end # Note: unlike `Model.valid_password?`, this method does not actually # ensure that the password in the params matches the password stored in # the database. It only checks if the password is *present*. Do not rely # on this method for validating that a given password is correct. def valid_password? password.present? end # Helper to decode credentials from HTTP. def decode_credentials return [] unless request.authorization && request.authorization =~ /^Basic (.*)/mi Base64.decode64($1).split(/:/, 2) end # Sets the authentication hash and the password from params_auth_hash or http_auth_hash. def with_authentication_hash(auth_type, auth_values) self.authentication_hash, self.authentication_type = {}, auth_type self.password = auth_values[:password] parse_authentication_key_values(auth_values, authentication_keys) && parse_authentication_key_values(request_values, request_keys) end def authentication_keys @authentication_keys ||= mapping.to.authentication_keys end def http_authentication_key @http_authentication_key ||= mapping.to.http_authentication_key || case authentication_keys when Array then authentication_keys.first when Hash then authentication_keys.keys.first end end def request_keys @request_keys ||= mapping.to.request_keys end def request_values keys = request_keys.respond_to?(:keys) ? request_keys.keys : request_keys values = keys.map { |k| self.request.send(k) } Hash[keys.zip(values)] end def parse_authentication_key_values(hash, keys) keys.each do |key, enforce| value = hash[key].presence if value self.authentication_hash[key] = value else return false unless enforce == false end end true end # Holds the authenticatable name for this class. Devise::Strategies::DatabaseAuthenticatable # becomes simply :database. def authenticatable_name @authenticatable_name ||= ActiveSupport::Inflector.underscore(self.class.name.split("::").last). sub("_authenticatable", "").to_sym end end end end devise-3.5.6/lib/devise/strategies/base.rb0000644000004100000410000000113712663066463020510 0ustar www-datawww-datamodule Devise module Strategies # Base strategy for Devise. Responsible for verifying correct scope and mapping. class Base < ::Warden::Strategies::Base # Whenever CSRF cannot be verified, we turn off any kind of storage def store? !env["devise.skip_storage"] end # Checks if a valid scope was given for devise and find mapping based on this scope. def mapping @mapping ||= begin mapping = Devise.mappings[scope] raise "Could not find mapping for #{scope}" unless mapping mapping end end end end end devise-3.5.6/lib/devise/hooks/0000755000004100000410000000000012663066463016220 5ustar www-datawww-datadevise-3.5.6/lib/devise/hooks/timeoutable.rb0000644000004100000410000000242312663066463021060 0ustar www-datawww-data# Each time a record is set we check whether its session has already timed out # or not, based on last request time. If so, the record is logged out and # redirected to the sign in page. Also, each time the request comes and the # record is set, we set the last request time inside its scoped session to # verify timeout in the following request. Warden::Manager.after_set_user do |record, warden, options| scope = options[:scope] env = warden.request.env if record && record.respond_to?(:timedout?) && warden.authenticated?(scope) && options[:store] != false && !env['devise.skip_timeoutable'] last_request_at = warden.session(scope)['last_request_at'] if last_request_at.is_a? Integer last_request_at = Time.at(last_request_at).utc elsif last_request_at.is_a? String last_request_at = Time.parse(last_request_at) end proxy = Devise::Hooks::Proxy.new(warden) if record.timedout?(last_request_at) && !env['devise.skip_timeout'] && !proxy.remember_me_is_active?(record) Devise.sign_out_all_scopes ? proxy.sign_out : proxy.sign_out(scope) throw :warden, scope: scope, message: :timeout end unless env['devise.skip_trackable'] warden.session(scope)['last_request_at'] = Time.now.utc.to_i end end end devise-3.5.6/lib/devise/hooks/lockable.rb0000644000004100000410000000063012663066463020320 0ustar www-datawww-data# After each sign in, if resource responds to failed_attempts, sets it to 0 # This is only triggered when the user is explicitly set (with set_user) Warden::Manager.after_set_user except: :fetch do |record, warden, options| if record.respond_to?(:failed_attempts) && warden.authenticated?(options[:scope]) record.update_attribute(:failed_attempts, 0) unless record.failed_attempts.to_i.zero? end end devise-3.5.6/lib/devise/hooks/forgetable.rb0000644000004100000410000000066112663066463020662 0ustar www-datawww-data# Before logout hook to forget the user in the given scope, if it responds # to forget_me! Also clear remember token to ensure the user won't be # remembered again. Notice that we forget the user unless the record is not persisted. # This avoids forgetting deleted users. Warden::Manager.before_logout do |record, warden, options| if record.respond_to?(:forget_me!) Devise::Hooks::Proxy.new(warden).forget_me(record) end end devise-3.5.6/lib/devise/hooks/proxy.rb0000644000004100000410000000070312663066463017726 0ustar www-datawww-datamodule Devise module Hooks # A small warden proxy so we can remember, forget and # sign out users from hooks. class Proxy #:nodoc: include Devise::Controllers::Rememberable include Devise::Controllers::SignInOut attr_reader :warden delegate :cookies, :env, to: :warden def initialize(warden) @warden = warden end def session warden.request.session end end end end devise-3.5.6/lib/devise/hooks/rememberable.rb0000644000004100000410000000044512663066463021172 0ustar www-datawww-dataWarden::Manager.after_set_user except: :fetch do |record, warden, options| scope = options[:scope] if record.respond_to?(:remember_me) && options[:store] != false && record.remember_me && warden.authenticated?(scope) Devise::Hooks::Proxy.new(warden).remember_me(record) end end devise-3.5.6/lib/devise/hooks/trackable.rb0000644000004100000410000000077612663066463020507 0ustar www-datawww-data# After each sign in, update sign in time, sign in count and sign in IP. # This is only triggered when the user is explicitly set (with set_user) # and on authentication. Retrieving the user from session (:fetch) does # not trigger it. Warden::Manager.after_set_user except: :fetch do |record, warden, options| if record.respond_to?(:update_tracked_fields!) && warden.authenticated?(options[:scope]) && !warden.request.env['devise.skip_trackable'] record.update_tracked_fields!(warden.request) end end devise-3.5.6/lib/devise/hooks/csrf_cleaner.rb0000644000004100000410000000053312663066463021174 0ustar www-datawww-dataWarden::Manager.after_authentication do |record, warden, options| clean_up_for_winning_strategy = !warden.winning_strategy.respond_to?(:clean_up_csrf?) || warden.winning_strategy.clean_up_csrf? if Devise.clean_up_csrf_token_on_authentication && clean_up_for_winning_strategy warden.request.session.try(:delete, :_csrf_token) end end devise-3.5.6/lib/devise/hooks/activatable.rb0000644000004100000410000000075112663066463021027 0ustar www-datawww-data# Deny user access whenever their account is not active yet. # We need this as hook to validate the user activity on each request # and in case the user is using other strategies beside Devise ones. Warden::Manager.after_set_user do |record, warden, options| if record && record.respond_to?(:active_for_authentication?) && !record.active_for_authentication? scope = options[:scope] warden.logout(scope) throw :warden, scope: scope, message: record.inactive_message end end devise-3.5.6/lib/devise/mapping.rb0000644000004100000410000001255512663066463017065 0ustar www-datawww-datamodule Devise # Responsible for handling devise mappings and routes configuration. Each # resource configured by devise_for in routes is actually creating a mapping # object. You can refer to devise_for in routes for usage options. # # The required value in devise_for is actually not used internally, but it's # inflected to find all other values. # # map.devise_for :users # mapping = Devise.mappings[:user] # # mapping.name #=> :user # # is the scope used in controllers and warden, given in the route as :singular. # # mapping.as #=> "users" # # how the mapping should be search in the path, given in the route as :as. # # mapping.to #=> User # # is the class to be loaded from routes, given in the route as :class_name. # # mapping.modules #=> [:authenticatable] # # is the modules included in the class # class Mapping #:nodoc: attr_reader :singular, :scoped_path, :path, :controllers, :path_names, :class_name, :sign_out_via, :format, :used_routes, :used_helpers, :failure_app, :router_name alias :name :singular # Receives an object and find a scope for it. If a scope cannot be found, # raises an error. If a symbol is given, it's considered to be the scope. def self.find_scope!(obj) obj = obj.devise_scope if obj.respond_to?(:devise_scope) case obj when String, Symbol return obj.to_sym when Class Devise.mappings.each_value { |m| return m.name if obj <= m.to } else Devise.mappings.each_value { |m| return m.name if obj.is_a?(m.to) } end raise "Could not find a valid mapping for #{obj.inspect}" end def self.find_by_path!(path, path_type=:fullpath) Devise.mappings.each_value { |m| return m if path.include?(m.send(path_type)) } raise "Could not find a valid mapping for path #{path.inspect}" end def initialize(name, options) #:nodoc: @scoped_path = options[:as] ? "#{options[:as]}/#{name}" : name.to_s @singular = (options[:singular] || @scoped_path.tr('/', '_').singularize).to_sym @class_name = (options[:class_name] || name.to_s.classify).to_s @klass = Devise.ref(@class_name) @path = (options[:path] || name).to_s @path_prefix = options[:path_prefix] @sign_out_via = options[:sign_out_via] || Devise.sign_out_via @format = options[:format] @router_name = options[:router_name] default_failure_app(options) default_controllers(options) default_path_names(options) default_used_route(options) default_used_helpers(options) end # Return modules for the mapping. def modules @modules ||= to.respond_to?(:devise_modules) ? to.devise_modules : [] end # Gives the class the mapping points to. def to @klass.get end def strategies @strategies ||= STRATEGIES.values_at(*self.modules).compact.uniq.reverse end def no_input_strategies self.strategies & Devise::NO_INPUT end def routes @routes ||= ROUTES.values_at(*self.modules).compact.uniq end def authenticatable? @authenticatable ||= self.modules.any? { |m| m.to_s =~ /authenticatable/ } end def fullpath "/#{@path_prefix}/#{@path}".squeeze("/") end # Create magic predicates for verifying what module is activated by this map. # Example: # # def confirmable? # self.modules.include?(:confirmable) # end # def self.add_module(m) class_eval <<-METHOD, __FILE__, __LINE__ + 1 def #{m}? self.modules.include?(:#{m}) end METHOD end private def default_failure_app(options) @failure_app = options[:failure_app] || Devise::FailureApp if @failure_app.is_a?(String) ref = Devise.ref(@failure_app) @failure_app = lambda { |env| ref.get.call(env) } end end def default_controllers(options) mod = options[:module] || "devise" @controllers = Hash.new { |h,k| h[k] = "#{mod}/#{k}" } @controllers.merge!(options[:controllers]) if options[:controllers] @controllers.each { |k,v| @controllers[k] = v.to_s } end def default_path_names(options) @path_names = Hash.new { |h,k| h[k] = k.to_s } @path_names[:registration] = "" @path_names.merge!(options[:path_names]) if options[:path_names] end def default_constraints(options) @constraints = Hash.new @constraints.merge!(options[:constraints]) if options[:constraints] end def default_defaults(options) @defaults = Hash.new @defaults.merge!(options[:defaults]) if options[:defaults] end def default_used_route(options) singularizer = lambda { |s| s.to_s.singularize.to_sym } if options.has_key?(:only) @used_routes = self.routes & Array(options[:only]).map(&singularizer) elsif options[:skip] == :all @used_routes = [] else @used_routes = self.routes - Array(options[:skip]).map(&singularizer) end end def default_used_helpers(options) singularizer = lambda { |s| s.to_s.singularize.to_sym } if options[:skip_helpers] == true @used_helpers = @used_routes elsif skip = options[:skip_helpers] @used_helpers = self.routes - Array(skip).map(&singularizer) else @used_helpers = self.routes end end end end devise-3.5.6/lib/devise/delegator.rb0000644000004100000410000000061012663066463017365 0ustar www-datawww-datamodule Devise # Checks the scope in the given environment and returns the associated failure app. class Delegator def call(env) failure_app(env).call(env) end def failure_app(env) app = env["warden.options"] && (scope = env["warden.options"][:scope]) && Devise.mappings[scope.to_sym].failure_app app || Devise::FailureApp end end end devise-3.5.6/lib/devise/orm/0000755000004100000410000000000012663066463015672 5ustar www-datawww-datadevise-3.5.6/lib/devise/orm/active_record.rb0000644000004100000410000000012712663066463021030 0ustar www-datawww-datarequire 'orm_adapter/adapters/active_record' ActiveRecord::Base.extend Devise::Models devise-3.5.6/lib/devise/orm/mongoid.rb0000644000004100000410000000014612663066463017654 0ustar www-datawww-datarequire 'orm_adapter/adapters/mongoid' Mongoid::Document::ClassMethods.send :include, Devise::Models devise-3.5.6/lib/devise/models.rb0000644000004100000410000000667012663066463016716 0ustar www-datawww-datamodule Devise module Models class MissingAttribute < StandardError def initialize(attributes) @attributes = attributes end def message "The following attribute(s) is (are) missing on your model: #{@attributes.join(", ")}" end end # Creates configuration values for Devise and for the given module. # # Devise::Models.config(Devise::DatabaseAuthenticatable, :stretches) # # The line above creates: # # 1) An accessor called Devise.stretches, which value is used by default; # # 2) Some class methods for your model Model.stretches and Model.stretches= # which have higher priority than Devise.stretches; # # 3) And an instance method stretches. # # To add the class methods you need to have a module ClassMethods defined # inside the given class. # def self.config(mod, *accessors) #:nodoc: class << mod; attr_accessor :available_configs; end mod.available_configs = accessors accessors.each do |accessor| mod.class_eval <<-METHOD, __FILE__, __LINE__ + 1 def #{accessor} if defined?(@#{accessor}) @#{accessor} elsif superclass.respond_to?(:#{accessor}) superclass.#{accessor} else Devise.#{accessor} end end def #{accessor}=(value) @#{accessor} = value end METHOD end end def self.check_fields!(klass) failed_attributes = [] instance = klass.new klass.devise_modules.each do |mod| constant = const_get(mod.to_s.classify) constant.required_fields(klass).each do |field| failed_attributes << field unless instance.respond_to?(field) end end if failed_attributes.any? fail Devise::Models::MissingAttribute.new(failed_attributes) end end # Include the chosen devise modules in your model: # # devise :database_authenticatable, :confirmable, :recoverable # # You can also give any of the devise configuration values in form of a hash, # with specific values for this model. Please check your Devise initializer # for a complete description on those values. # def devise(*modules) options = modules.extract_options!.dup selected_modules = modules.map(&:to_sym).uniq.sort_by do |s| Devise::ALL.index(s) || -1 # follow Devise::ALL order end devise_modules_hook! do include Devise::Models::Authenticatable selected_modules.each do |m| mod = Devise::Models.const_get(m.to_s.classify) if mod.const_defined?("ClassMethods") class_mod = mod.const_get("ClassMethods") extend class_mod if class_mod.respond_to?(:available_configs) available_configs = class_mod.available_configs available_configs.each do |config| next unless options.key?(config) send(:"#{config}=", options.delete(config)) end end end include mod end self.devise_modules |= selected_modules options.each { |key, value| send(:"#{key}=", value) } end end # The hook which is called inside devise. # So your ORM can include devise compatibility stuff. def devise_modules_hook! yield end end end require 'devise/models/authenticatable' devise-3.5.6/lib/devise/version.rb0000644000004100000410000000005512663066463017107 0ustar www-datawww-datamodule Devise VERSION = "3.5.6".freeze end devise-3.5.6/lib/devise/token_generator.rb0000644000004100000410000000457012663066463020616 0ustar www-datawww-data# Deprecate: Copied verbatim from Rails source, remove once we move to Rails 4 only. require 'thread_safe' require 'openssl' require 'securerandom' module Devise class TokenGenerator def initialize(key_generator, digest="SHA256") @key_generator = key_generator @digest = digest end def digest(klass, column, value) value.present? && OpenSSL::HMAC.hexdigest(@digest, key_for(column), value.to_s) end def generate(klass, column) key = key_for(column) loop do raw = Devise.friendly_token enc = OpenSSL::HMAC.hexdigest(@digest, key, raw) break [raw, enc] unless klass.to_adapter.find_first({ column => enc }) end end private def key_for(column) @key_generator.generate_key("Devise #{column}") end end # KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2 # It can be used to derive a number of keys for various purposes from a given secret. # This lets Rails applications have a single secure secret, but avoid reusing that # key in multiple incompatible contexts. class KeyGenerator def initialize(secret, options = {}) @secret = secret # The default iterations are higher than required for our key derivation uses # on the off chance someone uses this for password storage @iterations = options[:iterations] || 2**16 end # Returns a derived key suitable for use. The default key_size is chosen # to be compatible with the default settings of ActiveSupport::MessageVerifier. # i.e. OpenSSL::Digest::SHA1#block_length def generate_key(salt, key_size=64) OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size) end end # CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid # re-executing the key generation process when it's called using the same salt and # key_size class CachingKeyGenerator def initialize(key_generator) @key_generator = key_generator @cache_keys = ThreadSafe::Cache.new end # Returns a derived key suitable for use. The default key_size is chosen # to be compatible with the default settings of ActiveSupport::MessageVerifier. # i.e. OpenSSL::Digest::SHA1#block_length def generate_key(salt, key_size=64) @cache_keys["#{salt}#{key_size}"] ||= @key_generator.generate_key(salt, key_size) end end end devise-3.5.6/lib/devise/modules.rb0000644000004100000410000000206412663066463017074 0ustar www-datawww-datarequire 'active_support/core_ext/object/with_options' Devise.with_options model: true do |d| # Strategies first d.with_options strategy: true do |s| routes = [nil, :new, :destroy] s.add_module :database_authenticatable, controller: :sessions, route: { session: routes } s.add_module :rememberable, no_input: true end # Other authentications d.add_module :omniauthable, controller: :omniauth_callbacks, route: :omniauth_callback # Misc after routes = [nil, :new, :edit] d.add_module :recoverable, controller: :passwords, route: { password: routes } d.add_module :registerable, controller: :registrations, route: { registration: (routes << :cancel) } d.add_module :validatable # The ones which can sign out after routes = [nil, :new] d.add_module :confirmable, controller: :confirmations, route: { confirmation: routes } d.add_module :lockable, controller: :unlocks, route: { unlock: routes } d.add_module :timeoutable # Stats for last, so we make sure the user is really signed in d.add_module :trackable end devise-3.5.6/lib/devise/rails/0000755000004100000410000000000012663066463016207 5ustar www-datawww-datadevise-3.5.6/lib/devise/rails/routes.rb0000644000004100000410000004675312663066463020074 0ustar www-datawww-datarequire "active_support/core_ext/object/try" require "active_support/core_ext/hash/slice" module ActionDispatch::Routing class RouteSet #:nodoc: # Ensure Devise modules are included only after loading routes, because we # need devise_for mappings already declared to create filters and helpers. def finalize_with_devise! result = finalize_without_devise! @devise_finalized ||= begin if Devise.router_name.nil? && defined?(@devise_finalized) && self != Rails.application.try(:routes) warn "[DEVISE] We have detected that you are using devise_for inside engine routes. " \ "In this case, you probably want to set Devise.router_name = MOUNT_POINT, where " \ "MOUNT_POINT is a symbol representing where this engine will be mounted at. For " \ "now Devise will default the mount point to :main_app. You can explicitly set it" \ " to :main_app as well in case you want to keep the current behavior." end Devise.configure_warden! Devise.regenerate_helpers! true end result end alias_method_chain :finalize!, :devise end class Mapper # Includes devise_for method for routes. This method is responsible to # generate all needed routes for devise, based on what modules you have # defined in your model. # # ==== Examples # # Let's say you have an User model configured to use authenticatable, # confirmable and recoverable modules. After creating this inside your routes: # # devise_for :users # # This method is going to look inside your User model and create the # needed routes: # # # Session routes for Authenticatable (default) # new_user_session GET /users/sign_in {controller:"devise/sessions", action:"new"} # user_session POST /users/sign_in {controller:"devise/sessions", action:"create"} # destroy_user_session DELETE /users/sign_out {controller:"devise/sessions", action:"destroy"} # # # Password routes for Recoverable, if User model has :recoverable configured # new_user_password GET /users/password/new(.:format) {controller:"devise/passwords", action:"new"} # edit_user_password GET /users/password/edit(.:format) {controller:"devise/passwords", action:"edit"} # user_password PUT /users/password(.:format) {controller:"devise/passwords", action:"update"} # POST /users/password(.:format) {controller:"devise/passwords", action:"create"} # # # Confirmation routes for Confirmable, if User model has :confirmable configured # new_user_confirmation GET /users/confirmation/new(.:format) {controller:"devise/confirmations", action:"new"} # user_confirmation GET /users/confirmation(.:format) {controller:"devise/confirmations", action:"show"} # POST /users/confirmation(.:format) {controller:"devise/confirmations", action:"create"} # # ==== Routes integration # # +devise_for+ is meant to play nicely with other routes methods. For example, # by calling +devise_for+ inside a namespace, it automatically nests your devise # controllers: # # namespace :publisher do # devise_for :account # end # # The snippet above will use publisher/sessions controller instead of devise/sessions # controller. You can revert this change or configure it directly by passing the :module # option described below to +devise_for+. # # Also note that when you use a namespace it will affect all the helpers and methods # for controllers and views. For example, using the above setup you'll end with # following methods: current_publisher_account, authenticate_publisher_account!, # publisher_account_signed_in, etc. # # The only aspect not affect by the router configuration is the model name. The # model name can be explicitly set via the :class_name option. # # ==== Options # # You can configure your routes with some options: # # * class_name: setup a different class to be looked up by devise, if it cannot be # properly found by the route name. # # devise_for :users, class_name: 'Account' # # * path: allows you to setup path name that will be used, as rails routes does. # The following route configuration would setup your route as /accounts instead of /users: # # devise_for :users, path: 'accounts' # # * singular: setup the singular name for the given resource. This is used as the helper methods # names in controller ("authenticate_#{singular}!", "#{singular}_signed_in?", "current_#{singular}" # and "#{singular}_session"), as the scope name in routes and as the scope given to warden. # # devise_for :admins, singular: :manager # # devise_scope :manager do # ... # end # # class ManagerController < ApplicationController # before_filter authenticate_manager! # # def show # @manager = current_manager # ... # end # end # # * path_names: configure different path names to overwrite defaults :sign_in, :sign_out, :sign_up, # :password, :confirmation, :unlock. # # devise_for :users, path_names: { # sign_in: 'login', sign_out: 'logout', # password: 'secret', confirmation: 'verification', # registration: 'register', edit: 'edit/profile' # } # # * controllers: the controller which should be used. All routes by default points to Devise controllers. # However, if you want them to point to custom controller, you should do: # # devise_for :users, controllers: { sessions: "users/sessions" } # # * failure_app: a rack app which is invoked whenever there is a failure. Strings representing a given # are also allowed as parameter. # # * sign_out_via: the HTTP method(s) accepted for the :sign_out action (default: :get), # if you wish to restrict this to accept only :post or :delete requests you should do: # # devise_for :users, sign_out_via: [:post, :delete] # # You need to make sure that your sign_out controls trigger a request with a matching HTTP method. # # * module: the namespace to find controllers (default: "devise", thus # accessing devise/sessions, devise/registrations, and so on). If you want # to namespace all at once, use module: # # devise_for :users, module: "users" # # * skip: tell which controller you want to skip routes from being created. # It accepts :all as an option, meaning it will not generate any route at all: # # devise_for :users, skip: :sessions # # * only: the opposite of :skip, tell which controllers only to generate routes to: # # devise_for :users, only: :sessions # # * skip_helpers: skip generating Devise url helpers like new_session_path(@user). # This is useful to avoid conflicts with previous routes and is false by default. # It accepts true as option, meaning it will skip all the helpers for the controllers # given in :skip but it also accepts specific helpers to be skipped: # # devise_for :users, skip: [:registrations, :confirmations], skip_helpers: true # devise_for :users, skip_helpers: [:registrations, :confirmations] # # * format: include "(.:format)" in the generated routes? true by default, set to false to disable: # # devise_for :users, format: false # # * constraints: works the same as Rails' constraints # # * defaults: works the same as Rails' defaults # # * router_name: allows application level router name to be overwritten for the current scope # # ==== Scoping # # Following Rails 3 routes DSL, you can nest devise_for calls inside a scope: # # scope "/my" do # devise_for :users # end # # However, since Devise uses the request path to retrieve the current user, # this has one caveat: If you are using a dynamic segment, like so ... # # scope ":locale" do # devise_for :users # end # # you are required to configure default_url_options in your # ApplicationController class, so Devise can pick it: # # class ApplicationController < ActionController::Base # def self.default_url_options # { locale: I18n.locale } # end # end # # ==== Adding custom actions to override controllers # # You can pass a block to devise_for that will add any routes defined in the block to Devise's # list of known actions. This is important if you add a custom action to a controller that # overrides an out of the box Devise controller. # For example: # # class RegistrationsController < Devise::RegistrationsController # def update # # do something different here # end # # def deactivate # # not a standard action # # deactivate code here # end # end # # In order to get Devise to recognize the deactivate action, your devise_scope entry should look like this: # # devise_scope :owner do # post "deactivate", to: "registrations#deactivate", as: "deactivate_registration" # end # def devise_for(*resources) @devise_finalized = false raise_no_secret_key unless Devise.secret_key options = resources.extract_options! options[:as] ||= @scope[:as] if @scope[:as].present? options[:module] ||= @scope[:module] if @scope[:module].present? options[:path_prefix] ||= @scope[:path] if @scope[:path].present? options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {}) options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {}) options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {}) options[:options] = @scope[:options] || {} options[:options][:format] = false if options[:format] == false resources.map!(&:to_sym) resources.each do |resource| mapping = Devise.add_mapping(resource, options) begin raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise) rescue NameError => e raise unless mapping.class_name == resource.to_s.classify warn "[WARNING] You provided devise_for #{resource.inspect} but there is " \ "no model #{mapping.class_name} defined in your application" next rescue NoMethodError => e raise unless e.message.include?("undefined method `devise'") raise_no_devise_method_error!(mapping.class_name) end if options[:controllers] && options[:controllers][:omniauth_callbacks] unless mapping.omniauthable? raise ArgumentError, "Mapping omniauth_callbacks on a resource that is not omniauthable\n" \ "Please add `devise :omniauthable` to the `#{mapping.class_name}` model" end end routes = mapping.used_routes devise_scope mapping.name do with_devise_exclusive_scope mapping.fullpath, mapping.name, options do routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) } end end end end # Allow you to add authentication request from the router. # Takes an optional scope and block to provide constraints # on the model instance itself. # # authenticate do # resources :post # end # # authenticate(:admin) do # resources :users # end # # authenticate :user, lambda {|u| u.role == "admin"} do # root to: "admin/dashboard#show", as: :user_root # end # def authenticate(scope=nil, block=nil) constraints_for(:authenticate!, scope, block) do yield end end # Allow you to route based on whether a scope is authenticated. You # can optionally specify which scope and a block. The block accepts # a model and allows extra constraints to be done on the instance. # # authenticated :admin do # root to: 'admin/dashboard#show', as: :admin_root # end # # authenticated do # root to: 'dashboard#show', as: :authenticated_root # end # # authenticated :user, lambda {|u| u.role == "admin"} do # root to: "admin/dashboard#show", as: :user_root # end # # root to: 'landing#show' # def authenticated(scope=nil, block=nil) constraints_for(:authenticate?, scope, block) do yield end end # Allow you to route based on whether a scope is *not* authenticated. # You can optionally specify which scope. # # unauthenticated do # as :user do # root to: 'devise/registrations#new' # end # end # # root to: 'dashboard#show' # def unauthenticated(scope=nil) constraint = lambda do |request| not request.env["warden"].authenticate? scope: scope end constraints(constraint) do yield end end # Sets the devise scope to be used in the controller. If you have custom routes, # you are required to call this method (also aliased as :as) in order to specify # to which controller it is targetted. # # as :user do # get "sign_in", to: "devise/sessions#new" # end # # Notice you cannot have two scopes mapping to the same URL. And remember, if # you try to access a devise controller without specifying a scope, it will # raise ActionNotFound error. # # Also be aware of that 'devise_scope' and 'as' use the singular form of the # noun where other devise route commands expect the plural form. This would be a # good and working example. # # devise_scope :user do # get "/some/route" => "some_devise_controller" # end # devise_for :users # # Notice and be aware of the differences above between :user and :users def devise_scope(scope) constraint = lambda do |request| request.env["devise.mapping"] = Devise.mappings[scope] true end constraints(constraint) do yield end end alias :as :devise_scope protected def devise_session(mapping, controllers) #:nodoc: resource :session, only: [], controller: controllers[:sessions], path: "" do get :new, path: mapping.path_names[:sign_in], as: "new" post :create, path: mapping.path_names[:sign_in] match :destroy, path: mapping.path_names[:sign_out], as: "destroy", via: mapping.sign_out_via end end def devise_password(mapping, controllers) #:nodoc: resource :password, only: [:new, :create, :edit, :update], path: mapping.path_names[:password], controller: controllers[:passwords] end def devise_confirmation(mapping, controllers) #:nodoc: resource :confirmation, only: [:new, :create, :show], path: mapping.path_names[:confirmation], controller: controllers[:confirmations] end def devise_unlock(mapping, controllers) #:nodoc: if mapping.to.unlock_strategy_enabled?(:email) resource :unlock, only: [:new, :create, :show], path: mapping.path_names[:unlock], controller: controllers[:unlocks] end end def devise_registration(mapping, controllers) #:nodoc: path_names = { new: mapping.path_names[:sign_up], edit: mapping.path_names[:edit], cancel: mapping.path_names[:cancel] } options = { only: [:new, :create, :edit, :update, :destroy], path: mapping.path_names[:registration], path_names: path_names, controller: controllers[:registrations] } resource :registration, options do get :cancel end end def devise_omniauth_callback(mapping, controllers) #:nodoc: if mapping.fullpath =~ /:[a-zA-Z_]/ raise <<-ERROR Devise does not support scoping OmniAuth callbacks under a dynamic segment and you have set #{mapping.fullpath.inspect}. You can work around by passing `skip: :omniauth_callbacks` to the `devise_for` call and extract omniauth options to another `devise_for` call outside the scope. Here is an example: devise_for :users, only: :omniauth_callbacks, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'} scope '/(:locale)', locale: /ru|en/ do devise_for :users, skip: :omniauth_callbacks end ERROR end path, @scope[:path] = @scope[:path], nil path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/") set_omniauth_path_prefix!(path_prefix) providers = Regexp.union(mapping.to.omniauth_providers.map(&:to_s)) match "#{path_prefix}/:provider", constraints: { provider: providers }, to: "#{controllers[:omniauth_callbacks]}#passthru", as: :omniauth_authorize, via: [:get, :post] match "#{path_prefix}/:action/callback", constraints: { action: providers }, to: "#{controllers[:omniauth_callbacks]}#:action", as: :omniauth_callback, via: [:get, :post] ensure @scope[:path] = path end def with_devise_exclusive_scope(new_path, new_as, options) #:nodoc: current_scope = @scope.dup exclusive = { as: new_as, path: new_path, module: nil } exclusive.merge!(options.slice(:constraints, :defaults, :options)) exclusive.each_pair { |key, value| @scope[key] = value } yield ensure @scope = current_scope end def constraints_for(method_to_apply, scope=nil, block=nil) constraint = lambda do |request| request.env['warden'].send(method_to_apply, scope: scope) && (block.nil? || block.call(request.env["warden"].user(scope))) end constraints(constraint) do yield end end def set_omniauth_path_prefix!(path_prefix) #:nodoc: if ::OmniAuth.config.path_prefix && ::OmniAuth.config.path_prefix != path_prefix raise "Wrong OmniAuth configuration. If you are getting this exception, it means that either:\n\n" \ "1) You are manually setting OmniAuth.config.path_prefix and it doesn't match the Devise one\n" \ "2) You are setting :omniauthable in more than one model\n" \ "3) You changed your Devise routes/OmniAuth setting and haven't restarted your server" else ::OmniAuth.config.path_prefix = path_prefix end end def raise_no_secret_key #:nodoc: raise <<-ERROR Devise.secret_key was not set. Please add the following to your Devise initializer: config.secret_key = '#{SecureRandom.hex(64)}' Please ensure you restarted your application after installing Devise or setting the key. ERROR end def raise_no_devise_method_error!(klass) #:nodoc: raise "#{klass} does not respond to 'devise' method. This usually means you haven't " \ "loaded your ORM file or it's being loaded too late. To fix it, be sure to require 'devise/orm/YOUR_ORM' " \ "inside 'config/initializers/devise.rb' or before your application definition in 'config/application.rb'" end end end devise-3.5.6/lib/devise/rails/warden_compat.rb0000644000004100000410000000124112663066463021355 0ustar www-datawww-datamodule Warden::Mixins::Common def request @request ||= ActionDispatch::Request.new(env) end # Deprecate: Remove this check once we move to Rails 4 only. NULL_STORE = defined?(ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash) ? ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullSessionHash : nil def reset_session! # Calling reset_session on NULL_STORE causes it fail. # This is a bug that needs to be fixed in Rails. unless NULL_STORE && request.session.is_a?(NULL_STORE) request.reset_session end end def cookies request.cookie_jar end end devise-3.5.6/lib/devise/models/0000755000004100000410000000000012663066463016360 5ustar www-datawww-datadevise-3.5.6/lib/devise/models/timeoutable.rb0000644000004100000410000000206412663066463021221 0ustar www-datawww-datarequire 'devise/hooks/timeoutable' module Devise module Models # Timeoutable takes care of verifying whether a user session has already # expired or not. When a session expires after the configured time, the user # will be asked for credentials again, it means, they will be redirected # to the sign in page. # # == Options # # Timeoutable adds the following options to devise_for: # # * +timeout_in+: the interval to timeout the user session without activity. # # == Examples # # user.timedout?(30.minutes.ago) # module Timeoutable extend ActiveSupport::Concern def self.required_fields(klass) [] end # Checks whether the user session has expired based on configured time. def timedout?(last_access) !timeout_in.nil? && last_access && last_access <= timeout_in.ago end def timeout_in self.class.timeout_in end private module ClassMethods Devise::Models.config(self, :timeout_in) end end end end devise-3.5.6/lib/devise/models/registerable.rb0000644000004100000410000000132512663066463021356 0ustar www-datawww-datamodule Devise module Models # Registerable is responsible for everything related to registering a new # resource (ie user sign up). module Registerable extend ActiveSupport::Concern def self.required_fields(klass) [] end module ClassMethods # A convenience method that receives both parameters and session to # initialize a user. This can be used by OAuth, for example, to send # in the user token and be stored on initialization. # # By default discards all information sent by the session by calling # new with params. def new_with_session(params, session) new(params) end end end end end devise-3.5.6/lib/devise/models/lockable.rb0000644000004100000410000001613212663066463020464 0ustar www-datawww-datarequire "devise/hooks/lockable" module Devise module Models # Handles blocking a user access after a certain number of attempts. # Lockable accepts two different strategies to unlock a user after it's # blocked: email and time. The former will send an email to the user when # the lock happens, containing a link to unlock its account. The second # will unlock the user automatically after some configured time (ie 2.hours). # It's also possible to setup lockable to use both email and time strategies. # # == Options # # Lockable adds the following options to +devise+: # # * +maximum_attempts+: how many attempts should be accepted before blocking the user. # * +lock_strategy+: lock the user account by :failed_attempts or :none. # * +unlock_strategy+: unlock the user account by :time, :email, :both or :none. # * +unlock_in+: the time you want to lock the user after to lock happens. Only available when unlock_strategy is :time or :both. # * +unlock_keys+: the keys you want to use when locking and unlocking an account # module Lockable extend ActiveSupport::Concern delegate :lock_strategy_enabled?, :unlock_strategy_enabled?, to: "self.class" def self.required_fields(klass) attributes = [] attributes << :failed_attempts if klass.lock_strategy_enabled?(:failed_attempts) attributes << :locked_at if klass.unlock_strategy_enabled?(:time) attributes << :unlock_token if klass.unlock_strategy_enabled?(:email) attributes end # Lock a user setting its locked_at to actual time. # * +opts+: Hash options if you don't want to send email # when you lock access, you could pass the next hash # `{ send_instructions: false } as option`. def lock_access!(opts = { }) self.locked_at = Time.now.utc if unlock_strategy_enabled?(:email) && opts.fetch(:send_instructions, true) send_unlock_instructions else save(validate: false) end end # Unlock a user by cleaning locked_at and failed_attempts. def unlock_access! self.locked_at = nil self.failed_attempts = 0 if respond_to?(:failed_attempts=) self.unlock_token = nil if respond_to?(:unlock_token=) save(validate: false) end # Verifies whether a user is locked or not. def access_locked? !!locked_at && !lock_expired? end # Send unlock instructions by email def send_unlock_instructions raw, enc = Devise.token_generator.generate(self.class, :unlock_token) self.unlock_token = enc self.save(validate: false) send_devise_notification(:unlock_instructions, raw, {}) raw end # Resend the unlock instructions if the user is locked. def resend_unlock_instructions if_access_locked { send_unlock_instructions } end # Overwrites active_for_authentication? from Devise::Models::Activatable for locking purposes # by verifying whether a user is active to sign in or not based on locked? def active_for_authentication? super && !access_locked? end # Overwrites invalid_message from Devise::Models::Authenticatable to define # the correct reason for blocking the sign in. def inactive_message access_locked? ? :locked : super end # Overwrites valid_for_authentication? from Devise::Models::Authenticatable # for verifying whether a user is allowed to sign in or not. If the user # is locked, it should never be allowed. def valid_for_authentication? return super unless persisted? && lock_strategy_enabled?(:failed_attempts) # Unlock the user if the lock is expired, no matter # if the user can login or not (wrong password, etc) unlock_access! if lock_expired? if super && !access_locked? true else self.failed_attempts ||= 0 self.failed_attempts += 1 if attempts_exceeded? lock_access! unless access_locked? else save(validate: false) end false end end def unauthenticated_message # If set to paranoid mode, do not show the locked message because it # leaks the existence of an account. if Devise.paranoid super elsif access_locked? || (lock_strategy_enabled?(:failed_attempts) && attempts_exceeded?) :locked elsif lock_strategy_enabled?(:failed_attempts) && last_attempt? && self.class.last_attempt_warning :last_attempt else super end end protected def attempts_exceeded? self.failed_attempts >= self.class.maximum_attempts end def last_attempt? self.failed_attempts == self.class.maximum_attempts - 1 end # Tells if the lock is expired if :time unlock strategy is active def lock_expired? if unlock_strategy_enabled?(:time) locked_at && locked_at < self.class.unlock_in.ago else false end end # Checks whether the record is locked or not, yielding to the block # if it's locked, otherwise adds an error to email. def if_access_locked if access_locked? yield else self.errors.add(Devise.unlock_keys.first, :not_locked) false end end module ClassMethods # Attempt to find a user by its unlock keys. If a record is found, send new # unlock instructions to it. If not user is found, returns a new user # with an email not found error. # Options must contain the user's unlock keys def send_unlock_instructions(attributes={}) lockable = find_or_initialize_with_errors(unlock_keys, attributes, :not_found) lockable.resend_unlock_instructions if lockable.persisted? lockable end # Find a user by its unlock token and try to unlock it. # If no user is found, returns a new user with an error. # If the user is not locked, creates an error for the user # Options must have the unlock_token def unlock_access_by_token(unlock_token) original_token = unlock_token unlock_token = Devise.token_generator.digest(self, :unlock_token, unlock_token) lockable = find_or_initialize_with_error_by(:unlock_token, unlock_token) lockable.unlock_access! if lockable.persisted? lockable.unlock_token = original_token lockable end # Is the unlock enabled for the given unlock strategy? def unlock_strategy_enabled?(strategy) [:both, strategy].include?(self.unlock_strategy) end # Is the lock enabled for the given lock strategy? def lock_strategy_enabled?(strategy) self.lock_strategy == strategy end Devise::Models.config(self, :maximum_attempts, :lock_strategy, :unlock_strategy, :unlock_in, :unlock_keys, :last_attempt_warning) end end end end devise-3.5.6/lib/devise/models/recoverable.rb0000644000004100000410000001432412663066463021202 0ustar www-datawww-datamodule Devise module Models # Recoverable takes care of resetting the user password and send reset instructions. # # ==Options # # Recoverable adds the following options to devise_for: # # * +reset_password_keys+: the keys you want to use when recovering the password for an account # * +reset_password_within+: the time period within which the password must be reset or the token expires. # * +sign_in_after_reset_password+: whether or not to sign in the user automatically after a password reset. # # == Examples # # # resets the user password and save the record, true if valid passwords are given, otherwise false # User.find(1).reset_password('password123', 'password123') # # # creates a new token and send it with instructions about how to reset the password # User.find(1).send_reset_password_instructions # module Recoverable extend ActiveSupport::Concern def self.required_fields(klass) [:reset_password_sent_at, :reset_password_token] end included do before_update do if (respond_to?(:email_changed?) && email_changed?) || encrypted_password_changed? clear_reset_password_token end end end # Update password saving the record and clearing token. Returns true if # the passwords are valid and the record was saved, false otherwise. def reset_password(new_password, new_password_confirmation) self.password = new_password self.password_confirmation = new_password_confirmation if respond_to?(:after_password_reset) && valid? ActiveSupport::Deprecation.warn "after_password_reset is deprecated" after_password_reset end save end def reset_password!(new_password, new_password_confirmation) ActiveSupport::Deprecation.warn "reset_password! is deprecated in favor of reset_password" reset_password(new_password, new_password_confirmation) end # Resets reset password token and send reset password instructions by email. # Returns the token sent in the e-mail. def send_reset_password_instructions token = set_reset_password_token send_reset_password_instructions_notification(token) token end # Checks if the reset password token sent is within the limit time. # We do this by calculating if the difference between today and the # sending date does not exceed the confirm in time configured. # Returns true if the resource is not responding to reset_password_sent_at at all. # reset_password_within is a model configuration, must always be an integer value. # # Example: # # # reset_password_within = 1.day and reset_password_sent_at = today # reset_password_period_valid? # returns true # # # reset_password_within = 5.days and reset_password_sent_at = 4.days.ago # reset_password_period_valid? # returns true # # # reset_password_within = 5.days and reset_password_sent_at = 5.days.ago # reset_password_period_valid? # returns false # # # reset_password_within = 0.days # reset_password_period_valid? # will always return false # def reset_password_period_valid? reset_password_sent_at && reset_password_sent_at.utc >= self.class.reset_password_within.ago.utc end protected # Removes reset_password token def clear_reset_password_token self.reset_password_token = nil self.reset_password_sent_at = nil end def set_reset_password_token raw, enc = Devise.token_generator.generate(self.class, :reset_password_token) self.reset_password_token = enc self.reset_password_sent_at = Time.now.utc self.save(validate: false) raw end def send_reset_password_instructions_notification(token) send_devise_notification(:reset_password_instructions, token, {}) end module ClassMethods # Attempt to find a user by password reset token. If a user is found, return it # If a user is not found, return nil def with_reset_password_token(token) reset_password_token = Devise.token_generator.digest(self, :reset_password_token, token) to_adapter.find_first(reset_password_token: reset_password_token) end # Attempt to find a user by its email. If a record is found, send new # password instructions to it. If user is not found, returns a new user # with an email not found error. # Attributes must contain the user's email def send_reset_password_instructions(attributes={}) recoverable = find_or_initialize_with_errors(reset_password_keys, attributes, :not_found) recoverable.send_reset_password_instructions if recoverable.persisted? recoverable end # Attempt to find a user by its reset_password_token to reset its # password. If a user is found and token is still valid, reset its password and automatically # try saving the record. If not user is found, returns a new user # containing an error in reset_password_token attribute. # Attributes must contain reset_password_token, password and confirmation def reset_password_by_token(attributes={}) original_token = attributes[:reset_password_token] reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token) recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token) if recoverable.persisted? if recoverable.reset_password_period_valid? recoverable.reset_password(attributes[:password], attributes[:password_confirmation]) else recoverable.errors.add(:reset_password_token, :expired) end end recoverable.reset_password_token = original_token if recoverable.reset_password_token.present? recoverable end Devise::Models.config(self, :reset_password_keys, :reset_password_within, :sign_in_after_reset_password) end end end end devise-3.5.6/lib/devise/models/rememberable.rb0000644000004100000410000001337512663066463021340 0ustar www-datawww-datarequire 'devise/strategies/rememberable' require 'devise/hooks/rememberable' require 'devise/hooks/forgetable' module Devise module Models # Rememberable manages generating and clearing token for remember the user # from a saved cookie. Rememberable also has utility methods for dealing # with serializing the user into the cookie and back from the cookie, trying # to lookup the record based on the saved information. # You probably wouldn't use rememberable methods directly, they are used # mostly internally for handling the remember token. # # == Options # # Rememberable adds the following options in devise_for: # # * +remember_for+: the time you want the user will be remembered without # asking for credentials. After this time the user will be blocked and # will have to enter their credentials again. This configuration is also # used to calculate the expires time for the cookie created to remember # the user. By default remember_for is 2.weeks. # # * +extend_remember_period+: if true, extends the user's remember period # when remembered via cookie. False by default. # # * +rememberable_options+: configuration options passed to the created cookie. # # == Examples # # User.find(1).remember_me! # regenerating the token # User.find(1).forget_me! # clearing the token # # # generating info to put into cookies # User.serialize_into_cookie(user) # # # lookup the user based on the incoming cookie information # User.serialize_from_cookie(cookie_string) module Rememberable extend ActiveSupport::Concern attr_accessor :remember_me, :extend_remember_period def self.required_fields(klass) [:remember_created_at] end # TODO: We were used to receive a extend period argument but we no longer do. # Remove this for Devise 4.0. def remember_me!(*) self.remember_token = self.class.remember_token if respond_to?(:remember_token) self.remember_created_at ||= Time.now.utc save(validate: false) if self.changed? end # If the record is persisted, remove the remember token (but only if # it exists), and save the record without validations. def forget_me! return unless persisted? self.remember_token = nil if respond_to?(:remember_token) self.remember_created_at = nil if self.class.expire_all_remember_me_on_sign_out save(validate: false) end # Remember token should be expired if expiration time not overpass now. def remember_expired? remember_created_at.nil? end def remember_expires_at self.class.remember_for.from_now end def rememberable_value if respond_to?(:remember_token) remember_token elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt.presence) salt else raise "authenticable_salt returned nil for the #{self.class.name} model. " \ "In order to use rememberable, you must ensure a password is always set " \ "or have a remember_token column in your model or implement your own " \ "rememberable_value in the model with custom logic." end end def rememberable_options self.class.rememberable_options end # A callback initiated after successfully being remembered. This can be # used to insert your own logic that is only run after the user is # remembered. # # Example: # # def after_remembered # self.update_attribute(:invite_code, nil) # end # def after_remembered end def remember_me?(token, generated_at) # TODO: Normalize the JSON type coercion along with the Timeoutable hook # in a single place https://github.com/plataformatec/devise/blob/ffe9d6d406e79108cf32a2c6a1d0b3828849c40b/lib/devise/hooks/timeoutable.rb#L14-L18 if generated_at.is_a?(String) generated_at = time_from_json(generated_at) end # The token is only valid if: # 1. we have a date # 2. the current time does not pass the expiry period # 3. the record has a remember_created_at date # 4. the token date is bigger than the remember_created_at # 5. the token matches generated_at.is_a?(Time) && (self.class.remember_for.ago < generated_at) && (generated_at > (remember_created_at || Time.now).utc) && Devise.secure_compare(rememberable_value, token) end private def time_from_json(value) if value =~ /\A\d+\.\d+\Z/ Time.at(value.to_f) else Time.parse(value) rescue nil end end module ClassMethods # Create the cookie key using the record id and remember_token def serialize_into_cookie(record) [record.to_key, record.rememberable_value, Time.now.utc.to_f.to_s] end # Recreate the user based on the stored cookie def serialize_from_cookie(*args) id, token, generated_at = *args record = to_adapter.get(id) record if record && record.remember_me?(token, generated_at) end # Generate a token checking if one does not already exist in the database. def remember_token #:nodoc: loop do token = Devise.friendly_token break token unless to_adapter.find_first({ remember_token: token }) end end private # TODO: extend_remember_period is no longer used Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options, :expire_all_remember_me_on_sign_out) end end end end devise-3.5.6/lib/devise/models/trackable.rb0000644000004100000410000000247612663066463020646 0ustar www-datawww-datarequire 'devise/hooks/trackable' module Devise module Models # Track information about your user sign in. It tracks the following columns: # # * sign_in_count - Increased every time a sign in is made (by form, openid, oauth) # * current_sign_in_at - A timestamp updated when the user signs in # * last_sign_in_at - Holds the timestamp of the previous sign in # * current_sign_in_ip - The remote ip updated when the user sign in # * last_sign_in_ip - Holds the remote ip of the previous sign in # module Trackable def self.required_fields(klass) [:current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count] end def update_tracked_fields(request) old_current, new_current = self.current_sign_in_at, Time.now.utc self.last_sign_in_at = old_current || new_current self.current_sign_in_at = new_current old_current, new_current = self.current_sign_in_ip, request.remote_ip self.last_sign_in_ip = old_current || new_current self.current_sign_in_ip = new_current self.sign_in_count ||= 0 self.sign_in_count += 1 end def update_tracked_fields!(request) update_tracked_fields(request) save(validate: false) end end end end devise-3.5.6/lib/devise/models/omniauthable.rb0000644000004100000410000000116712663066463021362 0ustar www-datawww-datarequire 'devise/omniauth' module Devise module Models # Adds OmniAuth support to your model. # # == Options # # Oauthable adds the following options to devise_for: # # * +omniauth_providers+: Which providers are available to this model. It expects an array: # # devise_for :database_authenticatable, :omniauthable, omniauth_providers: [:twitter] # module Omniauthable extend ActiveSupport::Concern def self.required_fields(klass) [] end module ClassMethods Devise::Models.config(self, :omniauth_providers) end end end end devise-3.5.6/lib/devise/models/database_authenticatable.rb0000644000004100000410000001312712663066463023672 0ustar www-datawww-datarequire 'devise/strategies/database_authenticatable' module Devise def self.bcrypt(klass, password) ActiveSupport::Deprecation.warn "Devise.bcrypt is deprecated; use Devise::Encryptor.digest instead" Devise::Encryptor.digest(klass, password) end module Models # Authenticatable Module, responsible for encrypting password and validating # authenticity of a user while signing in. # # == Options # # DatabaseAuthenticatable adds the following options to devise_for: # # * +pepper+: a random string used to provide a more secure hash. Use # `rake secret` to generate new keys. # # * +stretches+: the cost given to bcrypt. # # == Examples # # User.find(1).valid_password?('password123') # returns true/false # module DatabaseAuthenticatable extend ActiveSupport::Concern included do after_update :send_password_change_notification, if: :send_password_change_notification? attr_reader :password, :current_password attr_accessor :password_confirmation end def self.required_fields(klass) [:encrypted_password] + klass.authentication_keys end # Generates password encryption based on the given value. def password=(new_password) @password = new_password self.encrypted_password = password_digest(@password) if @password.present? end # Verifies whether a password (ie from sign in) is the user password. def valid_password?(password) Devise::Encryptor.compare(self.class, encrypted_password, password) end # Set password and password confirmation to nil def clean_up_passwords self.password = self.password_confirmation = nil end # Update record attributes when :current_password matches, otherwise # returns error on :current_password. # # This method also rejects the password field if it is blank (allowing # users to change relevant information like the e-mail without changing # their password). In case the password field is rejected, the confirmation # is also rejected as long as it is also blank. def update_with_password(params, *options) current_password = params.delete(:current_password) if params[:password].blank? params.delete(:password) params.delete(:password_confirmation) if params[:password_confirmation].blank? end result = if valid_password?(current_password) update_attributes(params, *options) else self.assign_attributes(params, *options) self.valid? self.errors.add(:current_password, current_password.blank? ? :blank : :invalid) false end clean_up_passwords result end # Updates record attributes without asking for the current password. # Never allows a change to the current password. If you are using this # method, you should probably override this method to protect other # attributes you would not like to be updated without a password. # # Example: # # def update_without_password(params, *options) # params.delete(:email) # super(params) # end # def update_without_password(params, *options) params.delete(:password) params.delete(:password_confirmation) result = update_attributes(params, *options) clean_up_passwords result end # Destroy record when :current_password matches, otherwise returns # error on :current_password. It also automatically rejects # :current_password if it is blank. def destroy_with_password(current_password) result = if valid_password?(current_password) destroy else self.valid? self.errors.add(:current_password, current_password.blank? ? :blank : :invalid) false end result end # A callback initiated after successfully authenticating. This can be # used to insert your own logic that is only run after the user successfully # authenticates. # # Example: # # def after_database_authentication # self.update_attribute(:invite_code, nil) # end # def after_database_authentication end # A reliable way to expose the salt regardless of the implementation. def authenticatable_salt encrypted_password[0,29] if encrypted_password end def send_password_change_notification send_devise_notification(:password_change) end protected # Digests the password using bcrypt. Custom encryption should override # this method to apply their own algorithm. # # See https://github.com/plataformatec/devise-encryptable for examples # of other encryption engines. def password_digest(password) Devise::Encryptor.digest(self.class, password) end def send_password_change_notification? self.class.send_password_change_notification && encrypted_password_changed? end module ClassMethods Devise::Models.config(self, :pepper, :stretches, :send_password_change_notification) # We assume this method already gets the sanitized values from the # DatabaseAuthenticatable strategy. If you are using this method on # your own, be sure to sanitize the conditions hash to only include # the proper fields. def find_for_database_authentication(conditions) find_for_authentication(conditions) end end end end end devise-3.5.6/lib/devise/models/validatable.rb0000644000004100000410000000454512663066463021165 0ustar www-datawww-datamodule Devise module Models # Validatable creates all needed validations for a user email and password. # It's optional, given you may want to create the validations by yourself. # Automatically validate if the email is present, unique and its format is # valid. Also tests presence of password, confirmation and length. # # == Options # # Validatable adds the following options to devise_for: # # * +email_regexp+: the regular expression used to validate e-mails; # * +password_length+: a range expressing password length. Defaults to 8..72. # module Validatable # All validations used by this module. VALIDATIONS = [:validates_presence_of, :validates_uniqueness_of, :validates_format_of, :validates_confirmation_of, :validates_length_of].freeze def self.required_fields(klass) [] end def self.included(base) base.extend ClassMethods assert_validations_api!(base) base.class_eval do validates_presence_of :email, if: :email_required? validates_uniqueness_of :email, allow_blank: true, if: :email_changed? validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? validates_presence_of :password, if: :password_required? validates_confirmation_of :password, if: :password_required? validates_length_of :password, within: password_length, allow_blank: true end end def self.assert_validations_api!(base) #:nodoc: unavailable_validations = VALIDATIONS.select { |v| !base.respond_to?(v) } unless unavailable_validations.empty? raise "Could not use :validatable module since #{base} does not respond " << "to the following methods: #{unavailable_validations.to_sentence}." end end protected # Checks whether a password is needed or not. For validations only. # Passwords are always required if it's a new record, or if the password # or confirmation are being set somewhere. def password_required? !persisted? || !password.nil? || !password_confirmation.nil? end def email_required? true end module ClassMethods Devise::Models.config(self, :email_regexp, :password_length) end end end end devise-3.5.6/lib/devise/models/authenticatable.rb0000644000004100000410000002576712663066463022063 0ustar www-datawww-datarequire 'active_model/version' require 'devise/hooks/activatable' require 'devise/hooks/csrf_cleaner' module Devise module Models # Authenticatable module. Holds common settings for authentication. # # == Options # # Authenticatable adds the following options to devise_for: # # * +authentication_keys+: parameters used for authentication. By default [:email]. # # * +http_authentication_key+: map the username passed via HTTP Auth to this parameter. Defaults to # the first element in +authentication_keys+. # # * +request_keys+: parameters from the request object used for authentication. # By specifying a symbol (which should be a request method), it will automatically be # passed to find_for_authentication method and considered in your model lookup. # # For instance, if you set :request_keys to [:subdomain], :subdomain will be considered # as key on authentication. This can also be a hash where the value is a boolean specifying # if the value is required or not. # # * +http_authenticatable+: if this model allows http authentication. By default false. # It also accepts an array specifying the strategies that should allow http. # # * +params_authenticatable+: if this model allows authentication through request params. By default true. # It also accepts an array specifying the strategies that should allow params authentication. # # * +skip_session_storage+: By default Devise will store the user in session. # By default is set to skip_session_storage: [:http_auth]. # # == active_for_authentication? # # After authenticating a user and in each request, Devise checks if your model is active by # calling model.active_for_authentication?. This method is overwritten by other devise modules. For instance, # :confirmable overwrites .active_for_authentication? to only return true if your model was confirmed. # # You can overwrite this method yourself, but if you do, don't forget to call super: # # def active_for_authentication? # super && special_condition_is_valid? # end # # Whenever active_for_authentication? returns false, Devise asks the reason why your model is inactive using # the inactive_message method. You can overwrite it as well: # # def inactive_message # special_condition_is_valid? ? super : :special_condition_is_not_valid # end # module Authenticatable extend ActiveSupport::Concern BLACKLIST_FOR_SERIALIZATION = [:encrypted_password, :reset_password_token, :reset_password_sent_at, :remember_created_at, :sign_in_count, :current_sign_in_at, :last_sign_in_at, :current_sign_in_ip, :last_sign_in_ip, :password_salt, :confirmation_token, :confirmed_at, :confirmation_sent_at, :remember_token, :unconfirmed_email, :failed_attempts, :unlock_token, :locked_at] included do class_attribute :devise_modules, instance_writer: false self.devise_modules ||= [] before_validation :downcase_keys before_validation :strip_whitespace end def self.required_fields(klass) [] end # Check if the current object is valid for authentication. This method and # find_for_authentication are the methods used in a Warden::Strategy to check # if a model should be signed in or not. # # However, you should not overwrite this method, you should overwrite active_for_authentication? # and inactive_message instead. def valid_for_authentication? block_given? ? yield : true end def unauthenticated_message :invalid end def active_for_authentication? true end def inactive_message :inactive end def authenticatable_salt end # Redefine serializable_hash in models for more secure defaults. # By default, it removes from the serializable model all attributes that # are *not* accessible. You can remove this default by using :force_except # and passing a new list of attributes you want to exempt. All attributes # given to :except will simply add names to exempt to Devise internal list. def serializable_hash(options = nil) options ||= {} options[:except] = Array(options[:except]) if options[:force_except] options[:except].concat Array(options[:force_except]) else options[:except].concat BLACKLIST_FOR_SERIALIZATION end super(options) end protected def devise_mailer Devise.mailer end # This is an internal method called every time Devise needs # to send a notification/mail. This can be overridden if you # need to customize the e-mail delivery logic. For instance, # if you are using a queue to deliver e-mails (delayed job, # sidekiq, resque, etc), you must add the delivery to the queue # just after the transaction was committed. To achieve this, # you can override send_devise_notification to store the # deliveries until the after_commit callback is triggered: # # class User # devise :database_authenticatable, :confirmable # # after_commit :send_pending_notifications # # protected # # def send_devise_notification(notification, *args) # # If the record is new or changed then delay the # # delivery until the after_commit callback otherwise # # send now because after_commit will not be called. # if new_record? || changed? # pending_notifications << [notification, args] # else # devise_mailer.send(notification, self, *args).deliver # end # end # # def send_pending_notifications # pending_notifications.each do |notification, args| # devise_mailer.send(notification, self, *args).deliver # end # # # Empty the pending notifications array because the # # after_commit hook can be called multiple times which # # could cause multiple emails to be sent. # pending_notifications.clear # end # # def pending_notifications # @pending_notifications ||= [] # end # end # def send_devise_notification(notification, *args) message = devise_mailer.send(notification, self, *args) # Remove once we move to Rails 4.2+ only. if message.respond_to?(:deliver_now) message.deliver_now else message.deliver end end def downcase_keys self.class.case_insensitive_keys.each { |k| apply_to_attribute_or_variable(k, :downcase) } end def strip_whitespace self.class.strip_whitespace_keys.each { |k| apply_to_attribute_or_variable(k, :strip) } end def apply_to_attribute_or_variable(attr, method) if self[attr] self[attr] = self[attr].try(method) # Use respond_to? here to avoid a regression where globally # configured strip_whitespace_keys or case_insensitive_keys were # attempting to strip or downcase when a model didn't have the # globally configured key. elsif respond_to?(attr) && respond_to?("#{attr}=") new_value = send(attr).try(method) send("#{attr}=", new_value) end end module ClassMethods Devise::Models.config(self, :authentication_keys, :request_keys, :strip_whitespace_keys, :case_insensitive_keys, :http_authenticatable, :params_authenticatable, :skip_session_storage, :http_authentication_key) def serialize_into_session(record) [record.to_key, record.authenticatable_salt] end def serialize_from_session(key, salt) record = to_adapter.get(key) record if record && record.authenticatable_salt == salt end def params_authenticatable?(strategy) params_authenticatable.is_a?(Array) ? params_authenticatable.include?(strategy) : params_authenticatable end def http_authenticatable?(strategy) http_authenticatable.is_a?(Array) ? http_authenticatable.include?(strategy) : http_authenticatable end # Find first record based on conditions given (ie by the sign in form). # This method is always called during an authentication process but # it may be wrapped as well. For instance, database authenticatable # provides a `find_for_database_authentication` that wraps a call to # this method. This allows you to customize both database authenticatable # or the whole authenticate stack by customize `find_for_authentication.` # # Overwrite to add customized conditions, create a join, or maybe use a # namedscope to filter records while authenticating. # Example: # # def self.find_for_authentication(tainted_conditions) # find_first_by_auth_conditions(tainted_conditions, active: true) # end # # Finally, notice that Devise also queries for users in other scenarios # besides authentication, for example when retrieving an user to send # an e-mail for password reset. In such cases, find_for_authentication # is not called. def find_for_authentication(tainted_conditions) find_first_by_auth_conditions(tainted_conditions) end def find_first_by_auth_conditions(tainted_conditions, opts={}) to_adapter.find_first(devise_parameter_filter.filter(tainted_conditions).merge(opts)) end # Find or initialize a record setting an error if it can't be found. def find_or_initialize_with_error_by(attribute, value, error=:invalid) #:nodoc: find_or_initialize_with_errors([attribute], { attribute => value }, error) end # Find or initialize a record with group of attributes based on a list of required attributes. def find_or_initialize_with_errors(required_attributes, attributes, error=:invalid) #:nodoc: attributes = attributes.slice(*required_attributes).with_indifferent_access attributes.delete_if { |key, value| value.blank? } if attributes.size == required_attributes.size record = find_first_by_auth_conditions(attributes) end unless record record = new required_attributes.each do |key| value = attributes[key] record.send("#{key}=", value) record.errors.add(key, value.present? ? error : :blank) end end record end protected def devise_parameter_filter @devise_parameter_filter ||= Devise::ParameterFilter.new(case_insensitive_keys, strip_whitespace_keys) end end end end end devise-3.5.6/lib/devise/models/confirmable.rb0000644000004100000410000003267212663066463021200 0ustar www-datawww-datamodule Devise module Models # Confirmable is responsible to verify if an account is already confirmed to # sign in, and to send emails with confirmation instructions. # Confirmation instructions are sent to the user email after creating a # record and when manually requested by a new confirmation instruction request. # # Confirmable tracks the following columns: # # * confirmation_token - A unique random token # * confirmed_at - A timestamp when the user clicked the confirmation link # * confirmation_sent_at - A timestamp when the confirmation_token was generated (not sent) # * unconfirmed_email - An email address copied from the email attr. After confirmation # this value is copied to the email attr then cleared # # == Options # # Confirmable adds the following options to +devise+: # # * +allow_unconfirmed_access_for+: the time you want to allow the user to access their account # before confirming it. After this period, the user access is denied. You can # use this to let your user access some features of your application without # confirming the account, but blocking it after a certain period (ie 7 days). # By default allow_unconfirmed_access_for is zero, it means users always have to confirm to sign in. # * +reconfirmable+: requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field to be setup (t.reconfirmable in migrations). Until confirmed, new email is # stored in unconfirmed email column, and copied to email column on successful # confirmation. # * +confirm_within+: the time before a sent confirmation token becomes invalid. # You can use this to force the user to confirm within a set period of time. # Confirmable will not generate a new token if a repeat confirmation is requested # during this time frame, unless the user's email changed too. # # == Examples # # User.find(1).confirm # returns true unless it's already confirmed # User.find(1).confirmed? # true/false # User.find(1).send_confirmation_instructions # manually send instructions # module Confirmable extend ActiveSupport::Concern include ActionView::Helpers::DateHelper included do before_create :generate_confirmation_token, if: :confirmation_required? after_create :send_on_create_confirmation_instructions, if: :send_confirmation_notification? before_update :postpone_email_change_until_confirmation_and_regenerate_confirmation_token, if: :postpone_email_change? after_update :send_reconfirmation_instructions, if: :reconfirmation_required? end def initialize(*args, &block) @bypass_confirmation_postpone = false @reconfirmation_required = false @skip_confirmation_notification = false @raw_confirmation_token = nil super end def self.required_fields(klass) required_methods = [:confirmation_token, :confirmed_at, :confirmation_sent_at] required_methods << :unconfirmed_email if klass.reconfirmable required_methods end # Confirm a user by setting it's confirmed_at to actual time. If the user # is already confirmed, add an error to email field. If the user is invalid # add errors def confirm(args={}) pending_any_confirmation do if confirmation_period_expired? self.errors.add(:email, :confirmation_period_expired, period: Devise::TimeInflector.time_ago_in_words(self.class.confirm_within.ago)) return false end self.confirmed_at = Time.now.utc saved = if self.class.reconfirmable && unconfirmed_email.present? skip_reconfirmation! self.email = unconfirmed_email self.unconfirmed_email = nil # We need to validate in such cases to enforce e-mail uniqueness save(validate: true) else save(validate: args[:ensure_valid] == true) end after_confirmation if saved saved end end def confirm!(args={}) ActiveSupport::Deprecation.warn "confirm! is deprecated in favor of confirm" confirm(args) end # Verifies whether a user is confirmed or not def confirmed? !!confirmed_at end def pending_reconfirmation? self.class.reconfirmable && unconfirmed_email.present? end # Send confirmation instructions by email def send_confirmation_instructions unless @raw_confirmation_token generate_confirmation_token! end opts = pending_reconfirmation? ? { to: unconfirmed_email } : { } send_devise_notification(:confirmation_instructions, @raw_confirmation_token, opts) end def send_reconfirmation_instructions @reconfirmation_required = false unless @skip_confirmation_notification send_confirmation_instructions end end # Resend confirmation token. # Regenerates the token if the period is expired. def resend_confirmation_instructions pending_any_confirmation do send_confirmation_instructions end end # Overwrites active_for_authentication? for confirmation # by verifying whether a user is active to sign in or not. If the user # is already confirmed, it should never be blocked. Otherwise we need to # calculate if the confirm time has not expired for this user. def active_for_authentication? super && (!confirmation_required? || confirmed? || confirmation_period_valid?) end # The message to be shown if the account is inactive. def inactive_message !confirmed? ? :unconfirmed : super end # If you don't want confirmation to be sent on create, neither a code # to be generated, call skip_confirmation! def skip_confirmation! self.confirmed_at = Time.now.utc end # Skips sending the confirmation/reconfirmation notification email after_create/after_update. Unlike # #skip_confirmation!, record still requires confirmation. def skip_confirmation_notification! @skip_confirmation_notification = true end # If you don't want reconfirmation to be sent, neither a code # to be generated, call skip_reconfirmation! def skip_reconfirmation! @bypass_confirmation_postpone = true end protected # A callback method used to deliver confirmation # instructions on creation. This can be overridden # in models to map to a nice sign up e-mail. def send_on_create_confirmation_instructions send_confirmation_instructions end # Callback to overwrite if confirmation is required or not. def confirmation_required? !confirmed? end # Checks if the confirmation for the user is within the limit time. # We do this by calculating if the difference between today and the # confirmation sent date does not exceed the confirm in time configured. # Confirm_within is a model configuration, must always be an integer value. # # Example: # # # allow_unconfirmed_access_for = 1.day and confirmation_sent_at = today # confirmation_period_valid? # returns true # # # allow_unconfirmed_access_for = 5.days and confirmation_sent_at = 4.days.ago # confirmation_period_valid? # returns true # # # allow_unconfirmed_access_for = 5.days and confirmation_sent_at = 5.days.ago # confirmation_period_valid? # returns false # # # allow_unconfirmed_access_for = 0.days # confirmation_period_valid? # will always return false # # # allow_unconfirmed_access_for = nil # confirmation_period_valid? # will always return true # def confirmation_period_valid? self.class.allow_unconfirmed_access_for.nil? || (confirmation_sent_at && confirmation_sent_at.utc >= self.class.allow_unconfirmed_access_for.ago) end # Checks if the user confirmation happens before the token becomes invalid # Examples: # # # confirm_within = 3.days and confirmation_sent_at = 2.days.ago # confirmation_period_expired? # returns false # # # confirm_within = 3.days and confirmation_sent_at = 4.days.ago # confirmation_period_expired? # returns true # # # confirm_within = nil # confirmation_period_expired? # will always return false # def confirmation_period_expired? self.class.confirm_within && self.confirmation_sent_at && (Time.now > self.confirmation_sent_at + self.class.confirm_within) end # Checks whether the record requires any confirmation. def pending_any_confirmation if (!confirmed? || pending_reconfirmation?) yield else self.errors.add(:email, :already_confirmed) false end end # Generates a new random token for confirmation, and stores # the time this token is being generated in confirmation_sent_at def generate_confirmation_token if self.confirmation_token && !confirmation_period_expired? @raw_confirmation_token = self.confirmation_token else raw, _ = Devise.token_generator.generate(self.class, :confirmation_token) self.confirmation_token = @raw_confirmation_token = raw self.confirmation_sent_at = Time.now.utc end end def generate_confirmation_token! generate_confirmation_token && save(validate: false) end def postpone_email_change_until_confirmation_and_regenerate_confirmation_token @reconfirmation_required = true self.unconfirmed_email = self.email self.email = self.email_was self.confirmation_token = nil generate_confirmation_token end def postpone_email_change? postpone = self.class.reconfirmable && email_changed? && email_was.present? && !@bypass_confirmation_postpone && self.email.present? @bypass_confirmation_postpone = false postpone end def reconfirmation_required? self.class.reconfirmable && @reconfirmation_required && self.email.present? end def send_confirmation_notification? confirmation_required? && !@skip_confirmation_notification && self.email.present? end # A callback initiated after successfully confirming. This can be # used to insert your own logic that is only run after the user successfully # confirms. # # Example: # # def after_confirmation # self.update_attribute(:invite_code, nil) # end # def after_confirmation end module ClassMethods # Attempt to find a user by its email. If a record is found, send new # confirmation instructions to it. If not, try searching for a user by unconfirmed_email # field. If no user is found, returns a new user with an email not found error. # Options must contain the user email def send_confirmation_instructions(attributes={}) confirmable = find_by_unconfirmed_email_with_errors(attributes) if reconfirmable unless confirmable.try(:persisted?) confirmable = find_or_initialize_with_errors(confirmation_keys, attributes, :not_found) end confirmable.resend_confirmation_instructions if confirmable.persisted? confirmable end # Find a user by its confirmation token and try to confirm it. # If no user is found, returns a new user with an error. # If the user is already confirmed, create an error for the user # Options must have the confirmation_token def confirm_by_token(confirmation_token) confirmable = find_first_by_auth_conditions(confirmation_token: confirmation_token) unless confirmable confirmation_digest = Devise.token_generator.digest(self, :confirmation_token, confirmation_token) confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_digest) end # TODO: replace above lines with # confirmable = find_or_initialize_with_error_by(:confirmation_token, confirmation_token) # after enough time has passed that Devise clients do not use digested tokens confirmable.confirm if confirmable.persisted? confirmable end # Find a record for confirmation by unconfirmed email field def find_by_unconfirmed_email_with_errors(attributes = {}) unconfirmed_required_attributes = confirmation_keys.map { |k| k == :email ? :unconfirmed_email : k } unconfirmed_attributes = attributes.symbolize_keys unconfirmed_attributes[:unconfirmed_email] = unconfirmed_attributes.delete(:email) find_or_initialize_with_errors(unconfirmed_required_attributes, unconfirmed_attributes, :not_found) end Devise::Models.config(self, :allow_unconfirmed_access_for, :confirmation_keys, :reconfirmable, :confirm_within) end end end end devise-3.5.6/lib/devise/rails.rb0000644000004100000410000000333212663066463016535 0ustar www-datawww-datarequire 'devise/rails/routes' require 'devise/rails/warden_compat' module Devise class Engine < ::Rails::Engine config.devise = Devise # Initialize Warden and copy its configurations. config.app_middleware.use Warden::Manager do |config| Devise.warden_config = config end # Force routes to be loaded if we are doing any eager load. config.before_eager_load { |app| app.reload_routes! } initializer "devise.url_helpers" do Devise.include_helpers(Devise::Controllers) end initializer "devise.omniauth", after: :load_config_initializers, before: :build_middleware_stack do |app| Devise.omniauth_configs.each do |provider, config| app.middleware.use config.strategy_class, *config.args do |strategy| config.strategy = strategy end end if Devise.omniauth_configs.any? Devise.include_helpers(Devise::OmniAuth) end end initializer "devise.secret_key" do |app| if app.respond_to?(:secrets) Devise.secret_key ||= app.secrets.secret_key_base elsif app.config.respond_to?(:secret_key_base) Devise.secret_key ||= app.config.secret_key_base end Devise.token_generator ||= if secret_key = Devise.secret_key Devise::TokenGenerator.new( Devise::CachingKeyGenerator.new(Devise::KeyGenerator.new(secret_key)) ) end end initializer "devise.fix_routes_proxy_missing_respond_to_bug" do # Deprecate: Remove once we move to Rails 4 only. ActionDispatch::Routing::RoutesProxy.class_eval do def respond_to?(method, include_private = false) super || routes.url_helpers.respond_to?(method) end end end end end devise-3.5.6/lib/devise/parameter_sanitizer.rb0000644000004100000410000000446712663066463021505 0ustar www-datawww-datamodule Devise class BaseSanitizer attr_reader :params, :resource_name, :resource_class def initialize(resource_class, resource_name, params) @resource_class = resource_class @resource_name = resource_name @params = params @blocks = Hash.new end def for(kind, &block) if block_given? @blocks[kind] = block else default_for(kind) end end def sanitize(kind) if block = @blocks[kind] block.call(default_params) else default_sanitize(kind) end end private def default_for(kind) raise ArgumentError, "a block is expected in Devise base sanitizer" end def default_sanitize(kind) default_params end def default_params params.fetch(resource_name, {}) end end class ParameterSanitizer < BaseSanitizer def initialize(*) super @permitted = Hash.new { |h,k| h[k] = attributes_for(k) } end def sign_in permit self.for(:sign_in) end def sign_up permit self.for(:sign_up) end def account_update permit self.for(:account_update) end private # TODO: We do need to flatten so it works with strong_parameters # gem. We should drop it once we move to Rails 4 only support. def permit(keys) default_params.permit(*Array(keys)) end # Change for(kind) to return the values in the @permitted # hash, allowing the developer to customize at runtime. def default_for(kind) @permitted[kind] || raise("No sanitizer provided for #{kind}") end def default_sanitize(kind) if respond_to?(kind, true) send(kind) else raise NotImplementedError, "Devise doesn't know how to sanitize parameters for #{kind}" end end def attributes_for(kind) case kind when :sign_in auth_keys + [:password, :remember_me] when :sign_up auth_keys + [:password, :password_confirmation] when :account_update auth_keys + [:password, :password_confirmation, :current_password] end end def auth_keys @auth_keys ||= @resource_class.authentication_keys.respond_to?(:keys) ? @resource_class.authentication_keys.keys : @resource_class.authentication_keys end end end devise-3.5.6/lib/devise.rb0000644000004100000410000003767212663066463015441 0ustar www-datawww-datarequire 'rails' require 'active_support/core_ext/numeric/time' require 'active_support/dependencies' require 'orm_adapter' require 'set' require 'securerandom' require 'responders' module Devise autoload :Delegator, 'devise/delegator' autoload :Encryptor, 'devise/encryptor' autoload :FailureApp, 'devise/failure_app' autoload :OmniAuth, 'devise/omniauth' autoload :ParameterFilter, 'devise/parameter_filter' autoload :BaseSanitizer, 'devise/parameter_sanitizer' autoload :ParameterSanitizer, 'devise/parameter_sanitizer' autoload :TestHelpers, 'devise/test_helpers' autoload :TimeInflector, 'devise/time_inflector' autoload :TokenGenerator, 'devise/token_generator' module Controllers autoload :Helpers, 'devise/controllers/helpers' autoload :Rememberable, 'devise/controllers/rememberable' autoload :ScopedViews, 'devise/controllers/scoped_views' autoload :SignInOut, 'devise/controllers/sign_in_out' autoload :StoreLocation, 'devise/controllers/store_location' autoload :UrlHelpers, 'devise/controllers/url_helpers' end module Hooks autoload :Proxy, 'devise/hooks/proxy' end module Mailers autoload :Helpers, 'devise/mailers/helpers' end module Strategies autoload :Base, 'devise/strategies/base' autoload :Authenticatable, 'devise/strategies/authenticatable' end # Constants which holds devise configuration for extensions. Those should # not be modified by the "end user" (this is why they are constants). ALL = [] CONTROLLERS = ActiveSupport::OrderedHash.new ROUTES = ActiveSupport::OrderedHash.new STRATEGIES = ActiveSupport::OrderedHash.new URL_HELPERS = ActiveSupport::OrderedHash.new # Strategies that do not require user input. NO_INPUT = [] # True values used to check params TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'] # Secret key used by the key generator mattr_accessor :secret_key @@secret_key = nil # Custom domain or key for cookies. Not set by default mattr_accessor :rememberable_options @@rememberable_options = {} # The number of times to encrypt password. mattr_accessor :stretches @@stretches = 10 # The default key used when authenticating over http auth. mattr_accessor :http_authentication_key @@http_authentication_key = nil # Keys used when authenticating a user. mattr_accessor :authentication_keys @@authentication_keys = [:email] # Request keys used when authenticating a user. mattr_accessor :request_keys @@request_keys = [] # Keys that should be case-insensitive. mattr_accessor :case_insensitive_keys @@case_insensitive_keys = [:email] # Keys that should have whitespace stripped. mattr_accessor :strip_whitespace_keys @@strip_whitespace_keys = [] # If http authentication is enabled by default. mattr_accessor :http_authenticatable @@http_authenticatable = false # If http headers should be returned for ajax requests. True by default. mattr_accessor :http_authenticatable_on_xhr @@http_authenticatable_on_xhr = true # If params authenticatable is enabled by default. mattr_accessor :params_authenticatable @@params_authenticatable = true # The realm used in Http Basic Authentication. mattr_accessor :http_authentication_realm @@http_authentication_realm = "Application" # Email regex used to validate email formats. It simply asserts that # an one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. mattr_accessor :email_regexp @@email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\W]+\z/ # Range validation for password length mattr_accessor :password_length @@password_length = 6..128 # The time the user will be remembered without asking for credentials again. mattr_accessor :remember_for @@remember_for = 2.weeks # TODO: extend_remember_period is no longer used # If true, extends the user's remember period when remembered via cookie. mattr_accessor :extend_remember_period @@extend_remember_period = false # If true, all the remember me tokens are going to be invalidated when the user signs out. mattr_accessor :expire_all_remember_me_on_sign_out @@expire_all_remember_me_on_sign_out = true # Time interval you can access your account before confirming your account. # nil - allows unconfirmed access for unlimited time mattr_accessor :allow_unconfirmed_access_for @@allow_unconfirmed_access_for = 0.days # Time interval the confirmation token is valid. nil = unlimited mattr_accessor :confirm_within @@confirm_within = nil # Defines which key will be used when confirming an account. mattr_accessor :confirmation_keys @@confirmation_keys = [:email] # Defines if email should be reconfirmable. # False by default for backwards compatibility. mattr_accessor :reconfirmable @@reconfirmable = false # Time interval to timeout the user session without activity. mattr_accessor :timeout_in @@timeout_in = 30.minutes # Used to encrypt password. Please generate one with rake secret. mattr_accessor :pepper @@pepper = nil # Used to enable sending notification to user when their password is changed mattr_accessor :send_password_change_notification @@send_password_change_notification = false # Scoped views. Since it relies on fallbacks to render default views, it's # turned off by default. mattr_accessor :scoped_views @@scoped_views = false # Defines which strategy can be used to lock an account. # Values: :failed_attempts, :none mattr_accessor :lock_strategy @@lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account mattr_accessor :unlock_keys @@unlock_keys = [:email] # Defines which strategy can be used to unlock an account. # Values: :email, :time, :both mattr_accessor :unlock_strategy @@unlock_strategy = :both # Number of authentication tries before locking an account mattr_accessor :maximum_attempts @@maximum_attempts = 20 # Time interval to unlock the account if :time is defined as unlock_strategy. mattr_accessor :unlock_in @@unlock_in = 1.hour # Defines which key will be used when recovering the password for an account mattr_accessor :reset_password_keys @@reset_password_keys = [:email] # Time interval you can reset your password with a reset password key mattr_accessor :reset_password_within @@reset_password_within = 6.hours # When set to false, resetting a password does not automatically sign in a user mattr_accessor :sign_in_after_reset_password @@sign_in_after_reset_password = true # The default scope which is used by warden. mattr_accessor :default_scope @@default_scope = nil # Address which sends Devise e-mails. mattr_accessor :mailer_sender @@mailer_sender = nil # Skip session storage for the following strategies mattr_accessor :skip_session_storage @@skip_session_storage = [] # Which formats should be treated as navigational. mattr_accessor :navigational_formats @@navigational_formats = ["*/*", :html] # When set to true, signing out a user signs out all other scopes. mattr_accessor :sign_out_all_scopes @@sign_out_all_scopes = true # The default method used while signing out mattr_accessor :sign_out_via @@sign_out_via = :get # The parent controller all Devise controllers inherits from. # Defaults to ApplicationController. This should be set early # in the initialization process and should be set to a string. mattr_accessor :parent_controller @@parent_controller = "ApplicationController" # The parent mailer all Devise mailers inherit from. # Defaults to ActionMailer::Base. This should be set early # in the initialization process and should be set to a string. mattr_accessor :parent_mailer @@parent_mailer = "ActionMailer::Base" # The router Devise should use to generate routes. Defaults # to :main_app. Should be overridden by engines in order # to provide custom routes. mattr_accessor :router_name @@router_name = nil # Set the OmniAuth path prefix so it can be overridden when # Devise is used in a mountable engine mattr_accessor :omniauth_path_prefix @@omniauth_path_prefix = nil # Set if we should clean up the CSRF Token on authentication mattr_accessor :clean_up_csrf_token_on_authentication @@clean_up_csrf_token_on_authentication = true # PRIVATE CONFIGURATION # Store scopes mappings. mattr_reader :mappings @@mappings = ActiveSupport::OrderedHash.new # OmniAuth configurations. mattr_reader :omniauth_configs @@omniauth_configs = ActiveSupport::OrderedHash.new # Define a set of modules that are called when a mapping is added. mattr_reader :helpers @@helpers = Set.new @@helpers << Devise::Controllers::Helpers # Private methods to interface with Warden. mattr_accessor :warden_config @@warden_config = nil @@warden_config_blocks = [] # When true, enter in paranoid mode to avoid user enumeration. mattr_accessor :paranoid @@paranoid = false # When true, warn user if they just used next-to-last attempt of authentication mattr_accessor :last_attempt_warning @@last_attempt_warning = true # Stores the token generator mattr_accessor :token_generator @@token_generator = nil # Default way to setup Devise. Run rails generate devise_install to create # a fresh initializer with all configuration values. def self.setup yield self end class Getter def initialize name @name = name end def get ActiveSupport::Dependencies.constantize(@name) end end def self.ref(arg) if defined?(ActiveSupport::Dependencies::ClassCache) ActiveSupport::Dependencies::reference(arg) Getter.new(arg) else ActiveSupport::Dependencies.ref(arg) end end def self.available_router_name router_name || :main_app end def self.omniauth_providers omniauth_configs.keys end # Get the mailer class from the mailer reference object. def self.mailer @@mailer_ref.get end # Set the mailer reference object to access the mailer. def self.mailer=(class_name) @@mailer_ref = ref(class_name) end self.mailer = "Devise::Mailer" # Small method that adds a mapping to Devise. def self.add_mapping(resource, options) mapping = Devise::Mapping.new(resource, options) @@mappings[mapping.name] = mapping @@default_scope ||= mapping.name @@helpers.each { |h| h.define_helpers(mapping) } mapping end # Register available devise modules. For the standard modules that Devise provides, this method is # called from lib/devise/modules.rb. Third-party modules need to be added explicitly using this method. # # Note that adding a module using this method does not cause it to be used in the authentication # process. That requires that the module be listed in the arguments passed to the 'devise' method # in the model class definition. # # == Options: # # +model+ - String representing the load path to a custom *model* for this module (to autoload.) # +controller+ - Symbol representing the name of an existing or custom *controller* for this module. # +route+ - Symbol representing the named *route* helper for this module. # +strategy+ - Symbol representing if this module got a custom *strategy*. # +insert_at+ - Integer representing the order in which this module's model will be included # # All values, except :model, accept also a boolean and will have the same name as the given module # name. # # == Examples: # # Devise.add_module(:party_module) # Devise.add_module(:party_module, strategy: true, controller: :sessions) # Devise.add_module(:party_module, model: 'party_module/model') # Devise.add_module(:party_module, insert_at: 0) # def self.add_module(module_name, options = {}) options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input, :insert_at) ALL.insert (options[:insert_at] || -1), module_name if strategy = options[:strategy] strategy = (strategy == true ? module_name : strategy) STRATEGIES[module_name] = strategy end if controller = options[:controller] controller = (controller == true ? module_name : controller) CONTROLLERS[module_name] = controller end NO_INPUT << strategy if options[:no_input] if route = options[:route] case route when TrueClass key, value = module_name, [] when Symbol key, value = route, [] when Hash key, value = route.keys.first, route.values.flatten else raise ArgumentError, ":route should be true, a Symbol or a Hash" end URL_HELPERS[key] ||= [] URL_HELPERS[key].concat(value) URL_HELPERS[key].uniq! ROUTES[module_name] = key end if options[:model] path = (options[:model] == true ? "devise/models/#{module_name}" : options[:model]) camelized = ActiveSupport::Inflector.camelize(module_name.to_s) Devise::Models.send(:autoload, camelized.to_sym, path) end Devise::Mapping.add_module module_name end # Sets warden configuration using a block that will be invoked on warden # initialization. # # Devise.setup do |config| # config.allow_unconfirmed_access_for = 2.days # # config.warden do |manager| # # Configure warden to use other strategies, like oauth. # manager.oauth(:twitter) # end # end def self.warden(&block) @@warden_config_blocks << block end # Specify an OmniAuth provider. # # config.omniauth :github, APP_ID, APP_SECRET # def self.omniauth(provider, *args) @@helpers << Devise::OmniAuth::UrlHelpers config = Devise::OmniAuth::Config.new(provider, args) @@omniauth_configs[config.strategy_name.to_sym] = config end # Include helpers in the given scope to AC and AV. def self.include_helpers(scope) ActiveSupport.on_load(:action_controller) do include scope::Helpers if defined?(scope::Helpers) include scope::UrlHelpers end ActiveSupport.on_load(:action_view) do include scope::UrlHelpers end end # Regenerates url helpers considering Devise.mapping def self.regenerate_helpers! Devise::Controllers::UrlHelpers.remove_helpers! Devise::Controllers::UrlHelpers.generate_helpers! end # A method used internally to complete the setup of warden manager after routes are loaded. # See lib/devise/rails/routes.rb - ActionDispatch::Routing::RouteSet#finalize_with_devise! def self.configure_warden! #:nodoc: @@warden_configured ||= begin warden_config.failure_app = Devise::Delegator.new warden_config.default_scope = Devise.default_scope warden_config.intercept_401 = false Devise.mappings.each_value do |mapping| warden_config.scope_defaults mapping.name, strategies: mapping.strategies warden_config.serialize_into_session(mapping.name) do |record| mapping.to.serialize_into_session(record) end warden_config.serialize_from_session(mapping.name) do |key| # Previous versions contained an additional entry at the beginning of # key with the record's class name. args = key[-2, 2] mapping.to.serialize_from_session(*args) end end @@warden_config_blocks.map { |block| block.call Devise.warden_config } true end end # Generate a friendly string randomly to be used as token. # By default, length is 20 characters. def self.friendly_token(length = 20) # To calculate real characters, we must perform this operation. # See SecureRandom.urlsafe_base64 rlength = (length * 3) / 4 SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz') end # constant-time comparison algorithm to prevent timing attacks def self.secure_compare(a, b) return false if a.blank? || b.blank? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end end require 'warden' require 'devise/mapping' require 'devise/models' require 'devise/modules' require 'devise/rails' devise-3.5.6/gemfiles/0000755000004100000410000000000012663066463014643 5ustar www-datawww-datadevise-3.5.6/gemfiles/Gemfile.rails-3.2-stable0000644000004100000410000000105112663066463021014 0ustar www-datawww-datasource "https://rubygems.org" gemspec path: '..' gem "rails", github: 'rails/rails', branch: '3-2-stable' gem "omniauth", "~> 1.2.0" gem "omniauth-oauth2", "~> 1.1.0" gem "rdoc" group :test do gem "omniauth-facebook" gem "omniauth-openid", "~> 1.0.1" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false end platforms :jruby do gem "activerecord-jdbc-adapter" gem "activerecord-jdbcsqlite3-adapter" gem "jruby-openssl" end platforms :ruby do gem "sqlite3" end group :mongoid do gem "mongoid", "~> 3.0" end devise-3.5.6/gemfiles/Gemfile.rails-4.2-stable.lock0000644000004100000410000001072712663066463021756 0ustar www-datawww-dataGIT remote: git://github.com/rails/rails.git revision: f12ff8ddab7b199707ec36d72bd72f206f142c8b branch: 4-2-stable specs: actionmailer (4.2.1) actionpack (= 4.2.1) actionview (= 4.2.1) activejob (= 4.2.1) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 1.0, >= 1.0.5) actionpack (4.2.1) actionview (= 4.2.1) activesupport (= 4.2.1) rack (~> 1.6) rack-test (~> 0.6.2) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (4.2.1) activesupport (= 4.2.1) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.2) activejob (4.2.1) activesupport (= 4.2.1) globalid (>= 0.3.0) activemodel (4.2.1) activesupport (= 4.2.1) builder (~> 3.1) activerecord (4.2.1) activemodel (= 4.2.1) activesupport (= 4.2.1) arel (~> 6.0) activesupport (4.2.1) i18n (~> 0.7) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) rails (4.2.1) actionmailer (= 4.2.1) actionpack (= 4.2.1) actionview (= 4.2.1) activejob (= 4.2.1) activemodel (= 4.2.1) activerecord (= 4.2.1) activesupport (= 4.2.1) bundler (>= 1.3.0, < 2.0) railties (= 4.2.1) sprockets-rails railties (4.2.1) actionpack (= 4.2.1) activesupport (= 4.2.1) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) PATH remote: .. specs: devise (3.5.6) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 3.2.6, < 5) responders thread_safe (~> 0.1) warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: arel (6.0.0) bcrypt (3.1.10) bson (2.3.0) builder (3.2.2) connection_pool (2.1.3) erubis (2.7.0) faraday (0.9.1) multipart-post (>= 1.2, < 3) globalid (0.3.3) activesupport (>= 4.1.0) hashie (3.4.0) hike (1.2.3) i18n (0.7.0) json (1.8.2) jwt (1.4.1) loofah (2.0.1) nokogiri (>= 1.5.9) mail (2.6.3) mime-types (>= 1.16, < 3) metaclass (0.0.4) mime-types (2.4.3) mini_portile (0.6.2) minitest (5.5.1) mocha (1.1.0) metaclass (~> 0.0.1) mongoid (4.0.2) activemodel (~> 4.0) moped (~> 2.0.0) origin (~> 2.1) tzinfo (>= 0.3.37) moped (2.0.4) bson (~> 2.2) connection_pool (~> 2.0) optionable (~> 0.2.0) multi_json (1.11.0) multi_xml (0.5.5) multipart-post (2.0.0) nokogiri (1.6.6.2) mini_portile (~> 0.6.0) oauth2 (1.0.0) faraday (>= 0.8, < 0.10) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (~> 1.2) omniauth (1.2.2) hashie (>= 1.2, < 4) rack (~> 1.0) omniauth-facebook (2.0.1) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.2.0) faraday (>= 0.8, < 0.10) multi_json (~> 1.3) oauth2 (~> 1.0) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) optionable (0.2.0) origin (2.1.1) orm_adapter (0.5.0) rack (1.6.0) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.6.3) rack (>= 1.0) rails-deprecated_sanitizer (1.0.3) activesupport (>= 4.2.0.alpha) rails-dom-testing (1.0.6) activesupport (>= 4.2.0.beta, < 5.0) nokogiri (~> 1.6.0) rails-deprecated_sanitizer (>= 1.0.1) rails-html-sanitizer (1.0.2) loofah (~> 2.0) rake (10.4.2) rdoc (4.2.0) responders (2.1.1) railties (>= 4.2.0, < 5.1) ruby-openid (2.7.0) sprockets (2.12.3) hike (~> 1.2) multi_json (~> 1.0) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) sprockets-rails (2.2.4) actionpack (>= 3.0) activesupport (>= 3.0) sprockets (>= 2.8, < 4.0) sqlite3 (1.3.10) thor (0.19.1) thread_safe (0.3.5) tilt (1.4.1) tzinfo (1.2.2) thread_safe (~> 0.1) warden (1.2.6) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES activerecord-jdbc-adapter activerecord-jdbcsqlite3-adapter devise! jruby-openssl mocha (~> 1.1) mongoid (~> 4.0.0) omniauth (~> 1.2.2) omniauth-facebook omniauth-oauth2 (~> 1.2.0) omniauth-openid (~> 1.0.1) rails! rdoc sqlite3 webrat (= 0.7.3) BUNDLED WITH 1.11.2 devise-3.5.6/gemfiles/Gemfile.rails-4.2-stable0000644000004100000410000000105312663066463021017 0ustar www-datawww-datasource "https://rubygems.org" gemspec path: '..' gem "rails", github: 'rails/rails', branch: '4-2-stable' gem "omniauth", "~> 1.2.2" gem "omniauth-oauth2", "~> 1.2.0" gem "rdoc" group :test do gem "omniauth-facebook" gem "omniauth-openid", "~> 1.0.1" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false end platforms :jruby do gem "activerecord-jdbc-adapter" gem "activerecord-jdbcsqlite3-adapter" gem "jruby-openssl" end platforms :ruby do gem "sqlite3" end group :mongoid do gem "mongoid", "~> 4.0.0" end devise-3.5.6/gemfiles/Gemfile.rails-4.0-stable0000644000004100000410000000105312663066463021015 0ustar www-datawww-datasource "https://rubygems.org" gemspec path: '..' gem "rails", github: 'rails/rails', branch: '4-0-stable' gem "omniauth", "~> 1.2.0" gem "omniauth-oauth2", "~> 1.1.0" gem "rdoc" group :test do gem "omniauth-facebook" gem "omniauth-openid", "~> 1.0.1" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false end platforms :jruby do gem "activerecord-jdbc-adapter" gem "activerecord-jdbcsqlite3-adapter" gem "jruby-openssl" end platforms :ruby do gem "sqlite3" end group :mongoid do gem "mongoid", "~> 4.0.0" end devise-3.5.6/gemfiles/Gemfile.rails-3.2-stable.lock0000644000004100000410000000732412663066463021754 0ustar www-datawww-dataGIT remote: git://github.com/rails/rails.git revision: b344986bc3d94ca7821fc5e0eef1874882ac6cbb branch: 3-2-stable specs: actionmailer (3.2.21) actionpack (= 3.2.21) mail (~> 2.5.4) actionpack (3.2.21) activemodel (= 3.2.21) activesupport (= 3.2.21) builder (~> 3.0.0) erubis (~> 2.7.0) journey (~> 1.0.4) rack (~> 1.4.5) rack-cache (~> 1.2) rack-test (~> 0.6.1) sprockets (~> 2.2.1) activemodel (3.2.21) activesupport (= 3.2.21) builder (~> 3.0.0) activerecord (3.2.21) activemodel (= 3.2.21) activesupport (= 3.2.21) arel (~> 3.0.2) tzinfo (~> 0.3.29) activeresource (3.2.21) activemodel (= 3.2.21) activesupport (= 3.2.21) activesupport (3.2.21) i18n (~> 0.6, >= 0.6.4) multi_json (~> 1.0) rails (3.2.21) actionmailer (= 3.2.21) actionpack (= 3.2.21) activerecord (= 3.2.21) activeresource (= 3.2.21) activesupport (= 3.2.21) bundler (~> 1.0) railties (= 3.2.21) railties (3.2.21) actionpack (= 3.2.21) activesupport (= 3.2.21) rack-ssl (~> 1.3.2) rake (>= 0.8.7) rdoc (~> 3.4) thor (>= 0.14.6, < 2.0) PATH remote: .. specs: devise (3.5.6) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 3.2.6, < 5) responders thread_safe (~> 0.1) warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: arel (3.0.3) bcrypt (3.1.10) builder (3.0.4) erubis (2.7.0) faraday (0.9.1) multipart-post (>= 1.2, < 3) hashie (3.4.0) hike (1.2.3) i18n (0.7.0) journey (1.0.4) json (1.8.2) jwt (1.4.1) mail (2.5.4) mime-types (~> 1.16) treetop (~> 1.4.8) metaclass (0.0.4) mime-types (1.25.1) mini_portile (0.6.2) mocha (1.1.0) metaclass (~> 0.0.1) mongoid (3.1.6) activemodel (~> 3.2) moped (~> 1.4) origin (~> 1.0) tzinfo (~> 0.3.29) moped (1.5.2) multi_json (1.11.0) multi_xml (0.5.5) multipart-post (2.0.0) nokogiri (1.6.6.2) mini_portile (~> 0.6.0) oauth2 (0.9.4) faraday (>= 0.8, < 0.10) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (~> 1.2) omniauth (1.2.2) hashie (>= 1.2, < 4) rack (~> 1.0) omniauth-facebook (1.6.0) omniauth-oauth2 (~> 1.1) omniauth-oauth2 (1.1.2) faraday (>= 0.8, < 0.10) multi_json (~> 1.3) oauth2 (~> 0.9.3) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) origin (1.1.0) orm_adapter (0.5.0) polyglot (0.3.5) rack (1.4.5) rack-cache (1.2) rack (>= 0.4) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-ssl (1.3.4) rack rack-test (0.6.3) rack (>= 1.0) rake (10.4.2) rdoc (3.12.2) json (~> 1.4) responders (1.1.2) railties (>= 3.2, < 4.2) ruby-openid (2.7.0) sprockets (2.2.3) hike (~> 1.2) multi_json (~> 1.0) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) sqlite3 (1.3.10) thor (0.19.1) thread_safe (0.3.5) tilt (1.4.1) treetop (1.4.15) polyglot polyglot (>= 0.3.1) tzinfo (0.3.43) warden (1.2.6) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES activerecord-jdbc-adapter activerecord-jdbcsqlite3-adapter devise! jruby-openssl mocha (~> 1.1) mongoid (~> 3.0) omniauth (~> 1.2.0) omniauth-facebook omniauth-oauth2 (~> 1.1.0) omniauth-openid (~> 1.0.1) rails! rdoc sqlite3 webrat (= 0.7.3) BUNDLED WITH 1.11.2 devise-3.5.6/gemfiles/Gemfile.rails-4.1-stable.lock0000644000004100000410000000747212663066463021760 0ustar www-datawww-dataGIT remote: git://github.com/rails/rails.git revision: bf32ec7b8611e6b4c7e9398f7d297a1f0221e9b9 branch: 4-1-stable specs: actionmailer (4.1.10) actionpack (= 4.1.10) actionview (= 4.1.10) mail (~> 2.5, >= 2.5.4) actionpack (4.1.10) actionview (= 4.1.10) activesupport (= 4.1.10) rack (~> 1.5.2) rack-test (~> 0.6.2) actionview (4.1.10) activesupport (= 4.1.10) builder (~> 3.1) erubis (~> 2.7.0) activemodel (4.1.10) activesupport (= 4.1.10) builder (~> 3.1) activerecord (4.1.10) activemodel (= 4.1.10) activesupport (= 4.1.10) arel (~> 5.0.0) activesupport (4.1.10) i18n (~> 0.6, >= 0.6.9) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.1) tzinfo (~> 1.1) rails (4.1.10) actionmailer (= 4.1.10) actionpack (= 4.1.10) actionview (= 4.1.10) activemodel (= 4.1.10) activerecord (= 4.1.10) activesupport (= 4.1.10) bundler (>= 1.3.0, < 2.0) railties (= 4.1.10) sprockets-rails (~> 2.0) railties (4.1.10) actionpack (= 4.1.10) activesupport (= 4.1.10) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) PATH remote: .. specs: devise (3.5.6) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 3.2.6, < 5) responders thread_safe (~> 0.1) warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: arel (5.0.1.20140414130214) bcrypt (3.1.10) bson (2.3.0) builder (3.2.2) connection_pool (2.1.3) erubis (2.7.0) faraday (0.9.1) multipart-post (>= 1.2, < 3) hashie (3.4.0) hike (1.2.3) i18n (0.7.0) json (1.8.2) jwt (1.4.1) mail (2.6.3) mime-types (>= 1.16, < 3) metaclass (0.0.4) mime-types (2.4.3) mini_portile (0.6.2) minitest (5.5.1) mocha (1.1.0) metaclass (~> 0.0.1) mongoid (4.0.2) activemodel (~> 4.0) moped (~> 2.0.0) origin (~> 2.1) tzinfo (>= 0.3.37) moped (2.0.4) bson (~> 2.2) connection_pool (~> 2.0) optionable (~> 0.2.0) multi_json (1.11.0) multi_xml (0.5.5) multipart-post (2.0.0) nokogiri (1.6.6.2) mini_portile (~> 0.6.0) oauth2 (0.9.4) faraday (>= 0.8, < 0.10) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (~> 1.2) omniauth (1.2.2) hashie (>= 1.2, < 4) rack (~> 1.0) omniauth-facebook (1.6.0) omniauth-oauth2 (~> 1.1) omniauth-oauth2 (1.1.2) faraday (>= 0.8, < 0.10) multi_json (~> 1.3) oauth2 (~> 0.9.3) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) optionable (0.2.0) origin (2.1.1) orm_adapter (0.5.0) rack (1.5.2) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.6.3) rack (>= 1.0) rake (10.4.2) rdoc (4.2.0) responders (1.1.2) railties (>= 3.2, < 4.2) ruby-openid (2.7.0) sprockets (2.12.3) hike (~> 1.2) multi_json (~> 1.0) rack (~> 1.0) tilt (~> 1.1, != 1.3.0) sprockets-rails (2.2.4) actionpack (>= 3.0) activesupport (>= 3.0) sprockets (>= 2.8, < 4.0) sqlite3 (1.3.10) thor (0.19.1) thread_safe (0.3.5) tilt (1.4.1) tzinfo (1.2.2) thread_safe (~> 0.1) warden (1.2.6) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES activerecord-jdbc-adapter activerecord-jdbcsqlite3-adapter devise! jruby-openssl mocha (~> 1.1) mongoid (~> 4.0.0) omniauth (~> 1.2.0) omniauth-facebook omniauth-oauth2 (~> 1.1.0) omniauth-openid (~> 1.0.1) rails! rdoc sqlite3 webrat (= 0.7.3) BUNDLED WITH 1.11.2 devise-3.5.6/gemfiles/Gemfile.rails-4.0-stable.lock0000644000004100000410000000721312663066463021750 0ustar www-datawww-dataGIT remote: git://github.com/rails/rails.git revision: 9be9597e510d185ca7964d0a05b4ea2a7f2d50d1 branch: 4-0-stable specs: actionmailer (4.0.13) actionpack (= 4.0.13) mail (~> 2.5, >= 2.5.4) actionpack (4.0.13) activesupport (= 4.0.13) builder (~> 3.1.0) erubis (~> 2.7.0) rack (~> 1.5.2) rack-test (~> 0.6.2) activemodel (4.0.13) activesupport (= 4.0.13) builder (~> 3.1.0) activerecord (4.0.13) activemodel (= 4.0.13) activerecord-deprecated_finders (~> 1.0.2) activesupport (= 4.0.13) arel (~> 4.0.0) activesupport (4.0.13) i18n (~> 0.6, >= 0.6.9) minitest (~> 4.2) multi_json (~> 1.3) thread_safe (~> 0.1) tzinfo (~> 0.3.37) rails (4.0.13) actionmailer (= 4.0.13) actionpack (= 4.0.13) activerecord (= 4.0.13) activesupport (= 4.0.13) bundler (>= 1.3.0, < 2.0) railties (= 4.0.13) sprockets-rails (~> 2.0) railties (4.0.13) actionpack (= 4.0.13) activesupport (= 4.0.13) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) PATH remote: .. specs: devise (3.5.6) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 3.2.6, < 5) responders thread_safe (~> 0.1) warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: activerecord-deprecated_finders (1.0.4) arel (4.0.2) bcrypt (3.1.10) bson (3.2.6) builder (3.1.4) concurrent-ruby (1.0.0) connection_pool (2.2.0) erubis (2.7.0) faraday (0.9.2) multipart-post (>= 1.2, < 3) hashie (3.4.3) i18n (0.7.0) jwt (1.5.2) mail (2.6.3) mime-types (>= 1.16, < 3) metaclass (0.0.4) mime-types (2.99) mini_portile2 (2.0.0) minitest (4.7.5) mocha (1.1.0) metaclass (~> 0.0.1) mongoid (4.0.2) activemodel (~> 4.0) moped (~> 2.0.0) origin (~> 2.1) tzinfo (>= 0.3.37) moped (2.0.7) bson (~> 3.0) connection_pool (~> 2.0) optionable (~> 0.2.0) multi_json (1.11.2) multi_xml (0.5.5) multipart-post (2.0.0) nokogiri (1.6.7.2) mini_portile2 (~> 2.0.0.rc2) oauth2 (0.9.4) faraday (>= 0.8, < 0.10) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (~> 1.2) omniauth (1.2.2) hashie (>= 1.2, < 4) rack (~> 1.0) omniauth-facebook (1.6.0) omniauth-oauth2 (~> 1.1) omniauth-oauth2 (1.1.2) faraday (>= 0.8, < 0.10) multi_json (~> 1.3) oauth2 (~> 0.9.3) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) optionable (0.2.0) origin (2.2.0) orm_adapter (0.5.0) rack (1.5.5) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.6.3) rack (>= 1.0) rake (10.5.0) rdoc (4.2.1) responders (1.1.2) railties (>= 3.2, < 4.2) ruby-openid (2.7.0) sprockets (3.5.2) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (2.3.3) actionpack (>= 3.0) activesupport (>= 3.0) sprockets (>= 2.8, < 4.0) sqlite3 (1.3.11) thor (0.19.1) thread_safe (0.3.5) tzinfo (0.3.46) warden (1.2.6) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) PLATFORMS ruby DEPENDENCIES activerecord-jdbc-adapter activerecord-jdbcsqlite3-adapter devise! jruby-openssl mocha (~> 1.1) mongoid (~> 4.0.0) omniauth (~> 1.2.0) omniauth-facebook omniauth-oauth2 (~> 1.1.0) omniauth-openid (~> 1.0.1) rails! rdoc sqlite3 webrat (= 0.7.3) BUNDLED WITH 1.11.2 devise-3.5.6/gemfiles/Gemfile.rails-4.1-stable0000644000004100000410000000105312663066463021016 0ustar www-datawww-datasource "https://rubygems.org" gemspec path: '..' gem "rails", github: 'rails/rails', branch: '4-1-stable' gem "omniauth", "~> 1.2.0" gem "omniauth-oauth2", "~> 1.1.0" gem "rdoc" group :test do gem "omniauth-facebook" gem "omniauth-openid", "~> 1.0.1" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false end platforms :jruby do gem "activerecord-jdbc-adapter" gem "activerecord-jdbcsqlite3-adapter" gem "jruby-openssl" end platforms :ruby do gem "sqlite3" end group :mongoid do gem "mongoid", "~> 4.0.0" end devise-3.5.6/metadata.yml0000644000004100000410000004564112663066463015365 0ustar www-datawww-data--- !ruby/object:Gem::Specification name: devise version: !ruby/object:Gem::Version version: 3.5.6 platform: ruby authors: - José Valim - Carlos Antônio autorequire: bindir: bin cert_chain: [] date: 2016-02-01 00:00:00.000000000 Z dependencies: - !ruby/object:Gem::Dependency name: warden requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.2.3 type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: 1.2.3 - !ruby/object:Gem::Dependency name: orm_adapter requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '0.1' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '0.1' - !ruby/object:Gem::Dependency name: bcrypt requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '3.0' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '3.0' - !ruby/object:Gem::Dependency name: thread_safe requirement: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '0.1' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - "~>" - !ruby/object:Gem::Version version: '0.1' - !ruby/object:Gem::Dependency name: railties requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 3.2.6 - - "<" - !ruby/object:Gem::Version version: '5' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 3.2.6 - - "<" - !ruby/object:Gem::Version version: '5' - !ruby/object:Gem::Dependency name: responders requirement: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' type: :runtime prerelease: false version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' description: Flexible authentication solution for Rails with Warden email: contact@plataformatec.com.br executables: [] extensions: [] extra_rdoc_files: [] files: - ".gitignore" - ".travis.yml" - ".yardopts" - CHANGELOG.md - CODE_OF_CONDUCT.md - CONTRIBUTING.md - Gemfile - Gemfile.lock - MIT-LICENSE - README.md - Rakefile - app/controllers/devise/confirmations_controller.rb - app/controllers/devise/omniauth_callbacks_controller.rb - app/controllers/devise/passwords_controller.rb - app/controllers/devise/registrations_controller.rb - app/controllers/devise/sessions_controller.rb - app/controllers/devise/unlocks_controller.rb - app/controllers/devise_controller.rb - app/helpers/devise_helper.rb - app/mailers/devise/mailer.rb - app/views/devise/confirmations/new.html.erb - app/views/devise/mailer/confirmation_instructions.html.erb - app/views/devise/mailer/password_change.html.erb - app/views/devise/mailer/reset_password_instructions.html.erb - app/views/devise/mailer/unlock_instructions.html.erb - app/views/devise/passwords/edit.html.erb - app/views/devise/passwords/new.html.erb - app/views/devise/registrations/edit.html.erb - app/views/devise/registrations/new.html.erb - app/views/devise/sessions/new.html.erb - app/views/devise/shared/_links.html.erb - app/views/devise/unlocks/new.html.erb - config/locales/en.yml - devise.gemspec - devise.png - gemfiles/Gemfile.rails-3.2-stable - gemfiles/Gemfile.rails-3.2-stable.lock - gemfiles/Gemfile.rails-4.0-stable - gemfiles/Gemfile.rails-4.0-stable.lock - gemfiles/Gemfile.rails-4.1-stable - gemfiles/Gemfile.rails-4.1-stable.lock - gemfiles/Gemfile.rails-4.2-stable - gemfiles/Gemfile.rails-4.2-stable.lock - lib/devise.rb - lib/devise/controllers/helpers.rb - lib/devise/controllers/rememberable.rb - lib/devise/controllers/scoped_views.rb - lib/devise/controllers/sign_in_out.rb - lib/devise/controllers/store_location.rb - lib/devise/controllers/url_helpers.rb - lib/devise/delegator.rb - lib/devise/encryptor.rb - lib/devise/failure_app.rb - lib/devise/hooks/activatable.rb - lib/devise/hooks/csrf_cleaner.rb - lib/devise/hooks/forgetable.rb - lib/devise/hooks/lockable.rb - lib/devise/hooks/proxy.rb - lib/devise/hooks/rememberable.rb - lib/devise/hooks/timeoutable.rb - lib/devise/hooks/trackable.rb - lib/devise/mailers/helpers.rb - lib/devise/mapping.rb - lib/devise/models.rb - lib/devise/models/authenticatable.rb - lib/devise/models/confirmable.rb - lib/devise/models/database_authenticatable.rb - lib/devise/models/lockable.rb - lib/devise/models/omniauthable.rb - lib/devise/models/recoverable.rb - lib/devise/models/registerable.rb - lib/devise/models/rememberable.rb - lib/devise/models/timeoutable.rb - lib/devise/models/trackable.rb - lib/devise/models/validatable.rb - lib/devise/modules.rb - lib/devise/omniauth.rb - lib/devise/omniauth/config.rb - lib/devise/omniauth/url_helpers.rb - lib/devise/orm/active_record.rb - lib/devise/orm/mongoid.rb - lib/devise/parameter_filter.rb - lib/devise/parameter_sanitizer.rb - lib/devise/rails.rb - lib/devise/rails/routes.rb - lib/devise/rails/warden_compat.rb - lib/devise/strategies/authenticatable.rb - lib/devise/strategies/base.rb - lib/devise/strategies/database_authenticatable.rb - lib/devise/strategies/rememberable.rb - lib/devise/test_helpers.rb - lib/devise/time_inflector.rb - lib/devise/token_generator.rb - lib/devise/version.rb - lib/generators/active_record/devise_generator.rb - lib/generators/active_record/templates/migration.rb - lib/generators/active_record/templates/migration_existing.rb - lib/generators/devise/controllers_generator.rb - lib/generators/devise/devise_generator.rb - lib/generators/devise/install_generator.rb - lib/generators/devise/orm_helpers.rb - lib/generators/devise/views_generator.rb - lib/generators/mongoid/devise_generator.rb - lib/generators/templates/README - lib/generators/templates/controllers/README - lib/generators/templates/controllers/confirmations_controller.rb - lib/generators/templates/controllers/omniauth_callbacks_controller.rb - lib/generators/templates/controllers/passwords_controller.rb - lib/generators/templates/controllers/registrations_controller.rb - lib/generators/templates/controllers/sessions_controller.rb - lib/generators/templates/controllers/unlocks_controller.rb - lib/generators/templates/devise.rb - lib/generators/templates/markerb/confirmation_instructions.markerb - lib/generators/templates/markerb/password_change.markerb - lib/generators/templates/markerb/reset_password_instructions.markerb - lib/generators/templates/markerb/unlock_instructions.markerb - lib/generators/templates/simple_form_for/confirmations/new.html.erb - lib/generators/templates/simple_form_for/passwords/edit.html.erb - lib/generators/templates/simple_form_for/passwords/new.html.erb - lib/generators/templates/simple_form_for/registrations/edit.html.erb - lib/generators/templates/simple_form_for/registrations/new.html.erb - lib/generators/templates/simple_form_for/sessions/new.html.erb - lib/generators/templates/simple_form_for/unlocks/new.html.erb - script/cached-bundle - script/s3-put - test/controllers/custom_registrations_controller_test.rb - test/controllers/custom_strategy_test.rb - test/controllers/helper_methods_test.rb - test/controllers/helpers_test.rb - test/controllers/inherited_controller_i18n_messages_test.rb - test/controllers/internal_helpers_test.rb - test/controllers/load_hooks_controller_test.rb - test/controllers/passwords_controller_test.rb - test/controllers/sessions_controller_test.rb - test/controllers/url_helpers_test.rb - test/delegator_test.rb - test/devise_test.rb - test/failure_app_test.rb - test/generators/active_record_generator_test.rb - test/generators/controllers_generator_test.rb - test/generators/devise_generator_test.rb - test/generators/install_generator_test.rb - test/generators/mongoid_generator_test.rb - test/generators/views_generator_test.rb - test/helpers/devise_helper_test.rb - test/integration/authenticatable_test.rb - test/integration/confirmable_test.rb - test/integration/database_authenticatable_test.rb - test/integration/http_authenticatable_test.rb - test/integration/lockable_test.rb - test/integration/omniauthable_test.rb - test/integration/recoverable_test.rb - test/integration/registerable_test.rb - test/integration/rememberable_test.rb - test/integration/timeoutable_test.rb - test/integration/trackable_test.rb - test/mailers/confirmation_instructions_test.rb - test/mailers/reset_password_instructions_test.rb - test/mailers/unlock_instructions_test.rb - test/mapping_test.rb - test/models/authenticatable_test.rb - test/models/confirmable_test.rb - test/models/database_authenticatable_test.rb - test/models/lockable_test.rb - test/models/omniauthable_test.rb - test/models/recoverable_test.rb - test/models/registerable_test.rb - test/models/rememberable_test.rb - test/models/serializable_test.rb - test/models/timeoutable_test.rb - test/models/trackable_test.rb - test/models/validatable_test.rb - test/models_test.rb - test/omniauth/config_test.rb - test/omniauth/url_helpers_test.rb - test/orm/active_record.rb - test/orm/mongoid.rb - test/parameter_sanitizer_test.rb - test/rails_app/Rakefile - test/rails_app/app/active_record/admin.rb - test/rails_app/app/active_record/shim.rb - test/rails_app/app/active_record/user.rb - test/rails_app/app/active_record/user_on_engine.rb - test/rails_app/app/active_record/user_on_main_app.rb - test/rails_app/app/active_record/user_without_email.rb - test/rails_app/app/controllers/admins/sessions_controller.rb - test/rails_app/app/controllers/admins_controller.rb - test/rails_app/app/controllers/application_controller.rb - test/rails_app/app/controllers/application_with_fake_engine.rb - test/rails_app/app/controllers/custom/registrations_controller.rb - test/rails_app/app/controllers/home_controller.rb - test/rails_app/app/controllers/publisher/registrations_controller.rb - test/rails_app/app/controllers/publisher/sessions_controller.rb - test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb - test/rails_app/app/controllers/users_controller.rb - test/rails_app/app/helpers/application_helper.rb - test/rails_app/app/mailers/users/from_proc_mailer.rb - test/rails_app/app/mailers/users/mailer.rb - test/rails_app/app/mailers/users/reply_to_mailer.rb - test/rails_app/app/mongoid/admin.rb - test/rails_app/app/mongoid/shim.rb - test/rails_app/app/mongoid/user.rb - test/rails_app/app/mongoid/user_on_engine.rb - test/rails_app/app/mongoid/user_on_main_app.rb - test/rails_app/app/mongoid/user_without_email.rb - test/rails_app/app/views/admins/index.html.erb - test/rails_app/app/views/admins/sessions/new.html.erb - test/rails_app/app/views/home/admin_dashboard.html.erb - test/rails_app/app/views/home/index.html.erb - test/rails_app/app/views/home/join.html.erb - test/rails_app/app/views/home/private.html.erb - test/rails_app/app/views/home/user_dashboard.html.erb - test/rails_app/app/views/layouts/application.html.erb - test/rails_app/app/views/users/edit_form.html.erb - test/rails_app/app/views/users/index.html.erb - test/rails_app/app/views/users/mailer/confirmation_instructions.erb - test/rails_app/app/views/users/sessions/new.html.erb - test/rails_app/bin/bundle - test/rails_app/bin/rails - test/rails_app/bin/rake - test/rails_app/config.ru - test/rails_app/config/application.rb - test/rails_app/config/boot.rb - test/rails_app/config/database.yml - test/rails_app/config/environment.rb - test/rails_app/config/environments/development.rb - test/rails_app/config/environments/production.rb - test/rails_app/config/environments/test.rb - test/rails_app/config/initializers/backtrace_silencers.rb - test/rails_app/config/initializers/devise.rb - test/rails_app/config/initializers/inflections.rb - test/rails_app/config/initializers/secret_token.rb - test/rails_app/config/initializers/session_store.rb - test/rails_app/config/routes.rb - test/rails_app/db/migrate/20100401102949_create_tables.rb - test/rails_app/db/schema.rb - test/rails_app/lib/shared_admin.rb - test/rails_app/lib/shared_user.rb - test/rails_app/lib/shared_user_without_email.rb - test/rails_app/lib/shared_user_without_omniauth.rb - test/rails_app/public/404.html - test/rails_app/public/422.html - test/rails_app/public/500.html - test/rails_app/public/favicon.ico - test/rails_test.rb - test/routes_test.rb - test/support/action_controller/record_identifier.rb - test/support/assertions.rb - test/support/helpers.rb - test/support/integration.rb - test/support/locale/en.yml - test/support/mongoid.yml - test/support/webrat/integrations/rails.rb - test/test_helper.rb - test/test_helpers_test.rb - test/test_models.rb homepage: https://github.com/plataformatec/devise licenses: - MIT metadata: {} post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.9.3 required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 2.5.1 signing_key: specification_version: 4 summary: Flexible authentication solution for Rails with Warden test_files: - test/controllers/custom_registrations_controller_test.rb - test/controllers/custom_strategy_test.rb - test/controllers/helper_methods_test.rb - test/controllers/helpers_test.rb - test/controllers/inherited_controller_i18n_messages_test.rb - test/controllers/internal_helpers_test.rb - test/controllers/load_hooks_controller_test.rb - test/controllers/passwords_controller_test.rb - test/controllers/sessions_controller_test.rb - test/controllers/url_helpers_test.rb - test/delegator_test.rb - test/devise_test.rb - test/failure_app_test.rb - test/generators/active_record_generator_test.rb - test/generators/controllers_generator_test.rb - test/generators/devise_generator_test.rb - test/generators/install_generator_test.rb - test/generators/mongoid_generator_test.rb - test/generators/views_generator_test.rb - test/helpers/devise_helper_test.rb - test/integration/authenticatable_test.rb - test/integration/confirmable_test.rb - test/integration/database_authenticatable_test.rb - test/integration/http_authenticatable_test.rb - test/integration/lockable_test.rb - test/integration/omniauthable_test.rb - test/integration/recoverable_test.rb - test/integration/registerable_test.rb - test/integration/rememberable_test.rb - test/integration/timeoutable_test.rb - test/integration/trackable_test.rb - test/mailers/confirmation_instructions_test.rb - test/mailers/reset_password_instructions_test.rb - test/mailers/unlock_instructions_test.rb - test/mapping_test.rb - test/models/authenticatable_test.rb - test/models/confirmable_test.rb - test/models/database_authenticatable_test.rb - test/models/lockable_test.rb - test/models/omniauthable_test.rb - test/models/recoverable_test.rb - test/models/registerable_test.rb - test/models/rememberable_test.rb - test/models/serializable_test.rb - test/models/timeoutable_test.rb - test/models/trackable_test.rb - test/models/validatable_test.rb - test/models_test.rb - test/omniauth/config_test.rb - test/omniauth/url_helpers_test.rb - test/orm/active_record.rb - test/orm/mongoid.rb - test/parameter_sanitizer_test.rb - test/rails_app/Rakefile - test/rails_app/app/active_record/admin.rb - test/rails_app/app/active_record/shim.rb - test/rails_app/app/active_record/user.rb - test/rails_app/app/active_record/user_on_engine.rb - test/rails_app/app/active_record/user_on_main_app.rb - test/rails_app/app/active_record/user_without_email.rb - test/rails_app/app/controllers/admins/sessions_controller.rb - test/rails_app/app/controllers/admins_controller.rb - test/rails_app/app/controllers/application_controller.rb - test/rails_app/app/controllers/application_with_fake_engine.rb - test/rails_app/app/controllers/custom/registrations_controller.rb - test/rails_app/app/controllers/home_controller.rb - test/rails_app/app/controllers/publisher/registrations_controller.rb - test/rails_app/app/controllers/publisher/sessions_controller.rb - test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb - test/rails_app/app/controllers/users_controller.rb - test/rails_app/app/helpers/application_helper.rb - test/rails_app/app/mailers/users/from_proc_mailer.rb - test/rails_app/app/mailers/users/mailer.rb - test/rails_app/app/mailers/users/reply_to_mailer.rb - test/rails_app/app/mongoid/admin.rb - test/rails_app/app/mongoid/shim.rb - test/rails_app/app/mongoid/user.rb - test/rails_app/app/mongoid/user_on_engine.rb - test/rails_app/app/mongoid/user_on_main_app.rb - test/rails_app/app/mongoid/user_without_email.rb - test/rails_app/app/views/admins/index.html.erb - test/rails_app/app/views/admins/sessions/new.html.erb - test/rails_app/app/views/home/admin_dashboard.html.erb - test/rails_app/app/views/home/index.html.erb - test/rails_app/app/views/home/join.html.erb - test/rails_app/app/views/home/private.html.erb - test/rails_app/app/views/home/user_dashboard.html.erb - test/rails_app/app/views/layouts/application.html.erb - test/rails_app/app/views/users/edit_form.html.erb - test/rails_app/app/views/users/index.html.erb - test/rails_app/app/views/users/mailer/confirmation_instructions.erb - test/rails_app/app/views/users/sessions/new.html.erb - test/rails_app/bin/bundle - test/rails_app/bin/rails - test/rails_app/bin/rake - test/rails_app/config.ru - test/rails_app/config/application.rb - test/rails_app/config/boot.rb - test/rails_app/config/database.yml - test/rails_app/config/environment.rb - test/rails_app/config/environments/development.rb - test/rails_app/config/environments/production.rb - test/rails_app/config/environments/test.rb - test/rails_app/config/initializers/backtrace_silencers.rb - test/rails_app/config/initializers/devise.rb - test/rails_app/config/initializers/inflections.rb - test/rails_app/config/initializers/secret_token.rb - test/rails_app/config/initializers/session_store.rb - test/rails_app/config/routes.rb - test/rails_app/db/migrate/20100401102949_create_tables.rb - test/rails_app/db/schema.rb - test/rails_app/lib/shared_admin.rb - test/rails_app/lib/shared_user.rb - test/rails_app/lib/shared_user_without_email.rb - test/rails_app/lib/shared_user_without_omniauth.rb - test/rails_app/public/404.html - test/rails_app/public/422.html - test/rails_app/public/500.html - test/rails_app/public/favicon.ico - test/rails_test.rb - test/routes_test.rb - test/support/action_controller/record_identifier.rb - test/support/assertions.rb - test/support/helpers.rb - test/support/integration.rb - test/support/locale/en.yml - test/support/mongoid.yml - test/support/webrat/integrations/rails.rb - test/test_helper.rb - test/test_helpers_test.rb - test/test_models.rb devise-3.5.6/test/0000755000004100000410000000000012663066463014027 5ustar www-datawww-datadevise-3.5.6/test/devise_test.rb0000644000004100000410000000650112663066463016674 0ustar www-datawww-datarequire 'test_helper' module Devise def self.yield_and_restore @@warden_configured = nil c, b = @@warden_config, @@warden_config_blocks yield ensure @@warden_config, @@warden_config_blocks = c, b end end class DeviseTest < ActiveSupport::TestCase test 'bcrypt on the class' do password = "super secret" klass = Struct.new(:pepper, :stretches).new("blahblah", 2) hash = Devise::Encryptor.digest(klass, password) assert_equal ::BCrypt::Password.create(hash), hash klass = Struct.new(:pepper, :stretches).new("bla", 2) hash = Devise::Encryptor.digest(klass, password) assert_not_equal ::BCrypt::Password.new(hash), hash end test 'model options can be configured through Devise' do swap Devise, allow_unconfirmed_access_for: 113, pepper: "foo" do assert_equal 113, Devise.allow_unconfirmed_access_for assert_equal "foo", Devise.pepper end end test 'setup block yields self' do Devise.setup do |config| assert_equal Devise, config end end test 'stores warden configuration' do assert_kind_of Devise::Delegator, Devise.warden_config.failure_app assert_equal :user, Devise.warden_config.default_scope end test 'warden manager user configuration through a block' do Devise.yield_and_restore do executed = false Devise.warden do |config| executed = true assert_kind_of Warden::Config, config end Devise.configure_warden! assert executed end end test 'warden manager user configuration through multiple blocks' do Devise.yield_and_restore do executed = 0 3.times do Devise.warden { |config| executed += 1 } end Devise.configure_warden! assert_equal 3, executed end end test 'add new module using the helper method' do assert_nothing_raised(Exception) { Devise.add_module(:coconut) } assert_equal 1, Devise::ALL.select { |v| v == :coconut }.size assert_not Devise::STRATEGIES.include?(:coconut) assert_not defined?(Devise::Models::Coconut) Devise::ALL.delete(:coconut) assert_nothing_raised(Exception) { Devise.add_module(:banana, strategy: :fruits) } assert_equal :fruits, Devise::STRATEGIES[:banana] Devise::ALL.delete(:banana) Devise::STRATEGIES.delete(:banana) assert_nothing_raised(Exception) { Devise.add_module(:kivi, controller: :fruits) } assert_equal :fruits, Devise::CONTROLLERS[:kivi] Devise::ALL.delete(:kivi) Devise::CONTROLLERS.delete(:kivi) end test 'should complain when comparing empty or different sized passes' do [nil, ""].each do |empty| assert_not Devise.secure_compare(empty, "something") assert_not Devise.secure_compare("something", empty) assert_not Devise.secure_compare(empty, empty) end assert_not Devise.secure_compare("size_1", "size_four") end test 'Devise.email_regexp should match valid email addresses' do valid_emails = ["test@example.com", "jo@jo.co", "f4$_m@you.com", "testing.example@example.com.ua"] non_valid_emails = ["rex", "test@go,com", "test user@example.com", "test_user@example server.com", "test_user@example.com."] valid_emails.each do |email| assert_match Devise.email_regexp, email end non_valid_emails.each do |email| assert_no_match Devise.email_regexp, email end end end devise-3.5.6/test/failure_app_test.rb0000644000004100000410000002731412663066463017711 0ustar www-datawww-datarequire 'test_helper' require 'ostruct' class FailureTest < ActiveSupport::TestCase class RootFailureApp < Devise::FailureApp def fake_app Object.new end end class FailureWithSubdomain < RootFailureApp routes = ActionDispatch::Routing::RouteSet.new routes.draw do scope subdomain: 'sub' do root to: 'foo#bar' end end include routes.url_helpers end class FailureWithI18nOptions < Devise::FailureApp def i18n_options(options) options.merge(name: 'Steve') end end class FakeEngineApp < Devise::FailureApp class FakeEngine def new_user_on_engine_session_url _ '/user_on_engines/sign_in' end end def main_app raise 'main_app router called instead of fake_engine' end def fake_engine @fake_engine ||= FakeEngine.new end end def self.context(name, &block) instance_eval(&block) end def call_failure(env_params={}) env = { 'REQUEST_URI' => 'http://test.host/', 'HTTP_HOST' => 'test.host', 'REQUEST_METHOD' => 'GET', 'warden.options' => { scope: :user }, 'rack.session' => {}, 'action_dispatch.request.formats' => Array(env_params.delete('formats') || Mime::HTML), 'rack.input' => "", 'warden' => OpenStruct.new(message: nil) }.merge!(env_params) @response = (env.delete(:app) || Devise::FailureApp).call(env).to_a @request = ActionDispatch::Request.new(env) end context 'When redirecting' do test 'returns to the default redirect location' do call_failure assert_equal 302, @response.first assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] assert_equal 'http://test.host/users/sign_in', @response.second['Location'] end test 'returns to the default redirect location considering subdomain' do call_failure('warden.options' => { scope: :subdomain_user }) assert_equal 302, @response.first assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] assert_equal 'http://sub.test.host/subdomain_users/sign_in', @response.second['Location'] end test 'returns to the default redirect location for wildcard requests' do call_failure 'action_dispatch.request.formats' => nil, 'HTTP_ACCEPT' => '*/*' assert_equal 302, @response.first assert_equal 'http://test.host/users/sign_in', @response.second['Location'] end test 'returns to the root path if no session path is available' do swap Devise, router_name: :fake_app do call_failure app: RootFailureApp assert_equal 302, @response.first assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] assert_equal 'http://test.host/', @response.second['Location'] end end test 'returns to the root path considering subdomain if no session path is available' do swap Devise, router_name: :fake_app do call_failure app: FailureWithSubdomain assert_equal 302, @response.first assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] assert_equal 'http://sub.test.host/', @response.second['Location'] end end test 'returns to the default redirect location considering the router for supplied scope' do call_failure app: FakeEngineApp, 'warden.options' => { scope: :user_on_engine } assert_equal 302, @response.first assert_equal 'You need to sign in or sign up before continuing.', @request.flash[:alert] assert_equal 'http://test.host/user_on_engines/sign_in', @response.second['Location'] end if Rails.application.config.respond_to?(:relative_url_root) test 'returns to the default redirect location considering the relative url root' do swap Rails.application.config, relative_url_root: "/sample" do call_failure assert_equal 302, @response.first assert_equal 'http://test.host/sample/users/sign_in', @response.second['Location'] end end test 'returns to the default redirect location considering the relative url root and subdomain' do swap Rails.application.config, relative_url_root: "/sample" do call_failure('warden.options' => { scope: :subdomain_user }) assert_equal 302, @response.first assert_equal 'http://sub.test.host/sample/subdomain_users/sign_in', @response.second['Location'] end end end test 'uses the proxy failure message as symbol' do call_failure('warden' => OpenStruct.new(message: :invalid)) assert_equal 'Invalid email or password.', @request.flash[:alert] assert_equal 'http://test.host/users/sign_in', @response.second["Location"] end test 'supports authentication_keys as a Hash for the flash message' do swap Devise, authentication_keys: { email: true, login: true } do call_failure('warden' => OpenStruct.new(message: :invalid)) assert_equal 'Invalid email, login or password.', @request.flash[:alert] end end test 'uses custom i18n options' do call_failure('warden' => OpenStruct.new(message: :does_not_exist), app: FailureWithI18nOptions) assert_equal 'User Steve does not exist', @request.flash[:alert] end test 'uses the proxy failure message as string' do call_failure('warden' => OpenStruct.new(message: 'Hello world')) assert_equal 'Hello world', @request.flash[:alert] assert_equal 'http://test.host/users/sign_in', @response.second["Location"] end test 'set content type to default text/html' do call_failure assert_equal 'text/html; charset=utf-8', @response.second['Content-Type'] end test 'setup a default message' do call_failure assert_match(/You are being/, @response.last.body) assert_match(/redirected/, @response.last.body) assert_match(/users\/sign_in/, @response.last.body) end test 'works for any navigational format' do swap Devise, navigational_formats: [:xml] do call_failure('formats' => Mime::XML) assert_equal 302, @response.first end end test 'redirects the correct format if it is a non-html format request' do swap Devise, navigational_formats: [:js] do call_failure('formats' => Mime::JS) assert_equal 'http://test.host/users/sign_in.js', @response.second["Location"] end end end context 'For HTTP request' do test 'return 401 status' do call_failure('formats' => Mime::XML) assert_equal 401, @response.first end test 'return appropriate body for xml' do call_failure('formats' => Mime::XML) result = %(\n\n You need to sign in or sign up before continuing.\n\n) assert_equal result, @response.last.body end test 'return appropriate body for json' do call_failure('formats' => Mime::JSON) result = %({"error":"You need to sign in or sign up before continuing."}) assert_equal result, @response.last.body end test 'return 401 status for unknown formats' do call_failure 'formats' => [] assert_equal 401, @response.first end test 'return WWW-authenticate headers if model allows' do call_failure('formats' => Mime::XML) assert_equal 'Basic realm="Application"', @response.second["WWW-Authenticate"] end test 'does not return WWW-authenticate headers if model does not allow' do swap Devise, http_authenticatable: false do call_failure('formats' => Mime::XML) assert_nil @response.second["WWW-Authenticate"] end end test 'works for any non navigational format' do swap Devise, navigational_formats: [] do call_failure('formats' => Mime::HTML) assert_equal 401, @response.first end end test 'uses the failure message as response body' do call_failure('formats' => Mime::XML, 'warden' => OpenStruct.new(message: :invalid)) assert_match 'Invalid email or password.', @response.third.body end context 'on ajax call' do context 'when http_authenticatable_on_xhr is false' do test 'dont return 401 with navigational formats' do swap Devise, http_authenticatable_on_xhr: false do call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_equal 302, @response.first assert_equal 'http://test.host/users/sign_in', @response.second["Location"] end end test 'dont return 401 with non navigational formats' do swap Devise, http_authenticatable_on_xhr: false do call_failure('formats' => Mime::JSON, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_equal 302, @response.first assert_equal 'http://test.host/users/sign_in.json', @response.second["Location"] end end end context 'when http_authenticatable_on_xhr is true' do test 'return 401' do swap Devise, http_authenticatable_on_xhr: true do call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_equal 401, @response.first end end test 'skip WWW-Authenticate header' do swap Devise, http_authenticatable_on_xhr: true do call_failure('formats' => Mime::HTML, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest') assert_nil @response.second['WWW-Authenticate'] end end end end end context 'With recall' do test 'calls the original controller if invalid email or password' do env = { "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in" }, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) assert @response.third.body.include?('

Log in

') assert @response.third.body.include?('Invalid email or password.') end test 'calls the original controller if not confirmed email' do env = { "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :unconfirmed }, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) assert @response.third.body.include?('

Log in

') assert @response.third.body.include?('You have to confirm your email address before continuing.') end test 'calls the original controller if inactive account' do env = { "warden.options" => { recall: "devise/sessions#new", attempted_path: "/users/sign_in", message: :inactive }, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) assert @response.third.body.include?('

Log in

') assert @response.third.body.include?('Your account is not activated yet.') end if Rails.application.config.respond_to?(:relative_url_root) test 'calls the original controller with the proper environment considering the relative url root' do swap Rails.application.config, relative_url_root: "/sample" do env = { "warden.options" => { recall: "devise/sessions#new", attempted_path: "/sample/users/sign_in"}, "devise.mapping" => Devise.mappings[:user], "warden" => stub_everything } call_failure(env) assert @response.third.body.include?('

Log in

') assert @response.third.body.include?('Invalid email or password.') assert_equal @request.env["SCRIPT_NAME"], '/sample' assert_equal @request.env["PATH_INFO"], '/users/sign_in' end end end end end devise-3.5.6/test/omniauth/0000755000004100000410000000000012663066463015653 5ustar www-datawww-datadevise-3.5.6/test/omniauth/url_helpers_test.rb0000644000004100000410000000356012663066463021567 0ustar www-datawww-datarequire 'test_helper' class OmniAuthRoutesTest < ActionController::TestCase ExpectedUrlGeneratiorError = Devise.rails4? ? ActionController::UrlGenerationError : ActionController::RoutingError tests ApplicationController def assert_path(action, provider, with_param=true) # Resource param assert_equal @controller.send(action, :user, provider), @controller.send("user_#{action}", provider) # With an object assert_equal @controller.send(action, User.new, provider), @controller.send("user_#{action}", provider) if with_param # Default url params assert_equal @controller.send(action, :user, provider, param: 123), @controller.send("user_#{action}", provider, param: 123) end end test 'should alias omniauth_callback to mapped user auth_callback' do assert_path :omniauth_callback_path, :facebook end test 'should alias omniauth_authorize to mapped user auth_authorize' do assert_path :omniauth_authorize_path, :facebook, false end test 'should generate authorization path' do assert_match "/users/auth/facebook", @controller.omniauth_authorize_path(:user, :facebook) assert_raise ExpectedUrlGeneratiorError do @controller.omniauth_authorize_path(:user, :github) end end test 'should generate authorization path for named open_id omniauth' do assert_match "/users/auth/google", @controller.omniauth_authorize_path(:user, :google) end test 'should generate authorization path with params' do assert_match "/users/auth/openid?openid_url=http%3A%2F%2Fyahoo.com", @controller.omniauth_authorize_path(:user, :openid, openid_url: "http://yahoo.com") end test 'should not add a "?" if no param was sent' do assert_equal "/users/auth/openid", @controller.omniauth_authorize_path(:user, :openid) end end devise-3.5.6/test/omniauth/config_test.rb0000644000004100000410000000361512663066463020511 0ustar www-datawww-datarequire 'test_helper' class OmniAuthConfigTest < ActiveSupport::TestCase class MyStrategy include OmniAuth::Strategy end test 'strategy_name returns provider if no options given' do config = Devise::OmniAuth::Config.new :facebook, [{}] assert_equal :facebook, config.strategy_name end test 'strategy_name returns provider if no name option are given' do config = Devise::OmniAuth::Config.new :facebook, [{ other: :option }] assert_equal :facebook, config.strategy_name end test 'returns name option when have a name' do config = Devise::OmniAuth::Config.new :facebook, [{ name: :github }] assert_equal :github, config.strategy_name end test "finds contrib strategies" do config = Devise::OmniAuth::Config.new :facebook, [{}] assert_equal OmniAuth::Strategies::Facebook, config.strategy_class end test "finds the strategy in OmniAuth's list by name" do NamedTestStrategy = Class.new NamedTestStrategy.send :include, OmniAuth::Strategy NamedTestStrategy.option :name, :the_one config = Devise::OmniAuth::Config.new :the_one, [{}] assert_equal NamedTestStrategy, config.strategy_class end test "finds the strategy in OmniAuth's list by class name" do UnNamedTestStrategy = Class.new UnNamedTestStrategy.send :include, OmniAuth::Strategy config = Devise::OmniAuth::Config.new :un_named_test_strategy, [{}] assert_equal UnNamedTestStrategy, config.strategy_class end test 'raises an error if strategy cannot be found' do config = Devise::OmniAuth::Config.new :my_other_strategy, [{}] assert_raise Devise::OmniAuth::StrategyNotFound do config.strategy_class end end test 'allows the user to define a custom require path' do config = Devise::OmniAuth::Config.new :my_strategy, [{strategy_class: MyStrategy}] config_class = config.strategy_class assert_equal MyStrategy, config_class end end devise-3.5.6/test/models_test.rb0000644000004100000410000001121312663066463016674 0ustar www-datawww-datarequire 'test_helper' require 'test_models' class ActiveRecordTest < ActiveSupport::TestCase def include_module?(klass, mod) klass.devise_modules.include?(mod) && klass.included_modules.include?(Devise::Models::const_get(mod.to_s.classify)) end def assert_include_modules(klass, *modules) modules.each do |mod| assert include_module?(klass, mod) end (Devise::ALL - modules).each do |mod| assert_not include_module?(klass, mod) end end test 'can cherry pick modules' do assert_include_modules Admin, :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable end test 'validations options are not applied too late' do validators = WithValidation.validators_on :password length = validators.find { |v| v.kind == :length } assert_equal 2, length.options[:minimum] assert_equal 6, length.options[:maximum] end test 'validations are applied just once' do validators = Several.validators_on :password assert_equal 1, validators.select{ |v| v.kind == :length }.length end test 'chosen modules are inheritable' do assert_include_modules Inheritable, :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable end test 'order of module inclusion' do correct_module_order = [:database_authenticatable, :recoverable, :registerable, :confirmable, :lockable, :timeoutable] incorrect_module_order = [:database_authenticatable, :timeoutable, :registerable, :recoverable, :lockable, :confirmable] assert_include_modules Admin, *incorrect_module_order # get module constants from symbol list module_constants = correct_module_order.collect { |mod| Devise::Models::const_get(mod.to_s.classify) } # confirm that they adhere to the order in ALL # get included modules, filter out the noise, and reverse the order assert_equal module_constants, (Admin.included_modules & module_constants).reverse end test 'raise error on invalid module' do assert_raise NameError do # Mix valid an invalid modules. Configurable.class_eval { devise :database_authenticatable, :doesnotexit } end end test 'set a default value for stretches' do assert_equal 15, Configurable.stretches end test 'set a default value for pepper' do assert_equal 'abcdef', Configurable.pepper end test 'set a default value for allow_unconfirmed_access_for' do assert_equal 5.days, Configurable.allow_unconfirmed_access_for end test 'set a default value for remember_for' do assert_equal 7.days, Configurable.remember_for end test 'set a default value for timeout_in' do assert_equal 15.minutes, Configurable.timeout_in end test 'set a default value for unlock_in' do assert_equal 10.days, Configurable.unlock_in end test 'set null fields on migrations' do # Ignore email sending since no email exists. klass = Class.new(Admin) do def send_devise_notification(*); end end klass.create! end end module StubModelFilters def stub_filter(name) define_singleton_method(name) { |*| nil } end end class CheckFieldsTest < ActiveSupport::TestCase test 'checks if the class respond_to the required fields' do Player = Class.new do extend Devise::Models extend StubModelFilters stub_filter :before_validation stub_filter :after_update devise :database_authenticatable attr_accessor :encrypted_password, :email end assert_nothing_raised Devise::Models::MissingAttribute do Devise::Models.check_fields!(Player) end end test 'raises Devise::Models::MissingAtrribute and shows the missing attribute if the class doesn\'t respond_to one of the attributes' do Clown = Class.new do extend Devise::Models extend StubModelFilters stub_filter :before_validation stub_filter :after_update devise :database_authenticatable attr_accessor :encrypted_password end assert_raise_with_message Devise::Models::MissingAttribute, "The following attribute(s) is (are) missing on your model: email" do Devise::Models.check_fields!(Clown) end end test 'raises Devise::Models::MissingAtrribute with all the missing attributes if there is more than one' do Magician = Class.new do extend Devise::Models extend StubModelFilters stub_filter :before_validation stub_filter :after_update devise :database_authenticatable end assert_raise_with_message Devise::Models::MissingAttribute, "The following attribute(s) is (are) missing on your model: encrypted_password, email" do Devise::Models.check_fields!(Magician) end end end devise-3.5.6/test/test_helpers_test.rb0000644000004100000410000001042712663066463020120 0ustar www-datawww-datarequire 'test_helper' class TestHelpersTest < ActionController::TestCase tests UsersController include Devise::TestHelpers test "redirects if attempting to access a page unauthenticated" do get :index assert_redirected_to new_user_session_path assert_equal "You need to sign in or sign up before continuing.", flash[:alert] end test "redirects if attempting to access a page with an unconfirmed account" do swap Devise, allow_unconfirmed_access_for: 0.days do user = create_user assert !user.active_for_authentication? sign_in user get :index assert_redirected_to new_user_session_path end end test "returns nil if accessing current_user with an unconfirmed account" do swap Devise, allow_unconfirmed_access_for: 0.days do user = create_user assert !user.active_for_authentication? sign_in user get :accept, id: user assert_nil assigns(:current_user) end end test "does not redirect with valid user" do user = create_user user.confirm sign_in user get :index assert_response :success end test "does not redirect with valid user after failed first attempt" do get :index assert_response :redirect user = create_user user.confirm sign_in user get :index assert_response :success end test "redirects if valid user signed out" do user = create_user user.confirm sign_in user get :index sign_out user get :index assert_redirected_to new_user_session_path end test "respects custom failure app" do custom_failure_app = Class.new(Devise::FailureApp) do def redirect self.status = 306 end end swap Devise.warden_config, failure_app: custom_failure_app do get :index assert_response 306 end end test "passes given headers from the failure app to the response" do custom_failure_app = Class.new(Devise::FailureApp) do def respond self.status = 401 self.response.headers["CUSTOMHEADER"] = 1 end end swap Devise.warden_config, failure_app: custom_failure_app do sign_in create_user get :index assert_equal 1, @response.headers["CUSTOMHEADER"] end end test "returns the body of a failure app" do get :index assert_equal response.body, "You are being redirected." end test "defined Warden after_authentication callback should not be called when sign_in is called" do begin Warden::Manager.after_authentication do |user, auth, opts| flunk "callback was called while it should not" end user = create_user user.confirm sign_in user ensure Warden::Manager._after_set_user.pop end end test "defined Warden before_logout callback should not be called when sign_out is called" do begin Warden::Manager.before_logout do |user, auth, opts| flunk "callback was called while it should not" end user = create_user user.confirm sign_in user sign_out user ensure Warden::Manager._before_logout.pop end end test "before_failure call should work" do begin executed = false Warden::Manager.before_failure do |env,opts| executed = true end user = create_user sign_in user get :index assert executed ensure Warden::Manager._before_failure.pop end end test "allows to sign in with different users" do first_user = create_user first_user.confirm sign_in first_user get :index assert_match /User ##{first_user.id}/, @response.body sign_out first_user second_user = create_user second_user.confirm sign_in second_user get :index assert_match /User ##{second_user.id}/, @response.body end test "creates a new warden proxy if the request object has changed" do old_warden_proxy = warden @request = ActionController::TestRequest.new new_warden_proxy = warden assert_not_equal old_warden_proxy, new_warden_proxy end test "doesn't create a new warden proxy if the request object hasn't changed" do old_warden_proxy = warden new_warden_proxy = warden assert_equal old_warden_proxy, new_warden_proxy end end devise-3.5.6/test/controllers/0000755000004100000410000000000012663066463016375 5ustar www-datawww-datadevise-3.5.6/test/controllers/url_helpers_test.rb0000644000004100000410000000450012663066463022304 0ustar www-datawww-datarequire 'test_helper' class RoutesTest < ActionController::TestCase tests ApplicationController def assert_path_and_url(name, prepend_path=nil) @request.path = '/users/session' prepend_path = "#{prepend_path}_" if prepend_path # Resource param assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user), send(:"#{prepend_path}user_#{name}_path") assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user), send(:"#{prepend_path}user_#{name}_url") # With string assert_equal @controller.send(:"#{prepend_path}#{name}_path", "user"), send(:"#{prepend_path}user_#{name}_path") assert_equal @controller.send(:"#{prepend_path}#{name}_url", "user"), send(:"#{prepend_path}user_#{name}_url") # Default url params assert_equal @controller.send(:"#{prepend_path}#{name}_path", :user, param: 123), send(:"#{prepend_path}user_#{name}_path", param: 123) assert_equal @controller.send(:"#{prepend_path}#{name}_url", :user, param: 123), send(:"#{prepend_path}user_#{name}_url", param: 123) @request.path = nil # With an object assert_equal @controller.send(:"#{prepend_path}#{name}_path", User.new), send(:"#{prepend_path}user_#{name}_path") assert_equal @controller.send(:"#{prepend_path}#{name}_url", User.new), send(:"#{prepend_path}user_#{name}_url") end test 'should alias session to mapped user session' do assert_path_and_url :session assert_path_and_url :session, :new assert_path_and_url :session, :destroy end test 'should alias password to mapped user password' do assert_path_and_url :password assert_path_and_url :password, :new assert_path_and_url :password, :edit end test 'should alias confirmation to mapped user confirmation' do assert_path_and_url :confirmation assert_path_and_url :confirmation, :new end test 'should alias unlock to mapped user unlock' do assert_path_and_url :unlock assert_path_and_url :unlock, :new end test 'should alias registration to mapped user registration' do assert_path_and_url :registration assert_path_and_url :registration, :new assert_path_and_url :registration, :edit assert_path_and_url :registration, :cancel end end devise-3.5.6/test/controllers/custom_registrations_controller_test.rb0000644000004100000410000000262012663066463026513 0ustar www-datawww-datarequire 'test_helper' class CustomRegistrationsControllerTest < ActionController::TestCase tests Custom::RegistrationsController include Devise::TestHelpers setup do request.env["devise.mapping"] = Devise.mappings[:user] @password = 'password' @user = create_user(password: @password, password_confirmation: @password).tap(&:confirm) end test "yield resource to block on create success" do post :create, { user: { email: "user@example.org", password: "password", password_confirmation: "password" } } assert @controller.create_block_called?, "create failed to yield resource to provided block" end test "yield resource to block on create failure" do post :create, { user: { } } assert @controller.create_block_called?, "create failed to yield resource to provided block" end test "yield resource to block on update success" do sign_in @user put :update, { user: { current_password: @password } } assert @controller.update_block_called?, "update failed to yield resource to provided block" end test "yield resource to block on update failure" do sign_in @user put :update, { user: { } } assert @controller.update_block_called?, "update failed to yield resource to provided block" end test "yield resource to block on new" do get :new assert @controller.new_block_called?, "new failed to yield resource to provided block" end end devise-3.5.6/test/controllers/load_hooks_controller_test.rb0000644000004100000410000000077012663066463024352 0ustar www-datawww-datarequire 'test_helper' class LoadHooksControllerTest < ActionController::TestCase setup do ActiveSupport.on_load(:devise_controller) do define_method :defined_by_load_hook do puts 'I am defined dynamically by activesupport load hook' end end end teardown do DeviseController.class_eval { undef :defined_by_load_hook } end test 'load hook called when controller is loaded' do assert DeviseController.instance_methods.include? :defined_by_load_hook end enddevise-3.5.6/test/controllers/passwords_controller_test.rb0000644000004100000410000000173312663066463024255 0ustar www-datawww-datarequire 'test_helper' class PasswordsControllerTest < ActionController::TestCase tests Devise::PasswordsController include Devise::TestHelpers setup do request.env["devise.mapping"] = Devise.mappings[:user] @user = create_user.tap(&:confirm) @raw = @user.send_reset_password_instructions end def put_update_with_params put :update, "user" => { "reset_password_token" => @raw, "password" => "1234567", "password_confirmation" => "1234567" } end test 'redirect to after_sign_in_path_for if after_resetting_password_path_for is not overridden' do put_update_with_params assert_redirected_to "http://test.host/" end test 'redirect accordingly if after_resetting_password_path_for is overridden' do custom_path = "http://custom.path/" Devise::PasswordsController.any_instance.stubs(:after_resetting_password_path_for).with(@user).returns(custom_path) put_update_with_params assert_redirected_to custom_path end end devise-3.5.6/test/controllers/custom_strategy_test.rb0000644000004100000410000000351012663066463023214 0ustar www-datawww-datarequire 'test_helper' require 'ostruct' require 'warden/strategies/base' require 'devise/test_helpers' class CustomStrategyController < ActionController::Base def new warden.authenticate!(:custom_strategy) end end # These tests are to prove that a warden strategy can successfully # return a custom response, including a specific status code and # custom http response headers. This does work in production, # however, at the time of writing this, the Devise test helpers do # not recognise the custom response and proceed to calling the # Failure App. This makes it impossible to write tests for a # strategy that return a custom response with Devise. class CustomStrategy < Warden::Strategies::Base def authenticate! custom_headers = { "X-FOO" => "BAR" } response = Rack::Response.new("BAD REQUEST", 400, custom_headers) custom! response.finish end end class CustomStrategyTest < ActionController::TestCase tests CustomStrategyController include Devise::TestHelpers setup do Warden::Strategies.add(:custom_strategy, CustomStrategy) end teardown do Warden::Strategies._strategies.delete(:custom_strategy) end test "custom strategy can return its own status code" do ret = get :new # check the returned rack array assert ret.is_a?(Array) assert_equal 400, ret.first # check the saved response as well. This is purely so that the response is available to the testing framework # for verification. In production, the above array would be delivered directly to Rack. assert_response 400 end test "custom strategy can return custom headers" do ret = get :new # check the returned rack array assert ret.is_a?(Array) assert_equal ret.third['X-FOO'], 'BAR' # check the saved response headers as well. assert_equal response.headers['X-FOO'], 'BAR' end end devise-3.5.6/test/controllers/helper_methods_test.rb0000644000004100000410000000103212663066463022757 0ustar www-datawww-datarequire 'test_helper' class ApiController < ActionController::Metal include Devise::Controllers::Helpers end class HelperMethodsTest < ActionController::TestCase tests ApiController test 'includes Devise::Controllers::Helpers' do assert_includes @controller.class.ancestors, Devise::Controllers::Helpers end test 'does not respond_to helper_method' do refute_respond_to @controller.class, :helper_method end test 'defines methods like current_user' do assert_respond_to @controller, :current_user end end devise-3.5.6/test/controllers/helpers_test.rb0000644000004100000410000003006412663066463021426 0ustar www-datawww-datarequire 'test_helper' require 'ostruct' class ControllerAuthenticatableTest < ActionController::TestCase tests ApplicationController def setup @mock_warden = OpenStruct.new @controller.request.env['warden'] = @mock_warden end test 'provide access to warden instance' do assert_equal @mock_warden, @controller.warden end test 'proxy signed_in?(scope) to authenticate?' do @mock_warden.expects(:authenticate?).with(scope: :my_scope) @controller.signed_in?(:my_scope) end test 'proxy signed_in?(nil) to authenticate?' do Devise.mappings.keys.each do |scope| # :user, :admin, :manager @mock_warden.expects(:authenticate?).with(scope: scope) end @controller.signed_in? end test 'proxy [group]_signed_in? to authenticate? with each scope' do [:user, :admin].each do |scope| @mock_warden.expects(:authenticate?).with(scope: scope).returns(false) end @controller.commenter_signed_in? end test 'proxy current_user to authenticate with user scope' do @mock_warden.expects(:authenticate).with(scope: :user) @controller.current_user end test 'proxy current_admin to authenticate with admin scope' do @mock_warden.expects(:authenticate).with(scope: :admin) @controller.current_admin end test 'proxy current_[group] to authenticate with each scope' do [:user, :admin].each do |scope| @mock_warden.expects(:authenticate).with(scope: scope).returns(nil) end @controller.current_commenter end test 'proxy current_[plural_group] to authenticate with each scope' do [:user, :admin].each do |scope| @mock_warden.expects(:authenticate).with(scope: scope) end @controller.current_commenters end test 'proxy current_publisher_account to authenticate with namespaced publisher account scope' do @mock_warden.expects(:authenticate).with(scope: :publisher_account) @controller.current_publisher_account end test 'proxy authenticate_user! to authenticate with user scope' do @mock_warden.expects(:authenticate!).with(scope: :user) @controller.authenticate_user! end test 'proxy authenticate_user! options to authenticate with user scope' do @mock_warden.expects(:authenticate!).with(scope: :user, recall: "foo") @controller.authenticate_user!(recall: "foo") end test 'proxy authenticate_admin! to authenticate with admin scope' do @mock_warden.expects(:authenticate!).with(scope: :admin) @controller.authenticate_admin! end test 'proxy authenticate_[group]! to authenticate!? with each scope' do [:user, :admin].each do |scope| @mock_warden.expects(:authenticate!).with(scope: scope) @mock_warden.expects(:authenticate?).with(scope: scope).returns(false) end @controller.authenticate_commenter! end test 'proxy authenticate_publisher_account! to authenticate with namespaced publisher account scope' do @mock_warden.expects(:authenticate!).with(scope: :publisher_account) @controller.authenticate_publisher_account! end test 'proxy user_signed_in? to authenticate with user scope' do @mock_warden.expects(:authenticate).with(scope: :user).returns("user") assert @controller.user_signed_in? end test 'proxy admin_signed_in? to authenticatewith admin scope' do @mock_warden.expects(:authenticate).with(scope: :admin) assert_not @controller.admin_signed_in? end test 'proxy publisher_account_signed_in? to authenticate with namespaced publisher account scope' do @mock_warden.expects(:authenticate).with(scope: :publisher_account) @controller.publisher_account_signed_in? end test 'proxy user_session to session scope in warden' do @mock_warden.expects(:authenticate).with(scope: :user).returns(true) @mock_warden.expects(:session).with(:user).returns({}) @controller.user_session end test 'proxy admin_session to session scope in warden' do @mock_warden.expects(:authenticate).with(scope: :admin).returns(true) @mock_warden.expects(:session).with(:admin).returns({}) @controller.admin_session end test 'proxy publisher_account_session from namespaced scope to session scope in warden' do @mock_warden.expects(:authenticate).with(scope: :publisher_account).returns(true) @mock_warden.expects(:session).with(:publisher_account).returns({}) @controller.publisher_account_session end test 'sign in proxy to set_user on warden' do user = User.new @mock_warden.expects(:user).returns(nil) @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) @controller.sign_in(:user, user) end test 'sign in accepts a resource as argument' do user = User.new @mock_warden.expects(:user).returns(nil) @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) @controller.sign_in(user) end test 'does not sign in again if the user is already in' do user = User.new @mock_warden.expects(:user).returns(user) @mock_warden.expects(:set_user).never assert @controller.sign_in(user) end test 'sign in again when the user is already in only if force is given' do user = User.new @mock_warden.expects(:user).returns(user) @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) @controller.sign_in(user, force: true) end test 'sign in accepts bypass as option' do user = User.new @mock_warden.expects(:session_serializer).returns(serializer = mock()) serializer.expects(:store).with(user, :user) @controller.sign_in(user, bypass: true) end test 'sign out clears up any signed in user from all scopes' do user = User.new @mock_warden.expects(:user).times(Devise.mappings.size) @mock_warden.expects(:logout).with().returns(true) @controller.instance_variable_set(:@current_user, user) @controller.instance_variable_set(:@current_admin, user) @controller.sign_out assert_equal nil, @controller.instance_variable_get(:@current_user) assert_equal nil, @controller.instance_variable_get(:@current_admin) end test 'sign out logs out and clears up any signed in user by scope' do user = User.new @mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(user) @mock_warden.expects(:logout).with(:user).returns(true) @mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true) @controller.instance_variable_set(:@current_user, user) @controller.sign_out(:user) assert_equal nil, @controller.instance_variable_get(:@current_user) end test 'sign out accepts a resource as argument' do @mock_warden.expects(:user).with(scope: :user, run_callbacks: false).returns(true) @mock_warden.expects(:logout).with(:user).returns(true) @mock_warden.expects(:clear_strategies_cache!).with(scope: :user).returns(true) @controller.sign_out(User.new) end test 'sign out without args proxy to sign out all scopes' do @mock_warden.expects(:user).times(Devise.mappings.size) @mock_warden.expects(:logout).with().returns(true) @mock_warden.expects(:clear_strategies_cache!).with().returns(true) @controller.sign_out end test 'sign out everybody proxy to logout on warden' do @mock_warden.expects(:user).times(Devise.mappings.size) @mock_warden.expects(:logout).with().returns(true) @controller.sign_out_all_scopes end test 'stored location for returns the location for a given scope' do assert_nil @controller.stored_location_for(:user) @controller.session[:"user_return_to"] = "/foo.bar" assert_equal "/foo.bar", @controller.stored_location_for(:user) end test 'stored location for accepts a resource as argument' do assert_nil @controller.stored_location_for(:user) @controller.session[:"user_return_to"] = "/foo.bar" assert_equal "/foo.bar", @controller.stored_location_for(User.new) end test 'stored location cleans information after reading' do @controller.session[:"user_return_to"] = "/foo.bar" assert_equal "/foo.bar", @controller.stored_location_for(:user) assert_nil @controller.session[:"user_return_to"] end test 'store location for stores a location to redirect back to' do assert_nil @controller.stored_location_for(:user) @controller.store_location_for(:user, "/foo.bar") assert_equal "/foo.bar", @controller.stored_location_for(:user) end test 'store bad location for stores a location to redirect back to' do assert_nil @controller.stored_location_for(:user) @controller.store_location_for(:user, "/foo.bar\">Carry") assert_nil @controller.stored_location_for(:user) end test 'store location for accepts a resource as argument' do @controller.store_location_for(User.new, "/foo.bar") assert_equal "/foo.bar", @controller.stored_location_for(User.new) end test 'store location for stores paths' do @controller.store_location_for(:user, "//host/foo.bar") assert_equal "/foo.bar", @controller.stored_location_for(:user) @controller.store_location_for(:user, "///foo.bar") assert_equal "/foo.bar", @controller.stored_location_for(:user) end test 'store location for stores query string' do @controller.store_location_for(:user, "/foo?bar=baz") assert_equal "/foo?bar=baz", @controller.stored_location_for(:user) end test 'store location for stores fragments' do @controller.store_location_for(:user, "/foo#bar") assert_equal "/foo#bar", @controller.stored_location_for(:user) end test 'after sign in path defaults to root path if none by was specified for the given scope' do assert_equal root_path, @controller.after_sign_in_path_for(:user) end test 'after sign in path defaults to the scoped root path' do assert_equal admin_root_path, @controller.after_sign_in_path_for(:admin) end test 'after sign out path defaults to the root path' do assert_equal root_path, @controller.after_sign_out_path_for(:admin) assert_equal root_path, @controller.after_sign_out_path_for(:user) end test 'sign in and redirect uses the stored location' do user = User.new @controller.session[:user_return_to] = "/foo.bar" @mock_warden.expects(:user).with(:user).returns(nil) @mock_warden.expects(:set_user).with(user, scope: :user).returns(true) @controller.expects(:redirect_to).with("/foo.bar") @controller.sign_in_and_redirect(user) end test 'sign in and redirect uses the configured after sign in path' do admin = Admin.new @mock_warden.expects(:user).with(:admin).returns(nil) @mock_warden.expects(:set_user).with(admin, scope: :admin).returns(true) @controller.expects(:redirect_to).with(admin_root_path) @controller.sign_in_and_redirect(admin) end test 'sign in and redirect does not sign in again if user is already signed' do admin = Admin.new @mock_warden.expects(:user).with(:admin).returns(admin) @mock_warden.expects(:set_user).never @controller.expects(:redirect_to).with(admin_root_path) @controller.sign_in_and_redirect(admin) end test 'sign out and redirect uses the configured after sign out path when signing out only the current scope' do swap Devise, sign_out_all_scopes: false do @mock_warden.expects(:user).with(scope: :admin, run_callbacks: false).returns(true) @mock_warden.expects(:logout).with(:admin).returns(true) @mock_warden.expects(:clear_strategies_cache!).with(scope: :admin).returns(true) @controller.expects(:redirect_to).with(admin_root_path) @controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end" @controller.sign_out_and_redirect(:admin) end end test 'sign out and redirect uses the configured after sign out path when signing out all scopes' do swap Devise, sign_out_all_scopes: true do @mock_warden.expects(:user).times(Devise.mappings.size) @mock_warden.expects(:logout).with().returns(true) @mock_warden.expects(:clear_strategies_cache!).with().returns(true) @controller.expects(:redirect_to).with(admin_root_path) @controller.instance_eval "def after_sign_out_path_for(resource); admin_root_path; end" @controller.sign_out_and_redirect(:admin) end end test 'is not a devise controller' do assert_not @controller.devise_controller? end end devise-3.5.6/test/controllers/internal_helpers_test.rb0000644000004100000410000001123612663066463023322 0ustar www-datawww-datarequire 'test_helper' class MyController < DeviseController end class HelpersTest < ActionController::TestCase tests MyController def setup @mock_warden = OpenStruct.new @controller.request.env['warden'] = @mock_warden @controller.request.env['devise.mapping'] = Devise.mappings[:user] end test 'get resource name from env' do assert_equal :user, @controller.send(:resource_name) end test 'get resource class from env' do assert_equal User, @controller.send(:resource_class) end test 'get resource instance variable from env' do @controller.instance_variable_set(:@user, user = User.new) assert_equal user, @controller.send(:resource) end test 'set resource instance variable from env' do user = @controller.send(:resource_class).new @controller.send(:resource=, user) assert_equal user, @controller.send(:resource) assert_equal user, @controller.instance_variable_get(:@user) end test 'get resource params from request params using resource name as key' do user_params = {'email' => 'shirley@templar.com'} params = if Devise.rails4? # Stub controller name so strong parameters can filter properly. # DeviseController does not allow any parameters by default. @controller.stubs(:controller_name).returns(:sessions_controller) ActionController::Parameters.new({'user' => user_params}) else HashWithIndifferentAccess.new({'user' => user_params}) end @controller.stubs(:params).returns(params) assert_equal user_params, @controller.send(:resource_params) end test 'resources methods are not controller actions' do assert @controller.class.action_methods.delete_if { |m| m.include? 'commenter' }.empty? end test 'require no authentication tests current mapping' do @mock_warden.expects(:authenticate?).with(:rememberable, scope: :user).returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication end test 'require no authentication only checks if already authenticated if no inputs strategies are available' do Devise.mappings[:user].expects(:no_input_strategies).returns([]) @mock_warden.expects(:authenticate?).never @mock_warden.expects(:authenticated?).with(:user).once.returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication end test 'require no authentication sets a flash message' do @mock_warden.expects(:authenticate?).with(:rememberable, scope: :user).returns(true) @mock_warden.expects(:user).with(:user).returns(User.new) @controller.expects(:redirect_to).with(root_path) @controller.send :require_no_authentication assert flash[:alert] == I18n.t("devise.failure.already_authenticated") end test 'signed in resource returns signed in resource for current scope' do @mock_warden.expects(:authenticate).with(scope: :user).returns(User.new) assert_kind_of User, @controller.send(:signed_in_resource) end test 'is a devise controller' do assert @controller.devise_controller? end test 'does not issue blank flash messages' do I18n.stubs(:t).returns(' ') @controller.send :set_flash_message, :notice, :send_instructions assert flash[:notice].nil? end test 'issues non-blank flash messages normally' do I18n.stubs(:t).returns('non-blank') @controller.send :set_flash_message, :notice, :send_instructions assert_equal 'non-blank', flash[:notice] end test 'issues non-blank flash.now messages normally' do I18n.stubs(:t).returns('non-blank') @controller.send :set_flash_message, :notice, :send_instructions, { now: true } assert_equal 'non-blank', flash.now[:notice] end test 'uses custom i18n options' do @controller.stubs(:devise_i18n_options).returns(default: "devise custom options") @controller.send :set_flash_message, :notice, :invalid_i18n_messagesend_instructions assert_equal 'devise custom options', flash[:notice] end test 'allows custom i18n options to override resource_name' do I18n.expects(:t).with("custom_resource_name.confirmed", anything) @controller.stubs(:devise_i18n_options).returns(resource_name: "custom_resource_name") @controller.send :set_flash_message, :notice, :confirmed end test 'navigational_formats not returning a wild card' do MyController.send(:public, :navigational_formats) swap Devise, navigational_formats: ['*/*', :html] do assert_not @controller.navigational_formats.include?("*/*") end MyController.send(:protected, :navigational_formats) end end devise-3.5.6/test/controllers/sessions_controller_test.rb0000644000004100000410000000641612663066463024101 0ustar www-datawww-datarequire 'test_helper' class SessionsControllerTest < ActionController::TestCase tests Devise::SessionsController include Devise::TestHelpers test "#create doesn't raise unpermitted params when sign in fails" do begin subscriber = ActiveSupport::Notifications.subscribe /unpermitted_parameters/ do |name, start, finish, id, payload| flunk "Unpermitted params: #{payload}" end request.env["devise.mapping"] = Devise.mappings[:user] request.session["user_return_to"] = 'foo.bar' create_user post :create, user: { email: "wrong@email.com", password: "wrongpassword" } assert_equal 200, @response.status ensure ActiveSupport::Notifications.unsubscribe(subscriber) end end test "#create works even with scoped views" do swap Devise, scoped_views: true do request.env["devise.mapping"] = Devise.mappings[:user] post :create assert_equal 200, @response.status assert_template "users/sessions/new" end end test "#create delete the url stored in the session if the requested format is navigational" do request.env["devise.mapping"] = Devise.mappings[:user] request.session["user_return_to"] = 'foo.bar' user = create_user user.confirm post :create, user: { email: user.email, password: user.password } assert_nil request.session["user_return_to"] end test "#create doesn't delete the url stored in the session if the requested format is not navigational" do request.env["devise.mapping"] = Devise.mappings[:user] request.session["user_return_to"] = 'foo.bar' user = create_user user.confirm post :create, format: 'json', user: { email: user.email, password: user.password } assert_equal 'foo.bar', request.session["user_return_to"] end test "#create doesn't raise exception after Warden authentication fails when TestHelpers included" do request.env["devise.mapping"] = Devise.mappings[:user] post :create, user: { email: "nosuchuser@example.com", password: "wevdude" } assert_equal 200, @response.status assert_template "devise/sessions/new" end test "#destroy doesn't set the flash if the requested format is not navigational" do request.env["devise.mapping"] = Devise.mappings[:user] user = create_user user.confirm post :create, format: 'json', user: { email: user.email, password: user.password } delete :destroy, format: 'json' assert flash[:notice].blank?, "flash[:notice] should be blank, not #{flash[:notice].inspect}" assert_equal 204, @response.status end if defined?(ActiveRecord) && ActiveRecord::Base.respond_to?(:mass_assignment_sanitizer) test "#new doesn't raise mass-assignment exception even if sign-in key is attr_protected" do request.env["devise.mapping"] = Devise.mappings[:user] ActiveRecord::Base.mass_assignment_sanitizer = :strict User.class_eval { attr_protected :email } begin assert_nothing_raised ActiveModel::MassAssignmentSecurity::Error do get :new, user: { email: "allez viens!" } end ensure ActiveRecord::Base.mass_assignment_sanitizer = :logger User.class_eval { attr_accessible :email } end end end end devise-3.5.6/test/controllers/inherited_controller_i18n_messages_test.rb0000644000004100000410000000240712663066463026730 0ustar www-datawww-datarequire 'test_helper' class SessionsInheritedController < Devise::SessionsController def test_i18n_scope set_flash_message(:notice, :signed_in) end end class AnotherInheritedController < SessionsInheritedController protected def translation_scope 'another' end end class InheritedControllerTest < ActionController::TestCase tests SessionsInheritedController def setup @mock_warden = OpenStruct.new @controller.request.env['warden'] = @mock_warden @controller.request.env['devise.mapping'] = Devise.mappings[:user] end test 'I18n scope is inherited from Devise::Sessions' do I18n.expects(:t).with do |message, options| message == 'user.signed_in' && options[:scope] == 'devise.sessions' end @controller.test_i18n_scope end end class AnotherInheritedControllerTest < ActionController::TestCase tests AnotherInheritedController def setup @mock_warden = OpenStruct.new @controller.request.env['warden'] = @mock_warden @controller.request.env['devise.mapping'] = Devise.mappings[:user] end test 'I18n scope is overridden' do I18n.expects(:t).with do |message, options| message == 'user.signed_in' && options[:scope] == 'another' end @controller.test_i18n_scope end end devise-3.5.6/test/mailers/0000755000004100000410000000000012663066463015463 5ustar www-datawww-datadevise-3.5.6/test/mailers/reset_password_instructions_test.rb0000644000004100000410000000522112663066463024737 0ustar www-datawww-datarequire 'test_helper' class ResetPasswordInstructionsTest < ActionMailer::TestCase def setup setup_mailer Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'test@example.com' end def teardown Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' end def user @user ||= begin user = create_user user.send_reset_password_instructions user end end def mail @mail ||= begin user ActionMailer::Base.deliveries.last end end test 'email sent after reseting the user password' do assert_not_nil mail end test 'content type should be set to html' do assert mail.content_type.include?('text/html') end test 'send confirmation instructions to the user email' do assert_equal [user.email], mail.to end test 'setup sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'setup sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'setup sender from custom mailer defaults with proc' do Devise.mailer = 'Users::FromProcMailer' assert_equal ['custom@example.com'], mail.from end test 'custom mailer renders parent mailer template' do Devise.mailer = 'Users::Mailer' assert_present mail.body.encoded end test 'setup reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'setup subject from I18n' do store_translations :en, devise: { mailer: { reset_password_instructions: { subject: 'Reset instructions' } } } do assert_equal 'Reset instructions', mail.subject end end test 'subject namespaced by model' do store_translations :en, devise: { mailer: { reset_password_instructions: { user_subject: 'User Reset Instructions' } } } do assert_equal 'User Reset Instructions', mail.subject end end test 'body should have user info' do assert_match user.email, mail.body.encoded end test 'body should have link to confirm the account' do host, port = ActionMailer::Base.default_url_options.values_at :host, :port if mail.body.encoded =~ %r{} assert_equal Devise.token_generator.digest(user.class, :reset_password_token, $1), user.reset_password_token else flunk "expected reset password url regex to match" end end test 'mailer sender accepts a proc' do swap Devise, mailer_sender: proc { "another@example.com" } do assert_equal ['another@example.com'], mail.from end end end devise-3.5.6/test/mailers/unlock_instructions_test.rb0000644000004100000410000000461212663066463023171 0ustar www-datawww-datarequire 'test_helper' class UnlockInstructionsTest < ActionMailer::TestCase def setup setup_mailer Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'test@example.com' end def teardown Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' end def user @user ||= begin user = create_user user.lock_access! user end end def mail @mail ||= begin user ActionMailer::Base.deliveries.last end end test 'email sent after locking the user' do assert_not_nil mail end test 'content type should be set to html' do assert mail.content_type.include?('text/html') end test 'send unlock instructions to the user email' do assert_equal [user.email], mail.to end test 'setup sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'setup sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'setup sender from custom mailer defaults with proc' do Devise.mailer = 'Users::FromProcMailer' assert_equal ['custom@example.com'], mail.from end test 'custom mailer renders parent mailer template' do Devise.mailer = 'Users::Mailer' assert_present mail.body.encoded end test 'setup reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'setup subject from I18n' do store_translations :en, devise: { mailer: { unlock_instructions: { subject: 'Yo unlock instructions' } } } do assert_equal 'Yo unlock instructions', mail.subject end end test 'subject namespaced by model' do store_translations :en, devise: { mailer: { unlock_instructions: { user_subject: 'User Unlock Instructions' } } } do assert_equal 'User Unlock Instructions', mail.subject end end test 'body should have user info' do assert_match user.email, mail.body.encoded end test 'body should have link to unlock the account' do host, port = ActionMailer::Base.default_url_options.values_at :host, :port if mail.body.encoded =~ %r{} assert_equal Devise.token_generator.digest(user.class, :unlock_token, $1), user.unlock_token else flunk "expected unlock url regex to match" end end end devise-3.5.6/test/mailers/confirmation_instructions_test.rb0000644000004100000410000000621012663066463024362 0ustar www-datawww-datarequire 'test_helper' class ConfirmationInstructionsTest < ActionMailer::TestCase def setup setup_mailer Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'test@example.com' end def teardown Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' end def user @user ||= create_user end def mail @mail ||= begin user ActionMailer::Base.deliveries.first end end test 'email sent after creating the user' do assert_not_nil mail end test 'content type should be set to html' do assert mail.content_type.include?('text/html') end test 'send confirmation instructions to the user email' do mail assert_equal [user.email], mail.to end test 'setup sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'setup sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'setup sender from custom mailer defaults with proc' do Devise.mailer = 'Users::FromProcMailer' assert_equal ['custom@example.com'], mail.from end test 'custom mailer renders parent mailer template' do Devise.mailer = 'Users::Mailer' assert_present mail.body.encoded end test 'setup reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'setup reply to as different if set in defaults' do Devise.mailer = 'Users::ReplyToMailer' assert_equal ['custom@example.com'], mail.from assert_equal ['custom_reply_to@example.com'], mail.reply_to end test 'setup subject from I18n' do store_translations :en, devise: { mailer: { confirmation_instructions: { subject: 'Account Confirmation' } } } do assert_equal 'Account Confirmation', mail.subject end end test 'subject namespaced by model' do store_translations :en, devise: { mailer: { confirmation_instructions: { user_subject: 'User Account Confirmation' } } } do assert_equal 'User Account Confirmation', mail.subject end end test 'body should have user info' do assert_match user.email, mail.body.encoded end test 'body should have link to confirm the account' do host, port = ActionMailer::Base.default_url_options.values_at :host, :port if mail.body.encoded =~ %r{} assert_equal $1, user.confirmation_token else flunk "expected confirmation url regex to match" end end test 'renders a scoped if scoped_views is set to true' do swap Devise, scoped_views: true do assert_equal user.email, mail.body.decoded end end test 'renders a scoped if scoped_views is set in the mailer class' do begin Devise::Mailer.scoped_views = true assert_equal user.email, mail.body.decoded ensure Devise::Mailer.send :remove_instance_variable, :@scoped_views end end test 'mailer sender accepts a proc' do swap Devise, mailer_sender: proc { "another@example.com" } do assert_equal ['another@example.com'], mail.from end end end devise-3.5.6/test/parameter_sanitizer_test.rb0000644000004100000410000000620712663066463021470 0ustar www-datawww-datarequire 'test_helper' require 'devise/parameter_sanitizer' class BaseSanitizerTest < ActiveSupport::TestCase def sanitizer(params) Devise::BaseSanitizer.new(User, :user, params) end test 'returns chosen params' do sanitizer = sanitizer(user: { "email" => "jose" }) assert_equal({ "email" => "jose" }, sanitizer.sanitize(:sign_in)) end end if defined?(ActionController::StrongParameters) require 'active_model/forbidden_attributes_protection' class ParameterSanitizerTest < ActiveSupport::TestCase def sanitizer(params) params = ActionController::Parameters.new(params) Devise::ParameterSanitizer.new(User, :user, params) end test 'filters some parameters on sign in by default' do sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid", "remember_me" => "1" }) assert_equal({ "email" => "jose", "password" => "invalid", "remember_me" => "1" }, sanitizer.sanitize(:sign_in)) end test 'handles auth keys as a hash' do swap Devise, authentication_keys: {email: true} do sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" }) assert_equal({ "email" => "jose", "password" => "invalid" }, sanitizer.sanitize(:sign_in)) end end test 'filters some parameters on sign up by default' do sanitizer = sanitizer(user: { "email" => "jose", "role" => "invalid" }) assert_equal({ "email" => "jose" }, sanitizer.sanitize(:sign_up)) end test 'filters some parameters on account update by default' do sanitizer = sanitizer(user: { "email" => "jose", "role" => "invalid" }) assert_equal({ "email" => "jose" }, sanitizer.sanitize(:account_update)) end test 'allows custom hooks' do sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" }) sanitizer.for(:sign_in) { |user| user.permit(:email, :password) } assert_equal({ "email" => "jose", "password" => "invalid" }, sanitizer.sanitize(:sign_in)) end test 'adding multiple permitted parameters' do sanitizer = sanitizer(user: { "email" => "jose", "username" => "jose1", "role" => "valid" }) sanitizer.for(:sign_in).concat([:username, :role]) assert_equal({ "email" => "jose", "username" => "jose1", "role" => "valid" }, sanitizer.sanitize(:sign_in)) end test 'removing multiple default parameters' do sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid", "remember_me" => "1" }) sanitizer.for(:sign_in).delete(:email) sanitizer.for(:sign_in).delete(:password) assert_equal({ "remember_me" => "1" }, sanitizer.sanitize(:sign_in)) end test 'raises on unknown hooks' do sanitizer = sanitizer(user: { "email" => "jose", "password" => "invalid" }) assert_raise NotImplementedError do sanitizer.sanitize(:unknown) end end test 'passes parameters to filter as arguments to sanitizer' do params = {user: stub} sanitizer = Devise::ParameterSanitizer.new(User, :user, params) params[:user].expects(:permit).with(kind_of(Symbol), kind_of(Symbol), kind_of(Symbol)) sanitizer.sanitize(:sign_in) end end end devise-3.5.6/test/orm/0000755000004100000410000000000012663066463014624 5ustar www-datawww-datadevise-3.5.6/test/orm/active_record.rb0000644000004100000410000000052412663066463017763 0ustar www-datawww-dataActiveRecord::Migration.verbose = false ActiveRecord::Base.logger = Logger.new(nil) ActiveRecord::Base.include_root_in_json = true ActiveRecord::Migrator.migrate(File.expand_path("../../rails_app/db/migrate/", __FILE__)) class ActiveSupport::TestCase self.use_transactional_fixtures = true self.use_instantiated_fixtures = false end devise-3.5.6/test/orm/mongoid.rb0000644000004100000410000000035412663066463016607 0ustar www-datawww-datarequire 'mongoid/version' Mongoid.configure do |config| config.load!('test/support/mongoid.yml') config.use_utc = true config.include_root_in_json = true end class ActiveSupport::TestCase setup do Mongoid.purge! end end devise-3.5.6/test/test_helper.rb0000644000004100000410000000173312663066463016676 0ustar www-datawww-dataENV["RAILS_ENV"] = "test" DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym $:.unshift File.dirname(__FILE__) puts "\n==> Devise.orm = #{DEVISE_ORM.inspect}" require "rails_app/config/environment" require "rails/test_help" require "orm/#{DEVISE_ORM}" I18n.load_path << File.expand_path("../support/locale/en.yml", __FILE__) require 'mocha/setup' require 'webrat' Webrat.configure do |config| config.mode = :rails config.open_error_files = false end if ActiveSupport.respond_to?(:test_order) ActiveSupport.test_order = :random end OmniAuth.config.logger = Logger.new('/dev/null') # Add support to load paths so we can overwrite broken webrat setup $:.unshift File.expand_path('../support', __FILE__) Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } # For generators require "rails/generators/test_case" require "generators/devise/install_generator" require "generators/devise/views_generator" require "generators/devise/controllers_generator" devise-3.5.6/test/rails_app/0000755000004100000410000000000012663066463016001 5ustar www-datawww-datadevise-3.5.6/test/rails_app/Rakefile0000644000004100000410000000037112663066463017447 0ustar www-datawww-data# 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 devise-3.5.6/test/rails_app/bin/0000755000004100000410000000000012663066463016551 5ustar www-datawww-datadevise-3.5.6/test/rails_app/bin/rake0000755000004100000410000000013212663066463017415 0ustar www-datawww-data#!/usr/bin/env ruby require_relative '../config/boot' require 'rake' Rake.application.run devise-3.5.6/test/rails_app/bin/rails0000755000004100000410000000022212663066463017605 0ustar www-datawww-data#!/usr/bin/env ruby APP_PATH = File.expand_path('../../config/application', __FILE__) require_relative '../config/boot' require 'rails/commands' devise-3.5.6/test/rails_app/bin/bundle0000755000004100000410000000020112663066463017741 0ustar www-datawww-data#!/usr/bin/env ruby ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) load Gem.bin_path('bundler', 'bundle') devise-3.5.6/test/rails_app/db/0000755000004100000410000000000012663066463016366 5ustar www-datawww-datadevise-3.5.6/test/rails_app/db/schema.rb0000644000004100000410000000410712663066463020155 0ustar www-datawww-data# 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: 20100401102949) do create_table "admins", force: true do |t| t.string "email" t.string "encrypted_password" t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.string "unconfirmed_email" t.datetime "locked_at" t.boolean "active", default: false t.datetime "created_at" t.datetime "updated_at" end create_table "users", force: true do |t| t.string "username" t.string "facebook_token" t.string "email", default: "", null: false t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0 t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.string "confirmation_token" t.datetime "confirmed_at" t.datetime "confirmation_sent_at" t.integer "failed_attempts", default: 0 t.string "unlock_token" t.datetime "locked_at" t.datetime "created_at" t.datetime "updated_at" end end devise-3.5.6/test/rails_app/db/migrate/0000755000004100000410000000000012663066463020016 5ustar www-datawww-datadevise-3.5.6/test/rails_app/db/migrate/20100401102949_create_tables.rb0000644000004100000410000000354312663066463024605 0ustar www-datawww-dataclass CreateTables < ActiveRecord::Migration def self.up create_table :users do |t| t.string :username t.string :facebook_token ## Database authenticatable t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Trackable t.integer :sign_in_count, default: 0 t.datetime :current_sign_in_at t.datetime :last_sign_in_at t.string :current_sign_in_ip t.string :last_sign_in_ip ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at # t.string :unconfirmed_email # Only if using reconfirmable ## Lockable t.integer :failed_attempts, default: 0 # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at t.timestamps null: false end create_table :admins do |t| ## Database authenticatable t.string :email, null: true t.string :encrypted_password, null: true ## Recoverable t.string :reset_password_token t.datetime :reset_password_sent_at ## Rememberable t.datetime :remember_created_at ## Confirmable t.string :confirmation_token t.datetime :confirmed_at t.datetime :confirmation_sent_at t.string :unconfirmed_email # Only if using reconfirmable ## Lockable t.datetime :locked_at ## Attribute for testing route blocks t.boolean :active, default: false t.timestamps null: false end end def self.down drop_table :users drop_table :admins end end devise-3.5.6/test/rails_app/public/0000755000004100000410000000000012663066463017257 5ustar www-datawww-datadevise-3.5.6/test/rails_app/public/422.html0000644000004100000410000000130712663066463020455 0ustar www-datawww-data 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.

devise-3.5.6/test/rails_app/public/favicon.ico0000644000004100000410000000000012663066463021366 0ustar www-datawww-datadevise-3.5.6/test/rails_app/public/404.html0000644000004100000410000000133012663066463020451 0ustar www-datawww-data 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.

devise-3.5.6/test/rails_app/public/500.html0000644000004100000410000000133012663066463020446 0ustar www-datawww-data We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

We've been notified about this issue and we'll take a look at it shortly.

devise-3.5.6/test/rails_app/lib/0000755000004100000410000000000012663066463016547 5ustar www-datawww-datadevise-3.5.6/test/rails_app/lib/shared_admin.rb0000644000004100000410000000103512663066463021511 0ustar www-datawww-datamodule SharedAdmin extend ActiveSupport::Concern included do devise :database_authenticatable, :registerable, :timeoutable, :recoverable, :lockable, :confirmable, unlock_strategy: :time, lock_strategy: :none, allow_unconfirmed_access_for: 2.weeks, reconfirmable: true validates_length_of :reset_password_token, minimum: 3, allow_blank: true validates_uniqueness_of :email, allow_blank: true, if: :email_changed? end def raw_confirmation_token @raw_confirmation_token end end devise-3.5.6/test/rails_app/lib/shared_user_without_email.rb0000644000004100000410000000170612663066463024336 0ustar www-datawww-datamodule SharedUserWithoutEmail extend ActiveSupport::Concern included do # NOTE: This is missing :validatable and :confirmable, as they both require # an email field at the moment. It is also missing :omniauthable because that # adds unnecessary complexity to the setup devise :database_authenticatable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :trackable end # This test stub is a bit rubbish because it's tied very closely to the # implementation where we care about this one case. However, completely # removing the email field breaks "recoverable" tests completely, so we are # just taking the approach here that "email" is something that is a not an # ActiveRecord field. def email_changed? raise NoMethodError end def respond_to?(method_name, include_all=false) return false if method_name.to_sym == :email_changed? super(method_name, include_all) end end devise-3.5.6/test/rails_app/lib/shared_user.rb0000644000004100000410000000130712663066463021401 0ustar www-datawww-datamodule SharedUser extend ActiveSupport::Concern included do devise :database_authenticatable, :confirmable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :trackable, :validatable, :omniauthable, password_length: 7..72 attr_accessor :other_key # They need to be included after Devise is called. extend ExtendMethods end def raw_confirmation_token @raw_confirmation_token end module ExtendMethods def new_with_session(params, session) super.tap do |user| if data = session["devise.facebook_data"] user.email = data["email"] user.confirmed_at = Time.now end end end end end devise-3.5.6/test/rails_app/lib/shared_user_without_omniauth.rb0000644000004100000410000000047012663066463025070 0ustar www-datawww-datamodule SharedUserWithoutOmniauth extend ActiveSupport::Concern included do devise :database_authenticatable, :confirmable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :trackable, :validatable end def raw_confirmation_token @raw_confirmation_token end end devise-3.5.6/test/rails_app/config/0000755000004100000410000000000012663066463017246 5ustar www-datawww-datadevise-3.5.6/test/rails_app/config/application.rb0000644000004100000410000000231312663066463022075 0ustar www-datawww-datarequire File.expand_path('../boot', __FILE__) require "action_controller/railtie" require "action_mailer/railtie" require "rails/test_unit/railtie" Bundler.require :default, DEVISE_ORM begin require "#{DEVISE_ORM}/railtie" rescue LoadError end require "devise" module RailsApp class Application < Rails::Application # Add additional load paths for your own custom dirs config.autoload_paths.reject!{ |p| p =~ /\/app\/(\w+)$/ && !%w(controllers helpers mailers views).include?($1) } config.autoload_paths += ["#{config.root}/app/#{DEVISE_ORM}"] # Configure generators values. Many other options are available, be sure to check the documentation. # config.generators do |g| # g.orm :active_record # g.template_engine :erb # g.test_framework :test_unit, fixture: true # end # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters << :password config.assets.enabled = false config.action_mailer.default_url_options = { host: "localhost", port: 3000 } # This was used to break devise in some situations config.to_prepare do Devise::SessionsController.layout "application" end end end devise-3.5.6/test/rails_app/config/initializers/0000755000004100000410000000000012663066463021754 5ustar www-datawww-datadevise-3.5.6/test/rails_app/config/initializers/secret_token.rb0000644000004100000410000000065412663066463024773 0ustar www-datawww-dataconfig = Rails.application.config if Devise.rails4? config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10' else config.secret_token = 'ea942c41850d502f2c8283e26bdc57829f471bb18224ddff0a192c4f32cdf6cb5aa0d82b3a7a7adbeb640c4b06f3aa1cd5f098162d8240f669b39d6b49680571' config.session_store :cookie_store, key: "_my_app" end devise-3.5.6/test/rails_app/config/initializers/session_store.rb0000644000004100000410000000012412663066463025175 0ustar www-datawww-dataRailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session' devise-3.5.6/test/rails_app/config/initializers/backtrace_silencers.rb0000644000004100000410000000062212663066463026267 0ustar www-datawww-data# 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! devise-3.5.6/test/rails_app/config/initializers/devise.rb0000644000004100000410000002040612663066463023562 0ustar www-datawww-datarequire "omniauth-facebook" require "omniauth-openid" # Use this hook to configure devise mailer, warden hooks and so forth. The first # four configuration values can also be set straight in your models. Devise.setup do |config| config.secret_key = "d9eb5171c59a4c817f68b0de27b8c1e340c2341b52cdbc60d3083d4e8958532" \ "18dcc5f589cafde048faec956b61f864b9b5513ff9ce29bf9e5d58b0f234f8e3b" # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class with default "from" parameter. config.mailer_sender = "please-change-me@config-initializers-devise.com" config.parent_controller = "ApplicationWithFakeEngine" # Configure the class responsible to send e-mails. # config.mailer = "Devise::Mailer" # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require "devise/orm/#{DEVISE_ORM}" # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. By default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply hash where the value is a boolean expliciting if authentication # should be aborted or not if the value is not present. By default is empty. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # config.params_authenticatable = true # Tell if authentication through HTTP Basic Auth is enabled. False by default. config.http_authenticatable = true # If http headers should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. "Application" by default. # config.http_authentication_realm = "Application" # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. config.stretches = Rails.env.test? ? 1 : 10 # ==> Configuration for :confirmable # The time you want to give your user to confirm their account. During this time # they will be able to access your application without confirming. Default is nil. # When allow_unconfirmed_access_for is zero, the user won't be able to sign in without confirming. # You can use this to let your user access some features of your application # without confirming the account, but blocking it after a certain period # (ie 2 days). # config.allow_unconfirmed_access_for = 2.days # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # ==> Configuration for :validatable # Range for password length. Default is 8..72. # config.password_length = 8..72 # Regex to use to validate the email address # config.email_regexp = /^([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})$/i # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 2.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # Setup a pepper to generate the encrypted password. config.pepper = "d142367154e5beacca404b1a6a4f8bc52c6fdcfa3ccc3cf8eb49f3458a688ee6ac3b9fae488432a3bfca863b8a90008368a9f3a3dfbe5a962e64b6ab8f3a3a1a" # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Configure sign_out behavior. # Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope). # The default is true, which means any logout action will sign out all active scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. Default is [:html] # config.navigational_formats = [:html, :iphone] # The default HTTP method used to sign out a resource. Default is :get. # config.sign_out_via = :get # ==> OmniAuth config.omniauth :facebook, 'APP_ID', 'APP_SECRET', scope: 'email,offline_access' config.omniauth :openid config.omniauth :openid, name: 'google', identifier: 'https://www.google.com/accounts/o8/id' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.failure_app = AnotherApp # manager.default_strategies(scope: :user).unshift :some_external_strategy # end end devise-3.5.6/test/rails_app/config/initializers/inflections.rb0000644000004100000410000000006612663066463024620 0ustar www-datawww-dataActiveSupport::Inflector.inflections do |inflect| end devise-3.5.6/test/rails_app/config/boot.rb0000644000004100000410000000064112663066463020537 0ustar www-datawww-dataunless defined?(DEVISE_ORM) DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym end module Devise # Detection for minor differences between Rails 3.2 and 4 in tests. def self.rails4? Rails.version.start_with? '4' end end # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) devise-3.5.6/test/rails_app/config/environments/0000755000004100000410000000000012663066463021775 5ustar www-datawww-datadevise-3.5.6/test/rails_app/config/environments/test.rb0000644000004100000410000000322112663066463023277 0ustar www-datawww-dataRailsApp::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 # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. if Rails.version >= "4.2.0" config.serve_static_files = true else config.serve_static_assets = true end 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 end devise-3.5.6/test/rails_app/config/environments/production.rb0000644000004100000410000000641212663066463024513 0ustar www-datawww-dataRailsApp::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 thread 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). if Rails.version >= "4.2.0" config.serve_static_files = false else config.serve_static_assets = false end # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Whether to fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # 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" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # 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 can not 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 end devise-3.5.6/test/rails_app/config/environments/development.rb0000644000004100000410000000214712663066463024650 0ustar www-datawww-dataRailsApp::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 # Only use best-standards-support built into browsers. config.action_dispatch.best_standards_support = :builtin # 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. config.assets.debug = true end devise-3.5.6/test/rails_app/config/database.yml0000644000004100000410000000072612663066463021542 0ustar www-datawww-data# SQLite version 3.x # gem install sqlite3-ruby (not necessary on OS X Leopard) development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 # 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: adapter: sqlite3 database: ":memory:" production: adapter: sqlite3 database: ":memory:" devise-3.5.6/test/rails_app/config/routes.rb0000644000004100000410000000750612663066463021124 0ustar www-datawww-dataRails.application.routes.draw do # Resources for testing resources :users, only: [:index] do member do get :expire get :accept get :edit_form put :update_form end authenticate do post :exhibit, on: :member end end resources :admins, only: [:index] # Users scope devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" } devise_for :user_on_main_apps, class_name: 'UserOnMainApp', router_name: :main_app, module: :devise devise_for :user_on_engines, class_name: 'UserOnEngine', router_name: :fake_engine, module: :devise devise_for :user_without_email, class_name: 'UserWithoutEmail', router_name: :main_app, module: :devise as :user do get "/as/sign_in", to: "devise/sessions#new" end get "/sign_in", to: "devise/sessions#new" # Routes for custom controller testing devise_for :user, only: [:registrations], controllers: { registrations: "custom/registrations" }, as: :custom, path: :custom # Admin scope devise_for :admin, path: "admin_area", controllers: { sessions: :"admins/sessions" }, skip: :passwords get "/admin_area/home", to: "admins#index", as: :admin_root get "/anywhere", to: "foo#bar", as: :new_admin_password authenticate(:admin) do get "/private", to: "home#private", as: :private end authenticate(:admin, lambda { |admin| admin.active? }) do get "/private/active", to: "home#private", as: :private_active end authenticated :admin do get "/dashboard", to: "home#admin_dashboard" end authenticated :admin, lambda { |admin| admin.active? } do get "/dashboard/active", to: "home#admin_dashboard" end authenticated do get "/dashboard", to: "home#user_dashboard" end unauthenticated do get "/join", to: "home#join" end # Routes for constraints testing devise_for :headquarters_admin, class_name: "Admin", path: "headquarters", constraints: {host: /192\.168\.1\.\d\d\d/} constraints(host: /192\.168\.1\.\d\d\d/) do devise_for :homebase_admin, class_name: "Admin", path: "homebase" end scope(subdomain: 'sub') do devise_for :subdomain_users, class_name: "User", only: [:sessions] end devise_for :skip_admin, class_name: "Admin", skip: :all # Routes for format=false testing devise_for :htmlonly_admin, class_name: "Admin", skip: [:confirmations, :unlocks], path: "htmlonly_admin", format: false, skip_helpers: [:confirmations, :unlocks] devise_for :htmlonly_users, class_name: "User", only: [:confirmations, :unlocks], path: "htmlonly_users", format: false, skip_helpers: true # Other routes for routing_test.rb devise_for :reader, class_name: "User", only: :passwords scope host: "sub.example.com" do devise_for :sub_admin, class_name: "Admin" end namespace :publisher, path_names: { sign_in: "i_dont_care", sign_out: "get_out" } do devise_for :accounts, class_name: "Admin", path_names: { sign_in: "get_in" } end scope ":locale", module: :invalid do devise_for :accounts, singular: "manager", class_name: "Admin", path_names: { sign_in: "login", sign_out: "logout", password: "secret", confirmation: "verification", unlock: "unblock", sign_up: "register", registration: "management", cancel: "giveup", edit: "edit/profile" }, failure_app: lambda { |env| [404, {"Content-Type" => "text/plain"}, ["Oops, not found"]] }, module: :devise end namespace :sign_out_via, module: "devise" do devise_for :deletes, sign_out_via: :delete, class_name: "Admin" devise_for :posts, sign_out_via: :post, class_name: "Admin" devise_for :delete_or_posts, sign_out_via: [:delete, :post], class_name: "Admin" end get "/set", to: "home#set" get "/unauthenticated", to: "home#unauthenticated" get "/custom_strategy/new" root to: "home#index", via: [:get, :post] end devise-3.5.6/test/rails_app/config/environment.rb0000644000004100000410000000023212663066463022134 0ustar www-datawww-data# Load the rails application. require File.expand_path('../application', __FILE__) # Initialize the rails application. RailsApp::Application.initialize! devise-3.5.6/test/rails_app/app/0000755000004100000410000000000012663066463016561 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/0000755000004100000410000000000012663066463017716 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/home/0000755000004100000410000000000012663066463020646 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/home/index.html.erb0000644000004100000410000000000612663066463023406 0ustar www-datawww-dataHome! devise-3.5.6/test/rails_app/app/views/home/user_dashboard.html.erb0000644000004100000410000000001712663066463025266 0ustar www-datawww-dataUser dashboard devise-3.5.6/test/rails_app/app/views/home/join.html.erb0000644000004100000410000000000512663066463023235 0ustar www-datawww-dataJoin devise-3.5.6/test/rails_app/app/views/home/admin_dashboard.html.erb0000644000004100000410000000002012663066463025372 0ustar www-datawww-dataAdmin dashboard devise-3.5.6/test/rails_app/app/views/home/private.html.erb0000644000004100000410000000001112663066463023745 0ustar www-datawww-dataPrivate! devise-3.5.6/test/rails_app/app/views/layouts/0000755000004100000410000000000012663066463021416 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/layouts/application.html.erb0000644000004100000410000000115312663066463025356 0ustar www-datawww-data Devise Test App
<%- flash.each do |name, msg| -%> <%= content_tag :div, msg, id: "flash_#{name}" %> <%- end -%> <% if user_signed_in? -%>

Hello User <%= current_user.email %>! You are signed in!

<% end -%> <% if admin_signed_in? -%>

Hello Admin <%= current_admin.email %>! You are signed in!

<% end -%> <%= yield %>
devise-3.5.6/test/rails_app/app/views/admins/0000755000004100000410000000000012663066463021171 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/admins/sessions/0000755000004100000410000000000012663066463023037 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/admins/sessions/new.html.erb0000644000004100000410000000011212663066463025257 0ustar www-datawww-dataWelcome to "sessions/new" view! <%= render file: "devise/sessions/new" %> devise-3.5.6/test/rails_app/app/views/admins/index.html.erb0000644000004100000410000000001712663066463023733 0ustar www-datawww-dataWelcome Admin! devise-3.5.6/test/rails_app/app/views/users/0000755000004100000410000000000012663066463021057 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/users/mailer/0000755000004100000410000000000012663066463022330 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/users/mailer/confirmation_instructions.erb0000644000004100000410000000002612663066463030334 0ustar www-datawww-data<%= @resource.email %>devise-3.5.6/test/rails_app/app/views/users/sessions/0000755000004100000410000000000012663066463022725 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/views/users/sessions/new.html.erb0000644000004100000410000000002212663066463025145 0ustar www-datawww-dataSpecial user view devise-3.5.6/test/rails_app/app/views/users/index.html.erb0000644000004100000410000000004612663066463023623 0ustar www-datawww-dataWelcome User #<%= current_user.id %>! devise-3.5.6/test/rails_app/app/views/users/edit_form.html.erb0000644000004100000410000000011612663066463024462 0ustar www-datawww-data<%= button_to 'Update', update_form_user_path(current_user), method: 'put' %> devise-3.5.6/test/rails_app/app/mongoid/0000755000004100000410000000000012663066463020215 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/mongoid/user_without_email.rb0000644000004100000410000000167012663066463024456 0ustar www-datawww-datarequire "shared_user_without_email" class UserWithoutEmail include Mongoid::Document include Shim include SharedUserWithoutEmail field :username, type: String field :facebook_token, type: String ## Database authenticatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Trackable field :sign_in_count, type: Integer, default: 0 field :current_sign_in_at, type: Time field :last_sign_in_at, type: Time field :current_sign_in_ip, type: String field :last_sign_in_ip, type: String ## Lockable field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts field :unlock_token, type: String # Only if unlock strategy is :email or :both field :locked_at, type: Time end devise-3.5.6/test/rails_app/app/mongoid/admin.rb0000644000004100000410000000127612663066463021640 0ustar www-datawww-datarequire 'shared_admin' class Admin include Mongoid::Document include Shim include SharedAdmin ## Database authenticatable field :email, type: String field :encrypted_password, type: String ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Confirmable field :confirmation_token, type: String field :confirmed_at, type: Time field :confirmation_sent_at, type: Time field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable field :locked_at, type: Time field :active, type: Boolean, default: false end devise-3.5.6/test/rails_app/app/mongoid/shim.rb0000644000004100000410000000070412663066463021503 0ustar www-datawww-datamodule Shim extend ::ActiveSupport::Concern included do include ::Mongoid::Timestamps field :created_at, type: DateTime end module ClassMethods def order(attribute) asc(attribute) end def find_by_email(email) find_by(email: email) end end # overwrite equality (because some devise tests use this for asserting model equality) def ==(other) other.is_a?(self.class) && _id == other._id end end devise-3.5.6/test/rails_app/app/mongoid/user.rb0000644000004100000410000000222312663066463021517 0ustar www-datawww-datarequire 'shared_user' class User include Mongoid::Document include Shim include SharedUser field :username, type: String field :facebook_token, type: String ## Database authenticatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Trackable field :sign_in_count, type: Integer, default: 0 field :current_sign_in_at, type: Time field :last_sign_in_at, type: Time field :current_sign_in_ip, type: String field :last_sign_in_ip, type: String ## Confirmable field :confirmation_token, type: String field :confirmed_at, type: Time field :confirmation_sent_at, type: Time # field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts field :unlock_token, type: String # Only if unlock strategy is :email or :both field :locked_at, type: Time end devise-3.5.6/test/rails_app/app/mongoid/user_on_main_app.rb0000644000004100000410000000221712663066463024062 0ustar www-datawww-datarequire 'shared_user_without_omniauth' class UserOnMainApp include Mongoid::Document include Shim include SharedUserWithoutOmniauth field :username, type: String field :facebook_token, type: String ## Database authenticatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Trackable field :sign_in_count, type: Integer, default: 0 field :current_sign_in_at, type: Time field :last_sign_in_at, type: Time field :current_sign_in_ip, type: String field :last_sign_in_ip, type: String ## Confirmable field :confirmation_token, type: String field :confirmed_at, type: Time field :confirmation_sent_at, type: Time # field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts field :unlock_token, type: String # Only if unlock strategy is :email or :both field :locked_at, type: Time end devise-3.5.6/test/rails_app/app/mongoid/user_on_engine.rb0000644000004100000410000000221612663066463023542 0ustar www-datawww-datarequire 'shared_user_without_omniauth' class UserOnEngine include Mongoid::Document include Shim include SharedUserWithoutOmniauth field :username, type: String field :facebook_token, type: String ## Database authenticatable field :email, type: String, default: "" field :encrypted_password, type: String, default: "" ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time ## Rememberable field :remember_created_at, type: Time ## Trackable field :sign_in_count, type: Integer, default: 0 field :current_sign_in_at, type: Time field :last_sign_in_at, type: Time field :current_sign_in_ip, type: String field :last_sign_in_ip, type: String ## Confirmable field :confirmation_token, type: String field :confirmed_at, type: Time field :confirmation_sent_at, type: Time # field :unconfirmed_email, type: String # Only if using reconfirmable ## Lockable field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts field :unlock_token, type: String # Only if unlock strategy is :email or :both field :locked_at, type: Time end devise-3.5.6/test/rails_app/app/controllers/0000755000004100000410000000000012663066463021127 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/controllers/application_with_fake_engine.rb0000644000004100000410000000112112663066463027320 0ustar www-datawww-dataclass ApplicationWithFakeEngine < ApplicationController private helper_method :fake_engine def fake_engine @fake_engine ||= FakeEngine.new end end class FakeEngine def user_on_engine_confirmation_path '/user_on_engine/confirmation' end def new_user_on_engine_session_path '/user_on_engine/confirmation/new' end def new_user_on_engine_registration_path '/user_on_engine/registration/new' end def new_user_on_engine_password_path '/user_on_engine/password/new' end def new_user_on_engine_unlock_path '/user_on_engine/unlock/new' end end devise-3.5.6/test/rails_app/app/controllers/custom/0000755000004100000410000000000012663066463022441 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/controllers/custom/registrations_controller.rb0000644000004100000410000000101212663066463030120 0ustar www-datawww-dataclass Custom::RegistrationsController < Devise::RegistrationsController def new super do |resource| @new_block_called = true end end def create super do |resource| @create_block_called = true end end def update super do |resource| @update_block_called = true end end def create_block_called? @create_block_called == true end def update_block_called? @update_block_called == true end def new_block_called? @new_block_called == true end end devise-3.5.6/test/rails_app/app/controllers/admins/0000755000004100000410000000000012663066463022402 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/controllers/admins/sessions_controller.rb0000644000004100000410000000024612663066463027042 0ustar www-datawww-dataclass Admins::SessionsController < Devise::SessionsController def new flash[:special] = "Welcome to #{controller_path.inspect} controller!" super end end devise-3.5.6/test/rails_app/app/controllers/users_controller.rb0000644000004100000410000000133512663066463025062 0ustar www-datawww-dataclass UsersController < ApplicationController prepend_before_filter :current_user, only: :exhibit before_filter :authenticate_user!, except: [:accept, :exhibit] respond_to :html, :xml def index user_session[:cart] = "Cart" respond_with(current_user) end def edit_form user_session['last_request_at'] = params.fetch(:last_request_at, 31.minutes.ago.utc) end def update_form render text: 'Update' end def accept @current_user = current_user end def exhibit render text: current_user ? "User is authenticated" : "User is not authenticated" end def expire user_session['last_request_at'] = 31.minutes.ago.utc render text: 'User will be expired on next request' end end devise-3.5.6/test/rails_app/app/controllers/publisher/0000755000004100000410000000000012663066463023124 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/controllers/publisher/registrations_controller.rb0000644000004100000410000000010512663066463030605 0ustar www-datawww-dataclass Publisher::RegistrationsController < ApplicationController end devise-3.5.6/test/rails_app/app/controllers/publisher/sessions_controller.rb0000644000004100000410000000010012663066463027551 0ustar www-datawww-dataclass Publisher::SessionsController < ApplicationController end devise-3.5.6/test/rails_app/app/controllers/home_controller.rb0000644000004100000410000000050412663066463024646 0ustar www-datawww-dataclass HomeController < ApplicationController def index end def private end def user_dashboard end def admin_dashboard end def join end def set session["devise.foo_bar"] = "something" head :ok end def unauthenticated render text: "unauthenticated", status: :unauthorized end end devise-3.5.6/test/rails_app/app/controllers/application_controller.rb0000644000004100000410000000067712663066463026234 0ustar www-datawww-data# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base protect_from_forgery before_filter :current_user, unless: :devise_controller? before_filter :authenticate_user!, if: :devise_controller? respond_to *Mime::SET.map(&:to_sym) devise_group :commenter, contains: [:user, :admin] end devise-3.5.6/test/rails_app/app/controllers/users/0000755000004100000410000000000012663066463022270 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb0000644000004100000410000000057412663066463030711 0ustar www-datawww-dataclass Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook data = env["omniauth.auth"] session["devise.facebook_data"] = data["extra"]["user_hash"] render json: data end def sign_in_facebook user = User.to_adapter.find_first(email: 'user@test.com') user.remember_me = true sign_in user render text: "" end end devise-3.5.6/test/rails_app/app/controllers/admins_controller.rb0000644000004100000410000000015312663066463025171 0ustar www-datawww-dataclass AdminsController < ApplicationController before_filter :authenticate_admin! def index end end devise-3.5.6/test/rails_app/app/mailers/0000755000004100000410000000000012663066463020215 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/mailers/users/0000755000004100000410000000000012663066463021356 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/mailers/users/from_proc_mailer.rb0000644000004100000410000000013712663066463025223 0ustar www-datawww-dataclass Users::FromProcMailer < Devise::Mailer default from: proc { 'custom@example.com' } end devise-3.5.6/test/rails_app/app/mailers/users/reply_to_mailer.rb0000644000004100000410000000020712663066463025070 0ustar www-datawww-dataclass Users::ReplyToMailer < Devise::Mailer default from: 'custom@example.com' default reply_to: 'custom_reply_to@example.com' end devise-3.5.6/test/rails_app/app/mailers/users/mailer.rb0000644000004100000410000000011612663066463023152 0ustar www-datawww-dataclass Users::Mailer < Devise::Mailer default from: 'custom@example.com' end devise-3.5.6/test/rails_app/app/active_record/0000755000004100000410000000000012663066463021372 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/active_record/user_without_email.rb0000644000004100000410000000024212663066463025625 0ustar www-datawww-datarequire "shared_user_without_email" class UserWithoutEmail < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutEmail end devise-3.5.6/test/rails_app/app/active_record/admin.rb0000644000004100000410000000014212663066463023004 0ustar www-datawww-datarequire 'shared_admin' class Admin < ActiveRecord::Base include Shim include SharedAdmin end devise-3.5.6/test/rails_app/app/active_record/shim.rb0000644000004100000410000000002012663066463022647 0ustar www-datawww-datamodule Shim end devise-3.5.6/test/rails_app/app/active_record/user.rb0000644000004100000410000000013712663066463022676 0ustar www-datawww-datarequire 'shared_user' class User < ActiveRecord::Base include Shim include SharedUser end devise-3.5.6/test/rails_app/app/active_record/user_on_main_app.rb0000644000004100000410000000024412663066463025235 0ustar www-datawww-datarequire 'shared_user_without_omniauth' class UserOnMainApp < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutOmniauth end devise-3.5.6/test/rails_app/app/active_record/user_on_engine.rb0000644000004100000410000000024312663066463024715 0ustar www-datawww-datarequire 'shared_user_without_omniauth' class UserOnEngine < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutOmniauth end devise-3.5.6/test/rails_app/app/helpers/0000755000004100000410000000000012663066463020223 5ustar www-datawww-datadevise-3.5.6/test/rails_app/app/helpers/application_helper.rb0000644000004100000410000000016312663066463024412 0ustar www-datawww-data# Methods added to this helper will be available to all templates in the application. module ApplicationHelper end devise-3.5.6/test/rails_app/config.ru0000644000004100000410000000023612663066463017617 0ustar www-datawww-data# This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) run RailsApp::Application devise-3.5.6/test/delegator_test.rb0000644000004100000410000000116612663066463017365 0ustar www-datawww-datarequire 'test_helper' class DelegatorTest < ActiveSupport::TestCase def delegator Devise::Delegator.new end test 'failure_app returns default failure app if no warden options in env' do assert_equal Devise::FailureApp, delegator.failure_app({}) end test 'failure_app returns default failure app if no scope in warden options' do assert_equal Devise::FailureApp, delegator.failure_app({"warden.options" => {}}) end test 'failure_app returns associated failure app by scope in the given environment' do assert_kind_of Proc, delegator.failure_app({"warden.options" => {scope: "manager"}}) end end devise-3.5.6/test/generators/0000755000004100000410000000000012663066463016200 5ustar www-datawww-datadevise-3.5.6/test/generators/mongoid_generator_test.rb0000644000004100000410000000115612663066463023271 0ustar www-datawww-datarequire "test_helper" if DEVISE_ORM == :mongoid require "generators/mongoid/devise_generator" class MongoidGeneratorTest < Rails::Generators::TestCase tests Mongoid::Generators::DeviseGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "all files are properly created" do run_generator %w(monster) assert_file "app/models/monster.rb", /devise/ end test "all files are properly deleted" do run_generator %w(monster) run_generator %w(monster), behavior: :revoke assert_no_file "app/models/monster.rb" end end end devise-3.5.6/test/generators/views_generator_test.rb0000644000004100000410000001002712663066463022767 0ustar www-datawww-datarequire "test_helper" class ViewsGeneratorTest < Rails::Generators::TestCase tests Devise::Generators::ViewsGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "Assert all views are properly created with no params" do run_generator assert_files assert_shared_links end test "Assert all views are properly created with scope param" do run_generator %w(users) assert_files "users" assert_shared_links "users" run_generator %w(admins) assert_files "admins" assert_shared_links "admins" end test "Assert views with simple form" do run_generator %w(-b simple_form_for) assert_files assert_file "app/views/devise/confirmations/new.html.erb", /simple_form_for/ run_generator %w(users -b simple_form_for) assert_files "users" assert_file "app/views/users/confirmations/new.html.erb", /simple_form_for/ end test "Assert views with markerb" do run_generator %w(--markerb) assert_files nil, mail_template_engine: "markerb" end test "Assert only views within specified directories" do run_generator %w(-v sessions registrations) assert_file "app/views/devise/sessions/new.html.erb" assert_file "app/views/devise/registrations/new.html.erb" assert_file "app/views/devise/registrations/edit.html.erb" assert_no_file "app/views/devise/confirmations/new.html.erb" assert_no_file "app/views/devise/mailer/confirmation_instructions.html.erb" end test "Assert mailer specific directory with simple form" do run_generator %w(-v mailer -b simple_form_for) assert_file "app/views/devise/mailer/confirmation_instructions.html.erb" assert_file "app/views/devise/mailer/reset_password_instructions.html.erb" assert_file "app/views/devise/mailer/unlock_instructions.html.erb" end test "Assert specified directories with scope" do run_generator %w(users -v sessions) assert_file "app/views/users/sessions/new.html.erb" assert_no_file "app/views/users/confirmations/new.html.erb" end test "Assert specified directories with simple form" do run_generator %w(-v registrations -b simple_form_for) assert_file "app/views/devise/registrations/new.html.erb", /simple_form_for/ assert_no_file "app/views/devise/confirmations/new.html.erb" end test "Assert specified directories with markerb" do run_generator %w(--markerb -v passwords mailer) assert_file "app/views/devise/passwords/new.html.erb" assert_no_file "app/views/devise/confirmations/new.html.erb" assert_file "app/views/devise/mailer/reset_password_instructions.markerb" end def assert_files(scope = nil, options={}) scope = "devise" if scope.nil? mail_template_engine = options[:mail_template_engine] || "html.erb" assert_file "app/views/#{scope}/confirmations/new.html.erb" assert_file "app/views/#{scope}/mailer/confirmation_instructions.#{mail_template_engine}" assert_file "app/views/#{scope}/mailer/reset_password_instructions.#{mail_template_engine}" assert_file "app/views/#{scope}/mailer/unlock_instructions.#{mail_template_engine}" assert_file "app/views/#{scope}/passwords/edit.html.erb" assert_file "app/views/#{scope}/passwords/new.html.erb" assert_file "app/views/#{scope}/registrations/new.html.erb" assert_file "app/views/#{scope}/registrations/edit.html.erb" assert_file "app/views/#{scope}/sessions/new.html.erb" assert_file "app/views/#{scope}/shared/_links.html.erb" assert_file "app/views/#{scope}/unlocks/new.html.erb" end def assert_shared_links(scope = nil) scope = "devise" if scope.nil? link = /<%= render \"#{scope}\/shared\/links\" %>/ assert_file "app/views/#{scope}/passwords/edit.html.erb", link assert_file "app/views/#{scope}/passwords/new.html.erb", link assert_file "app/views/#{scope}/confirmations/new.html.erb", link assert_file "app/views/#{scope}/registrations/new.html.erb", link assert_file "app/views/#{scope}/sessions/new.html.erb", link assert_file "app/views/#{scope}/unlocks/new.html.erb", link end end devise-3.5.6/test/generators/devise_generator_test.rb0000644000004100000410000000210512663066463023107 0ustar www-datawww-datarequire 'test_helper' require "generators/devise/devise_generator" class DeviseGeneratorTest < Rails::Generators::TestCase tests Devise::Generators::DeviseGenerator destination File.expand_path("../../tmp", __FILE__) setup do prepare_destination copy_routes end test "route generation for simple model names" do run_generator %w(monster name:string) assert_file "config/routes.rb", /devise_for :monsters/ end test "route generation for namespaced model names" do run_generator %w(monster/goblin name:string) match = /devise_for :goblins, class_name: "Monster::Goblin"/ assert_file "config/routes.rb", match end test "route generation with skip routes" do run_generator %w(monster name:string --skip-routes) match = /devise_for :monsters, skip: :all/ assert_file "config/routes.rb", match end def copy_routes routes = File.expand_path("../../rails_app/config/routes.rb", __FILE__) destination = File.join(destination_root, "config") FileUtils.mkdir_p(destination) FileUtils.cp routes, destination end end devise-3.5.6/test/generators/controllers_generator_test.rb0000644000004100000410000000353112663066463024202 0ustar www-datawww-datarequire "test_helper" class ControllersGeneratorTest < Rails::Generators::TestCase tests Devise::Generators::ControllersGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "Assert no controllers are created with no params" do capture(:stderr) { run_generator } assert_no_file "app/controllers/sessions_controller.rb" assert_no_file "app/controllers/registrations_controller.rb" assert_no_file "app/controllers/confirmations_controller.rb" assert_no_file "app/controllers/passwords_controller.rb" assert_no_file "app/controllers/unlocks_controller.rb" assert_no_file "app/controllers/omniauth_callbacks_controller.rb" end test "Assert all controllers are properly created with scope param" do run_generator %w(users) assert_class_names 'users' run_generator %w(admins) assert_class_names 'admins' end test "Assert specified controllers with scope" do run_generator %w(users -c sessions) assert_file "app/controllers/users/sessions_controller.rb" assert_no_file "app/controllers/users/registrations_controller.rb" assert_no_file "app/controllers/users/confirmations_controller.rb" assert_no_file "app/controllers/users/passwords_controller.rb" assert_no_file "app/controllers/users/unlocks_controller.rb" assert_no_file "app/controllers/users/omniauth_callbacks_controller.rb" end private def assert_class_names(scope, options = {}) base_dir = "app/controllers#{scope.blank? ? '' : ('/' + scope)}" scope_prefix = scope.blank? ? '' : (scope.camelize + '::') controllers = options[:controllers] || %w(confirmations passwords registrations sessions unlocks omniauth_callbacks) controllers.each do |c| assert_file "#{base_dir}/#{c}_controller.rb", /#{scope_prefix + c.camelize}/ end end end devise-3.5.6/test/generators/active_record_generator_test.rb0000644000004100000410000001005612663066463024445 0ustar www-datawww-datarequire "test_helper" if DEVISE_ORM == :active_record require "generators/active_record/devise_generator" class ActiveRecordGeneratorTest < Rails::Generators::TestCase tests ActiveRecord::Generators::DeviseGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "all files are properly created with rails31 migration syntax" do run_generator %w(monster) assert_migration "db/migrate/devise_create_monsters.rb", /def change/ end test "all files for namespaced model are properly created" do run_generator %w(admin/monster) assert_migration "db/migrate/devise_create_admin_monsters.rb", /def change/ end test "update model migration when model exists" do run_generator %w(monster) assert_file "app/models/monster.rb" run_generator %w(monster) assert_migration "db/migrate/add_devise_to_monsters.rb" end test "all files are properly deleted" do run_generator %w(monster) run_generator %w(monster) assert_migration "db/migrate/devise_create_monsters.rb" assert_migration "db/migrate/add_devise_to_monsters.rb" run_generator %w(monster), behavior: :revoke assert_no_migration "db/migrate/add_devise_to_monsters.rb" assert_migration "db/migrate/devise_create_monsters.rb" run_generator %w(monster), behavior: :revoke assert_no_file "app/models/monster.rb" assert_no_migration "db/migrate/devise_create_monsters.rb" end test "use string column type for ip addresses" do run_generator %w(monster) assert_migration "db/migrate/devise_create_monsters.rb", /t.string :current_sign_in_ip/ assert_migration "db/migrate/devise_create_monsters.rb", /t.string :last_sign_in_ip/ end end module RailsEngine class Engine < Rails::Engine isolate_namespace RailsEngine end end def simulate_inside_engine(engine, namespace) if Rails::Generators.respond_to?(:namespace=) swap Rails::Generators, namespace: namespace do yield end else swap Rails, application: engine.instance do yield end end end class ActiveRecordEngineGeneratorTest < Rails::Generators::TestCase tests ActiveRecord::Generators::DeviseGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "all files are properly created in rails 4.0" do ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:rails_3?).returns(false) simulate_inside_engine(RailsEngine::Engine, RailsEngine) do run_generator ["monster"] assert_file "app/models/rails_engine/monster.rb", /devise/ assert_file "app/models/rails_engine/monster.rb" do |content| assert_no_match /attr_accessible :email/, content end end end test "all files are properly created in rails 3.2 when strong_parameters gem is not installed" do ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:rails_3?).returns(true) ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:strong_parameters_enabled?).returns(false) simulate_inside_engine(RailsEngine::Engine, RailsEngine) do run_generator ["monster"] assert_file "app/models/rails_engine/monster.rb", /devise/ assert_file "app/models/rails_engine/monster.rb" do |content| assert_match /attr_accessible :email/, content end end end test "all files are properly created in rails 3.2 when strong_parameters gem is installed" do ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:rails_3?).returns(true) ActiveRecord::Generators::DeviseGenerator.any_instance.stubs(:strong_parameters_enabled?).returns(true) simulate_inside_engine(RailsEngine::Engine, RailsEngine) do run_generator ["monster"] assert_file "app/models/rails_engine/monster.rb", /devise/ assert_file "app/models/rails_engine/monster.rb" do |content| assert_no_match /attr_accessible :email/, content end end end end end devise-3.5.6/test/generators/install_generator_test.rb0000644000004100000410000000057612663066463023310 0ustar www-datawww-datarequire "test_helper" class InstallGeneratorTest < Rails::Generators::TestCase tests Devise::Generators::InstallGenerator destination File.expand_path("../../tmp", __FILE__) setup :prepare_destination test "Assert all files are properly created" do run_generator assert_file "config/initializers/devise.rb" assert_file "config/locales/devise.en.yml" end end devise-3.5.6/test/integration/0000755000004100000410000000000012663066463016352 5ustar www-datawww-datadevise-3.5.6/test/integration/http_authenticatable_test.rb0000644000004100000410000000754112663066463024141 0ustar www-datawww-datarequire 'test_helper' class HttpAuthenticationTest < ActionDispatch::IntegrationTest test 'handles unverified requests gets rid of caches but continues signed in' do swap ApplicationController, allow_forgery_protection: true do create_user post exhibit_user_url(1), {}, "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("user@test.com:12345678")}" assert warden.authenticated?(:user) assert_equal "User is authenticated", response.body end end test 'sign in should authenticate with http' do sign_in_as_new_user_with_http assert_response 200 assert_match 'user@test.com', response.body assert warden.authenticated?(:user) get users_path(format: :xml) assert_response 200 end test 'sign in should authenticate with http but not emit a cookie if skipping session storage' do swap Devise, skip_session_storage: [:http_auth] do sign_in_as_new_user_with_http assert_response 200 assert_match 'user@test.com', response.body assert warden.authenticated?(:user) get users_path(format: :xml) assert_response 401 end end test 'returns a custom response with www-authenticate header on failures' do sign_in_as_new_user_with_http("unknown") assert_equal 401, status assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"] end test 'uses the request format as response content type' do sign_in_as_new_user_with_http("unknown") assert_equal 401, status assert_equal "application/xml; charset=utf-8", headers["Content-Type"] assert_match "Invalid email or password.", response.body end test 'returns a custom response with www-authenticate and chosen realm' do swap Devise, http_authentication_realm: "MyApp" do sign_in_as_new_user_with_http("unknown") assert_equal 401, status assert_equal 'Basic realm="MyApp"', headers["WWW-Authenticate"] end end test 'sign in should authenticate with http even with specific authentication keys' do swap Devise, authentication_keys: [:username] do sign_in_as_new_user_with_http("usertest") assert_response :success assert_match 'user@test.com', response.body assert warden.authenticated?(:user) end end test 'it uses appropriate authentication_keys when configured with hash' do swap Devise, authentication_keys: ActiveSupport::OrderedHash[:username, false, :email, false] do sign_in_as_new_user_with_http("usertest") assert_response :success assert_match 'user@test.com', response.body assert warden.authenticated?(:user) end end test 'it uses the appropriate key when configured explicitly' do swap Devise, authentication_keys: ActiveSupport::OrderedHash[:email, false, :username, false], http_authentication_key: :username do sign_in_as_new_user_with_http("usertest") assert_response :success assert_match 'user@test.com', response.body assert warden.authenticated?(:user) end end test 'test request with oauth2 header doesnt get mistaken for basic authentication' do swap Devise, http_authenticatable: true do add_oauth2_header assert_equal 401, status assert_equal 'Basic realm="Application"', headers["WWW-Authenticate"] end end private def sign_in_as_new_user_with_http(username="user@test.com", password="12345678") user = create_user get users_path(format: :xml), {}, "HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("#{username}:#{password}")}" user end # Sign in with oauth2 token. This is just to test that it isn't misinterpreted as basic authentication def add_oauth2_header user = create_user get users_path(format: :xml), {}, "HTTP_AUTHORIZATION" => "OAuth #{Base64.encode64("#{user.email}:12345678")}" end end devise-3.5.6/test/integration/trackable_test.rb0000644000004100000410000000443612663066463021675 0ustar www-datawww-datarequire 'test_helper' class TrackableHooksTest < ActionDispatch::IntegrationTest test "current and last sign in timestamps are updated on each sign in" do user = create_user assert_nil user.current_sign_in_at assert_nil user.last_sign_in_at sign_in_as_user user.reload assert user.current_sign_in_at.acts_like?(:time) assert user.last_sign_in_at.acts_like?(:time) assert_equal user.current_sign_in_at, user.last_sign_in_at assert user.current_sign_in_at >= user.created_at visit destroy_user_session_path new_time = 2.seconds.from_now Time.stubs(:now).returns(new_time) sign_in_as_user user.reload assert user.current_sign_in_at > user.last_sign_in_at end test "current and last sign in remote ip are updated on each sign in" do user = create_user assert_nil user.current_sign_in_ip assert_nil user.last_sign_in_ip sign_in_as_user user.reload assert_equal "127.0.0.1", user.current_sign_in_ip assert_equal "127.0.0.1", user.last_sign_in_ip end test "current remote ip returns original ip behind a non transparent proxy" do user = create_user arbitrary_ip = '200.121.1.69' sign_in_as_user do header 'HTTP_X_FORWARDED_FOR', arbitrary_ip end user.reload assert_equal arbitrary_ip, user.current_sign_in_ip end test "increase sign in count" do user = create_user assert_equal 0, user.sign_in_count sign_in_as_user user.reload assert_equal 1, user.sign_in_count visit destroy_user_session_path sign_in_as_user user.reload assert_equal 2, user.sign_in_count end test "does not update anything if user has signed out along the way" do swap Devise, allow_unconfirmed_access_for: 0.days do user = create_user(confirm: false) sign_in_as_user user.reload assert_nil user.current_sign_in_at assert_nil user.last_sign_in_at end end test "do not track if devise.skip_trackable is set" do user = create_user sign_in_as_user do header 'devise.skip_trackable', '1' end user.reload assert_equal 0, user.sign_in_count visit destroy_user_session_path sign_in_as_user do header 'devise.skip_trackable', false end user.reload assert_equal 1, user.sign_in_count end end devise-3.5.6/test/integration/timeoutable_test.rb0000644000004100000410000001134612663066463022255 0ustar www-datawww-datarequire 'test_helper' class SessionTimeoutTest < ActionDispatch::IntegrationTest def last_request_at @controller.user_session['last_request_at'] end test 'set last request at in user session after each request' do sign_in_as_user assert_not_nil last_request_at @controller.user_session.delete('last_request_at') get users_path assert_not_nil last_request_at end test 'set last request at in user session after each request is skipped if tracking is disabled' do sign_in_as_user old_last_request = last_request_at assert_not_nil last_request_at get users_path, {}, 'devise.skip_trackable' => true assert_equal old_last_request, last_request_at end test 'does not set last request at in user session after each request if timeoutable is disabled' do sign_in_as_user old_last_request = last_request_at assert_not_nil last_request_at new_time = 2.seconds.from_now Time.stubs(:now).returns(new_time) get users_path, {}, 'devise.skip_timeoutable' => true assert_equal old_last_request, last_request_at end test 'does not time out user session before default limit time' do sign_in_as_user assert_response :success assert warden.authenticated?(:user) get users_path assert_response :success assert warden.authenticated?(:user) end test 'time out user session after default limit time when sign_out_all_scopes is false' do swap Devise, sign_out_all_scopes: false do sign_in_as_admin user = sign_in_as_user get expire_user_path(user) assert_not_nil last_request_at get users_path assert_redirected_to users_path assert_not warden.authenticated?(:user) assert warden.authenticated?(:admin) end end test 'time out all sessions after default limit time when sign_out_all_scopes is true' do swap Devise, sign_out_all_scopes: true do sign_in_as_admin user = sign_in_as_user get expire_user_path(user) assert_not_nil last_request_at get root_path assert_not warden.authenticated?(:user) assert_not warden.authenticated?(:admin) end end test 'time out user session after deault limit time and redirect to latest get request' do user = sign_in_as_user visit edit_form_user_path(user) click_button 'Update' sign_in_as_user assert_equal edit_form_user_url(user), current_url end test 'time out is not triggered on sign out' do user = sign_in_as_user get expire_user_path(user) get destroy_user_session_path assert_response :redirect assert_redirected_to root_path follow_redirect! assert_contain 'Signed out successfully' end test 'expired session is not extended by sign in page' do user = sign_in_as_user get expire_user_path(user) assert warden.authenticated?(:user) get "/users/sign_in" assert_redirected_to "/users/sign_in" follow_redirect! assert_response :success assert_contain 'Sign in' assert_not warden.authenticated?(:user) end test 'time out is not triggered on sign in' do user = sign_in_as_user get expire_user_path(user) post "/users/sign_in", email: user.email, password: "123456" assert_response :redirect follow_redirect! assert_contain 'You are signed in' end test 'user configured timeout limit' do swap Devise, timeout_in: 8.minutes do user = sign_in_as_user get users_path assert_not_nil last_request_at assert_response :success assert warden.authenticated?(:user) get expire_user_path(user) get users_path assert_redirected_to users_path assert_not warden.authenticated?(:user) end end test 'error message with i18n' do store_translations :en, devise: { failure: { user: { timeout: 'Session expired!' } } } do user = sign_in_as_user get expire_user_path(user) get root_path follow_redirect! assert_contain 'Session expired!' end end test 'error message with i18n with double redirect' do store_translations :en, devise: { failure: { user: { timeout: 'Session expired!' } } } do user = sign_in_as_user get expire_user_path(user) get users_path follow_redirect! follow_redirect! assert_contain 'Session expired!' end end test 'time out not triggered if remembered' do user = sign_in_as_user remember_me: true get expire_user_path(user) assert_not_nil last_request_at get users_path assert_response :success assert warden.authenticated?(:user) end test 'does not crash when the last_request_at is a String' do user = sign_in_as_user get edit_form_user_path(user, last_request_at: Time.now.utc.to_s) get users_path end end devise-3.5.6/test/integration/recoverable_test.rb0000644000004100000410000003033712663066463022235 0ustar www-datawww-datarequire 'test_helper' class PasswordTest < ActionDispatch::IntegrationTest def visit_new_password_path visit new_user_session_path click_link 'Forgot your password?' end def request_forgot_password(&block) visit_new_password_path assert_response :success assert_not warden.authenticated?(:user) fill_in 'email', with: 'user@test.com' yield if block_given? Devise.stubs(:friendly_token).returns("abcdef") click_button 'Send me reset password instructions' end def reset_password(options={}, &block) unless options[:visit] == false visit edit_user_password_path(reset_password_token: options[:reset_password_token] || "abcdef") assert_response :success end fill_in 'New password', with: '987654321' fill_in 'Confirm new password', with: '987654321' yield if block_given? click_button 'Change my password' end test 'reset password with email of different case should succeed when email is in the list of case insensitive keys' do create_user(email: 'Foo@Bar.com') request_forgot_password do fill_in 'email', with: 'foo@bar.com' end assert_current_url '/users/sign_in' assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.' end test 'reset password with email should send an email from a custom mailer' do create_user(email: 'Foo@Bar.com') User.any_instance.stubs(:devise_mailer).returns(Users::Mailer) request_forgot_password do fill_in 'email', with: 'foo@bar.com' end mail = ActionMailer::Base.deliveries.last assert_equal ['custom@example.com'], mail.from assert_match edit_user_password_path(reset_password_token: 'abcdef'), mail.body.encoded end test 'reset password with email of different case should fail when email is NOT the list of case insensitive keys' do swap Devise, case_insensitive_keys: [] do create_user(email: 'Foo@Bar.com') request_forgot_password do fill_in 'email', with: 'foo@bar.com' end assert_response :success assert_current_url '/users/password' assert_have_selector "input[type=email][value='foo@bar.com']" assert_contain 'not found' end end test 'reset password with email with extra whitespace should succeed when email is in the list of strip whitespace keys' do create_user(email: 'foo@bar.com') request_forgot_password do fill_in 'email', with: ' foo@bar.com ' end assert_current_url '/users/sign_in' assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.' end test 'reset password with email with extra whitespace should fail when email is NOT the list of strip whitespace keys' do swap Devise, strip_whitespace_keys: [] do create_user(email: 'foo@bar.com') request_forgot_password do fill_in 'email', with: ' foo@bar.com ' end assert_response :success assert_current_url '/users/password' assert_have_selector "input[type=email][value=' foo@bar.com ']" assert_contain 'not found' end end test 'authenticated user should not be able to visit forgot password page' do sign_in_as_user assert warden.authenticated?(:user) get new_user_password_path assert_response :redirect assert_redirected_to root_path end test 'not authenticated user should be able to request a forgot password' do create_user request_forgot_password assert_current_url '/users/sign_in' assert_contain 'You will receive an email with instructions on how to reset your password in a few minutes.' end test 'not authenticated user with invalid email should receive an error message' do request_forgot_password do fill_in 'email', with: 'invalid.test@test.com' end assert_response :success assert_current_url '/users/password' assert_have_selector "input[type=email][value='invalid.test@test.com']" assert_contain 'not found' end test 'authenticated user should not be able to visit edit password page' do sign_in_as_user get edit_user_password_path assert_response :redirect assert_redirected_to root_path assert warden.authenticated?(:user) end test 'not authenticated user without a reset password token should not be able to visit the page' do get edit_user_password_path assert_response :redirect assert_redirected_to "/users/sign_in" end test 'not authenticated user with invalid reset password token should not be able to change their password' do user = create_user reset_password reset_password_token: 'invalid_reset_password' assert_response :success assert_current_url '/users/password' assert_have_selector '#error_explanation' assert_contain /Reset password token(.*)invalid/ assert_not user.reload.valid_password?('987654321') end test 'not authenticated user with valid reset password token but invalid password should not be able to change their password' do user = create_user request_forgot_password reset_password do fill_in 'Confirm new password', with: 'other_password' end assert_response :success assert_current_url '/users/password' assert_have_selector '#error_explanation' assert_contain Devise.rails4? ? "Password confirmation doesn't match Password" : "Password doesn't match confirmation" assert_not user.reload.valid_password?('987654321') end test 'not authenticated user with valid data should be able to change their password' do user = create_user request_forgot_password reset_password assert_current_url '/' assert_contain 'Your password has been changed successfully. You are now signed in.' assert user.reload.valid_password?('987654321') end test 'after entering invalid data user should still be able to change their password' do user = create_user request_forgot_password reset_password { fill_in 'Confirm new password', with: 'other_password' } assert_response :success assert_have_selector '#error_explanation' assert_not user.reload.valid_password?('987654321') reset_password visit: false assert_contain 'Your password has been changed successfully.' assert user.reload.valid_password?('987654321') end test 'sign in user automatically after changing its password' do create_user request_forgot_password reset_password assert warden.authenticated?(:user) end test 'does not sign in user automatically after changing its password if config.sign_in_after_reset_password is false' do swap Devise, sign_in_after_reset_password: false do create_user request_forgot_password reset_password assert_contain 'Your password has been changed successfully.' assert_not_contain 'You are now signed in.' assert_equal new_user_session_path, @request.path assert !warden.authenticated?(:user) end end test 'does not sign in user automatically after changing its password if it\'s locked and unlock strategy is :none or :time' do [:none, :time].each do |strategy| swap Devise, unlock_strategy: strategy do user = create_user(locked: true) request_forgot_password reset_password assert_contain 'Your password has been changed successfully.' assert_not_contain 'You are now signed in.' assert_equal new_user_session_path, @request.path assert !warden.authenticated?(:user) end end end test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :email' do swap Devise, unlock_strategy: :email do user = create_user(locked: true) request_forgot_password reset_password assert_contain 'Your password has been changed successfully.' assert !user.reload.access_locked? assert warden.authenticated?(:user) end end test 'unlocks and signs in locked user automatically after changing it\'s password if unlock strategy is :both' do swap Devise, unlock_strategy: :both do user = create_user(locked: true) request_forgot_password reset_password assert_contain 'Your password has been changed successfully.' assert !user.reload.access_locked? assert warden.authenticated?(:user) end end test 'reset password request with valid E-Mail in XML format should return valid response' do create_user post user_password_path(format: 'xml'), user: {email: "user@test.com"} assert_response :success assert_equal response.body, { }.to_xml end test 'reset password request with invalid E-Mail in XML format should return valid response' do create_user post user_password_path(format: 'xml'), user: {email: "invalid.test@test.com"} assert_response :unprocessable_entity assert response.body.include? %(\n) end test 'reset password request with invalid E-Mail in XML format should return empty and valid response' do swap Devise, paranoid: true do create_user post user_password_path(format: 'xml'), user: {email: "invalid@test.com"} assert_response :success assert_equal response.body, { }.to_xml end end test 'change password with valid parameters in XML format should return valid response' do create_user request_forgot_password put user_password_path(format: 'xml'), user: { reset_password_token: 'abcdef', password: '987654321', password_confirmation: '987654321' } assert_response :success assert warden.authenticated?(:user) end test 'change password with invalid token in XML format should return invalid response' do create_user request_forgot_password put user_password_path(format: 'xml'), user: {reset_password_token: 'invalid.token', password: '987654321', password_confirmation: '987654321'} assert_response :unprocessable_entity assert response.body.include? %(\n) end test 'change password with invalid new password in XML format should return invalid response' do user = create_user request_forgot_password put user_password_path(format: 'xml'), user: {reset_password_token: user.reload.reset_password_token, password: '', password_confirmation: '987654321'} assert_response :unprocessable_entity assert response.body.include? %(\n) end test "when using json requests to ask a confirmable request, should not return the object" do user = create_user(confirm: false) post user_password_path(format: :json), user: { email: user.email } assert_response :success assert_equal response.body, "{}" end test "when in paranoid mode and with an invalid e-mail, asking to reset a password should display a message that does not indicates that the e-mail does not exists in the database" do swap Devise, paranoid: true do visit_new_password_path fill_in "email", with: "arandomemail@test.com" click_button 'Send me reset password instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." assert_current_url "/users/sign_in" end end test "when in paranoid mode and with a valid e-mail, asking to reset password should display a message that does not indicates that the email exists in the database and redirect to the failure route" do swap Devise, paranoid: true do user = create_user visit_new_password_path fill_in 'email', with: user.email click_button 'Send me reset password instructions' assert_contain "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." assert_current_url "/users/sign_in" end end test "after recovering a password, should set failed attempts to 0" do user = create_user user.update_attribute(:failed_attempts, 10) assert_equal 10, user.failed_attempts request_forgot_password reset_password assert warden.authenticated?(:user) user.reload assert_equal 0, user.failed_attempts end end devise-3.5.6/test/integration/lockable_test.rb0000644000004100000410000001737412663066463021526 0ustar www-datawww-datarequire 'test_helper' class LockTest < ActionDispatch::IntegrationTest def visit_user_unlock_with_token(unlock_token) visit user_unlock_path(unlock_token: unlock_token) end def send_unlock_request user = create_user(locked: true) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive unlock instructions?" Devise.stubs(:friendly_token).returns("abcdef") fill_in 'email', with: user.email click_button 'Resend unlock instructions' end test 'user should be able to request a new unlock token' do send_unlock_request assert_template 'sessions/new' assert_contain 'You will receive an email with instructions for how to unlock your account in a few minutes' mail = ActionMailer::Base.deliveries.last assert_equal 1, ActionMailer::Base.deliveries.size assert_equal ['please-change-me@config-initializers-devise.com'], mail.from assert_match user_unlock_path(unlock_token: 'abcdef'), mail.body.encoded end test 'user should receive the instructions from a custom mailer' do User.any_instance.stubs(:devise_mailer).returns(Users::Mailer) send_unlock_request assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from end test 'unlocked user should not be able to request a unlock token' do user = create_user(locked: false) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive unlock instructions?" fill_in 'email', with: user.email click_button 'Resend unlock instructions' assert_template 'unlocks/new' assert_contain 'not locked' assert_equal 0, ActionMailer::Base.deliveries.size end test 'unlocked pages should not be available if email strategy is disabled' do visit "/admin_area/sign_in" assert_raise Webrat::NotFoundError do click_link "Didn't receive unlock instructions?" end assert_raise NameError do visit new_admin_unlock_path end assert_raise ActionController::RoutingError do visit "/admin_area/unlock/new" end end test 'user with invalid unlock token should not be able to unlock an account' do visit_user_unlock_with_token('invalid_token') assert_response :success assert_current_url '/users/unlock?unlock_token=invalid_token' assert_have_selector '#error_explanation' assert_contain /Unlock token(.*)invalid/ end test "locked user should be able to unlock account" do user = create_user raw = user.lock_access! visit_user_unlock_with_token(raw) assert_current_url "/users/sign_in" assert_contain 'Your account has been unlocked successfully. Please sign in to continue.' assert_not user.reload.access_locked? end test "user should not send a new e-mail if already locked" do user = create_user(locked: true) user.failed_attempts = User.maximum_attempts + 1 user.save! ActionMailer::Base.deliveries.clear sign_in_as_user(password: "invalid") assert_contain 'Your account is locked.' assert ActionMailer::Base.deliveries.empty? end test 'error message is configurable by resource name' do store_translations :en, devise: { failure: {user: {locked: "You are locked!"}} } do user = create_user(locked: true) user.failed_attempts = User.maximum_attempts + 1 user.save! sign_in_as_user(password: "invalid") assert_contain "You are locked!" end end test "user should not be able to sign in when locked" do store_translations :en, devise: { failure: {user: {locked: "You are locked!"}} } do user = create_user(locked: true) user.failed_attempts = User.maximum_attempts + 1 user.save! sign_in_as_user(password: "123456") assert_contain "You are locked!" end end test 'user should be able to request a new unlock token via XML request' do user = create_user(locked: true) ActionMailer::Base.deliveries.clear post user_unlock_path(format: 'xml'), user: {email: user.email} assert_response :success assert_equal response.body, {}.to_xml assert_equal 1, ActionMailer::Base.deliveries.size end test 'unlocked user should not be able to request a unlock token via XML request' do user = create_user(locked: false) ActionMailer::Base.deliveries.clear post user_unlock_path(format: 'xml'), user: {email: user.email} assert_response :unprocessable_entity assert response.body.include? %(\n) assert_equal 0, ActionMailer::Base.deliveries.size end test 'user with valid unlock token should be able to unlock account via XML request' do user = create_user() raw = user.lock_access! assert user.access_locked? get user_unlock_path(format: 'xml', unlock_token: raw) assert_response :success assert response.body.include? %(\n) end test 'user with invalid unlock token should not be able to unlock the account via XML request' do get user_unlock_path(format: 'xml', unlock_token: 'invalid_token') assert_response :unprocessable_entity assert response.body.include? %(\n) end test "when using json to ask a unlock request, should not return the user" do user = create_user(locked: true) post user_unlock_path(format: "json", user: {email: user.email}) assert_response :success assert_equal response.body, {}.to_json end test "in paranoid mode, when trying to unlock an user that exists it should not say that it exists if it is locked" do swap Devise, paranoid: true do user = create_user(locked: true) visit new_user_session_path click_link "Didn't receive unlock instructions?" fill_in 'email', with: user.email click_button 'Resend unlock instructions' assert_current_url "/users/sign_in" assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." end end test "in paranoid mode, when trying to unlock an user that exists it should not say that it exists if it is not locked" do swap Devise, paranoid: true do user = create_user(locked: false) visit new_user_session_path click_link "Didn't receive unlock instructions?" fill_in 'email', with: user.email click_button 'Resend unlock instructions' assert_current_url "/users/sign_in" assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." end end test "in paranoid mode, when trying to unlock an user that does not exists it should not say that it does not exists" do swap Devise, paranoid: true do visit new_user_session_path click_link "Didn't receive unlock instructions?" fill_in 'email', with: "arandomemail@hotmail.com" click_button 'Resend unlock instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" assert_current_url "/users/sign_in" assert_contain "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." end end test "in paranoid mode, when locking a user that exists it should not say that the user was locked" do swap Devise, paranoid: true, maximum_attempts: 1 do user = create_user(locked: false) visit new_user_session_path fill_in 'email', with: user.email fill_in 'password', with: "abadpassword" click_button 'Log in' fill_in 'email', with: user.email fill_in 'password', with: "abadpassword" click_button 'Log in' assert_current_url "/users/sign_in" assert_not_contain "locked" end end end devise-3.5.6/test/integration/omniauthable_test.rb0000644000004100000410000000760712663066463022420 0ustar www-datawww-datarequire 'test_helper' class OmniauthableIntegrationTest < ActionDispatch::IntegrationTest FACEBOOK_INFO = { "id" => '12345', "link" => 'http://facebook.com/josevalim', "email" => 'user@example.com', "first_name" => 'Jose', "last_name" => 'Valim', "website" => 'http://blog.plataformatec.com.br' } setup do OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:facebook] = { "uid" => '12345', "provider" => 'facebook', "user_info" => {"nickname" => 'josevalim'}, "credentials" => {"token" => 'plataformatec'}, "extra" => {"user_hash" => FACEBOOK_INFO} } OmniAuth.config.add_camelization 'facebook', 'FaceBook' end teardown do OmniAuth.config.camelizations.delete('facebook') OmniAuth.config.test_mode = false end def stub_action!(name) Users::OmniauthCallbacksController.class_eval do alias_method :__old_facebook, :facebook alias_method :facebook, name end yield ensure Users::OmniauthCallbacksController.class_eval do alias_method :facebook, :__old_facebook end end test "can access omniauth.auth in the env hash" do visit "/users/sign_in" click_link "Sign in with FaceBook" json = ActiveSupport::JSON.decode(response.body) assert_equal "12345", json["uid"] assert_equal "facebook", json["provider"] assert_equal "josevalim", json["user_info"]["nickname"] assert_equal FACEBOOK_INFO, json["extra"]["user_hash"] assert_equal "plataformatec", json["credentials"]["token"] end test "cleans up session on sign up" do assert_no_difference "User.count" do visit "/users/sign_in" click_link "Sign in with FaceBook" end assert session["devise.facebook_data"] assert_difference "User.count" do visit "/users/sign_up" fill_in "Password", with: "12345678" fill_in "Password confirmation", with: "12345678" click_button "Sign up" end assert_current_url "/" assert_contain "You have signed up successfully." assert_contain "Hello User user@example.com" assert_not session["devise.facebook_data"] end test "cleans up session on cancel" do assert_no_difference "User.count" do visit "/users/sign_in" click_link "Sign in with FaceBook" end assert session["devise.facebook_data"] visit "/users/cancel" assert !session["devise.facebook_data"] end test "cleans up session on sign in" do assert_no_difference "User.count" do visit "/users/sign_in" click_link "Sign in with FaceBook" end assert session["devise.facebook_data"] sign_in_as_user assert !session["devise.facebook_data"] end test "sign in and send remember token if configured" do visit "/users/sign_in" click_link "Sign in with FaceBook" assert_nil warden.cookies["remember_user_token"] stub_action!(:sign_in_facebook) do create_user visit "/users/sign_in" click_link "Sign in with FaceBook" assert warden.authenticated?(:user) assert warden.cookies["remember_user_token"] end end test "generates a proper link when SCRIPT_NAME is set" do header 'SCRIPT_NAME', '/q' visit "/users/sign_in" assert_select "a", href: "/q/users/auth/facebook" end test "handles callback error parameter according to the specification" do OmniAuth.config.mock_auth[:facebook] = :access_denied visit "/users/auth/facebook/callback?error=access_denied" assert_current_url "/users/sign_in" assert_contain 'Could not authenticate you from FaceBook because "Access denied".' end test "handles other exceptions from OmniAuth" do OmniAuth.config.mock_auth[:facebook] = :invalid_credentials visit "/users/sign_in" click_link "Sign in with FaceBook" assert_current_url "/users/sign_in" assert_contain 'Could not authenticate you from FaceBook because "Invalid credentials".' end end devise-3.5.6/test/integration/confirmable_test.rb0000644000004100000410000003111512663066463022220 0ustar www-datawww-datarequire 'test_helper' class ConfirmationTest < ActionDispatch::IntegrationTest def visit_user_confirmation_with_token(confirmation_token) visit user_confirmation_path(confirmation_token: confirmation_token) end def resend_confirmation user = create_user(confirm: false) ActionMailer::Base.deliveries.clear visit new_user_session_path click_link "Didn't receive confirmation instructions?" fill_in 'email', with: user.email click_button 'Resend confirmation instructions' end test 'user should be able to request a new confirmation' do resend_confirmation assert_current_url '/users/sign_in' assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes' assert_equal 1, ActionMailer::Base.deliveries.size assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from end test 'user should receive a confirmation from a custom mailer' do User.any_instance.stubs(:devise_mailer).returns(Users::Mailer) resend_confirmation assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from end test 'user with invalid confirmation token should not be able to confirm an account' do visit_user_confirmation_with_token('invalid_confirmation') assert_have_selector '#error_explanation' assert_contain /Confirmation token(.*)invalid/ end test 'user with valid confirmation token should not be able to confirm an account after the token has expired' do swap Devise, confirm_within: 3.days do user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) assert_not user.confirmed? visit_user_confirmation_with_token(user.raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain /needs to be confirmed within 3 days/ assert_not user.reload.confirmed? assert_current_url "/users/confirmation?confirmation_token=#{user.raw_confirmation_token}" end end test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine it should raise an error' do user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) swap Devise, confirm_within: 3.days, router_name: :fake_engine do assert_raise ActionView::Template::Error do visit_user_confirmation_with_token(user.raw_confirmation_token) end end end test 'user with valid confirmation token where the token has expired and with application router_name set to a different engine and route overrides back to main it shows the path' do user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) swap Devise, confirm_within: 3.days, router_name: :fake_engine do visit user_on_main_app_confirmation_path(confirmation_token: user.raw_confirmation_token) assert_current_url "/user_on_main_apps/confirmation?confirmation_token=#{user.raw_confirmation_token}" end end test 'user with valid confirmation token where the token has expired with router overrides different engine it shows the path' do user = create_user(confirm: false, confirmation_sent_at: 4.days.ago) swap Devise, confirm_within: 3.days do visit user_on_engine_confirmation_path(confirmation_token: user.raw_confirmation_token) assert_current_url "/user_on_engines/confirmation?confirmation_token=#{user.raw_confirmation_token}" end end test 'user with valid confirmation token should be able to confirm an account before the token has expired' do swap Devise, confirm_within: 3.days do user = create_user(confirm: false, confirmation_sent_at: 2.days.ago) assert_not user.confirmed? visit_user_confirmation_with_token(user.raw_confirmation_token) assert_contain 'Your email address has been successfully confirmed.' assert_current_url '/users/sign_in' assert user.reload.confirmed? end end test 'user should be redirected to a custom path after confirmation' do Devise::ConfirmationsController.any_instance.stubs(:after_confirmation_path_for).returns("/?custom=1") user = create_user(confirm: false) visit_user_confirmation_with_token(user.raw_confirmation_token) assert_current_url "/?custom=1" end test 'already confirmed user should not be able to confirm the account again' do user = create_user(confirm: false) user.confirmed_at = Time.now user.save visit_user_confirmation_with_token(user.raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain 'already confirmed' end test 'already confirmed user should not be able to confirm the account again neither request confirmation' do user = create_user(confirm: false) user.confirmed_at = Time.now user.save visit_user_confirmation_with_token(user.raw_confirmation_token) assert_contain 'already confirmed' fill_in 'email', with: user.email click_button 'Resend confirmation instructions' assert_contain 'already confirmed' end test 'not confirmed user with setup to block without confirmation should not be able to sign in' do swap Devise, allow_unconfirmed_access_for: 0.days do sign_in_as_user(confirm: false) assert_contain 'You have to confirm your email address before continuing' assert_not warden.authenticated?(:user) end end test 'not confirmed user should not see confirmation message if invalid credentials are given' do swap Devise, allow_unconfirmed_access_for: 0.days do sign_in_as_user(confirm: false) do fill_in 'password', with: 'invalid' end assert_contain 'Invalid email or password' assert_not warden.authenticated?(:user) end end test 'not confirmed user but configured with some days to confirm should be able to sign in' do swap Devise, allow_unconfirmed_access_for: 1.day do sign_in_as_user(confirm: false) assert_response :success assert warden.authenticated?(:user) end end test 'unconfirmed but signed in user should be redirected to their root path' do swap Devise, allow_unconfirmed_access_for: 1.day do user = sign_in_as_user(confirm: false) visit_user_confirmation_with_token(user.raw_confirmation_token) assert_contain 'Your email address has been successfully confirmed.' assert_current_url '/' end end test 'user should be redirected to sign in page whenever signed in as another resource at same session already' do sign_in_as_admin user = create_user(confirm: false) visit_user_confirmation_with_token(user.raw_confirmation_token) assert_current_url '/users/sign_in' end test 'error message is configurable by resource name' do store_translations :en, devise: { failure: { user: { unconfirmed: "Not confirmed user" } } } do sign_in_as_user(confirm: false) assert_contain 'Not confirmed user' end end test 'resent confirmation token with valid E-Mail in XML format should return valid response' do user = create_user(confirm: false) post user_confirmation_path(format: 'xml'), user: { email: user.email } assert_response :success assert_equal response.body, {}.to_xml end test 'resent confirmation token with invalid E-Mail in XML format should return invalid response' do create_user(confirm: false) post user_confirmation_path(format: 'xml'), user: { email: 'invalid.test@test.com' } assert_response :unprocessable_entity assert response.body.include? %(\n) end test 'confirm account with valid confirmation token in XML format should return valid response' do user = create_user(confirm: false) get user_confirmation_path(confirmation_token: user.raw_confirmation_token, format: 'xml') assert_response :success assert response.body.include? %(\n) end test 'confirm account with invalid confirmation token in XML format should return invalid response' do create_user(confirm: false) get user_confirmation_path(confirmation_token: 'invalid_confirmation', format: 'xml') assert_response :unprocessable_entity assert response.body.include? %(\n) end test 'request an account confirmation account with JSON, should return an empty JSON' do user = create_user(confirm: false) post user_confirmation_path, user: { email: user.email }, format: :json assert_response :success assert_equal response.body, {}.to_json end test "when in paranoid mode and with a valid e-mail, should not say that the e-mail is valid" do swap Devise, paranoid: true do user = create_user(confirm: false) visit new_user_session_path click_link "Didn't receive confirmation instructions?" fill_in 'email', with: user.email click_button 'Resend confirmation instructions' assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." assert_current_url "/users/sign_in" end end test "when in paranoid mode and with a invalid e-mail, should not say that the e-mail is invalid" do swap Devise, paranoid: true do visit new_user_session_path click_link "Didn't receive confirmation instructions?" fill_in 'email', with: "idonthavethisemail@gmail.com" click_button 'Resend confirmation instructions' assert_not_contain "1 error prohibited this user from being saved:" assert_not_contain "Email not found" assert_contain "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." assert_current_url "/users/sign_in" end end end class ConfirmationOnChangeTest < ActionDispatch::IntegrationTest def create_second_admin(options={}) @admin = nil create_admin(options) end def visit_admin_confirmation_with_token(confirmation_token) visit admin_confirmation_path(confirmation_token: confirmation_token) end test 'admin should be able to request a new confirmation after email changed' do admin = create_admin admin.update_attributes(email: 'new_test@example.com') visit new_admin_session_path click_link "Didn't receive confirmation instructions?" fill_in 'email', with: admin.unconfirmed_email assert_difference "ActionMailer::Base.deliveries.size" do click_button 'Resend confirmation instructions' end assert_current_url '/admin_area/sign_in' assert_contain 'You will receive an email with instructions for how to confirm your email address in a few minutes' end test 'admin with valid confirmation token should be able to confirm email after email changed' do admin = create_admin admin.update_attributes(email: 'new_test@example.com') assert_equal 'new_test@example.com', admin.unconfirmed_email visit_admin_confirmation_with_token(admin.raw_confirmation_token) assert_contain 'Your email address has been successfully confirmed.' assert_current_url '/admin_area/sign_in' assert admin.reload.confirmed? assert_not admin.reload.pending_reconfirmation? end test 'admin with previously valid confirmation token should not be able to confirm email after email changed again' do admin = create_admin admin.update_attributes(email: 'first_test@example.com') assert_equal 'first_test@example.com', admin.unconfirmed_email raw_confirmation_token = admin.raw_confirmation_token admin = Admin.find(admin.id) admin.update_attributes(email: 'second_test@example.com') assert_equal 'second_test@example.com', admin.unconfirmed_email visit_admin_confirmation_with_token(raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain(/Confirmation token(.*)invalid/) visit_admin_confirmation_with_token(admin.raw_confirmation_token) assert_contain 'Your email address has been successfully confirmed.' assert_current_url '/admin_area/sign_in' assert admin.reload.confirmed? assert_not admin.reload.pending_reconfirmation? end test 'admin email should be unique also within unconfirmed_email' do admin = create_admin admin.update_attributes(email: 'new_admin_test@example.com') assert_equal 'new_admin_test@example.com', admin.unconfirmed_email create_second_admin(email: "new_admin_test@example.com") visit_admin_confirmation_with_token(admin.raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain(/Email.*already.*taken/) assert admin.reload.pending_reconfirmation? end end devise-3.5.6/test/integration/rememberable_test.rb0000644000004100000410000001261412663066463022364 0ustar www-datawww-datarequire 'test_helper' class RememberMeTest < ActionDispatch::IntegrationTest def create_user_and_remember(add_to_token='') user = create_user user.remember_me! raw_cookie = User.serialize_into_cookie(user).tap { |a| a[1] << add_to_token } cookies['remember_user_token'] = generate_signed_cookie(raw_cookie) user end def generate_signed_cookie(raw_cookie) request = ActionDispatch::TestRequest.new request.cookie_jar.signed['raw_cookie'] = raw_cookie request.cookie_jar['raw_cookie'] end def signed_cookie(key) controller.send(:cookies).signed[key] end def cookie_expires(key) cookie = response.headers["Set-Cookie"].split("\n").grep(/^#{key}/).first expires = cookie.split(";").map(&:strip).grep(/^expires=/).first Time.parse(expires).utc end test 'do not remember the user if they have not checked remember me option' do sign_in_as_user assert_nil request.cookies["remember_user_cookie"] end test 'handle unverified requests gets rid of caches' do swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) assert_not warden.authenticated?(:user) create_user_and_remember post exhibit_user_url(1) assert_equal "User is not authenticated", response.body assert_not warden.authenticated?(:user) end end test 'handle unverified requests does not create cookies on sign in' do swap ApplicationController, allow_forgery_protection: true do get new_user_session_path assert request.session[:_csrf_token] post user_session_path, authenticity_token: "oops", user: { email: "jose.valim@gmail.com", password: "123456", remember_me: "1" } assert_not warden.authenticated?(:user) assert_not request.cookies['remember_user_token'] end end test 'generate remember token after sign in' do sign_in_as_user remember_me: true assert request.cookies['remember_user_token'] end test 'generate remember token after sign in setting cookie options' do # We test this by asserting the cookie is not sent after the redirect # since we changed the domain. This is the only difference with the # previous test. swap Devise, rememberable_options: { domain: "omg.somewhere.com" } do sign_in_as_user remember_me: true assert_nil request.cookies["remember_user_token"] end end test 'generate remember token with a custom key' do swap Devise, rememberable_options: { key: "v1lat_token" } do sign_in_as_user remember_me: true assert request.cookies["v1lat_token"] end end test 'generate remember token after sign in setting session options' do begin Rails.configuration.session_options[:domain] = "omg.somewhere.com" sign_in_as_user remember_me: true assert_nil request.cookies["remember_user_token"] ensure Rails.configuration.session_options.delete(:domain) end end test 'remember the user before sign in' do user = create_user_and_remember get users_path assert_response :success assert warden.authenticated?(:user) assert warden.user(:user) == user assert_match /remember_user_token[^\n]*HttpOnly/, response.headers["Set-Cookie"], "Expected Set-Cookie header in response to set HttpOnly flag on remember_user_token cookie." end test 'remember the user before sign up and redirect them to their home' do create_user_and_remember get new_user_registration_path assert warden.authenticated?(:user) assert_redirected_to root_path end test 'does not extend remember period through sign in' do swap Devise, extend_remember_period: true, remember_for: 1.year do user = create_user user.remember_me! user.remember_created_at = old = 10.days.ago user.save sign_in_as_user remember_me: true user.reload assert warden.user(:user) == user assert_equal old.to_i, user.remember_created_at.to_i end end test 'do not remember other scopes' do create_user_and_remember get root_path assert_response :success assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) end test 'do not remember with invalid token' do create_user_and_remember('add') get users_path assert_not warden.authenticated?(:user) assert_redirected_to new_user_session_path end test 'do not remember with expired token' do create_user_and_remember swap Devise, remember_for: 0.days do get users_path assert_not warden.authenticated?(:user) assert_redirected_to new_user_session_path end end test 'do not remember the user anymore after forget' do create_user_and_remember get users_path assert warden.authenticated?(:user) get destroy_user_session_path assert_not warden.authenticated?(:user) assert_nil warden.cookies['remember_user_token'] get users_path assert_not warden.authenticated?(:user) end test 'changing user password expires remember me token' do user = create_user_and_remember user.password = "another_password" user.password_confirmation = "another_password" user.save! get users_path assert_not warden.authenticated?(:user) end test 'valid sign in calls after_remembered callback' do user = create_user_and_remember User.expects(:serialize_from_cookie).returns user user.expects :after_remembered get new_user_registration_path end end devise-3.5.6/test/integration/authenticatable_test.rb0000644000004100000410000005376212663066463023110 0ustar www-datawww-datarequire 'test_helper' class AuthenticationSanityTest < ActionDispatch::IntegrationTest test 'home should be accessible without sign in' do visit '/' assert_response :success assert_template 'home/index' end test 'sign in as user should not authenticate admin scope' do sign_in_as_user assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) end test 'sign in as admin should not authenticate user scope' do sign_in_as_admin assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) end test 'sign in as both user and admin at same time' do sign_in_as_user sign_in_as_admin assert warden.authenticated?(:user) assert warden.authenticated?(:admin) end test 'sign out as user should not touch admin authentication if sign_out_all_scopes is false' do swap Devise, sign_out_all_scopes: false do sign_in_as_user sign_in_as_admin get destroy_user_session_path assert_not warden.authenticated?(:user) assert warden.authenticated?(:admin) end end test 'sign out as admin should not touch user authentication if sign_out_all_scopes is false' do swap Devise, sign_out_all_scopes: false do sign_in_as_user sign_in_as_admin get destroy_admin_session_path assert_not warden.authenticated?(:admin) assert warden.authenticated?(:user) end end test 'sign out as user should also sign out admin if sign_out_all_scopes is true' do swap Devise, sign_out_all_scopes: true do sign_in_as_user sign_in_as_admin get destroy_user_session_path assert_not warden.authenticated?(:user) assert_not warden.authenticated?(:admin) end end test 'sign out as admin should also sign out user if sign_out_all_scopes is true' do swap Devise, sign_out_all_scopes: true do sign_in_as_user sign_in_as_admin get destroy_admin_session_path assert_not warden.authenticated?(:admin) assert_not warden.authenticated?(:user) end end test 'not signed in as admin should not be able to access admins actions' do get admins_path assert_redirected_to new_admin_session_path assert_not warden.authenticated?(:admin) end test 'signed in as user should not be able to access admins actions' do sign_in_as_user assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) get admins_path assert_redirected_to new_admin_session_path end test 'signed in as admin should be able to access admin actions' do sign_in_as_admin assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) get admins_path assert_response :success assert_template 'admins/index' assert_contain 'Welcome Admin' end test 'authenticated admin should not be able to sign as admin again' do sign_in_as_admin get new_admin_session_path assert_response :redirect assert_redirected_to admin_root_path assert warden.authenticated?(:admin) end test 'authenticated admin should be able to sign out' do sign_in_as_admin assert warden.authenticated?(:admin) get destroy_admin_session_path assert_response :redirect assert_redirected_to root_path get root_path assert_contain 'Signed out successfully' assert_not warden.authenticated?(:admin) end test 'unauthenticated admin set message on sign out' do get destroy_admin_session_path assert_response :redirect assert_redirected_to root_path get root_path assert_contain 'Signed out successfully' end test 'scope uses custom failure app' do put "/en/accounts/management" assert_equal "Oops, not found", response.body assert_equal 404, response.status end end class AuthenticationRoutesRestrictions < ActionDispatch::IntegrationTest test 'not signed in should not be able to access private route (authenticate denied)' do get private_path assert_redirected_to new_admin_session_path assert_not warden.authenticated?(:admin) end test 'signed in as user should not be able to access private route restricted to admins (authenticate denied)' do sign_in_as_user assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) get private_path assert_redirected_to new_admin_session_path end test 'signed in as admin should be able to access private route restricted to admins (authenticate accepted)' do sign_in_as_admin assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) get private_path assert_response :success assert_template 'home/private' assert_contain 'Private!' end test 'signed in as inactive admin should not be able to access private/active route restricted to active admins (authenticate denied)' do sign_in_as_admin(active: false) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) assert_raises ActionController::RoutingError do get "/private/active" end end test 'signed in as active admin should be able to access private/active route restricted to active admins (authenticate accepted)' do sign_in_as_admin(active: true) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) get private_active_path assert_response :success assert_template 'home/private' assert_contain 'Private!' end test 'signed in as admin should get admin dashboard (authenticated accepted)' do sign_in_as_admin assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) get dashboard_path assert_response :success assert_template 'home/admin_dashboard' assert_contain 'Admin dashboard' end test 'signed in as user should get user dashboard (authenticated accepted)' do sign_in_as_user assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) get dashboard_path assert_response :success assert_template 'home/user_dashboard' assert_contain 'User dashboard' end test 'not signed in should get no dashboard (authenticated denied)' do assert_raises ActionController::RoutingError do get dashboard_path end end test 'signed in as inactive admin should not be able to access dashboard/active route restricted to active admins (authenticated denied)' do sign_in_as_admin(active: false) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) assert_raises ActionController::RoutingError do get "/dashboard/active" end end test 'signed in as active admin should be able to access dashboard/active route restricted to active admins (authenticated accepted)' do sign_in_as_admin(active: true) assert warden.authenticated?(:admin) assert_not warden.authenticated?(:user) get dashboard_active_path assert_response :success assert_template 'home/admin_dashboard' assert_contain 'Admin dashboard' end test 'signed in user should not see unauthenticated page (unauthenticated denied)' do sign_in_as_user assert warden.authenticated?(:user) assert_not warden.authenticated?(:admin) assert_raises ActionController::RoutingError do get join_path end end test 'not signed in users should see unautheticated page (unauthenticated accepted)' do get join_path assert_response :success assert_template 'home/join' assert_contain 'Join' end end class AuthenticationRedirectTest < ActionDispatch::IntegrationTest test 'redirect from warden shows sign in or sign up message' do get admins_path warden_path = new_admin_session_path assert_redirected_to warden_path get warden_path assert_contain 'You need to sign in or sign up before continuing.' end test 'redirect to default url if no other was configured' do sign_in_as_user assert_template 'home/index' assert_nil session[:"user_return_to"] end test 'redirect to requested url after sign in' do get users_path assert_redirected_to new_user_session_path assert_equal users_path, session[:"user_return_to"] follow_redirect! sign_in_as_user visit: false assert_current_url '/users' assert_nil session[:"user_return_to"] end test 'redirect to last requested url overwriting the stored return_to option' do get expire_user_path(create_user) assert_redirected_to new_user_session_path assert_equal expire_user_path(create_user), session[:"user_return_to"] get users_path assert_redirected_to new_user_session_path assert_equal users_path, session[:"user_return_to"] follow_redirect! sign_in_as_user visit: false assert_current_url '/users' assert_nil session[:"user_return_to"] end test 'xml http requests does not store urls for redirect' do get users_path, {}, 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest' assert_equal 401, response.status assert_nil session[:"user_return_to"] end test 'redirect to configured home path for a given scope after sign in' do sign_in_as_admin assert_equal "/admin_area/home", @request.path end test 'require_no_authentication should set the already_authenticated flash message' do sign_in_as_user visit new_user_session_path assert_equal flash[:alert], I18n.t("devise.failure.already_authenticated") end end class AuthenticationSessionTest < ActionDispatch::IntegrationTest test 'destroyed account is signed out' do sign_in_as_user get '/users' User.destroy_all get '/users' assert_redirected_to new_user_session_path end test 'refreshes _csrf_token' do ApplicationController.allow_forgery_protection = true begin get new_user_session_path token = request.session[:_csrf_token] sign_in_as_user assert_not_equal request.session[:_csrf_token], token ensure ApplicationController.allow_forgery_protection = false end end test 'allows session to be set for a given scope' do sign_in_as_user get '/users' assert_equal "Cart", @controller.user_session[:cart] end test 'does not explode when class name is still stored in session' do # In order to test that old sessions do not break with the new scoped # deserialization, we need to serialize the session the old way. This is # done by removing the newly used scoped serialization method # (#user_serialize) and bringing back the old uncsoped #serialize method # that includes the record's class name in the serialization. begin Warden::SessionSerializer.class_eval do alias_method :original_serialize, :serialize alias_method :original_user_serialize, :user_serialize remove_method :user_serialize def serialize(record) klass = record.class array = klass.serialize_into_session(record) array.unshift(klass.name) end end sign_in_as_user assert warden.authenticated?(:user) ensure Warden::SessionSerializer.class_eval do alias_method :serialize, :original_serialize remove_method :original_serialize alias_method :user_serialize, :original_user_serialize remove_method :original_user_serialize end end end test 'session id is changed on sign in' do get '/users' session_id = request.session["session_id"] get '/users' assert_equal session_id, request.session["session_id"] sign_in_as_user assert_not_equal session_id, request.session["session_id"] end end class AuthenticationWithScopedViewsTest < ActionDispatch::IntegrationTest test 'renders the scoped view if turned on and view is available' do swap Devise, scoped_views: true do assert_raise Webrat::NotFoundError do sign_in_as_user end assert_match /Special user view/, response.body end end test 'renders the scoped view if turned on in an specific controller' do begin Devise::SessionsController.scoped_views = true assert_raise Webrat::NotFoundError do sign_in_as_user end assert_match /Special user view/, response.body assert !Devise::PasswordsController.scoped_views? ensure Devise::SessionsController.send :remove_instance_variable, :@scoped_views end end test 'does not render the scoped view if turned off' do swap Devise, scoped_views: false do assert_nothing_raised do sign_in_as_user end end end test 'does not render the scoped view if not available' do swap Devise, scoped_views: true do assert_nothing_raised do sign_in_as_admin end end end end class AuthenticationOthersTest < ActionDispatch::IntegrationTest test 'handles unverified requests gets rid of caches' do swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) assert_not warden.authenticated?(:user) sign_in_as_user assert warden.authenticated?(:user) post exhibit_user_url(1) assert_not warden.authenticated?(:user) assert_equal "User is not authenticated", response.body end end test 'uses the custom controller with the custom controller view' do get '/admin_area/sign_in' assert_contain 'Log in' assert_contain 'Welcome to "admins/sessions" controller!' assert_contain 'Welcome to "sessions/new" view!' end test 'render 404 on roles without routes' do assert_raise ActionController::RoutingError do get '/admin_area/password/new' end end test 'does not intercept Rails 401 responses' do get '/unauthenticated' assert_equal 401, response.status end test 'render 404 on roles without mapping' do assert_raise AbstractController::ActionNotFound do get '/sign_in' end end test 'sign in with script name' do assert_nothing_raised do get new_user_session_path, {}, "SCRIPT_NAME" => "/omg" fill_in "email", with: "user@test.com" end end test 'sign in stub in xml format' do get new_user_session_path(format: 'xml') assert_match '', response.body assert_match /.*<\/user>/m, response.body assert_match '', response.body assert_match '\n) end test 'sign in with xml format is idempotent' do get new_user_session_path(format: 'xml') assert_response :success create_user post user_session_path(format: 'xml'), user: {email: "user@test.com", password: '12345678'} assert_response :success get new_user_session_path(format: 'xml') assert_response :success post user_session_path(format: 'xml'), user: {email: "user@test.com", password: '12345678'} assert_response :success assert response.body.include? %(\n) end test 'sign out with html redirects' do sign_in_as_user get destroy_user_session_path assert_response :redirect assert_current_url '/' sign_in_as_user get destroy_user_session_path(format: 'html') assert_response :redirect assert_current_url '/' end test 'sign out with xml format returns no content' do sign_in_as_user get destroy_user_session_path(format: 'xml') assert_response :no_content assert_not warden.authenticated?(:user) end test 'sign out with json format returns no content' do sign_in_as_user get destroy_user_session_path(format: 'json') assert_response :no_content assert_not warden.authenticated?(:user) end test 'sign out with non-navigational format via XHR does not redirect' do swap Devise, navigational_formats: ['*/*', :html] do sign_in_as_user xml_http_request :get, destroy_user_session_path, {}, { "HTTP_ACCEPT" => "application/json,text/javascript,*/*" } # NOTE: Bug is triggered by combination of XHR and */*. assert_response :no_content assert_not warden.authenticated?(:user) end end # Belt and braces ... Perhaps this test is not necessary? test 'sign out with navigational format via XHR does redirect' do swap Devise, navigational_formats: ['*/*', :html] do sign_in_as_user xml_http_request :get, destroy_user_session_path, {}, { "HTTP_ACCEPT" => "text/html,*/*" } assert_response :redirect assert_not warden.authenticated?(:user) end end end class AuthenticationKeysTest < ActionDispatch::IntegrationTest test 'missing authentication keys cause authentication to abort' do swap Devise, authentication_keys: [:subdomain] do sign_in_as_user assert_contain "Invalid subdomain or password." assert_not warden.authenticated?(:user) end end test 'missing authentication keys cause authentication to abort unless marked as not required' do swap Devise, authentication_keys: { email: true, subdomain: false } do sign_in_as_user assert warden.authenticated?(:user) end end end class AuthenticationRequestKeysTest < ActionDispatch::IntegrationTest test 'request keys are used on authentication' do host! 'foo.bar.baz' swap Devise, request_keys: [:subdomain] do User.expects(:find_for_authentication).with(subdomain: 'foo', email: 'user@test.com').returns(create_user) sign_in_as_user assert warden.authenticated?(:user) end end test 'invalid request keys raises NoMethodError' do swap Devise, request_keys: [:unknown_method] do assert_raise NoMethodError do sign_in_as_user end assert_not warden.authenticated?(:user) end end test 'blank request keys cause authentication to abort' do host! 'test.com' swap Devise, request_keys: [:subdomain] do sign_in_as_user assert_contain "Invalid email or password." assert_not warden.authenticated?(:user) end end test 'blank request keys cause authentication to abort unless if marked as not required' do host! 'test.com' swap Devise, request_keys: { subdomain: false } do sign_in_as_user assert warden.authenticated?(:user) end end end class AuthenticationSignOutViaTest < ActionDispatch::IntegrationTest def sign_in!(scope) sign_in_as_admin(visit: send("new_#{scope}_session_path")) assert warden.authenticated?(scope) end test 'allow sign out via delete when sign_out_via provides only delete' do sign_in!(:sign_out_via_delete) delete destroy_sign_out_via_delete_session_path assert_not warden.authenticated?(:sign_out_via_delete) end test 'do not allow sign out via get when sign_out_via provides only delete' do sign_in!(:sign_out_via_delete) assert_raise ActionController::RoutingError do get destroy_sign_out_via_delete_session_path end assert warden.authenticated?(:sign_out_via_delete) end test 'allow sign out via post when sign_out_via provides only post' do sign_in!(:sign_out_via_post) post destroy_sign_out_via_post_session_path assert_not warden.authenticated?(:sign_out_via_post) end test 'do not allow sign out via get when sign_out_via provides only post' do sign_in!(:sign_out_via_post) assert_raise ActionController::RoutingError do get destroy_sign_out_via_delete_session_path end assert warden.authenticated?(:sign_out_via_post) end test 'allow sign out via delete when sign_out_via provides delete and post' do sign_in!(:sign_out_via_delete_or_post) delete destroy_sign_out_via_delete_or_post_session_path assert_not warden.authenticated?(:sign_out_via_delete_or_post) end test 'allow sign out via post when sign_out_via provides delete and post' do sign_in!(:sign_out_via_delete_or_post) post destroy_sign_out_via_delete_or_post_session_path assert_not warden.authenticated?(:sign_out_via_delete_or_post) end test 'do not allow sign out via get when sign_out_via provides delete and post' do sign_in!(:sign_out_via_delete_or_post) assert_raise ActionController::RoutingError do get destroy_sign_out_via_delete_or_post_session_path end assert warden.authenticated?(:sign_out_via_delete_or_post) end end class DoubleAuthenticationRedirectTest < ActionDispatch::IntegrationTest test 'signed in as user redirects when visiting user sign in page' do sign_in_as_user get new_user_session_path(format: :html) assert_redirected_to '/' end test 'signed in as admin redirects when visiting admin sign in page' do sign_in_as_admin get new_admin_session_path(format: :html) assert_redirected_to '/admin_area/home' end test 'signed in as both user and admin redirects when visiting admin sign in page' do sign_in_as_user sign_in_as_admin get new_user_session_path(format: :html) assert_redirected_to '/' get new_admin_session_path(format: :html) assert_redirected_to '/admin_area/home' end end class DoubleSignOutRedirectTest < ActionDispatch::IntegrationTest test 'sign out after already having signed out redirects to sign in' do sign_in_as_user post destroy_sign_out_via_delete_or_post_session_path get root_path assert_contain 'Signed out successfully.' post destroy_sign_out_via_delete_or_post_session_path get root_path assert_contain 'Signed out successfully.' end end devise-3.5.6/test/integration/registerable_test.rb0000644000004100000410000003155512663066463022417 0ustar www-datawww-datarequire 'test_helper' class RegistrationTest < ActionDispatch::IntegrationTest test 'a guest admin should be able to sign in successfully' do get new_admin_session_path click_link 'Sign up' assert_template 'registrations/new' fill_in 'email', with: 'new_user@test.com' fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_contain 'You have signed up successfully' assert warden.authenticated?(:admin) assert_current_url "/admin_area/home" admin = Admin.to_adapter.find_first(order: [:id, :desc]) assert_equal admin.email, 'new_user@test.com' end test 'a guest admin should be able to sign in and be redirected to a custom location' do Devise::RegistrationsController.any_instance.stubs(:after_sign_up_path_for).returns("/?custom=1") get new_admin_session_path click_link 'Sign up' fill_in 'email', with: 'new_user@test.com' fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_contain 'Welcome! You have signed up successfully.' assert warden.authenticated?(:admin) assert_current_url "/?custom=1" end test 'a guest admin should not see a warning about minimum password length' do get new_admin_session_path assert_not_contain 'characters minimum' end def user_sign_up ActionMailer::Base.deliveries.clear get new_user_registration_path fill_in 'email', with: 'new_user@test.com' fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' end test 'a guest user should see a warning about minimum password length' do get new_user_registration_path assert_contain '7 characters minimum' end test 'a guest user should be able to sign up successfully and be blocked by confirmation' do user_sign_up assert_contain 'A message with a confirmation link has been sent to your email address. Please follow the link to activate your account.' assert_not_contain 'You have to confirm your account before continuing' assert_current_url "/" assert_not warden.authenticated?(:user) user = User.to_adapter.find_first(order: [:id, :desc]) assert_equal user.email, 'new_user@test.com' assert_not user.confirmed? end test 'a guest user should receive the confirmation instructions from the default mailer' do user_sign_up assert_equal ['please-change-me@config-initializers-devise.com'], ActionMailer::Base.deliveries.first.from end test 'a guest user should receive the confirmation instructions from a custom mailer' do User.any_instance.stubs(:devise_mailer).returns(Users::Mailer) user_sign_up assert_equal ['custom@example.com'], ActionMailer::Base.deliveries.first.from end test 'a guest user should be blocked by confirmation and redirected to a custom path' do Devise::RegistrationsController.any_instance.stubs(:after_inactive_sign_up_path_for).returns("/?custom=1") get new_user_registration_path fill_in 'email', with: 'new_user@test.com' fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_current_url "/?custom=1" assert_not warden.authenticated?(:user) end test 'a guest user cannot sign up with invalid information' do # Dirty tracking behavior prevents email validations from being applied: # https://github.com/mongoid/mongoid/issues/756 (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1 get new_user_registration_path fill_in 'email', with: 'invalid_email' fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user321' click_button 'Sign up' assert_template 'registrations/new' assert_have_selector '#error_explanation' assert_contain "Email is invalid" assert_contain Devise.rails4? ? "Password confirmation doesn't match Password" : "Password doesn't match confirmation" assert_contain "2 errors prohibited" assert_nil User.to_adapter.find_first assert_not warden.authenticated?(:user) end test 'a guest should not sign up with email/password that already exists' do # Dirty tracking behavior prevents email validations from being applied: # https://github.com/mongoid/mongoid/issues/756 (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1 create_user get new_user_registration_path fill_in 'email', with: 'user@test.com' fill_in 'password', with: '123456' fill_in 'password confirmation', with: '123456' click_button 'Sign up' assert_current_url '/users' assert_contain(/Email.*already.*taken/) assert_not warden.authenticated?(:user) end test 'a guest should not be able to change account' do get edit_user_registration_path assert_redirected_to new_user_session_path follow_redirect! assert_contain 'You need to sign in or sign up before continuing.' end test 'a signed in user should not be able to access sign up' do sign_in_as_user get new_user_registration_path assert_redirected_to root_path end test 'a signed in user should be able to edit their account' do sign_in_as_user get edit_user_registration_path fill_in 'email', with: 'user.new@example.com' fill_in 'current password', with: '12345678' click_button 'Update' assert_current_url '/' assert_contain 'Your account has been updated successfully.' assert_equal "user.new@example.com", User.to_adapter.find_first.email end test 'a signed in user should still be able to use the website after changing their password' do sign_in_as_user get edit_user_registration_path fill_in 'password', with: '1234567890' fill_in 'password confirmation', with: '1234567890' fill_in 'current password', with: '12345678' click_button 'Update' assert_contain 'Your account has been updated successfully.' get users_path assert warden.authenticated?(:user) end test 'a signed in user should not change their current user with invalid password' do sign_in_as_user get edit_user_registration_path fill_in 'email', with: 'user.new@example.com' fill_in 'current password', with: 'invalid' click_button 'Update' assert_template 'registrations/edit' assert_contain 'user@test.com' assert_have_selector 'form input[value="user.new@example.com"]' assert_equal "user@test.com", User.to_adapter.find_first.email end test 'a signed in user should be able to edit their password' do sign_in_as_user get edit_user_registration_path fill_in 'password', with: 'pass1234' fill_in 'password confirmation', with: 'pass1234' fill_in 'current password', with: '12345678' click_button 'Update' assert_current_url '/' assert_contain 'Your account has been updated successfully.' assert User.to_adapter.find_first.valid_password?('pass1234') end test 'a signed in user should not be able to edit their password with invalid confirmation' do sign_in_as_user get edit_user_registration_path fill_in 'password', with: 'pas123' fill_in 'password confirmation', with: '' fill_in 'current password', with: '12345678' click_button 'Update' assert_contain Devise.rails4? ? "Password confirmation doesn't match Password" : "Password doesn't match confirmation" assert_not User.to_adapter.find_first.valid_password?('pas123') end test 'a signed in user should be able to cancel their account' do sign_in_as_user get edit_user_registration_path click_button "Cancel my account" assert_contain "Bye! Your account has been successfully cancelled. We hope to see you again soon." assert User.to_adapter.find_all.empty? end test 'a user should be able to cancel sign up by deleting data in the session' do get "/set" assert_equal "something", @request.session["devise.foo_bar"] get "/users/sign_up" assert_equal "something", @request.session["devise.foo_bar"] get "/users/cancel" assert_nil @request.session["devise.foo_bar"] assert_redirected_to new_user_registration_path end test 'a user with XML sign up stub' do get new_user_registration_path(format: 'xml') assert_response :success assert_match %(\n), response.body assert_no_match(/\n) admin = Admin.to_adapter.find_first(order: [:id, :desc]) assert_equal admin.email, 'new_user@test.com' end test 'a user sign up with valid information in XML format should return valid response' do post user_registration_path(format: 'xml'), user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'new_user123' } assert_response :success assert response.body.include? %(\n) user = User.to_adapter.find_first(order: [:id, :desc]) assert_equal user.email, 'new_user@test.com' end test 'a user sign up with invalid information in XML format should return invalid response' do post user_registration_path(format: 'xml'), user: { email: 'new_user@test.com', password: 'new_user123', password_confirmation: 'invalid' } assert_response :unprocessable_entity assert response.body.include? %(\n) end test 'a user update information with valid data in XML format should return valid response' do user = sign_in_as_user put user_registration_path(format: 'xml'), user: { current_password: '12345678', email: 'user.new@test.com' } assert_response :success assert_equal user.reload.email, 'user.new@test.com' end test 'a user update information with invalid data in XML format should return invalid response' do user = sign_in_as_user put user_registration_path(format: 'xml'), user: { current_password: 'invalid', email: 'user.new@test.com' } assert_response :unprocessable_entity assert_equal user.reload.email, 'user@test.com' end test 'a user cancel their account in XML format should return valid response' do sign_in_as_user delete user_registration_path(format: 'xml') assert_response :success assert_equal User.to_adapter.find_all.size, 0 end end class ReconfirmableRegistrationTest < ActionDispatch::IntegrationTest test 'a signed in admin should see a more appropriate flash message when editing their account if reconfirmable is enabled' do sign_in_as_admin get edit_admin_registration_path fill_in 'email', with: 'admin.new@example.com' fill_in 'current password', with: '123456' click_button 'Update' assert_current_url '/admin_area/home' assert_contain 'but we need to verify your new email address' assert_equal 'admin.new@example.com', Admin.to_adapter.find_first.unconfirmed_email get edit_admin_registration_path assert_contain 'Currently waiting confirmation for: admin.new@example.com' end test 'a signed in admin should not see a reconfirmation message if they did not change their password' do sign_in_as_admin get edit_admin_registration_path fill_in 'password', with: 'pas123' fill_in 'password confirmation', with: 'pas123' fill_in 'current password', with: '123456' click_button 'Update' assert_current_url '/admin_area/home' assert_contain 'Your account has been updated successfully.' assert Admin.to_adapter.find_first.valid_password?('pas123') end test 'a signed in admin should not see a reconfirmation message if they did not change their email, despite having an unconfirmed email' do sign_in_as_admin get edit_admin_registration_path fill_in 'email', with: 'admin.new@example.com' fill_in 'current password', with: '123456' click_button 'Update' get edit_admin_registration_path fill_in 'password', with: 'pas123' fill_in 'password confirmation', with: 'pas123' fill_in 'current password', with: '123456' click_button 'Update' assert_current_url '/admin_area/home' assert_contain 'Your account has been updated successfully.' assert_equal "admin.new@example.com", Admin.to_adapter.find_first.unconfirmed_email assert Admin.to_adapter.find_first.valid_password?('pas123') end end devise-3.5.6/test/integration/database_authenticatable_test.rb0000644000004100000410000000542212663066463024722 0ustar www-datawww-datarequire 'test_helper' class DatabaseAuthenticationTest < ActionDispatch::IntegrationTest test 'sign in with email of different case should succeed when email is in the list of case insensitive keys' do create_user(email: 'Foo@Bar.com') sign_in_as_user do fill_in 'email', with: 'foo@bar.com' end assert warden.authenticated?(:user) end test 'sign in with email of different case should fail when email is NOT the list of case insensitive keys' do swap Devise, case_insensitive_keys: [] do create_user(email: 'Foo@Bar.com') sign_in_as_user do fill_in 'email', with: 'foo@bar.com' end assert_not warden.authenticated?(:user) end end test 'sign in with email including extra spaces should succeed when email is in the list of strip whitespace keys' do create_user(email: ' foo@bar.com ') sign_in_as_user do fill_in 'email', with: 'foo@bar.com' end assert warden.authenticated?(:user) end test 'sign in with email including extra spaces should fail when email is NOT the list of strip whitespace keys' do swap Devise, strip_whitespace_keys: [] do create_user(email: 'foo@bar.com') sign_in_as_user do fill_in 'email', with: ' foo@bar.com ' end assert_not warden.authenticated?(:user) end end test 'sign in should not authenticate if not using proper authentication keys' do swap Devise, authentication_keys: [:username] do sign_in_as_user assert_not warden.authenticated?(:user) end end test 'sign in with invalid email should return to sign in form with error message' do store_translations :en, devise: { failure: { admin: { not_found_in_database: 'Invalid email address' } } } do sign_in_as_admin do fill_in 'email', with: 'wrongemail@test.com' end assert_contain 'Invalid email address' assert_not warden.authenticated?(:admin) end end test 'sign in with invalid pasword should return to sign in form with error message' do sign_in_as_admin do fill_in 'password', with: 'abcdef' end assert_contain 'Invalid email or password' assert_not warden.authenticated?(:admin) end test 'error message is configurable by resource name' do store_translations :en, devise: { failure: { admin: { invalid: "Invalid credentials" } } } do sign_in_as_admin do fill_in 'password', with: 'abcdef' end assert_contain 'Invalid credentials' end end test 'valid sign in calls after_database_authentication callback' do user = create_user(email: ' foo@bar.com ') User.expects(:find_for_database_authentication).returns user user.expects :after_database_authentication sign_in_as_user do fill_in 'email', with: 'foo@bar.com' end end end devise-3.5.6/test/routes_test.rb0000644000004100000410000003005512663066463016737 0ustar www-datawww-datarequire 'test_helper' ExpectedRoutingError = Devise.rails4? ? MiniTest::Assertion : ActionController::RoutingError class DefaultRoutingTest < ActionController::TestCase test 'map new user session' do assert_recognizes({controller: 'devise/sessions', action: 'new'}, {path: 'users/sign_in', method: :get}) assert_named_route "/users/sign_in", :new_user_session_path end test 'map create user session' do assert_recognizes({controller: 'devise/sessions', action: 'create'}, {path: 'users/sign_in', method: :post}) assert_named_route "/users/sign_in", :user_session_path end test 'map destroy user session' do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: 'users/sign_out', method: :get}) assert_named_route "/users/sign_out", :destroy_user_session_path end test 'map new user confirmation' do assert_recognizes({controller: 'devise/confirmations', action: 'new'}, 'users/confirmation/new') assert_named_route "/users/confirmation/new", :new_user_confirmation_path end test 'map create user confirmation' do assert_recognizes({controller: 'devise/confirmations', action: 'create'}, {path: 'users/confirmation', method: :post}) assert_named_route "/users/confirmation", :user_confirmation_path end test 'map show user confirmation' do assert_recognizes({controller: 'devise/confirmations', action: 'show'}, {path: 'users/confirmation', method: :get}) end test 'map new user password' do assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'users/password/new') assert_named_route "/users/password/new", :new_user_password_path end test 'map create user password' do assert_recognizes({controller: 'devise/passwords', action: 'create'}, {path: 'users/password', method: :post}) assert_named_route "/users/password", :user_password_path end test 'map edit user password' do assert_recognizes({controller: 'devise/passwords', action: 'edit'}, 'users/password/edit') assert_named_route "/users/password/edit", :edit_user_password_path end test 'map update user password' do assert_recognizes({controller: 'devise/passwords', action: 'update'}, {path: 'users/password', method: :put}) end test 'map new user unlock' do assert_recognizes({controller: 'devise/unlocks', action: 'new'}, 'users/unlock/new') assert_named_route "/users/unlock/new", :new_user_unlock_path end test 'map create user unlock' do assert_recognizes({controller: 'devise/unlocks', action: 'create'}, {path: 'users/unlock', method: :post}) assert_named_route "/users/unlock", :user_unlock_path end test 'map show user unlock' do assert_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: 'users/unlock', method: :get}) end test 'map new user registration' do assert_recognizes({controller: 'devise/registrations', action: 'new'}, 'users/sign_up') assert_named_route "/users/sign_up", :new_user_registration_path end test 'map create user registration' do assert_recognizes({controller: 'devise/registrations', action: 'create'}, {path: 'users', method: :post}) assert_named_route "/users", :user_registration_path end test 'map edit user registration' do assert_recognizes({controller: 'devise/registrations', action: 'edit'}, {path: 'users/edit', method: :get}) assert_named_route "/users/edit", :edit_user_registration_path end test 'map update user registration' do assert_recognizes({controller: 'devise/registrations', action: 'update'}, {path: 'users', method: :put}) end test 'map destroy user registration' do assert_recognizes({controller: 'devise/registrations', action: 'destroy'}, {path: 'users', method: :delete}) end test 'map cancel user registration' do assert_recognizes({controller: 'devise/registrations', action: 'cancel'}, {path: 'users/cancel', method: :get}) assert_named_route "/users/cancel", :cancel_user_registration_path end test 'map omniauth callbacks' do assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :get}) assert_recognizes({controller: 'users/omniauth_callbacks', action: 'facebook'}, {path: 'users/auth/facebook/callback', method: :post}) assert_named_route "/users/auth/facebook/callback", :user_omniauth_callback_path, :facebook # named open_id assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :get}) assert_recognizes({controller: 'users/omniauth_callbacks', action: 'google'}, {path: 'users/auth/google/callback', method: :post}) assert_named_route "/users/auth/google/callback", :user_omniauth_callback_path, :google assert_raise ExpectedRoutingError do assert_recognizes({controller: 'ysers/omniauth_callbacks', action: 'twitter'}, {path: 'users/auth/twitter/callback', method: :get}) end end protected def assert_named_route(result, *args) assert_equal result, @routes.url_helpers.send(*args) end end class CustomizedRoutingTest < ActionController::TestCase test 'map admin with :path option' do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'admin_area/sign_up', method: :get}) end test 'map admin with :controllers option' do assert_recognizes({controller: 'admins/sessions', action: 'new'}, {path: 'admin_area/sign_in', method: :get}) end test 'does not map admin password' do assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'admin_area/password/new') end end test 'subdomain admin' do assert_recognizes({"host"=>"sub.example.com", controller: 'devise/sessions', action: 'new'}, {host: "sub.example.com", path: '/sub_admin/sign_in', method: :get}) end test 'does only map reader password' do assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/sessions', action: 'new'}, 'reader/sessions/new') end assert_recognizes({controller: 'devise/passwords', action: 'new'}, 'reader/password/new') end test 'map account with custom path name for session sign in' do assert_recognizes({controller: 'devise/sessions', action: 'new', locale: 'en'}, '/en/accounts/login') end test 'map account with custom path name for session sign out' do assert_recognizes({controller: 'devise/sessions', action: 'destroy', locale: 'en'}, '/en/accounts/logout') end test 'map account with custom path name for password' do assert_recognizes({controller: 'devise/passwords', action: 'new', locale: 'en'}, '/en/accounts/secret/new') end test 'map account with custom path name for registration' do assert_recognizes({controller: 'devise/registrations', action: 'new', locale: 'en'}, '/en/accounts/management/register') end test 'map account with custom path name for edit registration' do assert_recognizes({controller: 'devise/registrations', action: 'edit', locale: 'en'}, '/en/accounts/management/edit/profile') end test 'map account with custom path name for cancel registration' do assert_recognizes({controller: 'devise/registrations', action: 'cancel', locale: 'en'}, '/en/accounts/management/giveup') end test 'map deletes with :sign_out_via option' do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/deletes/sign_out', method: :delete}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/deletes/sign_out', method: :get}) end end test 'map posts with :sign_out_via option' do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :post}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/posts/sign_out', method: :get}) end end test 'map delete_or_posts with :sign_out_via option' do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :post}) assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :delete}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/sessions', action: 'destroy'}, {path: '/sign_out_via/delete_or_posts/sign_out', method: :get}) end end test 'map with constraints defined in hash' do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://192.168.1.100/headquarters/sign_up', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://10.0.0.100/headquarters/sign_up', method: :get}) end end test 'map with constraints defined in block' do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://192.168.1.100/homebase/sign_up', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: 'http://10.0.0.100//homebase/sign_up', method: :get}) end end test 'map with format false for sessions' do assert_recognizes({controller: 'devise/sessions', action: 'new'}, {path: '/htmlonly_admin/sign_in', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/sessions', action: 'new'}, {path: '/htmlonly_admin/sign_in.xml', method: :get}) end end test 'map with format false for passwords' do assert_recognizes({controller: 'devise/passwords', action: 'create'}, {path: '/htmlonly_admin/password', method: :post}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/passwords', action: 'create'}, {path: '/htmlonly_admin/password.xml', method: :post}) end end test 'map with format false for registrations' do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: '/htmlonly_admin/sign_up', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/registrations', action: 'new'}, {path: '/htmlonly_admin/sign_up.xml', method: :get}) end end test 'map with format false for confirmations' do assert_recognizes({controller: 'devise/confirmations', action: 'show'}, {path: '/htmlonly_users/confirmation', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/confirmations', action: 'show'}, {path: '/htmlonly_users/confirmation.xml', method: :get}) end end test 'map with format false for unlocks' do assert_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: '/htmlonly_users/unlock', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes({controller: 'devise/unlocks', action: 'show'}, {path: '/htmlonly_users/unlock.xml', method: :get}) end end test 'map with format false is not permanent' do assert_equal "/set.xml", @routes.url_helpers.set_path(:xml) end test 'checks if mapping has proper configuration for omniauth callback' do e = assert_raise ArgumentError do routes = ActionDispatch::Routing::RouteSet.new routes.draw do devise_for :not_omniauthable, class_name: 'Admin', controllers: {omniauth_callbacks: "users/omniauth_callbacks"} end end assert_match "Mapping omniauth_callbacks on a resource that is not omniauthable", e.message end end class ScopedRoutingTest < ActionController::TestCase test 'map publisher account' do assert_recognizes({controller: 'publisher/registrations', action: 'new'}, {path: '/publisher/accounts/sign_up', method: :get}) assert_equal '/publisher/accounts/sign_up', @routes.url_helpers.new_publisher_account_registration_path end test 'map publisher account merges path names' do assert_recognizes({controller: 'publisher/sessions', action: 'new'}, {path: '/publisher/accounts/get_in', method: :get}) assert_equal '/publisher/accounts/get_in', @routes.url_helpers.new_publisher_account_session_path end end devise-3.5.6/test/models/0000755000004100000410000000000012663066463015312 5ustar www-datawww-datadevise-3.5.6/test/models/trackable_test.rb0000644000004100000410000000226512663066463020633 0ustar www-datawww-datarequire 'test_helper' class TrackableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do assert_same_content Devise::Models::Trackable.required_fields(User), [ :current_sign_in_at, :current_sign_in_ip, :last_sign_in_at, :last_sign_in_ip, :sign_in_count ] end test 'update_tracked_fields should only set attributes but not save the record' do user = create_user request = mock request.stubs(:remote_ip).returns("127.0.0.1") assert_nil user.current_sign_in_ip assert_nil user.last_sign_in_ip assert_nil user.current_sign_in_at assert_nil user.last_sign_in_at assert_equal 0, user.sign_in_count user.update_tracked_fields(request) assert_equal "127.0.0.1", user.current_sign_in_ip assert_equal "127.0.0.1", user.last_sign_in_ip assert_not_nil user.current_sign_in_at assert_not_nil user.last_sign_in_at assert_equal 1, user.sign_in_count user.reload assert_nil user.current_sign_in_ip assert_nil user.last_sign_in_ip assert_nil user.current_sign_in_at assert_nil user.last_sign_in_at assert_equal 0, user.sign_in_count end end devise-3.5.6/test/models/timeoutable_test.rb0000644000004100000410000000266212663066463021216 0ustar www-datawww-datarequire 'test_helper' class TimeoutableTest < ActiveSupport::TestCase test 'should be expired' do assert new_user.timedout?(31.minutes.ago) end test 'should not be expired' do assert_not new_user.timedout?(29.minutes.ago) end test 'should not be expired when params is nil' do assert_not new_user.timedout?(nil) end test 'should use timeout_in method' do user = new_user user.instance_eval { def timeout_in; 10.minutes end } assert user.timedout?(12.minutes.ago) assert_not user.timedout?(8.minutes.ago) end test 'should not be expired when timeout_in method returns nil' do user = new_user user.instance_eval { def timeout_in; nil end } assert_not user.timedout?(10.hours.ago) end test 'fallback to Devise config option' do swap Devise, timeout_in: 1.minute do user = new_user assert user.timedout?(2.minutes.ago) assert_not user.timedout?(30.seconds.ago) Devise.timeout_in = 5.minutes assert_not user.timedout?(2.minutes.ago) assert user.timedout?(6.minutes.ago) end end test 'required_fields should contain the fields that Devise uses' do assert_same_content Devise::Models::Timeoutable.required_fields(User), [] end test 'should not raise error if remember_created_at is not empty and rememberable is disabled' do user = create_admin(remember_created_at: Time.current) assert user.timedout?(31.minutes.ago) end end devise-3.5.6/test/models/recoverable_test.rb0000644000004100000410000002063212663066463021172 0ustar www-datawww-datarequire 'test_helper' class RecoverableTest < ActiveSupport::TestCase def setup setup_mailer end test 'should not generate reset password token after creating a record' do assert_nil new_user.reset_password_token end test 'should never generate the same reset password token for different users' do reset_password_tokens = [] 3.times do user = create_user user.send_reset_password_instructions token = user.reset_password_token assert !reset_password_tokens.include?(token) reset_password_tokens << token end end test 'should reset password and password confirmation from params' do user = create_user user.reset_password('123456789', '987654321') assert_equal '123456789', user.password assert_equal '987654321', user.password_confirmation end test 'should reset password and save the record' do assert create_user.reset_password('123456789', '123456789') end test 'should clear reset password token while reseting the password' do user = create_user assert_nil user.reset_password_token user.send_reset_password_instructions assert_present user.reset_password_token assert user.reset_password('123456789', '123456789') assert_nil user.reset_password_token end test 'should not clear reset password token for new user' do user = new_user assert_nil user.reset_password_token user.send_reset_password_instructions assert_present user.reset_password_token user.save assert_present user.reset_password_token end test 'should clear reset password token if changing password' do user = create_user assert_nil user.reset_password_token user.send_reset_password_instructions assert_present user.reset_password_token user.password = "123456678" user.password_confirmation = "123456678" user.save! assert_nil user.reset_password_token end test 'should clear reset password token if changing email' do user = create_user assert_nil user.reset_password_token user.send_reset_password_instructions assert_present user.reset_password_token user.email = "another@example.com" user.save! assert_nil user.reset_password_token end test 'should clear reset password successfully even if there is no email' do user = create_user_without_email assert_nil user.reset_password_token user.send_reset_password_instructions assert_present user.reset_password_token user.password = "123456678" user.password_confirmation = "123456678" user.save! assert_nil user.reset_password_token end test 'should not clear reset password token if record is invalid' do user = create_user user.send_reset_password_instructions assert_present user.reset_password_token assert_not user.reset_password('123456789', '987654321') assert_present user.reset_password_token end test 'should not reset password with invalid data' do user = create_user user.stubs(:valid?).returns(false) assert_not user.reset_password('123456789', '987654321') end test 'should reset reset password token and send instructions by email' do user = create_user assert_email_sent do token = user.reset_password_token user.send_reset_password_instructions assert_not_equal token, user.reset_password_token end end test 'should find a user to send instructions by email' do user = create_user reset_password_user = User.send_reset_password_instructions(email: user.email) assert_equal reset_password_user, user end test 'should return a new record with errors if user was not found by e-mail' do reset_password_user = User.send_reset_password_instructions(email: "invalid@example.com") assert_not reset_password_user.persisted? assert_equal "not found", reset_password_user.errors[:email].join end test 'should find a user to send instructions by authentication_keys' do swap Devise, authentication_keys: [:username, :email] do user = create_user reset_password_user = User.send_reset_password_instructions(email: user.email, username: user.username) assert_equal reset_password_user, user end end test 'should require all reset_password_keys' do swap Devise, reset_password_keys: [:username, :email] do user = create_user reset_password_user = User.send_reset_password_instructions(email: user.email) assert_not reset_password_user.persisted? assert_equal "can't be blank", reset_password_user.errors[:username].join end end test 'should reset reset_password_token before send the reset instructions email' do user = create_user token = user.reset_password_token User.send_reset_password_instructions(email: user.email) assert_not_equal token, user.reload.reset_password_token end test 'should send email instructions to the user reset their password' do user = create_user assert_email_sent do User.send_reset_password_instructions(email: user.email) end end test 'should find a user to reset their password based on the raw token' do user = create_user raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token(reset_password_token: raw) assert_equal reset_password_user, user end test 'should return a new record with errors if no reset_password_token is found' do reset_password_user = User.reset_password_by_token(reset_password_token: 'invalid_token') assert_not reset_password_user.persisted? assert_equal "is invalid", reset_password_user.errors[:reset_password_token].join end test 'should return a new record with errors if reset_password_token is blank' do reset_password_user = User.reset_password_by_token(reset_password_token: '') assert_not reset_password_user.persisted? assert_match "can't be blank", reset_password_user.errors[:reset_password_token].join end test 'should return a new record with errors if password is blank' do user = create_user raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token(reset_password_token: raw, password: '') assert_not reset_password_user.errors.empty? assert_match "can't be blank", reset_password_user.errors[:password].join assert_equal raw, reset_password_user.reset_password_token end test 'should reset successfully user password given the new password and confirmation' do user = create_user old_password = user.password raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token( reset_password_token: raw, password: 'new_password', password_confirmation: 'new_password' ) assert_nil reset_password_user.reset_password_token user.reload assert_not user.valid_password?(old_password) assert user.valid_password?('new_password') assert_nil user.reset_password_token end test 'should not reset password after reset_password_within time' do swap Devise, reset_password_within: 1.hour do user = create_user raw = user.send_reset_password_instructions old_password = user.password user.reset_password_sent_at = 2.days.ago user.save! reset_password_user = User.reset_password_by_token( reset_password_token: raw, password: 'new_password', password_confirmation: 'new_password' ) user.reload assert user.valid_password?(old_password) assert_not user.valid_password?('new_password') assert_equal "has expired, please request a new one", reset_password_user.errors[:reset_password_token].join end end test 'required_fields should contain the fields that Devise uses' do assert_same_content Devise::Models::Recoverable.required_fields(User), [ :reset_password_sent_at, :reset_password_token ] end test 'should return a user based on the raw token' do user = create_user raw = user.send_reset_password_instructions assert_equal User.with_reset_password_token(raw), user end test 'should return the same reset password token as generated' do user = create_user raw = user.send_reset_password_instructions assert_equal Devise.token_generator.digest(self.class, :reset_password_token, raw), user.reset_password_token end test 'should return nil if a user based on the raw token is not found' do assert_equal User.with_reset_password_token('random-token'), nil end end devise-3.5.6/test/models/lockable_test.rb0000644000004100000410000002401012663066463020447 0ustar www-datawww-datarequire 'test_helper' class LockableTest < ActiveSupport::TestCase def setup setup_mailer end test "should respect maximum attempts configuration" do user = create_user user.confirm swap Devise, maximum_attempts: 2 do 2.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end end test "should increment failed_attempts on successful validation if the user is already locked" do user = create_user user.confirm swap Devise, maximum_attempts: 2 do 2.times { user.valid_for_authentication?{ false } } assert user.reload.access_locked? end user.valid_for_authentication?{ true } assert_equal 3, user.reload.failed_attempts end test "should not touch failed_attempts if lock_strategy is none" do user = create_user user.confirm swap Devise, lock_strategy: :none, maximum_attempts: 2 do 3.times { user.valid_for_authentication?{ false } } assert !user.access_locked? assert_equal 0, user.failed_attempts end end test 'should be valid for authentication with a unlocked user' do user = create_user user.lock_access! user.unlock_access! assert user.valid_for_authentication?{ true } end test "should verify whether a user is locked or not" do user = create_user assert_not user.access_locked? user.lock_access! assert user.access_locked? end test "active_for_authentication? should be the opposite of locked?" do user = create_user user.confirm assert user.active_for_authentication? user.lock_access! assert_not user.active_for_authentication? end test "should unlock a user by cleaning locked_at, failed_attempts and unlock_token" do user = create_user user.lock_access! assert_not_nil user.reload.locked_at assert_not_nil user.reload.unlock_token user.unlock_access! assert_nil user.reload.locked_at assert_nil user.reload.unlock_token assert_equal 0, user.reload.failed_attempts end test "new user should not be locked and should have zero failed_attempts" do assert_not new_user.access_locked? assert_equal 0, create_user.failed_attempts end test "should unlock user after unlock_in period" do swap Devise, unlock_in: 3.hours do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? Devise.unlock_in = 1.hour assert_not user.access_locked? end end test "should not unlock in 'unlock_in' if :time unlock strategy is not set" do swap Devise, unlock_strategy: :email do user = new_user user.locked_at = 2.hours.ago assert user.access_locked? end end test "should set unlock_token when locking" do user = create_user assert_nil user.unlock_token user.lock_access! assert_not_nil user.unlock_token end test "should never generate the same unlock token for different users" do unlock_tokens = [] 3.times do user = create_user user.lock_access! token = user.unlock_token assert !unlock_tokens.include?(token) unlock_tokens << token end end test "should not generate unlock_token when :email is not an unlock strategy" do swap Devise, unlock_strategy: :time do user = create_user user.lock_access! assert_nil user.unlock_token end end test "should send email with unlock instructions when :email is an unlock strategy" do swap Devise, unlock_strategy: :email do user = create_user assert_email_sent do user.lock_access! end end end test "doesn't send email when you pass option send_instructions to false" do swap Devise, unlock_strategy: :email do user = create_user assert_email_not_sent do user.lock_access! send_instructions: false end end end test "sends email when you pass options other than send_instructions" do swap Devise, unlock_strategy: :email do user = create_user assert_email_sent do user.lock_access! foo: :bar, bar: :foo end end end test "should not send email with unlock instructions when :email is not an unlock strategy" do swap Devise, unlock_strategy: :time do user = create_user assert_email_not_sent do user.lock_access! end end end test 'should find and unlock a user automatically based on raw token' do user = create_user raw = user.send_unlock_instructions locked_user = User.unlock_access_by_token(raw) assert_equal locked_user, user assert_not user.reload.access_locked? end test 'should return a new record with errors when a invalid token is given' do locked_user = User.unlock_access_by_token('invalid_token') assert_not locked_user.persisted? assert_equal "is invalid", locked_user.errors[:unlock_token].join end test 'should return a new record with errors when a blank token is given' do locked_user = User.unlock_access_by_token('') assert_not locked_user.persisted? assert_equal "can't be blank", locked_user.errors[:unlock_token].join end test 'should find a user to send unlock instructions' do user = create_user user.lock_access! unlock_user = User.send_unlock_instructions(email: user.email) assert_equal unlock_user, user end test 'should return a new user if no email was found' do unlock_user = User.send_unlock_instructions(email: "invalid@example.com") assert_not unlock_user.persisted? end test 'should add error to new user email if no email was found' do unlock_user = User.send_unlock_instructions(email: "invalid@example.com") assert_equal 'not found', unlock_user.errors[:email].join end test 'should find a user to send unlock instructions by authentication_keys' do swap Devise, authentication_keys: [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(email: user.email, username: user.username) assert_equal unlock_user, user end end test 'should require all unlock_keys' do swap Devise, unlock_keys: [:username, :email] do user = create_user unlock_user = User.send_unlock_instructions(email: user.email) assert_not unlock_user.persisted? assert_equal "can't be blank", unlock_user.errors[:username].join end end test 'should not be able to send instructions if the user is not locked' do user = create_user assert_not user.resend_unlock_instructions assert_not user.access_locked? assert_equal 'was not locked', user.errors[:email].join end test 'should not be able to send instructions if the user if not locked and have username as unlock key' do swap Devise, unlock_keys: [:username] do user = create_user assert_not user.resend_unlock_instructions assert_not user.access_locked? assert_equal 'was not locked', user.errors[:username].join end end test 'should unlock account if lock has expired and increase attempts on failure' do swap Devise, unlock_in: 1.minute do user = create_user user.confirm user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { false } assert_equal 1, user.failed_attempts end end test 'should unlock account if lock has expired on success' do swap Devise, unlock_in: 1.minute do user = create_user user.confirm user.failed_attempts = 2 user.locked_at = 2.minutes.ago user.valid_for_authentication? { true } assert_equal 0, user.failed_attempts assert_nil user.locked_at end end test 'required_fields should contain the all the fields when all the strategies are enabled' do swap Devise, unlock_strategy: :both do swap Devise, lock_strategy: :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at, :unlock_token ] end end end test 'required_fields should contain only failed_attempts and locked_at when the strategies are time and failed_attempts are enabled' do swap Devise, unlock_strategy: :time do swap Devise, lock_strategy: :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :locked_at ] end end end test 'required_fields should contain only failed_attempts and unlock_token when the strategies are token and failed_attempts are enabled' do swap Devise, unlock_strategy: :email do swap Devise, lock_strategy: :failed_attempts do assert_same_content Devise::Models::Lockable.required_fields(User), [ :failed_attempts, :unlock_token ] end end end test 'should not return a locked unauthenticated message if in paranoid mode' do swap Devise, paranoid: :true do user = create_user user.failed_attempts = Devise.maximum_attempts + 1 user.lock_access! assert_equal :invalid, user.unauthenticated_message end end test 'should return last attempt message if user made next-to-last attempt of password entering' do swap Devise, last_attempt_warning: true, lock_strategy: :failed_attempts do user = create_user user.failed_attempts = Devise.maximum_attempts - 2 assert_equal :invalid, user.unauthenticated_message user.failed_attempts = Devise.maximum_attempts - 1 assert_equal :last_attempt, user.unauthenticated_message user.failed_attempts = Devise.maximum_attempts assert_equal :locked, user.unauthenticated_message end end test 'should not return last attempt message if last_attempt_warning is disabled' do swap Devise, last_attempt_warning: false, lock_strategy: :failed_attempts do user = create_user user.failed_attempts = Devise.maximum_attempts - 1 assert_equal :invalid, user.unauthenticated_message end end test 'should return locked message if user was programatically locked' do user = create_user user.lock_access! assert_equal :locked, user.unauthenticated_message end end devise-3.5.6/test/models/omniauthable_test.rb0000644000004100000410000000035012663066463021344 0ustar www-datawww-datarequire 'test_helper' class OmniauthableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do assert_same_content Devise::Models::Omniauthable.required_fields(User), [] end end devise-3.5.6/test/models/confirmable_test.rb0000644000004100000410000004062412663066463021165 0ustar www-datawww-datarequire 'test_helper' class ConfirmableTest < ActiveSupport::TestCase def setup setup_mailer end test 'should generate confirmation token after creating a record' do assert_nil new_user.confirmation_token assert_not_nil create_user.confirmation_token end test 'should never generate the same confirmation token for different users' do confirmation_tokens = [] 3.times do token = create_user.confirmation_token assert !confirmation_tokens.include?(token) confirmation_tokens << token end end test 'should confirm a user by updating confirmed at' do user = create_user assert_nil user.confirmed_at assert user.confirm assert_not_nil user.confirmed_at end test 'should verify whether a user is confirmed or not' do assert_not new_user.confirmed? user = create_user assert_not user.confirmed? user.confirm assert user.confirmed? end test 'should not confirm a user already confirmed' do user = create_user assert user.confirm assert_blank user.errors[:email] assert_not user.confirm assert_equal "was already confirmed, please try signing in", user.errors[:email].join end test 'should find and confirm a user automatically based on the raw token' do user = create_user raw = user.raw_confirmation_token confirmed_user = User.confirm_by_token(raw) assert_equal confirmed_user, user assert user.reload.confirmed? end test 'should return a new record with errors when a invalid token is given' do confirmed_user = User.confirm_by_token('invalid_confirmation_token') assert_not confirmed_user.persisted? assert_equal "is invalid", confirmed_user.errors[:confirmation_token].join end test 'should return a new record with errors when a blank token is given' do confirmed_user = User.confirm_by_token('') assert_not confirmed_user.persisted? assert_equal "can't be blank", confirmed_user.errors[:confirmation_token].join end test 'should generate errors for a user email if user is already confirmed' do user = create_user user.confirmed_at = Time.now user.save confirmed_user = User.confirm_by_token(user.raw_confirmation_token) assert confirmed_user.confirmed? assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join end test 'should show error when a token has already been used' do user = create_user raw = user.raw_confirmation_token User.confirm_by_token(raw) assert user.reload.confirmed? confirmed_user = User.confirm_by_token(raw) assert_equal "was already confirmed, please try signing in", confirmed_user.errors[:email].join end test 'should send confirmation instructions by email' do assert_email_sent "mynewuser@example.com" do create_user email: "mynewuser@example.com" end end test 'should not send confirmation when trying to save an invalid user' do assert_email_not_sent do user = new_user user.stubs(:valid?).returns(false) user.save end end test 'should not generate a new token neither send e-mail if skip_confirmation! is invoked' do user = new_user user.skip_confirmation! assert_email_not_sent do user.save! assert_nil user.confirmation_token assert_not_nil user.confirmed_at end end test 'should skip confirmation e-mail without confirming if skip_confirmation_notification! is invoked' do user = new_user user.skip_confirmation_notification! assert_email_not_sent do user.save! assert !user.confirmed? end end test 'should not send confirmation when no email is provided' do assert_email_not_sent do user = new_user user.email = '' user.save(validate: false) end end test 'should find a user to send confirmation instructions' do user = create_user confirmation_user = User.send_confirmation_instructions(email: user.email) assert_equal confirmation_user, user end test 'should return a new user if no email was found' do confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com") assert_not confirmation_user.persisted? end test 'should add error to new user email if no email was found' do confirmation_user = User.send_confirmation_instructions(email: "invalid@example.com") assert confirmation_user.errors[:email] assert_equal "not found", confirmation_user.errors[:email].join end test 'should send email instructions for the user confirm its email' do user = create_user assert_email_sent user.email do User.send_confirmation_instructions(email: user.email) end end test 'should always have confirmation token when email is sent' do user = new_user user.instance_eval { def confirmation_required?; false end } user.save user.send_confirmation_instructions assert_not_nil user.reload.confirmation_token end test 'should not resend email instructions if the user change their email' do user = create_user user.email = 'new_test@example.com' assert_email_not_sent do user.save! end end test 'should not reset confirmation status or token when updating email' do user = create_user original_token = user.confirmation_token user.confirm user.email = 'new_test@example.com' user.save! user.reload assert user.confirmed? assert_equal original_token, user.confirmation_token end test 'should not be able to send instructions if the user is already confirmed' do user = create_user user.confirm assert_not user.resend_confirmation_instructions assert user.confirmed? assert_equal 'was already confirmed, please try signing in', user.errors[:email].join end test 'confirm time should fallback to devise confirm in default configuration' do swap Devise, allow_unconfirmed_access_for: 1.day do user = new_user user.confirmation_sent_at = 2.days.ago assert_not user.active_for_authentication? Devise.allow_unconfirmed_access_for = 3.days assert user.active_for_authentication? end end test 'should be active when confirmation sent at is not overpast' do swap Devise, allow_unconfirmed_access_for: 5.days do Devise.allow_unconfirmed_access_for = 5.days user = create_user user.confirmation_sent_at = 4.days.ago assert user.active_for_authentication? user.confirmation_sent_at = 5.days.ago assert_not user.active_for_authentication? end end test 'should be active when already confirmed' do user = create_user assert_not user.confirmed? assert_not user.active_for_authentication? user.confirm assert user.confirmed? assert user.active_for_authentication? end test 'should not be active when confirm in is zero' do Devise.allow_unconfirmed_access_for = 0.days user = create_user user.confirmation_sent_at = Time.zone.today assert_not user.active_for_authentication? end test 'should be active when we set allow_unconfirmed_access_for to nil' do swap Devise, allow_unconfirmed_access_for: nil do user = create_user user.confirmation_sent_at = Time.zone.today assert user.active_for_authentication? end end test 'should not be active without confirmation' do user = create_user user.confirmation_sent_at = nil user.save assert_not user.reload.active_for_authentication? end test 'should be active without confirmation when confirmation is not required' do user = create_user user.instance_eval { def confirmation_required?; false end } user.confirmation_sent_at = nil user.save assert user.reload.active_for_authentication? end test 'should not break when a user tries to reset their password in the case where confirmation is not required and confirm_within is set' do swap Devise, confirm_within: 3.days do user = create_user user.instance_eval { def confirmation_required?; false end } user.confirmation_sent_at = nil user.save assert user.reload.confirm! end end test 'should find a user to send email instructions for the user confirm its email by authentication_keys' do swap Devise, authentication_keys: [:username, :email] do user = create_user confirm_user = User.send_confirmation_instructions(email: user.email, username: user.username) assert_equal confirm_user, user end end test 'should require all confirmation_keys' do swap Devise, confirmation_keys: [:username, :email] do user = create_user confirm_user = User.send_confirmation_instructions(email: user.email) assert_not confirm_user.persisted? assert_equal "can't be blank", confirm_user.errors[:username].join end end def confirm_user_by_token_with_confirmation_sent_at(confirmation_sent_at) user = create_user user.update_attribute(:confirmation_sent_at, confirmation_sent_at) confirmed_user = User.confirm_by_token(user.raw_confirmation_token) assert_equal confirmed_user, user user.reload.confirmed? end test 'should accept confirmation email token even after 5 years when no expiration is set' do assert confirm_user_by_token_with_confirmation_sent_at(5.years.ago) end test 'should accept confirmation email token after 2 days when expiration is set to 3 days' do swap Devise, confirm_within: 3.days do assert confirm_user_by_token_with_confirmation_sent_at(2.days.ago) end end test 'should not accept confirmation email token after 4 days when expiration is set to 3 days' do swap Devise, confirm_within: 3.days do assert_not confirm_user_by_token_with_confirmation_sent_at(4.days.ago) end end test 'do not generate a new token on resend' do user = create_user old = user.confirmation_token user = User.find(user.id) user.resend_confirmation_instructions assert_equal user.confirmation_token, old end test 'generate a new token after first has expired' do swap Devise, confirm_within: 3.days do user = create_user old = user.confirmation_token user.update_attribute(:confirmation_sent_at, 4.days.ago) user = User.find(user.id) user.resend_confirmation_instructions assert_not_equal user.confirmation_token, old end end test 'should call after_confirmation if confirmed' do user = create_user user.define_singleton_method :after_confirmation do self.username = self.username.to_s + 'updated' end old = user.username assert user.confirm assert_not_equal user.username, old end test 'should not call after_confirmation if not confirmed' do user = create_user assert user.confirm user.define_singleton_method :after_confirmation do self.username = self.username.to_s + 'updated' end old = user.username assert_not user.confirm assert_equal user.username, old end test 'should always perform validations upon confirm when ensure valid true' do admin = create_admin admin.stubs(:valid?).returns(false) assert_not admin.confirm(ensure_valid: true) end end class ReconfirmableTest < ActiveSupport::TestCase test 'should not worry about validations on confirm even with reconfirmable' do admin = create_admin admin.reset_password_token = "a" assert admin.confirm end test 'should generate confirmation token after changing email' do admin = create_admin assert admin.confirm residual_token = admin.confirmation_token assert admin.update_attributes(email: 'new_test@example.com') assert_not_equal residual_token, admin.confirmation_token end test 'should not regenerate confirmation token or require reconfirmation if skipping reconfirmation after changing email' do admin = create_admin original_token = admin.confirmation_token assert admin.confirm admin.skip_reconfirmation! assert admin.update_attributes(email: 'new_test@example.com') assert admin.confirmed? assert_not admin.pending_reconfirmation? assert_equal original_token, admin.confirmation_token end test 'should skip sending reconfirmation email when email is changed and skip_confirmation_notification! is invoked' do admin = create_admin admin.skip_confirmation_notification! assert_email_not_sent do admin.update_attributes(email: 'new_test@example.com') end end test 'should regenerate confirmation token after changing email' do admin = create_admin assert admin.confirm assert admin.update_attributes(email: 'old_test@example.com') token = admin.confirmation_token assert admin.update_attributes(email: 'new_test@example.com') assert_not_equal token, admin.confirmation_token end test 'should send confirmation instructions by email after changing email' do admin = create_admin assert admin.confirm assert_email_sent "new_test@example.com" do assert admin.update_attributes(email: 'new_test@example.com') end assert_match "new_test@example.com", ActionMailer::Base.deliveries.last.body.encoded end test 'should not send confirmation by email after changing password' do admin = create_admin assert admin.confirm assert_email_not_sent do assert admin.update_attributes(password: 'newpass', password_confirmation: 'newpass') end end test 'should not send confirmation by email after changing to a blank email' do admin = create_admin assert admin.confirm assert_email_not_sent do admin.email = '' admin.save(validate: false) end end test 'should stay confirmed when email is changed' do admin = create_admin assert admin.confirm assert admin.update_attributes(email: 'new_test@example.com') assert admin.confirmed? end test 'should update email only when it is confirmed' do admin = create_admin assert admin.confirm assert admin.update_attributes(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email assert admin.confirm assert_equal 'new_test@example.com', admin.email end test 'should not allow admin to get past confirmation email by resubmitting their new address' do admin = create_admin assert admin.confirm assert admin.update_attributes(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email assert admin.update_attributes(email: 'new_test@example.com') assert_not_equal 'new_test@example.com', admin.email end test 'should find a admin by send confirmation instructions with unconfirmed_email' do admin = create_admin assert admin.confirm assert admin.update_attributes(email: 'new_test@example.com') confirmation_admin = Admin.send_confirmation_instructions(email: admin.unconfirmed_email) assert_equal confirmation_admin, admin end test 'should return a new admin if no email or unconfirmed_email was found' do confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com") assert_not confirmation_admin.persisted? end test 'should add error to new admin email if no email or unconfirmed_email was found' do confirmation_admin = Admin.send_confirmation_instructions(email: "invalid@email.com") assert confirmation_admin.errors[:email] assert_equal "not found", confirmation_admin.errors[:email].join end test 'should find admin with email in unconfirmed_emails' do admin = create_admin admin.unconfirmed_email = "new_test@email.com" assert admin.save admin = Admin.find_by_unconfirmed_email_with_errors(email: "new_test@email.com") assert admin.persisted? end test 'required_fields should contain the fields that Devise uses' do assert_same_content Devise::Models::Confirmable.required_fields(User), [ :confirmation_sent_at, :confirmation_token, :confirmed_at ] end test 'required_fields should also contain unconfirmable when reconfirmable_email is true' do assert_same_content Devise::Models::Confirmable.required_fields(Admin), [ :confirmation_sent_at, :confirmation_token, :confirmed_at, :unconfirmed_email ] end test 'should not require reconfirmation after creating a record' do user = create_admin assert !user.pending_reconfirmation? end test 'should not require reconfirmation after creating a record with #save called in callback' do class Admin::WithSaveInCallback < Admin after_create :save end user = Admin::WithSaveInCallback.create(valid_attributes.except(:username)) assert !user.pending_reconfirmation? end end devise-3.5.6/test/models/serializable_test.rb0000644000004100000410000000324412663066463021347 0ustar www-datawww-datarequire 'test_helper' class SerializableTest < ActiveSupport::TestCase setup do @user = create_user end test 'should not include unsafe keys on XML' do assert_match(/email/, @user.to_xml) assert_no_match(/confirmation-token/, @user.to_xml) end test 'should not include unsafe keys on XML even if a new except is provided' do assert_no_match(/email/, @user.to_xml(except: :email)) assert_no_match(/confirmation-token/, @user.to_xml(except: :email)) end test 'should include unsafe keys on XML if a force_except is provided' do assert_no_match(/ 'example@example.com').returns(user) User.find_or_initialize_with_errors([:email], attributes) end end end devise-3.5.6/test/models/registerable_test.rb0000644000004100000410000000035012663066463021344 0ustar www-datawww-datarequire 'test_helper' class RegisterableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do assert_same_content Devise::Models::Registerable.required_fields(User), [] end end devise-3.5.6/test/models/database_authenticatable_test.rb0000644000004100000410000002264412663066463023667 0ustar www-datawww-datarequire 'test_helper' require 'test_models' require 'digest/sha1' class DatabaseAuthenticatableTest < ActiveSupport::TestCase def setup setup_mailer end test 'should downcase case insensitive keys when saving' do # case_insensitive_keys is set to :email by default. email = 'Foo@Bar.com' user = new_user(email: email) assert_equal email, user.email user.save! assert_equal email.downcase, user.email end test 'should downcase case insensitive keys that refer to virtual attributes when saving' do email = 'Foo@Bar1.com' confirmation = 'Foo@Bar1.com' attributes = valid_attributes(email: email, email_confirmation: confirmation) user = UserWithVirtualAttributes.new(attributes) assert_equal confirmation, user.email_confirmation user.save! assert_equal confirmation.downcase, user.email_confirmation end test 'should not mutate value assigned to case insensitive key' do email = 'Foo@Bar.com' original_email = email.dup user = new_user(email: email) user.save! assert_equal original_email, email end test 'should remove whitespace from strip whitespace keys when saving' do # strip_whitespace_keys is set to :email by default. email = ' foo@bar.com ' user = new_user(email: email) assert_equal email, user.email user.save! assert_equal email.strip, user.email end test 'should not mutate value assigned to string whitespace key' do email = ' foo@bar.com ' original_email = email.dup user = new_user(email: email) user.save! assert_equal original_email, email end test "doesn't throw exception when globally configured strip_whitespace_keys are not present on a model" do swap Devise, strip_whitespace_keys: [:fake_key] do assert_nothing_raised { create_user } end end test "doesn't throw exception when globally configured case_insensitive_keys are not present on a model" do swap Devise, case_insensitive_keys: [:fake_key] do assert_nothing_raised { create_user } end end test "param filter should not convert booleans and integer to strings" do conditions = { "login" => "foo@bar.com", "bool1" => true, "bool2" => false, "fixnum" => 123, "will_be_converted" => (1..10) } conditions = Devise::ParameterFilter.new([], []).filter(conditions) assert_equal( { "login" => "foo@bar.com", "bool1" => "true", "bool2" => "false", "fixnum" => "123", "will_be_converted" => "1..10" }, conditions) end test 'param filter should filter case_insensitive_keys as insensitive' do conditions = {'insensitive' => 'insensitive_VAL', 'sensitive' => 'sensitive_VAL'} conditions = Devise::ParameterFilter.new(['insensitive'], []).filter(conditions) assert_equal( {'insensitive' => 'insensitive_val', 'sensitive' => 'sensitive_VAL'}, conditions ) end test 'param filter should filter strip_whitespace_keys stripping whitespaces' do conditions = {'strip_whitespace' => ' strip_whitespace_val ', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '} conditions = Devise::ParameterFilter.new([], ['strip_whitespace']).filter(conditions) assert_equal( {'strip_whitespace' => 'strip_whitespace_val', 'do_not_strip_whitespace' => ' do_not_strip_whitespace_val '}, conditions ) end test 'should respond to password and password confirmation' do user = new_user assert user.respond_to?(:password) assert user.respond_to?(:password_confirmation) end test 'should generate encrypted password while setting password' do user = new_user assert_present user.encrypted_password end test 'should support custom encryption methods' do user = UserWithCustomEncryption.new(password: '654321') assert_equal user.encrypted_password, '123456' end test 'allow authenticatable_salt to work even with nil encrypted password' do user = User.new user.encrypted_password = nil assert_nil user.authenticatable_salt end test 'should not generate encrypted password if password is blank' do assert_blank new_user(password: nil).encrypted_password assert_blank new_user(password: '').encrypted_password end test 'should encrypt password again if password has changed' do user = create_user encrypted_password = user.encrypted_password user.password = user.password_confirmation = 'new_password' user.save! assert_not_equal encrypted_password, user.encrypted_password end test 'should test for a valid password' do user = create_user assert user.valid_password?('12345678') assert_not user.valid_password?('654321') end test 'should not raise error with an empty password' do user = create_user user.encrypted_password = '' assert_nothing_raised { user.valid_password?('12345678') } end test 'should be an invalid password if the user has an empty password' do user = create_user user.encrypted_password = '' assert_not user.valid_password?('654321') end test 'should respond to current password' do assert new_user.respond_to?(:current_password) end test 'should update password with valid current password' do user = create_user assert user.update_with_password(current_password: '12345678', password: 'pass4321', password_confirmation: 'pass4321') assert user.reload.valid_password?('pass4321') end test 'should add an error to current password when it is invalid' do user = create_user assert_not user.update_with_password(current_password: 'other', password: 'pass4321', password_confirmation: 'pass4321') assert user.reload.valid_password?('12345678') assert_match "is invalid", user.errors[:current_password].join end test 'should add an error to current password when it is blank' do user = create_user assert_not user.update_with_password(password: 'pass4321', password_confirmation: 'pass4321') assert user.reload.valid_password?('12345678') assert_match "can't be blank", user.errors[:current_password].join end test 'should run validations even when current password is invalid or blank' do user = UserWithValidation.create!(valid_attributes) user.save assert user.persisted? assert_not user.update_with_password(username: "") assert_match "usertest", user.reload.username assert_match "can't be blank", user.errors[:username].join end test 'should ignore password and its confirmation if they are blank' do user = create_user assert user.update_with_password(current_password: '12345678', email: "new@example.com") assert_equal "new@example.com", user.email end test 'should not update password with invalid confirmation' do user = create_user assert_not user.update_with_password(current_password: '12345678', password: 'pass4321', password_confirmation: 'other') assert user.reload.valid_password?('12345678') end test 'should clean up password fields on failure' do user = create_user assert_not user.update_with_password(current_password: '12345678', password: 'pass4321', password_confirmation: 'other') assert user.password.blank? assert user.password_confirmation.blank? end test 'should update the user without password' do user = create_user user.update_without_password(email: 'new@example.com') assert_equal 'new@example.com', user.email end test 'should not update password without password' do user = create_user user.update_without_password(password: 'pass4321', password_confirmation: 'pass4321') assert !user.reload.valid_password?('pass4321') assert user.valid_password?('12345678') end test 'should destroy user if current password is valid' do user = create_user assert user.destroy_with_password('12345678') assert !user.persisted? end test 'should not destroy user with invalid password' do user = create_user assert_not user.destroy_with_password('other') assert user.persisted? assert_match "is invalid", user.errors[:current_password].join end test 'should not destroy user with blank password' do user = create_user assert_not user.destroy_with_password(nil) assert user.persisted? assert_match "can't be blank", user.errors[:current_password].join end test 'should not email on password change' do user = create_user assert_email_not_sent do assert user.update_attributes(password: 'newpass', password_confirmation: 'newpass') end end test 'should email on password change when configured' do swap Devise, send_password_change_notification: true do user = create_user assert_email_sent user.email do assert user.update_attributes(password: 'newpass', password_confirmation: 'newpass') end end end test 'downcase_keys with validation' do User.create(email: "HEllO@example.com", password: "123456") user = User.create(email: "HEllO@example.com", password: "123456") assert !user.valid? end test 'required_fields should be encryptable_password and the email field by default' do assert_same_content Devise::Models::DatabaseAuthenticatable.required_fields(User), [ :email, :encrypted_password ] end test 'required_fields should be encryptable_password and the login when the login is on authentication_keys' do swap Devise, authentication_keys: [:login] do assert_same_content Devise::Models::DatabaseAuthenticatable.required_fields(User), [ :encrypted_password, :login ] end end end devise-3.5.6/test/helpers/0000755000004100000410000000000012663066463015471 5ustar www-datawww-datadevise-3.5.6/test/helpers/devise_helper_test.rb0000644000004100000410000000275712663066463021706 0ustar www-datawww-datarequire 'test_helper' class DeviseHelperTest < ActionDispatch::IntegrationTest setup do model_labels = { models: { user: "the user" } } translations = { errors: { messages: { not_saved: { one: "Can't save %{resource} because of 1 error", other: "Can't save %{resource} because of %{count} errors", } } }, activerecord: model_labels, mongoid: model_labels } I18n.available_locales I18n.backend.store_translations(:en, translations) end teardown do I18n.reload! end test 'test errors.messages.not_saved with single error from i18n' do get new_user_registration_path fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user123' click_button 'Sign up' assert_have_selector '#error_explanation' assert_contain "Can't save the user because of 1 error" end test 'test errors.messages.not_saved with multiple errors from i18n' do # Dirty tracking behavior prevents email validations from being applied: # https://github.com/mongoid/mongoid/issues/756 (pending "Fails on Mongoid < 2.1"; break) if defined?(Mongoid) && Mongoid::VERSION.to_f < 2.1 get new_user_registration_path fill_in 'email', with: 'invalid_email' fill_in 'password', with: 'new_user123' fill_in 'password confirmation', with: 'new_user321' click_button 'Sign up' assert_have_selector '#error_explanation' assert_contain "Can't save the user because of 2 errors" end end devise-3.5.6/test/support/0000755000004100000410000000000012663066463015543 5ustar www-datawww-datadevise-3.5.6/test/support/integration.rb0000644000004100000410000000476012663066463020422 0ustar www-datawww-datarequire 'action_dispatch/testing/integration' class ActionDispatch::IntegrationTest def warden request.env['warden'] end def create_user(options={}) @user ||= begin user = User.create!( username: 'usertest', email: options[:email] || 'user@test.com', password: options[:password] || '12345678', password_confirmation: options[:password] || '12345678', created_at: Time.now.utc ) user.update_attribute(:confirmation_sent_at, options[:confirmation_sent_at]) if options[:confirmation_sent_at] user.confirm unless options[:confirm] == false user.lock_access! if options[:locked] == true user end end def create_admin(options={}) @admin ||= begin admin = Admin.create!( email: options[:email] || 'admin@test.com', password: '123456', password_confirmation: '123456', active: options[:active] ) admin.confirm unless options[:confirm] == false admin end end def sign_in_as_user(options={}, &block) user = create_user(options) visit_with_option options[:visit], new_user_session_path fill_in 'email', with: options[:email] || 'user@test.com' fill_in 'password', with: options[:password] || '12345678' check 'remember me' if options[:remember_me] == true yield if block_given? click_button 'Log In' user end def sign_in_as_admin(options={}, &block) admin = create_admin(options) visit_with_option options[:visit], new_admin_session_path fill_in 'email', with: 'admin@test.com' fill_in 'password', with: '123456' yield if block_given? click_button 'Log In' admin end # Fix assert_redirect_to in integration sessions because they don't take into # account Middleware redirects. # def assert_redirected_to(url) assert [301, 302].include?(@integration_session.status), "Expected status to be 301 or 302, got #{@integration_session.status}" assert_url url, @integration_session.headers["Location"] end def assert_current_url(expected) assert_url expected, current_url end def assert_url(expected, actual) assert_equal prepend_host(expected), prepend_host(actual) end protected def visit_with_option(given, default) case given when String visit given when FalseClass # Do nothing else visit default end end def prepend_host(url) url = "http://#{request.host}#{url}" if url[0] == ?/ url end end devise-3.5.6/test/support/helpers.rb0000644000004100000410000000407612663066463017541 0ustar www-datawww-datarequire 'active_support/test_case' class ActiveSupport::TestCase VALID_AUTHENTICATION_TOKEN = 'AbCdEfGhIjKlMnOpQrSt'.freeze def setup_mailer ActionMailer::Base.deliveries = [] end def store_translations(locale, translations, &block) # Calling 'available_locales' before storing the translations to ensure # that the I18n backend will be initialized before we store our custom # translations, so they will always override the translations for the # YML file. I18n.available_locales I18n.backend.store_translations(locale, translations) yield ensure I18n.reload! end def generate_unique_email @@email_count ||= 0 @@email_count += 1 "test#{@@email_count}@example.com" end def valid_attributes(attributes={}) { username: "usertest", email: generate_unique_email, password: '12345678', password_confirmation: '12345678' }.update(attributes) end def new_user(attributes={}) User.new(valid_attributes(attributes)) end def create_user(attributes={}) User.create!(valid_attributes(attributes)) end def create_admin(attributes={}) valid_attributes = valid_attributes(attributes) valid_attributes.delete(:username) Admin.create!(valid_attributes) end def create_user_without_email(attributes={}) UserWithoutEmail.create!(valid_attributes(attributes)) end # Execute the block setting the given values and restoring old values after # the block is executed. def swap(object, new_values) old_values = {} new_values.each do |key, value| old_values[key] = object.send key object.send :"#{key}=", value end clear_cached_variables(new_values) yield ensure clear_cached_variables(new_values) old_values.each do |key, value| object.send :"#{key}=", value end end def clear_cached_variables(options) if options.key?(:case_insensitive_keys) || options.key?(:strip_whitespace_keys) Devise.mappings.each do |_, mapping| mapping.to.instance_variable_set(:@devise_parameter_filter, nil) end end end end devise-3.5.6/test/support/webrat/0000755000004100000410000000000012663066463017027 5ustar www-datawww-datadevise-3.5.6/test/support/webrat/integrations/0000755000004100000410000000000012663066463021535 5ustar www-datawww-datadevise-3.5.6/test/support/webrat/integrations/rails.rb0000644000004100000410000000075312663066463023201 0ustar www-datawww-datarequire 'webrat/core/elements/form' require 'action_dispatch/testing/integration' module Webrat Form.class_eval do def self.parse_rails_request_params(params) Rack::Utils.parse_nested_query(params) end end module Logging # Avoid RAILS_DEFAULT_LOGGER deprecation warning def logger # :nodoc: ::Rails.logger end end end module ActionDispatch #:nodoc: IntegrationTest.class_eval do include Webrat::Methods include Webrat::Matchers end end devise-3.5.6/test/support/action_controller/0000755000004100000410000000000012663066463021263 5ustar www-datawww-datadevise-3.5.6/test/support/action_controller/record_identifier.rb0000644000004100000410000000045412663066463025273 0ustar www-datawww-data# Since webrat uses ActionController::RecordIdentifier class that was moved to # ActionView namespace in Rails 4.1+ unless defined?(ActionController::RecordIdentifier) require 'action_view/record_identifier' module ActionController RecordIdentifier = ActionView::RecordIdentifier end end devise-3.5.6/test/support/mongoid.yml0000644000004100000410000000021012663066463017713 0ustar www-datawww-datatest: sessions: default: database: devise-test-suite hosts: - localhost:<%= ENV['MONGODB_PORT'] || '27017' %> devise-3.5.6/test/support/assertions.rb0000644000004100000410000000213512663066463020263 0ustar www-datawww-datarequire 'active_support/test_case' class ActiveSupport::TestCase def assert_not(assertion) assert !assertion end def assert_blank(assertion) assert assertion.blank? end def assert_present(assertion) assert assertion.present? end def assert_email_sent(address = nil, &block) assert_difference('ActionMailer::Base.deliveries.size', &block) if address.present? assert_equal address, ActionMailer::Base.deliveries.last['to'].to_s end end def assert_email_not_sent(&block) assert_no_difference('ActionMailer::Base.deliveries.size', &block) end def assert_same_content(result, expected) assert expected.size == result.size, "the arrays doesn't have the same size" expected.each do |element| assert result.include?(element), "The array doesn't include '#{element}'." end end def assert_raise_with_message(exception_klass, message, &block) exception = assert_raise exception_klass, &block assert_equal exception.message, message, "The expected message was #{message} but your exception throwed #{exception.message}" end end devise-3.5.6/test/support/locale/0000755000004100000410000000000012663066463017002 5ustar www-datawww-datadevise-3.5.6/test/support/locale/en.yml0000644000004100000410000000023312663066463020125 0ustar www-datawww-dataen: devise: failure: user: does_not_exist: "User %{name} does not exist" errors: messages: taken: "has already been taken" devise-3.5.6/test/mapping_test.rb0000644000004100000410000001116312663066463017050 0ustar www-datawww-datarequire 'test_helper' class FakeRequest < Struct.new(:path_info, :params) end class MappingTest < ActiveSupport::TestCase def fake_request(path, params={}) FakeRequest.new(path, params) end test 'store options' do mapping = Devise.mappings[:user] assert_equal User, mapping.to assert_equal User.devise_modules, mapping.modules assert_equal "users", mapping.scoped_path assert_equal :user, mapping.singular assert_equal "users", mapping.path assert_equal "/users", mapping.fullpath end test 'store options with namespace' do mapping = Devise.mappings[:publisher_account] assert_equal Admin, mapping.to assert_equal "publisher/accounts", mapping.scoped_path assert_equal :publisher_account, mapping.singular assert_equal "accounts", mapping.path assert_equal "/publisher/accounts", mapping.fullpath end test 'allows path to be given' do assert_equal "admin_area", Devise.mappings[:admin].path end test 'allows to skip all routes' do assert_equal [], Devise.mappings[:skip_admin].used_routes end test 'sign_out_via defaults to :get' do assert_equal :get, Devise.mappings[:user].sign_out_via end test 'allows custom sign_out_via to be given' do assert_equal :delete, Devise.mappings[:sign_out_via_delete].sign_out_via assert_equal :post, Devise.mappings[:sign_out_via_post].sign_out_via assert_equal [:delete, :post], Devise.mappings[:sign_out_via_delete_or_post].sign_out_via end test 'allows custom singular to be given' do assert_equal "accounts", Devise.mappings[:manager].path end test 'has strategies depending on the model declaration' do assert_equal [:rememberable, :database_authenticatable], Devise.mappings[:user].strategies assert_equal [:database_authenticatable], Devise.mappings[:admin].strategies end test 'has no input strategies depending on the model declaration' do assert_equal [:rememberable], Devise.mappings[:user].no_input_strategies assert_equal [], Devise.mappings[:admin].no_input_strategies end test 'find scope for a given object' do assert_equal :user, Devise::Mapping.find_scope!(User) assert_equal :user, Devise::Mapping.find_scope!(:user) assert_equal :user, Devise::Mapping.find_scope!("user") assert_equal :user, Devise::Mapping.find_scope!(User.new) end test 'find scope works with single table inheritance' do assert_equal :user, Devise::Mapping.find_scope!(Class.new(User)) assert_equal :user, Devise::Mapping.find_scope!(Class.new(User).new) end test 'find scope uses devise_scope' do user = User.new def user.devise_scope; :special_scope; end assert_equal :special_scope, Devise::Mapping.find_scope!(user) end test 'find scope raises an error if cannot be found' do assert_raise RuntimeError do Devise::Mapping.find_scope!(String) end end test 'return default path names' do mapping = Devise.mappings[:user] assert_equal 'sign_in', mapping.path_names[:sign_in] assert_equal 'sign_out', mapping.path_names[:sign_out] assert_equal 'password', mapping.path_names[:password] assert_equal 'confirmation', mapping.path_names[:confirmation] assert_equal 'sign_up', mapping.path_names[:sign_up] assert_equal 'unlock', mapping.path_names[:unlock] end test 'allow custom path names to be given' do mapping = Devise.mappings[:manager] assert_equal 'login', mapping.path_names[:sign_in] assert_equal 'logout', mapping.path_names[:sign_out] assert_equal 'secret', mapping.path_names[:password] assert_equal 'verification', mapping.path_names[:confirmation] assert_equal 'register', mapping.path_names[:sign_up] assert_equal 'unblock', mapping.path_names[:unlock] end test 'magic predicates' do mapping = Devise.mappings[:user] assert mapping.authenticatable? assert mapping.confirmable? assert mapping.recoverable? assert mapping.rememberable? assert mapping.registerable? mapping = Devise.mappings[:admin] assert mapping.authenticatable? assert mapping.recoverable? assert mapping.lockable? assert_not mapping.omniauthable? end test 'find mapping by path' do assert_raise RuntimeError do Devise::Mapping.find_by_path!('/accounts/facebook/callback') end assert_nothing_raised do Devise::Mapping.find_by_path!('/:locale/accounts/login') end assert_nothing_raised do Devise::Mapping.find_by_path!('/accounts/facebook/callback', :path) end end end devise-3.5.6/test/test_models.rb0000644000004100000410000000150412663066463016676 0ustar www-datawww-dataclass Configurable < User devise :database_authenticatable, :confirmable, :rememberable, :timeoutable, :lockable, stretches: 15, pepper: 'abcdef', allow_unconfirmed_access_for: 5.days, remember_for: 7.days, timeout_in: 15.minutes, unlock_in: 10.days end class WithValidation < Admin devise :database_authenticatable, :validatable, password_length: 2..6 end class UserWithValidation < User validates_presence_of :username end class UserWithCustomEncryption < User protected def password_digest(password) password.reverse end end class UserWithVirtualAttributes < User devise case_insensitive_keys: [:email, :email_confirmation] validates :email, presence: true, confirmation: { on: :create } end class Several < Admin devise :validatable devise :lockable end class Inheritable < Admin end devise-3.5.6/test/rails_test.rb0000644000004100000410000000051012663066463016521 0ustar www-datawww-datarequire 'test_helper' class RailsTest < ActiveSupport::TestCase test 'correct initializer position' do initializer = Devise::Engine.initializers.detect { |i| i.name == 'devise.omniauth' } assert_equal :load_config_initializers, initializer.after assert_equal :build_middleware_stack, initializer.before end end devise-3.5.6/.gitignore0000644000004100000410000000014412663066463015037 0ustar www-datawww-datatest/rails_app/log/* test/rails_app/tmp/* *~ coverage/* *.sqlite3 .bundle rdoc/* pkg log test/tmp/* devise-3.5.6/config/0000755000004100000410000000000012663066463014315 5ustar www-datawww-datadevise-3.5.6/config/locales/0000755000004100000410000000000012663066463015737 5ustar www-datawww-datadevise-3.5.6/config/locales/en.yml0000644000004100000410000000776412663066463017102 0ustar www-datawww-data# Additional translations at https://github.com/plataformatec/devise/wiki/I18n en: devise: confirmations: confirmed: "Your email address has been successfully confirmed." send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." failure: already_authenticated: "You are already signed in." inactive: "Your account is not activated yet." invalid: "Invalid %{authentication_keys} or password." locked: "Your account is locked." last_attempt: "You have one more attempt before your account is locked." not_found_in_database: "Invalid %{authentication_keys} or password." timeout: "Your session expired. Please sign in again to continue." unauthenticated: "You need to sign in or sign up before continuing." unconfirmed: "You have to confirm your email address before continuing." mailer: confirmation_instructions: subject: "Confirmation instructions" reset_password_instructions: subject: "Reset password instructions" unlock_instructions: subject: "Unlock instructions" password_change: subject: "Password Changed" omniauth_callbacks: failure: "Could not authenticate you from %{kind} because \"%{reason}\"." success: "Successfully authenticated from %{kind} account." passwords: no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." updated: "Your password has been changed successfully. You are now signed in." updated_not_active: "Your password has been changed successfully." registrations: destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." signed_up: "Welcome! You have signed up successfully." signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirm link to confirm your new email address." updated: "Your account has been updated successfully." sessions: signed_in: "Signed in successfully." signed_out: "Signed out successfully." already_signed_out: "Signed out successfully." unlocks: send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." unlocked: "Your account has been unlocked successfully. Please sign in to continue." errors: messages: already_confirmed: "was already confirmed, please try signing in" confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" expired: "has expired, please request a new one" not_found: "not found" not_locked: "was not locked" not_saved: one: "1 error prohibited this %{resource} from being saved:" other: "%{count} errors prohibited this %{resource} from being saved:" devise-3.5.6/.yardopts0000644000004100000410000000015412663066463014716 0ustar www-datawww-data--protected --no-private --embed-mixin ClassMethods - README.md CHANGELOG.rdoc CONTRIBUTING.md MIT-LICENSE devise-3.5.6/CONTRIBUTING.md0000644000004100000410000000211512663066463015300 0ustar www-datawww-data### Please read before contributing 1) Do not post questions in the issues tracker. If you have any questions about Devise, search the [Wiki](https://github.com/plataformatec/devise/wiki) or use the [Mailing List](https://groups.google.com/group/plataformatec-devise) or [Stack Overflow](http://stackoverflow.com/questions/tagged/devise). 2) If you find a security bug, **DO NOT** submit an issue here. Please send an e-mail to [opensource@plataformatec.com.br](mailto:opensource@plataformatec.com.br) instead. 3) Do a small search on the issues tracker before submitting your issue to see if it was already reported / fixed. 4) When reporting an issue, include Rails, Devise and Warden versions. If you are getting exceptions, please include the full backtrace. 5) Notice that all of your interactions in the project are expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md) That's it! The more information you give, the easier it becomes for us to track it down and fix it. Ideally, you should provide an application that reproduces the error or a test case to Devise's suite. Thanks! devise-3.5.6/app/0000755000004100000410000000000012663066463013630 5ustar www-datawww-datadevise-3.5.6/app/views/0000755000004100000410000000000012663066463014765 5ustar www-datawww-datadevise-3.5.6/app/views/devise/0000755000004100000410000000000012663066463016244 5ustar www-datawww-datadevise-3.5.6/app/views/devise/mailer/0000755000004100000410000000000012663066463017515 5ustar www-datawww-datadevise-3.5.6/app/views/devise/mailer/unlock_instructions.html.erb0000644000004100000410000000042412663066463025271 0ustar www-datawww-data

Hello <%= @resource.email %>!

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

Click the link below to unlock your account:

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

devise-3.5.6/app/views/devise/mailer/confirmation_instructions.html.erb0000644000004100000410000000030612663066463026465 0ustar www-datawww-data

Welcome <%= @email %>!

You can confirm your account email through the link below:

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

devise-3.5.6/app/views/devise/mailer/password_change.html.erb0000644000004100000410000000016512663066463024323 0ustar www-datawww-data

Hello <%= @resource.email %>!

We're contacting you to notify you that your password has been changed.

devise-3.5.6/app/views/devise/mailer/reset_password_instructions.html.erb0000644000004100000410000000061112663066463027040 0ustar www-datawww-data

Hello <%= @resource.email %>!

Someone has requested a link to change your password. You can do this through the link below.

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

If you didn't request this, please ignore this email.

Your password won't change until you access the link above and create a new one.

devise-3.5.6/app/views/devise/sessions/0000755000004100000410000000000012663066463020112 5ustar www-datawww-datadevise-3.5.6/app/views/devise/sessions/new.html.erb0000644000004100000410000000114512663066463022341 0ustar www-datawww-data

Log in

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
<%= f.label :password %>
<%= f.password_field :password, autocomplete: "off" %>
<% if devise_mapping.rememberable? -%>
<%= f.check_box :remember_me %> <%= f.label :remember_me %>
<% end -%>
<%= f.submit "Log in" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/app/views/devise/registrations/0000755000004100000410000000000012663066463021141 5ustar www-datawww-datadevise-3.5.6/app/views/devise/registrations/new.html.erb0000644000004100000410000000137112663066463023371 0ustar www-datawww-data

Sign up

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= devise_error_messages! %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
<%= f.label :password %> <% if @minimum_password_length %> (<%= @minimum_password_length %> characters minimum) <% end %>
<%= f.password_field :password, autocomplete: "off" %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, autocomplete: "off" %>
<%= f.submit "Sign up" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/app/views/devise/registrations/edit.html.erb0000644000004100000410000000241212663066463023522 0ustar www-datawww-data

Edit <%= resource_name.to_s.humanize %>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> <%= devise_error_messages! %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
<% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
<% end %>
<%= f.label :password %> (leave blank if you don't want to change it)
<%= f.password_field :password, autocomplete: "off" %>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation, autocomplete: "off" %>
<%= f.label :current_password %> (we need your current password to confirm your changes)
<%= f.password_field :current_password, autocomplete: "off" %>
<%= f.submit "Update" %>
<% end %>

Cancel my account

Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %>

<%= link_to "Back", :back %> devise-3.5.6/app/views/devise/unlocks/0000755000004100000410000000000012663066463017722 5ustar www-datawww-datadevise-3.5.6/app/views/devise/unlocks/new.html.erb0000644000004100000410000000064612663066463022156 0ustar www-datawww-data

Resend unlock instructions

<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> <%= devise_error_messages! %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
<%= f.submit "Resend unlock instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/app/views/devise/shared/0000755000004100000410000000000012663066463017512 5ustar www-datawww-datadevise-3.5.6/app/views/devise/shared/_links.html.erb0000644000004100000410000000217512663066463022433 0ustar www-datawww-data<%- if controller_name != 'sessions' %> <%= link_to "Log in", new_session_path(resource_name) %>
<% end -%> <%- if devise_mapping.registerable? && controller_name != 'registrations' %> <%= link_to "Sign up", new_registration_path(resource_name) %>
<% end -%> <%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> <%= link_to "Forgot your password?", new_password_path(resource_name) %>
<% end -%> <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
<% end -%> <%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
<% end -%> <%- if devise_mapping.omniauthable? %> <%- resource_class.omniauth_providers.each do |provider| %> <%= link_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider) %>
<% end -%> <% end -%> devise-3.5.6/app/views/devise/passwords/0000755000004100000410000000000012663066463020271 5ustar www-datawww-datadevise-3.5.6/app/views/devise/passwords/new.html.erb0000644000004100000410000000065412663066463022524 0ustar www-datawww-data

Forgot your password?

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> <%= devise_error_messages! %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true %>
<%= f.submit "Send me reset password instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/app/views/devise/passwords/edit.html.erb0000644000004100000410000000144312663066463022655 0ustar www-datawww-data

Change your password

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> <%= devise_error_messages! %> <%= f.hidden_field :reset_password_token %>
<%= f.label :password, "New password" %>
<% if @minimum_password_length %> (<%= @minimum_password_length %> characters minimum)
<% end %> <%= f.password_field :password, autofocus: true, autocomplete: "off" %>
<%= f.label :password_confirmation, "Confirm new password" %>
<%= f.password_field :password_confirmation, autocomplete: "off" %>
<%= f.submit "Change my password" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/app/views/devise/confirmations/0000755000004100000410000000000012663066463021117 5ustar www-datawww-datadevise-3.5.6/app/views/devise/confirmations/new.html.erb0000644000004100000410000000102212663066463023340 0ustar www-datawww-data

Resend confirmation instructions

<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> <%= devise_error_messages! %>
<%= f.label :email %>
<%= f.email_field :email, autofocus: true, value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %>
<%= f.submit "Resend confirmation instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-3.5.6/app/controllers/0000755000004100000410000000000012663066463016176 5ustar www-datawww-datadevise-3.5.6/app/controllers/devise_controller.rb0000644000004100000410000001361612663066463022254 0ustar www-datawww-data# All Devise controllers are inherited from here. class DeviseController < Devise.parent_controller.constantize include Devise::Controllers::ScopedViews helper DeviseHelper helpers = %w(resource scope_name resource_name signed_in_resource resource_class resource_params devise_mapping) helper_method(*helpers) prepend_before_filter :assert_is_devise_resource! respond_to :html if mimes_for_respond_to.empty? # Override prefixes to consider the scoped view. # Notice we need to check for the request due to a bug in # Action Controller tests that forces _prefixes to be # loaded before even having a request object. # # This method should be public as it is is in ActionPack # itself. Changing its visibility may break other gems. def _prefixes #:nodoc: @_prefixes ||= if self.class.scoped_views? && request && devise_mapping ["#{devise_mapping.scoped_path}/#{controller_name}"] + super else super end end protected # Gets the actual resource stored in the instance variable def resource instance_variable_get(:"@#{resource_name}") end # Proxy to devise map name def resource_name devise_mapping.name end alias :scope_name :resource_name # Proxy to devise map class def resource_class devise_mapping.to end # Returns a signed in resource from session (if one exists) def signed_in_resource warden.authenticate(scope: resource_name) end # Attempt to find the mapped route for devise based on request path def devise_mapping @devise_mapping ||= request.env["devise.mapping"] end # Checks whether it's a devise mapped resource or not. def assert_is_devise_resource! #:nodoc: unknown_action! <<-MESSAGE unless devise_mapping Could not find devise mapping for path #{request.fullpath.inspect}. This may happen for two reasons: 1) You forgot to wrap your route inside the scope block. For example: devise_scope :user do get "/some/route" => "some_devise_controller" end 2) You are testing a Devise controller bypassing the router. If so, you can explicitly tell Devise which mapping to use: @request.env["devise.mapping"] = Devise.mappings[:user] MESSAGE end # Returns real navigational formats which are supported by Rails def navigational_formats @navigational_formats ||= Devise.navigational_formats.select { |format| Mime::EXTENSION_LOOKUP[format.to_s] } end def unknown_action!(msg) logger.debug "[Devise] #{msg}" if logger raise AbstractController::ActionNotFound, msg end # Sets the resource creating an instance variable def resource=(new_resource) instance_variable_set(:"@#{resource_name}", new_resource) end # Helper for use in before_filters where no authentication is required. # # Example: # before_filter :require_no_authentication, only: :new def require_no_authentication assert_is_devise_resource! return unless is_navigational_format? no_input = devise_mapping.no_input_strategies authenticated = if no_input.present? args = no_input.dup.push scope: resource_name warden.authenticate?(*args) else warden.authenticated?(resource_name) end if authenticated && resource = warden.user(resource_name) flash[:alert] = I18n.t("devise.failure.already_authenticated") redirect_to after_sign_in_path_for(resource) end end # Helper for use after calling send_*_instructions methods on a resource. # If we are in paranoid mode, we always act as if the resource was valid # and instructions were sent. def successfully_sent?(resource) notice = if Devise.paranoid resource.errors.clear :send_paranoid_instructions elsif resource.errors.empty? :send_instructions end if notice set_flash_message :notice, notice if is_flashing_format? true end end # Sets the flash message with :key, using I18n. By default you are able # to setup your messages using specific resource scope, and if no message is # found we look to the default scope. Set the "now" options key to a true # value to populate the flash.now hash in lieu of the default flash hash (so # the flash message will be available to the current action instead of the # next action). # Example (i18n locale file): # # en: # devise: # passwords: # #default_scope_messages - only if resource_scope is not found # user: # #resource_scope_messages # # Please refer to README or en.yml locale file to check what messages are # available. def set_flash_message(key, kind, options = {}) message = find_message(kind, options) if options[:now] flash.now[key] = message if message.present? else flash[key] = message if message.present? end end # Sets minimum password length to show to user def set_minimum_password_length if devise_mapping.validatable? @minimum_password_length = resource_class.password_length.min end end def devise_i18n_options(options) options end # Get message for given def find_message(kind, options = {}) options[:scope] ||= translation_scope options[:default] = Array(options[:default]).unshift(kind.to_sym) options[:resource_name] = resource_name options = devise_i18n_options(options) I18n.t("#{options[:resource_name]}.#{kind}", options) end # Controllers inheriting DeviseController are advised to override this # method so that other controllers inheriting from them would use # existing translations. def translation_scope "devise.#{controller_name}" end def clean_up_passwords(object) object.clean_up_passwords if object.respond_to?(:clean_up_passwords) end def respond_with_navigational(*args, &block) respond_with(*args) do |format| format.any(*navigational_formats, &block) end end def resource_params params.fetch(resource_name, {}) end ActiveSupport.run_load_hooks(:devise_controller, self) end devise-3.5.6/app/controllers/devise/0000755000004100000410000000000012663066463017455 5ustar www-datawww-datadevise-3.5.6/app/controllers/devise/unlocks_controller.rb0000644000004100000410000000261312663066463023725 0ustar www-datawww-dataclass Devise::UnlocksController < DeviseController prepend_before_filter :require_no_authentication # GET /resource/unlock/new def new self.resource = resource_class.new end # POST /resource/unlock def create self.resource = resource_class.send_unlock_instructions(resource_params) yield resource if block_given? if successfully_sent?(resource) respond_with({}, location: after_sending_unlock_instructions_path_for(resource)) else respond_with(resource) end end # GET /resource/unlock?unlock_token=abcdef def show self.resource = resource_class.unlock_access_by_token(params[:unlock_token]) yield resource if block_given? if resource.errors.empty? set_flash_message :notice, :unlocked if is_flashing_format? respond_with_navigational(resource){ redirect_to after_unlock_path_for(resource) } else respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new } end end protected # The path used after sending unlock password instructions def after_sending_unlock_instructions_path_for(resource) new_session_path(resource) if is_navigational_format? end # The path used after unlocking the resource def after_unlock_path_for(resource) new_session_path(resource) if is_navigational_format? end def translation_scope 'devise.unlocks' end end devise-3.5.6/app/controllers/devise/registrations_controller.rb0000644000004100000410000001140112663066463025137 0ustar www-datawww-dataclass Devise::RegistrationsController < DeviseController prepend_before_filter :require_no_authentication, only: [:new, :create, :cancel] prepend_before_filter :authenticate_scope!, only: [:edit, :update, :destroy] # GET /resource/sign_up def new build_resource({}) set_minimum_password_length yield resource if block_given? respond_with self.resource end # POST /resource def create build_resource(sign_up_params) resource.save yield resource if block_given? if resource.persisted? if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_flashing_format? sign_up(resource_name, resource) respond_with resource, location: after_sign_up_path_for(resource) else set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? expire_data_after_sign_in! respond_with resource, location: after_inactive_sign_up_path_for(resource) end else clean_up_passwords resource set_minimum_password_length respond_with resource end end # GET /resource/edit def edit render :edit end # PUT /resource # We need to use a copy of the resource because we don't want to change # the current user in place. def update self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email) resource_updated = update_resource(resource, account_update_params) yield resource if block_given? if resource_updated if is_flashing_format? flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ? :update_needs_confirmation : :updated set_flash_message :notice, flash_key end sign_in resource_name, resource, bypass: true respond_with resource, location: after_update_path_for(resource) else clean_up_passwords resource respond_with resource end end # DELETE /resource def destroy resource.destroy Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name) set_flash_message :notice, :destroyed if is_flashing_format? yield resource if block_given? respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) } end # GET /resource/cancel # Forces the session data which is usually expired after sign # in to be expired now. This is useful if the user wants to # cancel oauth signing in/up in the middle of the process, # removing all OAuth session data. def cancel expire_data_after_sign_in! redirect_to new_registration_path(resource_name) end protected def update_needs_confirmation?(resource, previous) resource.respond_to?(:pending_reconfirmation?) && resource.pending_reconfirmation? && previous != resource.unconfirmed_email end # By default we want to require a password checks on update. # You can overwrite this method in your own RegistrationsController. def update_resource(resource, params) resource.update_with_password(params) end # Build a devise resource passing in the session. Useful to move # temporary session data to the newly created user. def build_resource(hash=nil) self.resource = resource_class.new_with_session(hash || {}, session) end # Signs in a user on sign up. You can overwrite this method in your own # RegistrationsController. def sign_up(resource_name, resource) sign_in(resource_name, resource) end # The path used after sign up. You need to overwrite this method # in your own RegistrationsController. def after_sign_up_path_for(resource) after_sign_in_path_for(resource) end # The path used after sign up for inactive accounts. You need to overwrite # this method in your own RegistrationsController. def after_inactive_sign_up_path_for(resource) scope = Devise::Mapping.find_scope!(resource) router_name = Devise.mappings[scope].router_name context = router_name ? send(router_name) : self context.respond_to?(:root_path) ? context.root_path : "/" end # The default url to be used after updating a resource. You need to overwrite # this method in your own RegistrationsController. def after_update_path_for(resource) signed_in_root_path(resource) end # Authenticates the current scope and gets the current resource from the session. def authenticate_scope! send(:"authenticate_#{resource_name}!", force: true) self.resource = send(:"current_#{resource_name}") end def sign_up_params devise_parameter_sanitizer.sanitize(:sign_up) end def account_update_params devise_parameter_sanitizer.sanitize(:account_update) end def translation_scope 'devise.registrations' end end devise-3.5.6/app/controllers/devise/sessions_controller.rb0000644000004100000410000000465612663066463024126 0ustar www-datawww-dataclass Devise::SessionsController < DeviseController prepend_before_filter :require_no_authentication, only: [:new, :create] prepend_before_filter :allow_params_authentication!, only: :create prepend_before_filter :verify_signed_out_user, only: :destroy prepend_before_filter only: [:create, :destroy] { request.env["devise.skip_timeout"] = true } # GET /resource/sign_in def new self.resource = resource_class.new(sign_in_params) clean_up_passwords(resource) yield resource if block_given? respond_with(resource, serialize_options(resource)) end # POST /resource/sign_in def create self.resource = warden.authenticate!(auth_options) set_flash_message(:notice, :signed_in) if is_flashing_format? sign_in(resource_name, resource) yield resource if block_given? respond_with resource, location: after_sign_in_path_for(resource) end # DELETE /resource/sign_out def destroy signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)) set_flash_message :notice, :signed_out if signed_out && is_flashing_format? yield if block_given? respond_to_on_destroy end protected def sign_in_params devise_parameter_sanitizer.sanitize(:sign_in) end def serialize_options(resource) methods = resource_class.authentication_keys.dup methods = methods.keys if methods.is_a?(Hash) methods << :password if resource.respond_to?(:password) { methods: methods, only: [:password] } end def auth_options { scope: resource_name, recall: "#{controller_path}#new" } end def translation_scope 'devise.sessions' end private # Check if there is no signed in user before doing the sign out. # # If there is no signed in user, it will set the flash message and redirect # to the after_sign_out path. def verify_signed_out_user if all_signed_out? set_flash_message :notice, :already_signed_out if is_flashing_format? respond_to_on_destroy end end def all_signed_out? users = Devise.mappings.keys.map { |s| warden.user(scope: s, run_callbacks: false) } users.all?(&:blank?) end def respond_to_on_destroy # We actually need to hardcode this as Rails default responder doesn't # support returning empty response on GET request respond_to do |format| format.all { head :no_content } format.any(*navigational_formats) { redirect_to after_sign_out_path_for(resource_name) } end end end devise-3.5.6/app/controllers/devise/omniauth_callbacks_controller.rb0000644000004100000410000000165412663066463026076 0ustar www-datawww-dataclass Devise::OmniauthCallbacksController < DeviseController prepend_before_filter { request.env["devise.skip_timeout"] = true } def passthru render status: 404, text: "Not found. Authentication passthru." end def failure set_flash_message :alert, :failure, kind: OmniAuth::Utils.camelize(failed_strategy.name), reason: failure_message redirect_to after_omniauth_failure_path_for(resource_name) end protected def failed_strategy env["omniauth.error.strategy"] end def failure_message exception = env["omniauth.error"] error = exception.error_reason if exception.respond_to?(:error_reason) error ||= exception.error if exception.respond_to?(:error) error ||= env["omniauth.error.type"].to_s error.to_s.humanize if error end def after_omniauth_failure_path_for(scope) new_session_path(scope) end def translation_scope 'devise.omniauth_callbacks' end end devise-3.5.6/app/controllers/devise/confirmations_controller.rb0000644000004100000410000000302112663066463025114 0ustar www-datawww-dataclass Devise::ConfirmationsController < DeviseController # GET /resource/confirmation/new def new self.resource = resource_class.new end # POST /resource/confirmation def create self.resource = resource_class.send_confirmation_instructions(resource_params) yield resource if block_given? if successfully_sent?(resource) respond_with({}, location: after_resending_confirmation_instructions_path_for(resource_name)) else respond_with(resource) end end # GET /resource/confirmation?confirmation_token=abcdef def show self.resource = resource_class.confirm_by_token(params[:confirmation_token]) yield resource if block_given? if resource.errors.empty? set_flash_message(:notice, :confirmed) if is_flashing_format? respond_with_navigational(resource){ redirect_to after_confirmation_path_for(resource_name, resource) } else respond_with_navigational(resource.errors, status: :unprocessable_entity){ render :new } end end protected # The path used after resending confirmation instructions. def after_resending_confirmation_instructions_path_for(resource_name) is_navigational_format? ? new_session_path(resource_name) : '/' end # The path used after confirmation. def after_confirmation_path_for(resource_name, resource) if signed_in?(resource_name) signed_in_root_path(resource) else new_session_path(resource_name) end end def translation_scope 'devise.confirmations' end end devise-3.5.6/app/controllers/devise/passwords_controller.rb0000644000004100000410000000517712663066463024304 0ustar www-datawww-dataclass Devise::PasswordsController < DeviseController prepend_before_filter :require_no_authentication # Render the #edit only if coming from a reset password email link append_before_filter :assert_reset_token_passed, only: :edit # GET /resource/password/new def new self.resource = resource_class.new end # POST /resource/password def create self.resource = resource_class.send_reset_password_instructions(resource_params) yield resource if block_given? if successfully_sent?(resource) respond_with({}, location: after_sending_reset_password_instructions_path_for(resource_name)) else respond_with(resource) end end # GET /resource/password/edit?reset_password_token=abcdef def edit self.resource = resource_class.new set_minimum_password_length resource.reset_password_token = params[:reset_password_token] end # PUT /resource/password def update self.resource = resource_class.reset_password_by_token(resource_params) yield resource if block_given? if resource.errors.empty? resource.unlock_access! if unlockable?(resource) if Devise.sign_in_after_reset_password flash_message = resource.active_for_authentication? ? :updated : :updated_not_active set_flash_message(:notice, flash_message) if is_flashing_format? sign_in(resource_name, resource) else set_flash_message(:notice, :updated_not_active) if is_flashing_format? end respond_with resource, location: after_resetting_password_path_for(resource) else set_minimum_password_length respond_with resource end end protected def after_resetting_password_path_for(resource) Devise.sign_in_after_reset_password ? after_sign_in_path_for(resource) : new_session_path(resource_name) end # The path used after sending reset password instructions def after_sending_reset_password_instructions_path_for(resource_name) new_session_path(resource_name) if is_navigational_format? end # Check if a reset_password_token is provided in the request def assert_reset_token_passed if params[:reset_password_token].blank? set_flash_message(:alert, :no_token) redirect_to new_session_path(resource_name) end end # Check if proper Lockable module methods are present & unlock strategy # allows to unlock resource on password reset def unlockable?(resource) resource.respond_to?(:unlock_access!) && resource.respond_to?(:unlock_strategy_enabled?) && resource.unlock_strategy_enabled?(:email) end def translation_scope 'devise.passwords' end end devise-3.5.6/app/mailers/0000755000004100000410000000000012663066463015264 5ustar www-datawww-datadevise-3.5.6/app/mailers/devise/0000755000004100000410000000000012663066463016543 5ustar www-datawww-datadevise-3.5.6/app/mailers/devise/mailer.rb0000644000004100000410000000123312663066463020340 0ustar www-datawww-dataif defined?(ActionMailer) class Devise::Mailer < Devise.parent_mailer.constantize include Devise::Mailers::Helpers def confirmation_instructions(record, token, opts={}) @token = token devise_mail(record, :confirmation_instructions, opts) end def reset_password_instructions(record, token, opts={}) @token = token devise_mail(record, :reset_password_instructions, opts) end def unlock_instructions(record, token, opts={}) @token = token devise_mail(record, :unlock_instructions, opts) end def password_change(record, opts={}) devise_mail(record, :password_change, opts) end end end devise-3.5.6/app/helpers/0000755000004100000410000000000012663066463015272 5ustar www-datawww-datadevise-3.5.6/app/helpers/devise_helper.rb0000644000004100000410000000153212663066463020436 0ustar www-datawww-datamodule DeviseHelper # A simple way to show error messages for the current devise resource. If you need # to customize this method, you can either overwrite it in your application helpers or # copy the views to your application. # # This method is intended to stay simple and it is unlikely that we are going to change # it to add more behavior or options. def devise_error_messages! return "" if resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join sentence = I18n.t("errors.messages.not_saved", count: resource.errors.count, resource: resource.class.model_name.human.downcase) html = <<-HTML

#{sentence}

    #{messages}
HTML html.html_safe end end devise-3.5.6/CHANGELOG.md0000644000004100000410000013232112663066463014663 0ustar www-datawww-data### 3.5.6 - 2016-01-02 * bug fixes * Fix type coercion of the rememberable timestamp stored on cookies. ### 3.5.5 - 2016-22-01 * bug fixes * Bring back remember_expired? implementation * Ensure timeouts are not triggered if remember me is being used ### 3.5.4 - 2016-18-01 * bug fixes * Store creation timestamps on remember cookies ### 3.5.3 - 2015-12-10 * bug fixes * Fix password reset for records where `confirmation_required?` is disabled and `confirmation_sent_at` is nil. (by @andygeers) * Allow resources with no `email` field to be recoverable (and do not clear the reset password token if the model was already persisted). (by @seddy, @stanhu) * enhancements * Upon setting `Devise.send_password_change_notification = true` a user will receive notification when their password has been changed. ### 3.5.2 - 2015-08-10 * enhancements * Perform case insensitive basic authorization matching * bug fixes * Do not use digests for password confirmation token * Fix infinite redirect in Rails 4.2 authenticated routes * Autoload Devise::Encryptor to avoid errors on thread-safe mode * deprecations * `config.expire_auth_token_on_timeout` was removed ### 3.5.1 - 2015-05-24 Note: 3.5.0 has been yanked due to a regression * security improvements * Clean up reset password token whenever e-mail or password changes. thanks to George Deglin & Dennis Charles Hackethal for reporting this bug * Ensure empty `authenticable_salt` cannot be used as remember token. This bug can only affect users who manually implement their own `authenticable_salt` and allow empty values as salt * enhancements * The hint about minimum password length required both `@validatable` and `@minimum_password_length` variables on the views, it now uses only the latter. If you have generated the views relying on the `@validatable` variable, replace it with `@minimum_password_length`. * Added an ActiveSupport load hook for `:devise_controller`. (by @nakhli) * Location fragments are now preserved between requests. (by @jbourassa) * Added an `after_remembered` callback for the Rememerable module. (by @BM5k) * `RegistrationsController#new` and `SessionsController#new` now yields the current resource. (by @mtarnovan, @deivid-rodriguez) * Password length validation is now limited to 72 characters for newer apps. (by @lleger) * Controllers inheriting from any Devise core controller will now use appropriate translations. The i18n scope can be overridden in `translation_scope`. * Allow the user to set the length of friendly token. (by @Angelmmiguel) * bug fixes * Use router_name from scope if one is available to support isolated engines. (by @cipater) * Do not clean up CSRF on rememberable. * Only use flash if it has been configured in failure app. (by @alex88) * deprecations * `confirm!` has been deprecated in favor of `confirm`. * `reset_password!` has been deprecated in favor of `reset_password`. * `Devise.bcrypt` has been deprecated in favor of `Devise::Encryptor.digest`". ### 3.4.1 - 2014-10-29 * enhancements * Devise default views now have a similar markup to Rails scaffold views. (by @udaysinghcode, @cllns) * Passing `now: true` to the `set_flash_message` helper now sets the message into the `flash.now` Hash. (by @hbriggs) * bugfixes * Fixed an regression with translation of flash messages for when the `authentication_keys` config is a Hash. (by @lucasmazza) ### 3.4.0 - 2014-10-03 * enhancements * Support added for Rails 4.2. Devise now depends on the `responders` gem due the extraction of the `respond_with` API from Rails. (by @lucasmazza) * The Simple Form templates follow the same change from 3.3.0 by using `Log in` and adding a hint about the minimum password length when `validatable` is enabled. (by @aried3r) * Controller generator added as `devise:controllers SCOPE`. You can use the `-c` flag to pick which controllers (`unlocks`, `confirmations`, etc) you want to generate. (by @Chun-Yang) * Removed the hardcoded references for "email" in the flash messages. If you are using different attributes as the `authentication_keys` they will be interpolated in the messages instead. (by @timoschilling) * bug fix * Fixed a regression where the devise generator would fail with a `ConnectionNotEstablished` exception when executed inside a mountable engine. (by @lucasmazza) * Ensure to return symbols in find_scope! fixing a previous regression from 3.3.0 (by @micat) * Ensure all causes of failed login have the same error message (by @pjungwir) * The `last_attempt_warning` now takes effect when generating the unauthenticated message for your users. To keep the current behavior, this flag is now `true` by default. (by @lucasmazza) ### 3.3.0 - 2014-08-13 * enhancements * Support multiple warden configuration blocks on devise configuration. (by @rossta) * Previously, when a user signed out, all remember me tokens for all sessions/browsers would be invalidated, and this behavior could not be changed. This behavior is now configurable via `expire_all_remember_me_on_sign_out`. The default continues to be true. (by @laurocaetano) * Default email messages was updated with grammar fixes, check the diff on #2906 for the updated copy (by @p-originate) * Allow a resource to be found based on its encrypted password token (by @karlentwistle) * Adds `devise_group`, a macro to define controller helpers for multiple mappings at once. (by @dropletzz) * The default views now use `Log in` instead of `Sign in` and have a hint about the minimum password length if the current scope is using the `validatable` module (by @alexsoble) * bug fix * Check if there is a signed in user before executing the `SessionsController#destroy`. * `SessionsController#destroy` no longer yields the `resource` to receiving block, since the resource isn't loaded in the action. If you need access to the current resource when overring the action use the scope helper (like `current_user`) before calling `super` * Serialize the `last_request_at` entry as an Integer * Ensure registration controller block yields happen on failure in addition to success (by @dpehrson) * Only valid paths will be stored for redirections (by @parallel588) ### 3.2.4 - 2014-03-17 * enhancements * `bcrypt` dependency updated due https://github.com/codahale/bcrypt-ruby/pull/86. * View generator now can generate specific views with the `-v` flag, like `rails g devise:views -v sessions` (by @kayline) ### 3.2.3 - 2014-02-20 * enhancements * Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key`. You can change this and use your own secret by changing the `devise.rb` initializer. * bug fix * Migrations will be properly generated when using rails 4.1.0. ### 3.2.2 - 2013-11-25 * bug fix * Ensure timeoutable works when `sign_out_all_scopes` is false (by @louman) * Keep the query string when storing location (by @csexton) * Require rails generator base class in devise generators ### 3.2.1 - 2013-11-13 Security announcement: http://blog.plataformatec.com.br/2013/11/e-mail-enumeration-in-devise-in-paranoid-mode * enhancements * Add `store_location_for` helper and ensure it is safe (by @matthewrudy and @homakov) * Add `yield` around resource methods in Devise controllers (by @edelpero) * bug fix * Bring `password_digest` back to fix compatibility with `devise-encryptable` * Avoid e-mail enumeration on sign in when in paranoid mode ### 3.2.0 - 2013-11-06 * enhancements * Previously deprecated token authenticatable and insecure lookups have been removed * Add a class method so you can encrypt passwords from fixtures (by @tenderlove) * Send custom message when user enters invalid password and it has only one attempt to enter correct password before their account will be locked (by @Lightpower) * Prevent mutation of values assigned to case and whitespace santitized members (by @iamvery) * Separate redirects and flash messages in `navigational_formats` and `flashing_formats` (by @ssendev) * bug fix * A GET to sign_in page shouldn't extend the session (by @drewish) * Splat the arguments to `strong_parameters#permit` to work around a limitation in the `strong_parameters` gem (by @memberful) * Omniauth now uses `mapping.fullpath` when generating routes. This means if you call `devise_for :users` inside a scope, like `scope "/api"`, the scope will now apply to the omniauth route (by @AlexanderZaytsev) * Ensure timeoutable hook respects `Devise.sign_out_all_scopes` configuration * deprecations * `expire_session_data_after_sign_in!` has been deprecated in favor of `expire_data_after_sign_in!` ### 3.1.1 - 2013-10-01 * bug fix * Improve default message which asked users to sign in even when they were already signed (by @gregates) * Improve error message for when the config.secret_key is missing ### 3.1.0 - 2013-09-05 Security announcement: http://blog.plataformatec.com.br/2013/08/devise-3-1-now-with-more-secure-defaults/ * backwards incompatible changes * Do not store confirmation, unlock and reset password tokens directly in the database. This means tokens previously stored in the database are no longer valid. You can reenable this temporarily by setting `config.allow_insecure_token_lookup = true` in your configuration file. It is recommended to keep this configuration set to true just temporarily in your production servers only to aid migration * The Devise mailer and its views were changed to explicitly receive a token argument as `@token`. You will need to update your mailers and re-copy the views to your application with `rails g devise:views` * Sanitization of parameters should be done by calling `devise_parameter_sanitizer.sanitize(:action)` instead of `devise_parameter_sanitizer.for(:action)` * deprecations * Token authentication is deprecated * enhancements * Better security defaults * Allow easier customization of parameter sanitizer (by @alexpeattie) * bug fix * Do not confirm e-mail after password reset (by @moll) * Do not sign in after confirmation * Do not store confirmation, unlock and reset password tokens directly in the database * Do not compare directly against confirmation, unlock and reset password tokens * Skip storage for cookies on unverified requests ### 3.0.2 - 2013-08-09 * bug fix * Skip storage for cookies on unverified requests ### 3.0.1 - 2013-08-02 Security announcement: http://blog.plataformatec.com.br/2013/08/csrf-token-fixation-attacks-in-devise/ * enhancements * Add after_confirmation callback * bug fix * When using rails 3.2, the generator adds 'attr_accessible' to the model (by @jcoyne) * Clean up CSRF token after authentication (by @homakov). Notice this change will clean up the CSRF Token after authentication (sign in, sign up, etc). So if you are using AJAX for such features, you will need to fetch a new CSRF token from the server. ### 3.0.0 - 2013-07-14 * enhancements * Rails 4 and Strong Parameters compatibility (by @carlosantoniodasilva, @josevalim, @latortuga, @lucasmazza, @nashby, @rafaelfranca, @spastorino) * Drop support for Rails < 3.2 and Ruby < 1.9.3 * Enable to skip sending reconfirmation email when reconfirmable is on and `skip_confirmation_notification!` is invoked (by @tkhr) * bug fix * Errors on unlock are now properly reflected on the first `unlock_keys` ### 2.2.4 - 2013-05-07 * enhancements * Add `destroy_with_password` to `DatabaseAuthenticatable`. Allows destroying a record when `:current_password` matches, similarly to how `update_with_password` works. (by @michiel3) * Allow to override path after password resetting (by @worker8) * Add `#skip_confirmation_notification!` method to `Confirmable`. Allows skipping confirmation email without auto-confirming. (by @gregates) * allow_unconfirmed_access_for config from `:confirmable` module can be set to `nil` that means unconfirmed access for unlimited time. (by @nashby) * Support Rails' token strategy on authentication (by @robhurring) * Support explicitly setting the http authentication key via `config.http_authentication_key` (by @neo) * bug fix * Do not redirect when accessing devise API via JSON. (by @sebastianwr) * Generating scoped devise views now uses the correct scoped shared links partial instead of the default devise one (by @nashby) * Fix inheriting mailer templates from `Devise::Mailer` * Fix a bug when procs are used as default mailer in Devise (by @tomasv) * backwards incompatible changes * Changes on session storage will expire all existing sessions on upgrade. For those storing the session in the DB, they can be upgraded according to this gist: https://gist.github.com/moll/6417606 ### 2.2.3 - 2013-01-26 Security announcement: http://blog.plataformatec.com.br/2013/01/security-announcement-devise-v2-2-3-v2-1-3-v2-0-5-and-v1-5-3-released/ * bug fix * Require string conversion for all values ### 2.2.2 - 2013-01-15 * bug fix * Fix bug when checking for reconfirmable in templates ### 2.2.1 - 2013-01-11 * bug fix * Fix regression with case_insensitive_keys * Fix regression when password is blank when it is invalid ### 2.2.0 - 2013-01-08 * backwards incompatible changes * `headers_for` is deprecated, customize the mailer directly instead * All mailer methods now expect a second argument with delivery options * Default minimum password length is now 8 (by @carlosgaldino) * Support alternate sign in error message when email record does not exist (this adds a new I18n key to the locale file) (by @gabetax) * DeviseController responds only to HTML requests by default (call `DeviseController.respond_to` or `ApplicationController.respond_to` to add new formats) * Support Mongoid 3 onwards (by @durran) * enhancements * Fix unlockable which could leak account existence on paranoid mode (by @latortuga) * Confirmable now has a confirm_within option to set a period while the confirmation token is still valid (by @promisedlandt) * Flash messages in controller now respects `resource_name` (by @latortuga) * Separate `sign_in` and `sign_up` on RegistrationsController (by @rubynortheast) * Add autofocus to default views (by @Radagaisus) * Unlock user on password reset (by @marcinb) * Allow validation callbacks to apply to virtual attributes (by @latortuga) * bug fix * unconfirmed_email now uses the proper e-mail on salutation * Fix default email_regexp config to not allow spaces (by @kukula) * Fix a regression introduced on warden 1.2.1 (by @ejfinneran) * Properly camelize omniauth strategies (by @saizai) * Do not set flash messages for non navigational requests on session sign out (by @mathieul) * Set the proper fields as required on the lockable module (by @nickhoffman) * Respects Devise mailer default's reply_to (by @mrchrisadams) * Properly assign resource on `sign_in` related action (by @adammcnamara) * `update_with_password` doesn't change encrypted password when it is invalid (by @nashby) * Properly handle namespaced models on Active Record generator (by @nashby) ### 2.1.4 - 2013-08-18 * bugfix * Do not confirm account after reset password ### 2.1.3 - 2013-01-26 * bugfix * Require string conversion for all values ### 2.1.2 - 2012-06-19 * enhancements * Handle backwards incompatibility between Rails 3.2.6 and Thor 0.15.x * bug fix * Fix regression on strategy validation on previous release ### 2.1.1 - 2012-06-15 (yanked) * enhancements * `sign_out_all_scopes` now locks warden and does not allow new logins in the same action * `Devise.omniauth_path_prefix` is available to configure omniauth path prefix * Redirect to sign in page when trying to access password#edit without a token (by @gbataille) * Allow a lambda in authenticate(d) routes helpers to further select the scope * Removed warnings on Rails 3.2.6 (by @nashby) * bug fix * `update_with_password` now relies on assign_attributes and forwards the :as option (by @wtn) * Do not trigger timeout on sign in related actions * Timeout does not explode when reset_authentication_token! is accidentally defined by Active Model (by @remomueller) * deprecations * Strategy#validate() no longer validates nil resources ### 2.1.0 - 2012-05-15 * enhancements * Add `check_fields!(model_class)` method on Devise::Models to check if the model includes the fields that Devise uses * Add `skip_reconfirmation!` to skip reconfirmation * Devise model generator now works with engines * Devise encryptable was moved to its new gem (http://github.com/plataformatec/devise-encryptable) * deprecations * Deprecations warnings added on Devise 2.0 are now removed with their features * All devise modules should now have a `required_fields(klass)` module method to help gathering missing attributes * `use_salt_as_remember_token` and `apply_schema` does not have any effect since 2.0 and are now deprecated * `valid_for_authentication?` must now return a boolean * bug fix * Ensure after sign in hook is not called without a resource * Fix a term: now on Omniauth related flash messages, we say that we're authenticating from an omniauth provider instead of authorizing * Fixed redirect when authenticated mounted apps (by @hakanensari) * Ensure the failure app still respects config.relative_url_root * `/users/sign_in` doesn't choke on protected attributes used to select sign in scope (by @Paymium) * `failed_attempts` is set to zero after any sign in (including via reset password) (by @rodrigoflores) * Added token expiration on timeout (by @antiarchitect) * Do not accidentally mark `_prefixes` as private * Better support for custom strategies on test helpers (by @mattconnolly) * Return `head :no_content` in SessionsController now that most JS libraries handle it (by @julianvargasalvarez) * Reverted moving devise/shared/_links.erb to devise/_links.erb ### 2.0.4 - 2012-02-17 Notes: https://github.com/plataformatec/devise/wiki/How-To:-Upgrade-to-Devise-2.0 * bug fix * Fix when :host is used with devise_for (by @mreinsch) * Fix a regression that caused Warden to be initialized too late ### 2.0.3 - 2012-06-16 (yanked) * bug fix * Ensure warning is not shown by mistake on apps with mounted engines * Fixes related to remember_token and rememberable_options * Ensure serializable_hash does not depend on accessible attributes * Ensure that timeout callback does not run on sign out action ### 2.0.2 - 2012-02-14 * enhancements * Add devise_i18n_options to customize I18n message * bug fix * Ensure Devise.available_router_name defaults to :main_app * Set autocomplete to off for password on edit forms * Better error messages in case a trackable model can't be saved * Show a warning in case someone gives a pluralized name to devise generator * Fix test behavior for rspec subject requests (by @sj26) ### 2.0.1 - 2012-02-09 * enhancements * Improved error messages on deprecation warnings * Hide Devise's internal generators from `rails g` command * bug fix * Removed tmp and log files from gem ### 2.0.0 - 2012-01-26 * enhancements * Add support for e-mail reconfirmation on change (by @Mandaryn and @heimidal) * Redirect users to sign in page after unlock (by @nashby) * Redirect to the previous URL on timeout * Inherit from the same Devise parent controller (by @sj26) * Allow parent_controller to be customizable via Devise.parent_controller, useful for engines * Allow router_name to be customizable via Devise.router_name, useful for engines * Allow alternate ORMs to run compatibility setup code before Authenticatable is included (by @jm81) * deprecation * Devise now only supports Rails 3.1 forward * Devise.confirm_within was deprecated in favor Devise.allow_unconfirmed_access_for * Devise.stateless_token= is deprecated in favor of appending :token_auth to Devise.skip_session_storage * Usage of Devise.apply_schema is deprecated * Usage of Devise migration helpers are deprecated * Usage of Devise.remember_across_browsers was deprecated * Usage of rememberable with remember_token was removed * Usage of recoverable without reset_password_sent_at was removed * Usage of Devise.case_insensitive_keys equals to false was removed * Move devise/shared/_links.erb to devise/_links.erb * Deprecated support of nested devise_for blocks * Deprecated support to devise.registrations.reasons and devise.registrations.inactive_signed_up in favor of devise.registrations.signed_up_but_* * Protected method render_with_scope was removed. ### 1.5.3 - 2011-12-19 * bug fix * Ensure delegator converts scope to symbol (by @dmitriy-kiriyenko) * Ensure passing :format => false to devise_for is not permanent * Ensure path checker does not check invalid routes ### 1.5.2 - 2011-11-30 * enhancements * Add support for Rails 3.1 new mass assignment conventions (by @kirs) * Add timeout_in method to Timeoutable, it can be overridden in a model (by @lest) * bug fix * OmniAuth error message now shows the proper option (:strategy_class instead of :klass) ### 1.5.1 - 2011-11-22 * bug fix * Devise should not attempt to load OmniAuth strategies. Strategies should be loaded before hand by the developer or explicitly given to Devise. ### 1.5.0 - 2011-11-13 * enhancements * Timeoutable also skips tracking if skip_trackable is given * devise_for now accepts :failure_app as an option * Models can select the proper mailer via devise_mailer method (by @locomotivecms) * Migration generator now uses the change method (by @nashby) * Support to markerb templates on the mailer generator (by @sbounmy) * Support for Omniauth 1.0 (older versions are no longer supported) (by @TamiasSibiricus) * bug fix * Allow idempotent API requests * Fix bug where logs did not show 401 as status code * Change paranoid settings to behave as success instead of as failure * Fix bug where activation messages were shown first than the credentials error message * Instance variables are expired after sign out * deprecation * redirect_location is deprecated, please use after_sign_in_path_for * after_sign_in_path_for now redirects to session[scope_return_to] if any value is stored in it ### 1.4.9 - 2011-10-19 * bug fix * url helpers were not being set under some circumstances ### 1.4.8 - 2011-10-09 * enhancements * Add docs for assets pipeline and Heroku * bug fix * confirmation_url was not being set under some circumstances ### 1.4.7 - 2011-09-21 * bug fix * Fix backward incompatible change from 1.4.6 for those using custom controllers ### 1.4.6 - 2011-09-19 (yanked) * enhancements * Allow devise_for :skip => :all * Allow options to be passed to authenticate_user! * Allow --skip-routes to devise generator * Add allow_params_authentication! to make it explicit when params authentication is allowed in a controller ### 1.4.5 - 2011-09-07 * bug fix * Failure app tries the root path if a session one does not exist * No need to finalize Devise helpers all the time (by @bradleypriest) * Reset password shows proper message if user is not active * `clean_up_passwords` sets the accessors to nil to skip validations ### 1.4.4 - 2011-08-30 * bug fix * Do not always skip helpers, instead provide :skip_helpers as option to trigger it manually ### 1.4.3 - 2011-08-29 * enhancements * Improve Rails 3.1 compatibility * Use serialize_into_session and serialize_from_session in Warden serialize to improve extensibility * bug fix * Generator properly generates a change_table migration if a model already exists * Properly deprecate setup_mail * Fix encoding issues with email regexp * Only generate helpers for the used mappings * Wrap :action constraints in the proper hash * deprecations * Loosened the used email regexp to simply assert the existent of "@". If someone relies on a more strict regexp, they may use https://github.com/SixArm/sixarm_ruby_email_address_validation ### 1.4.2 - 2011-06-30 * bug fix * Provide a more robust behavior to serializers and add :force_except option ### 1.4.1 - 2011-06-29 * enhancements * Add :defaults and :format support on router * Add simple form generators * Better localization for devise_error_messages! (by @zedtux) * bug fix * Ensure to_xml is properly white listened * Ensure handle_unverified_request clean up any cached signed-in user ### 1.4.0 - 2011-06-23 * enhancements * Added authenticated and unauthenticated to the router to route the used based on their status (by @sj26) * Improve e-mail regexp (by @rodrigoflores) * Add strip_whitespace_keys and default to e-mail (by @swrobel) * Do not run format and uniqueness validations on e-mail if it hasn't changed (by @Thibaut) * Added update_without_password to update models but not allowing the password to change (by @fschwahn) * Added config.paranoid, check the generator for more information (by @rodrigoflores) * bug fix * password_required? should not affect length validation * User cannot access sign up and similar pages if they are already signed in through a cookie or token * Do not convert booleans to strings on finders (by @xavier) * Run validations even if current_password fails (by @crx) * Devise now honors routes constraints (by @macmartine) * Do not return the user resource when requesting instructions (by @rodrigoflores) ### 1.3.4 - 2011-04-28 * bug fix * Do not add formats if html or "*/*" ### 1.3.3 - 2011-04-20 * bug fix * Explicitly mark the token as expired if so ### 1.3.2 - 2011-04-20 * bug fix * Fix another regression related to reset_password_sent_at (by @alexdreher) ### 1.3.1 - 2011-04-18 * enhancements * Improve failure_app responses (by @indirect) * sessions/new and registrations/new also respond to xml and json now * bug fix * Fix a regression that occurred if reset_password_sent_at is not present (by @stevehodgkiss) ### 1.3.0 - 2011-04-15 * enhancements * All controllers can now handle different mime types than html using Responders (by @sikachu) * Added reset_password_within as configuration option to send the token for recovery (by @jdguyot) * Bump password length to 128 characters (by @k33l0r) * Add :only as option to devise_for (by @timoschilling) * Allow to override path after sending password instructions (by @irohiroki) * require_no_authentication has its own flash message (by @jackdempsey) * bug fix * Fix a bug where configuration options were being included too late * Ensure Devise::TestHelpers can be used to tests Devise internal controllers (by @jwilger) * valid_password? should not choke on empty passwords (by @mikel) * Calling devise more than once does not include previously added modules anymore * downcase_keys before validation * backward incompatible changes * authentication_keys are no longer considered when creating the e-mail validations, the previous behavior was buggy. You must double check if you were relying on such behavior. ### 1.2.1 - 2011-03-27 * enhancements * Improve update path messages ### 1.2.0 - 2011-03-24 * bug fix * Properly ignore path prefix on omniauthable * Faster uniqueness queries * Rename active? to active_for_authentication? to avoid conflicts ### 1.2.rc2 - 2011-03-10 * enhancements * Make friendly_token 20 chars long * Use secure_compare * bug fix * Fix an issue causing infinite redirects in production * rails g destroy works properly with devise generators (by @andmej) * before_failure callbacks should work on test helpers (by @twinge) * rememberable cookie now is httponly by default (by @JamesFerguson) * Add missing confirmation_keys (by @JohnPlummer) * Ensure after_* hooks are called on RegistrationsController * When using database_authenticatable Devise will now only create an email field when appropriate (if using default authentication_keys or custom authentication_keys with email included) * Ensure stateless token does not trigger timeout (by @pixelauthority) * Implement handle_unverified_request for Rails 3.0.4 compatibility and improve FailureApp reliance on symbols * Consider namespaces while generating routes * Custom failure apps no longer ignored in test mode (by @jaghion) * Do not depend on ActiveModel::Dirty * Manual sign_in now triggers remember token * Be sure to halt strategies on failures * Consider SCRIPT_NAME on Omniauth paths * Reset failed attempts when lock is expired * Ensure there is no Mongoid injection * deprecations * Deprecated anybody_signed_in? in favor of signed_in? (by @gavinhughes) * Removed --haml and --slim view templates * Devise::OmniAuth helpers were deprecated and removed in favor of Omniauth.config.test_mode ### 1.2.rc - 2010-10-25 * deprecations * cookie_domain is deprecated in favor of cookie_options * after_update_path_for can no longer be defined in ApplicationController * enhancements * Added OmniAuth support * Added ORM adapter to abstract ORM iteraction * sign_out_via is available in the router to configure the method used for sign out (by @martinrehfeld) * Improved Ajax requests handling in failure app (by @spastorino) * Added request_keys to easily use request specific values (like subdomain) in authentication * Increased the size of friendly_token to 60 characters (reduces the chances of a successful brute attack) * Ensure the friendly token does not include "_" or "-" since some e-mails may not autolink it properly (by @rymai) * Extracted encryptors into :encryptable for better bcrypt support * :rememberable is now able to use salt as token if no remember_token is provided * Store the salt in session and expire the session if the user changes their password * Allow :stateless_token to be set to true avoiding users to be stored in session through token authentication * cookie_options uses session_options values by default * Sign up now checks if the user is active or not and redirect them accordingly, setting the inactive_signed_up message * Use ActiveModel#to_key instead of #id * sign_out_all_scopes now destroys the whole session * Added case_insensitive_keys that automatically downcases the given keys, by default downcases only e-mail (by @adahl) * default behavior changes * sign_out_all_scopes defaults to true as security measure * http authenticatable is disabled by default * Devise does not intercept 401 returned from applications * bugfix * after_sign_in_path_for always receives a resource * Do not execute Warden::Callbacks on Devise::TestHelpers (by @sgronblo) * Allow password recovery and account unlocking to change used keys (by @RStankov) * FailureApp now properly handles nil request.format * Fix a bug causing FailureApp to return with HTTP Auth Headers for IE7 * Ensure namespaces has proper scoped views * Ensure Devise does not set empty flash messages (by @sxross) ### 1.1.6 - 2011-02-14 * Use a more secure e-mail regexp * Implement Rails 3.0.4 handle unverified request * Use secure_compare to compare passwords ### 1.1.5 - 2010-11-26 * bugfix * Ensure to convert keys on indifferent hash * defaults * Set config.http_authenticatable to false to avoid confusion ### 1.1.4 - 2010-11-25 * bugfix * Avoid session fixation attacks ### 1.1.3 - 2010-09-23 * bugfix * Add reply-to to e-mail headers by default * Updated the views generator to respect the rails :template_engine option (by @fredwu) * Check the type of HTTP Authentication before using Basic headers * Avoid invalid_salt errors by checking salt presence (by @thibaudgg) * Forget user deletes the right cookie before logout, not remembering the user anymore (by @emtrane) * Fix for failed first-ever logins on PostgreSQL where column default is nil (by @bensie) * :default options is now honored in migrations ### 1.1.2 - 2010-08-25 * bugfix * Compatibility with latest Rails routes schema ### 1.1.1 - 2010-07-26 * bugfix * Fix a small bug where generated locale file was empty on devise:install ### 1.1.0 - 2010-07-25 * enhancements * Rememberable module allows user to be remembered across browsers and is enabled by default (by @trevorturk) * Rememberable module allows you to activate the period the remember me token is extended (by @trevorturk) * devise_for can now be used together with scope method in routes but with a few limitations (check the documentation) * Support `as` or `devise_scope` in the router to specify controller access scope * HTTP Basic Auth can now be disabled/enabled for xhr(ajax) requests using http_authenticatable_on_xhr option (by @pellja) * bug fix * Fix a bug in Devise::TestHelpers where current_user was returning a Response object for non active accounts * Devise should respect script_name and path_info contracts * Fix a bug when accessing a path with (.:format) (by @klacointe) * Do not add unlock routes unless unlock strategy is email or both * Email should be case insensitive * Store classes as string in session, to avoid serialization and stale data issues * deprecations * use_default_scope is deprecated and has no effect. Use :as or :devise_scope in the router instead ### 1.1.rc2 - 2010-06-22 * enhancements * Allow to set cookie domain for the remember token. (by @mantas) * Added navigational formats to specify when it should return a 302 and when a 401. * Added authenticate(scope) support in routes (by @wildchild) * Added after_update_path_for to registrations controller (by @thedelchop) * Allow the mailer object to be replaced through config.mailer = "MyOwnMailer" * bug fix * Fix a bug where session was timing out on sign out * deprecations * bcrypt is now the default encryptor * devise.mailer.confirmations_instructions now should be devise.mailer.confirmations_instructions.subject * devise.mailer.user.confirmations_instructions now should be devise.mailer.confirmations_instructions.user_subject * Generators now use Rails 3 syntax (devise:install) instead of devise_install ### 1.1.rc1 - 2010-04-14 * enhancements * Rails 3 compatibility * All controllers and views are namespaced, for example: Devise::SessionsController and "devise/sessions" * Devise.orm is deprecated. This reduces the required API to hook your ORM with devise * Use metal for failure app * HTML e-mails now have proper formatting * Allow to give :skip and :controllers in routes * Move trackable logic to the model * E-mails now use any template available in the filesystem. Easy to create multipart e-mails * E-mails asks headers_for in the model to set the proper headers * Allow to specify haml in devise_views * Compatibility with Mongoid * Make config.devise available on config/application.rb * TokenAuthenticatable now works with HTTP Basic Auth * Allow :unlock_strategy to be :none and add :lock_strategy which can be :failed_attempts or none. Setting those values to :none means that you want to handle lock and unlocking by yourself * No need to append ?unauthenticated=true in URLs anymore since Flash was moved to a middleware in Rails 3 * :activatable is included by default in your models * bug fix * Fix a bug with STI * deprecations * Rails 3 compatible only * Removed support for MongoMapper * Scoped views are no longer "sessions/users/new". Now use "users/sessions/new" * Devise.orm is deprecated, just require "devise/orm/YOUR_ORM" instead * Devise.default_url_options is deprecated, just modify ApplicationController.default_url_options * All messages under devise.sessions, except :signed_in and :signed_out, should be moved to devise.failure * :as and :scope in routes is deprecated. Use :path and :singular instead ### 1.0.8 - 2010-06-22 * enhancements * Support for latest MongoMapper * Added anybody_signed_in? helper (by @SSDany) * bug fix * confirmation_required? is properly honored on active? calls. (by @paulrosania) ### 1.0.7 - 2010-05-02 * bug fix * Ensure password confirmation is always required * deprecations * authenticatable was deprecated and renamed to database_authenticatable * confirmable is not included by default on generation ### 1.0.6 - 2010-04-02 * bug fix * Do not allow unlockable strategies based on time to access a controller. * Do not send unlockable email several times. * Allow controller to upstram custom! failures to Warden. ### 1.0.5 - 2010-03-25 * bug fix * Use prepend_before_filter in require_no_authentication. * require_no_authentication on unlockable. * Fix a bug when giving an association proxy to devise. * Do not use lock! on lockable since it's part of ActiveRecord API. ### 1.0.4 - 2010-03-02 * bug fix * Fixed a bug when deleting an account with rememberable * Fixed a bug with custom controllers ### 1.0.3 - 2010-02-22 * enhancements * HTML e-mails now have proper formatting * Do not remove MongoMapper options in find ### 1.0.2 - 2010-02-17 * enhancements * Allows you set mailer content type (by @glennr) * bug fix * Uses the same content type as request on http authenticatable 401 responses ### 1.0.1 - 2010-02-16 * enhancements * HttpAuthenticatable is not added by default automatically. * Avoid mass assignment error messages with current password. * bug fix * Fixed encryptors autoload ### 1.0.0 - 2010-02-08 * deprecation * :old_password in update_with_password is deprecated, use :current_password instead * enhancements * Added Registerable * Added Http Basic Authentication support * Allow scoped_views to be customized per controller/mailer class * Allow authenticatable to used in change_table statements ### 0.9.2 - 2010-02-04 * bug fix * Ensure inactive user cannot sign in * Ensure redirect to proper url after sign up * enhancements * Added gemspec to repo * Added token authenticatable (by @grimen) ### 0.9.1 - 2010-01-24 * bug fix * Allow bigger salt size (by @jgeiger) * Fix relative url root ### 0.9.0 - 2010-01-20 * deprecation * devise :all is deprecated * :success and :failure flash messages are now :notice and :alert * enhancements * Added devise lockable (by @mhfs) * Warden 0.9.0 compatibility * Mongomapper 0.6.10 compatibility * Added Devise.add_module as hooks for extensions (by @grimen) * Ruby 1.9.1 compatibility (by @grimen) * bug fix * Accept path prefix not starting with slash * url helpers should rely on find_scope! ### 0.8.2 - 2010-01-12 * enhancements * Allow Devise.mailer_sender to be a proc (by @grimen) * bug fix * Fix bug with passenger, update is required to anyone deploying on passenger (by @dvdpalm) ### 0.8.1 - 2010-01-07 * enhancements * Move salt to encryptors * Devise::Lockable * Moved view links into partial and I18n'ed them * bug fix * Bcrypt generator was not being loaded neither setting the proper salt ### 0.8.0 - 2010-01-06 * enhancements * Warden 0.8.0 compatibility * Add an easy for map.connect "sign_in", :controller => "sessions", :action => "new" to work * Added :bcrypt encryptor (by @capotej) * bug fix * sign_in_count is also increased when user signs in via password change, confirmation, etc.. * More DataMapper compatibility (by @lancecarlson) * deprecation * Removed DeviseMailer.sender ### 0.7.5 - 2010-01-01 * enhancements * Set a default value for mailer to avoid find_template issues * Add models configuration to MongoMapper::EmbeddedDocument as well ### 0.7.4 - 2009-12-21 * enhancements * Extract Activatable from Confirmable * Decouple Serializers from Devise modules ### 0.7.3 - 2009-12-15 * bug fix * Give scope to the proper model validation * enhancements * Mail views are scoped as well * Added update_with_password for authenticatable * Allow render_with_scope to accept :controller option ### 0.7.2 - 2009-12-14 * deprecation * Renamed reset_confirmation! to resend_confirmation! * Copying locale is part of the installation process * bug fix * Fixed render_with_scope to work with all controllers * Allow sign in with two different users in Devise::TestHelpers ### 0.7.1 - 2009-12-09 * enhancements * Small enhancements for other plugins compatibility (by @grimen) ### 0.7.0 - 2009-12-08 * deprecations * :authenticatable is not included by default anymore * enhancements * Improve loading process * Extract SessionSerializer from Authenticatable ### 0.6.3 - 2009-12-02 * bug fix * Added trackable to migrations * Allow inflections to work ### 0.6.2 - 2009-11-25 * enhancements * More DataMapper compatibility * Devise::Trackable - track sign in count, timestamps and ips ### 0.6.1 - 2009-11-24 * enhancements * Devise::Timeoutable - timeout sessions without activity * DataMapper now accepts conditions ### 0.6.0 - 2009-11-22 * deprecations * :authenticatable is still included by default, but yields a deprecation warning * enhancements * Added DataMapper support * Remove store_location from authenticatable strategy and add it to failure app * Allow a strategy to be placed after authenticatable * Do not rely attribute? methods, since they are not added on Datamapper ### 0.5.6 - 2009-11-21 * enhancements * Do not send nil to build (DataMapper compatibility) * Allow to have scoped views ### 0.5.5 - 2009-11-20 * enhancements * Allow overwriting find for authentication method * Remove Ruby 1.8.7 dependency ### 0.5.4 - 2009-11-19 * deprecations * Deprecate :singular in devise_for and use :scope instead * enhancements * Create after_sign_in_path_for and after_sign_out_path_for hooks to be overwriten in ApplicationController * Create sign_in_and_redirect and sign_out_and_redirect helpers * Warden::Manager.default_scope is automatically configured to the first given scope ### 0.5.3 - 2009-11-18 * bug fix * MongoMapper now converts DateTime to Time * Ensure all controllers are unloadable * enhancements * Moved friendly_token to Devise * Added Devise.all, so you can freeze your app strategies * Added Devise.apply_schema, so you can turn it to false in Datamapper or MongoMapper in cases you don't want it be handlded automatically ### 0.5.2 - 2009-11-17 * enhancements * Improved sign_in and sign_out helpers to accepts resources * Added stored_location_for as a helper * Added test helpers ### 0.5.1 - 2009-11-15 * enhancements * Added serializers based on Warden ones * Allow authentication keys to be set ### 0.5.0 - 2009-11-13 * bug fix * Fixed a bug where remember me module was not working properly * enhancements * Moved encryption strategy into the Encryptors module to allow several algorithms (by @mhfs) * Implemented encryptors for Clearance, Authlogic and Restful-Authentication (by @mhfs) * Added support for MongoMapper (by @shingara) ### 0.4.3 - 2009-11-10 * bug fix * Authentication just fails if user cannot be serialized from session, without raising errors; * Default configuration values should not overwrite user values; ### 0.4.2 - 2009-11-06 * deprecations * Renamed mail_sender to mailer_sender * enhancements * skip_before_filter added in Devise controllers * Use home_or_root_path on require_no_authentication as well * Added devise_controller?, useful to select or reject filters in ApplicationController * Allow :path_prefix to be given to devise_for * Allow default_url_options to be configured through devise (:path_prefix => "/:locale" is now supported) ### 0.4.1 - 2009-11-04 * bug fix * Ensure options can be set even if models were not loaded ### 0.4.0 - 2009-11-03 * deprecations * Notifier is deprecated, use DeviseMailer instead. Remember to rename app/views/notifier to app/views/devise_mailer and I18n key from devise.notifier to devise.mailer * :authenticable calls are deprecated, use :authenticatable instead * enhancements * Allow devise to be more agnostic and do not require ActiveRecord to be loaded * Allow Warden::Manager to be configured through Devise * Created a generator which creates an initializer ### 0.3.0 - 2009-10-30 * bug fix * Allow yml messages to be configured by not using engine locales * deprecations * Renamed confirm_in to confirm_within * Do not send confirmation messages when user changes their e-mail * Renamed authenticable to authenticatable and added deprecation warnings ### 0.2.3 - 2009-10-29 * enhancements * Ensure fail! works inside strategies * Make unauthenticated message (when you haven't signed in) different from invalid message * bug fix * Do not redirect on invalid authenticate * Allow model configuration to be set to nil ### 0.2.2 - 2009-10-28 * bug fix * Fix a bug when using customized resources ### 0.2.1 - 2009-10-27 * refactor * Clean devise_views generator to use devise existing views * enhancements * Create instance variables (like @user) for each devise controller * Use Devise::Controller::Helpers only internally * bug fix * Fix a bug with Mongrel and Ruby 1.8.6 ### 0.2.0 - 2009-10-24 * enhancements * Allow option :null => true in authenticable migration * Remove attr_accessible calls from devise modules * Customizable time frame for rememberable with :remember_for config * Customizable time frame for confirmable with :confirm_in config * Generators for creating a resource and copy views * optimize * Do not load hooks or strategies if they are not used * bug fixes * Fixed requiring devise strategies ### 0.1.1 - 2009-10-21 * bug fixes * Fixed requiring devise mapping ### 0.1.0 - 2009-10-21 * Devise::Authenticable * Devise::Confirmable * Devise::Recoverable * Devise::Validatable * Devise::Migratable * Devise::Rememberable * SessionsController * PasswordsController * ConfirmationsController * Create an example app * devise :all, :except => :rememberable * Use sign_in and sign_out in SessionsController * Mailer subjects namespaced by model * Allow stretches and pepper per model * Store session[:return_to] in session * Sign user in automatically after confirming or changing it's password devise-3.5.6/README.md0000644000004100000410000005754112663066463014343 0ustar www-datawww-data![Devise Logo](https://raw.github.com/plataformatec/devise/master/devise.png) By [Plataformatec](http://plataformatec.com.br/). [![Build Status](https://api.travis-ci.org/plataformatec/devise.svg?branch=master)](http://travis-ci.org/plataformatec/devise) [![Code Climate](https://codeclimate.com/github/plataformatec/devise.svg)](https://codeclimate.com/github/plataformatec/devise) [![Security](https://hakiri.io/github/plataformatec/devise/master.svg)](https://hakiri.io/github/plataformatec/devise/master) This README is [also available in a friendly navigable format](http://devise.plataformatec.com.br/). Devise is a flexible authentication solution for Rails based on Warden. It: * Is Rack based; * Is a complete MVC solution based on Rails engines; * Allows you to have multiple models signed in at the same time; * Is based on a modularity concept: use only what you really need. It's composed of 10 modules: * [Database Authenticatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/DatabaseAuthenticatable): encrypts and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication. * [Omniauthable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Omniauthable): adds OmniAuth (https://github.com/intridea/omniauth) support. * [Confirmable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Confirmable): sends emails with confirmation instructions and verifies whether an account is already confirmed during sign in. * [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable): resets the user password and sends reset instructions. * [Registerable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Registerable): handles signing up users through a registration process, also allowing them to edit and destroy their account. * [Rememberable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Rememberable): manages generating and clearing a token for remembering the user from a saved cookie. * [Trackable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Trackable): tracks sign in count, timestamps and IP address. * [Timeoutable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Timeoutable): expires sessions that have not been active in a specified period of time. * [Validatable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Validatable): provides validations of email and password. It's optional and can be customized, so you're able to define your own validations. * [Lockable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Lockable): locks an account after a specified number of failed sign-in attempts. Can unlock via email or after a specified time period. Devise is guaranteed to be thread-safe on YARV. Thread-safety support on JRuby is in progress. ## Information ### The Devise wiki The Devise Wiki has lots of additional information about Devise including many "how-to" articles and answers to the most frequently asked questions. Please browse the Wiki after finishing this README: https://github.com/plataformatec/devise/wiki ### Bug reports If you discover a problem with Devise, we would like to know about it. However, we ask that you please review these guidelines before submitting a bug report: https://github.com/plataformatec/devise/wiki/Bug-reports If you have discovered a security related bug, please do *NOT* use the GitHub issue tracker. Send an email to opensource@plataformatec.com.br. ### Mailing list If you have any questions, comments, or concerns, please use the Google Group instead of the GitHub issue tracker: https://groups.google.com/group/plataformatec-devise ### RDocs You can view the Devise documentation in RDoc format here: http://rubydoc.info/github/plataformatec/devise/master/frames If you need to use Devise with previous versions of Rails, you can always run "gem server" from the command line after you install the gem to access the old documentation. ### Example applications There are a few example applications available on GitHub that demonstrate various features of Devise with different versions of Rails. You can view them here: https://github.com/plataformatec/devise/wiki/Example-Applications ### Extensions Our community has created a number of extensions that add functionality above and beyond what is included with Devise. You can view a list of available extensions and add your own here: https://github.com/plataformatec/devise/wiki/Extensions ### Contributing We hope that you will consider contributing to Devise. Please read this short overview for some information about how to get started: https://github.com/plataformatec/devise/wiki/Contributing You will usually want to write tests for your changes. To run the test suite, go into Devise's top-level directory and run "bundle install" and "rake". For the tests to pass, you will need to have a MongoDB server (version 2.0 or newer) running on your system. ## Starting with Rails? If you are building your first Rails application, we recommend you *do not* use Devise. Devise requires a good understanding of the Rails Framework. In such cases, we advise you to start a simple authentication system from scratch. Today, we have three resources that should help you get started: * Michael Hartl's online book: https://www.railstutorial.org/book/modeling_users * Ryan Bates' Railscast: http://railscasts.com/episodes/250-authentication-from-scratch * Codecademy's Ruby on Rails: Authentication and Authorization: http://www.codecademy.com/en/learn/rails-auth Once you have solidified your understanding of Rails and authentication mechanisms, we assure you Devise will be very pleasant to work with. :smiley: ## Getting started Devise 3.0 works with Rails 3.2 onwards. You can add it to your Gemfile with: ```ruby gem 'devise' ``` Run the bundle command to install it. After you install Devise and add it to your Gemfile, you need to run the generator: ```console rails generate devise:install ``` The generator will install an initializer which describes ALL of Devise's configuration options. It is *imperative* that you take a look at it. When you are done, you are ready to add Devise to any of your models using the generator: ```console rails generate devise MODEL ``` Replace MODEL with the class name used for the application’s users (it’s frequently `User` but could also be `Admin`). This will create a model (if one does not exist) and configure it with default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller. Next, check the MODEL for any additional configuration options you might want to add, such as confirmable or lockable. If you add an option, be sure to inspect the migration file (created by the generator if your ORM supports them) and uncomment the appropriate section. For example, if you add the confirmable option in the model, you'll need to uncomment the Confirmable section in the migration. Then run `rake db:migrate` Next, you need to set up the default URL options for the Devise mailer in each environment. Here is a possible configuration for `config/environments/development.rb`: ```ruby config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } ``` You should restart your application after changing Devise's configuration options. Otherwise, you will run into strange errors, for example, users being unable to login and route helpers being undefined. ### Controller filters and helpers Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_action (assuming your devise model is 'User'): ```ruby before_action :authenticate_user! ``` If your devise model is something other than User, replace "_user" with "_yourmodel". The same logic applies to the instructions below. To verify if a user is signed in, use the following helper: ```ruby user_signed_in? ``` For the current signed-in user, this helper is available: ```ruby current_user ``` You can access the session for this scope: ```ruby user_session ``` After signing in a user, confirming the account or updating the password, Devise will look for a scoped root path to redirect to. For instance, when using a `:user` resource, the `user_root_path` will be used if it exists; otherwise, the default `root_path` will be used. This means that you need to set the root inside your routes: ```ruby root to: "home#index" ``` You can also override `after_sign_in_path_for` and `after_sign_out_path_for` to customize your redirect hooks. Notice that if your Devise model is called `Member` instead of `User`, for example, then the helpers available are: ```ruby before_action :authenticate_member! member_signed_in? current_member member_session ``` ### Configuring Models The Devise method in your models also accepts some options to configure its modules. For example, you can choose the cost of the encryption algorithm with: ```ruby devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 20 ``` Besides `:stretches`, you can define `:pepper`, `:encryptor`, `:confirm_within`, `:remember_for`, `:timeout_in`, `:unlock_in` among other options. For more details, see the initializer file that was created when you invoked the "devise:install" generator described above. This file is usually located at `/config/initializers/devise.rb`. ### Strong Parameters When you customize your own views, you may end up adding new attributes to forms. Rails 4 moved the parameter sanitization from the model to the controller, causing Devise to handle this concern at the controller as well. There are just three actions in Devise that allow any set of parameters to be passed down to the model, therefore requiring sanitization. Their names and the permitted parameters by default are: * `sign_in` (`Devise::SessionsController#create`) - Permits only the authentication keys (like `email`) * `sign_up` (`Devise::RegistrationsController#create`) - Permits authentication keys plus `password` and `password_confirmation` * `account_update` (`Devise::RegistrationsController#update`) - Permits authentication keys plus `password`, `password_confirmation` and `current_password` In case you want to permit additional parameters (the lazy way™), you can do so using a simple before filter in your `ApplicationController`: ```ruby class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :username end end ``` The above works for any additional fields where the parameters are simple scalar types. If you have nested attributes (say you're using `accepts_nested_attributes_for`), then you will need to tell devise about those nestings and types. Devise allows you to completely change Devise defaults or invoke custom behaviour by passing a block: To permit simple scalar values for username and email, use this ```ruby def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) } end ``` If you have some checkboxes that express the roles a user may take on registration, the browser will send those selected checkboxes as an array. An array is not one of Strong Parameters' permitted scalars, so we need to configure Devise in the following way: ```ruby def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) { |u| u.permit({ roles: [] }, :email, :password, :password_confirmation) } end ``` For the list of permitted scalars, and how to declare permitted keys in nested hashes and arrays, see https://github.com/rails/strong_parameters#nested-parameters If you have multiple Devise models, you may want to set up a different parameter sanitizer per model. In this case, we recommend inheriting from `Devise::ParameterSanitizer` and adding your own logic: ```ruby class User::ParameterSanitizer < Devise::ParameterSanitizer def sign_in default_params.permit(:username, :email) end end ``` And then configure your controllers to use it: ```ruby class ApplicationController < ActionController::Base protected def devise_parameter_sanitizer if resource_class == User User::ParameterSanitizer.new(User, :user, params) else super # Use the default one end end end ``` The example above overrides the permitted parameters for the user to be both `:username` and `:email`. The non-lazy way to configure parameters would be by defining the before filter above in a custom controller. We detail how to configure and customize controllers in some sections below. ### Configuring views We built Devise to help you quickly develop an application that uses authentication. However, we don't want to be in your way when you need to customize it. Since Devise is an engine, all its views are packaged inside the gem. These views will help you get started, but after some time you may want to change them. If this is the case, you just need to invoke the following generator, and it will copy all views to your application: ```console rails generate devise:views ``` If you have more than one Devise model in your application (such as `User` and `Admin`), you will notice that Devise uses the same views for all models. Fortunately, Devise offers an easy way to customize views. All you need to do is set `config.scoped_views = true` inside the `config/initializers/devise.rb` file. After doing so, you will be able to have views based on the role like `users/sessions/new` and `admins/sessions/new`. If no view is found within the scope, Devise will use the default view at `devise/sessions/new`. You can also use the generator to generate scoped views: ```console rails generate devise:views users ``` If you would like to generate only a few sets of views, like the ones for the `registerable` and `confirmable` module, you can pass a list of modules to the generator with the `-v` flag. ```console rails generate devise:views -v registrations confirmations ``` ### Configuring controllers If the customization at the views level is not enough, you can customize each controller by following these steps: 1. Create your custom controllers using the generator which requires a scope: ```console rails generate devise:controllers [scope] ``` If you specify `users` as the scope, controllers will be created in `app/controllers/users/`. And the sessions controller will look like this: ```ruby class Users::SessionsController < Devise::SessionsController # GET /resource/sign_in # def new # super # end ... end ``` 2. Tell the router to use this controller: ```ruby devise_for :users, controllers: { sessions: "users/sessions" } ``` 3. Copy the views from `devise/sessions` to `users/sessions`. Since the controller was changed, it won't use the default views located in `devise/sessions`. 4. Finally, change or extend the desired controller actions. You can completely override a controller action: ```ruby class Users::SessionsController < Devise::SessionsController def create # custom sign-in code end end ``` Or you can simply add new behaviour to it: ```ruby class Users::SessionsController < Devise::SessionsController def create super do |resource| BackgroundWorker.trigger(resource) end end end ``` This is useful for triggering background jobs or logging events during certain actions. Remember that Devise uses flash messages to let users know if sign in was successful or unsuccessful. Devise expects your application to call `flash[:notice]` and `flash[:alert]` as appropriate. Do not print the entire flash hash, print only specific keys. In some circumstances, Devise adds a `:timedout` key to the flash hash, which is not meant for display. Remove this key from the hash if you intend to print the entire hash. ### Configuring routes Devise also ships with default routes. If you need to customize them, you should probably be able to do it through the devise_for method. It accepts several options like :class_name, :path_prefix and so on, including the possibility to change path names for I18n: ```ruby devise_for :users, path: "auth", path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unblock', registration: 'register', sign_up: 'cmon_let_me_in' } ``` Be sure to check `devise_for` documentation for details. If you have the need for more deep customization, for instance to also allow "/sign_in" besides "/users/sign_in", all you need to do is create your routes normally and wrap them in a `devise_scope` block in the router: ```ruby devise_scope :user do get "sign_in", to: "devise/sessions#new" end ``` This way, you tell Devise to use the scope `:user` when "/sign_in" is accessed. Notice `devise_scope` is also aliased as `as` in your router. ### I18n Devise uses flash messages with I18n, in conjunction with the flash keys :notice and :alert. To customize your app, you can set up your locale file: ```yaml en: devise: sessions: signed_in: 'Signed in successfully.' ``` You can also create distinct messages based on the resource you've configured using the singular name given in routes: ```yaml en: devise: sessions: user: signed_in: 'Welcome user, you are signed in.' admin: signed_in: 'Hello admin!' ``` The Devise mailer uses a similar pattern to create subject messages: ```yaml en: devise: mailer: confirmation_instructions: subject: 'Hello everybody!' user_subject: 'Hello User! Please confirm your email' reset_password_instructions: subject: 'Reset instructions' ``` Take a look at our locale file to check all available messages. You may also be interested in one of the many translations that are available on our wiki: https://github.com/plataformatec/devise/wiki/I18n Caution: Devise Controllers inherit from ApplicationController. If your app uses multiple locales, you should be sure to set I18n.locale in ApplicationController. ### Test helpers Devise includes some test helpers for functional specs. In order to use them, you need to include Devise in your functional tests by adding the following to the bottom of your `test/test_helper.rb` file: ```ruby class ActionController::TestCase include Devise::TestHelpers end ``` If you're using RSpec, you can put the following inside a file named `spec/support/devise.rb` or in your `spec/spec_helper.rb` (or `spec/rails_helper.rb` if you are using rspec-rails): ```ruby RSpec.configure do |config| config.include Devise::TestHelpers, type: :controller end ``` Just be sure that this inclusion is made *after* the `require 'rspec/rails'` directive. Now you are ready to use the `sign_in` and `sign_out` methods. Such methods have the same signature as in controllers: ```ruby sign_in :user, @user # sign_in(scope, resource) sign_in @user # sign_in(resource) sign_out :user # sign_out(scope) sign_out @user # sign_out(resource) ``` There are two things that are important to keep in mind: 1. These helpers are not going to work for integration tests driven by Capybara or Webrat. They are meant to be used with functional tests only. Instead, fill in the form or explicitly set the user in session; 2. If you are testing Devise internal controllers or a controller that inherits from Devise's, you need to tell Devise which mapping should be used before a request. This is necessary because Devise gets this information from the router, but since functional tests do not pass through the router, it needs to be stated explicitly. For example, if you are testing the user scope, simply use: ```ruby @request.env["devise.mapping"] = Devise.mappings[:user] get :new ``` You can read more about testing your Rails 3 - Rails 4 controllers with RSpec in the wiki: * https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29 ### OmniAuth Devise comes with OmniAuth support out of the box to authenticate with other providers. To use it, simply specify your OmniAuth configuration in `config/initializers/devise.rb`: ```ruby config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' ``` You can read more about OmniAuth support in the wiki: * https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview ### Configuring multiple models Devise allows you to set up as many Devise models as you want. If you want to have an Admin model with just authentication and timeout features, in addition to the User model above, just run: ```ruby # Create a migration with the required fields create_table :admins do |t| t.string :email t.string :encrypted_password t.timestamps null: false end # Inside your Admin model devise :database_authenticatable, :timeoutable # Inside your routes devise_for :admins # Inside your protected controller before_filter :authenticate_admin! # Inside your controllers and views admin_signed_in? current_admin admin_session ``` Alternatively, you can simply run the Devise generator. Keep in mind that those models will have completely different routes. They **do not** and **cannot** share the same controller for sign in, sign out and so on. In case you want to have different roles sharing the same actions, we recommend that you use a role-based approach, by either providing a role column or using a dedicated gem for authorization. ### ActiveJob Integration If you are using Rails 4.2 and ActiveJob to deliver ActionMailer messages in the background through a queuing back-end, you can send Devise emails through your existing queue by overriding the `send_devise_notification` method in your model. ```ruby def send_devise_notification(notification, *args) devise_mailer.send(notification, self, *args).deliver_later end ``` ### Password reset tokens and Rails logs If you enable the [Recoverable](http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable) module, note that a stolen password reset token could give an attacker access to your application. Devise takes effort to generate random, secure tokens, and stores only token digests in the database, never plaintext. However the default logging behavior in Rails can cause plaintext tokens to leak into log files: 1. Action Mailer logs the entire contents of all outgoing emails to the DEBUG level. Password reset tokens delivered to users in email will be leaked. 2. Active Job logs all arguments to every enqueued job at the INFO level. If you configure Devise to use `deliver_later` to send password reset emails, password reset tokens will be leaked. Rails sets the production logger level to DEBUG by default. Consider changing your production logger level to WARN if you wish to prevent tokens from being leaked into your logs. In `config/environments/production.rb`: ```ruby config.log_level = :warn ``` ### Other ORMs Devise supports ActiveRecord (default) and Mongoid. To select another ORM, simply require it in the initializer file. ## Additional information ### Heroku Using Devise on Heroku with Ruby on Rails 3.2 requires setting: ```ruby config.assets.initialize_on_precompile = false ``` Read more about the potential issues at http://guides.rubyonrails.org/asset_pipeline.html ### Warden Devise is based on Warden, which is a general Rack authentication framework created by Daniel Neighman. We encourage you to read more about Warden here: https://github.com/hassox/warden ### Contributors We have a long list of valued contributors. Check them all at: https://github.com/plataformatec/devise/graphs/contributors ## License MIT License. Copyright 2009-2015 Plataformatec. http://plataformatec.com.br You are not granted rights or licenses to the trademarks of Plataformatec, including without limitation the Devise name or logo.