devise-4.4.3/0000755000004100000410000000000013254473005013034 5ustar www-datawww-datadevise-4.4.3/Rakefile0000644000004100000410000000200213254473005014473 0ustar www-datawww-data# encoding: UTF-8 # frozen_string_literal: true 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-4.4.3/Gemfile.lock0000644000004100000410000001101313254473005015252 0ustar www-datawww-dataGIT remote: git://github.com/rails/activemodel-serializers-xml.git revision: dd9c0acf26aab111ebc647cd8deb99ebc6946531 specs: activemodel-serializers-xml (1.0.1) activemodel (> 5.x) activesupport (> 5.x) builder (~> 3.1) PATH remote: . specs: devise (4.4.3) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0, < 6.0) responders warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: actioncable (5.1.0) actionpack (= 5.1.0) nio4r (~> 2.0) websocket-driver (~> 0.6.1) actionmailer (5.1.0) actionpack (= 5.1.0) actionview (= 5.1.0) activejob (= 5.1.0) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 2.0) actionpack (5.1.0) actionview (= 5.1.0) activesupport (= 5.1.0) rack (~> 2.0) rack-test (~> 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (5.1.0) activesupport (= 5.1.0) builder (~> 3.1) erubi (~> 1.4) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.3) activejob (5.1.0) activesupport (= 5.1.0) globalid (>= 0.3.6) activemodel (5.1.0) activesupport (= 5.1.0) activerecord (5.1.0) activemodel (= 5.1.0) activesupport (= 5.1.0) arel (~> 8.0) activesupport (5.1.0) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (~> 0.7) minitest (~> 5.1) tzinfo (~> 1.1) arel (8.0.0) bcrypt (3.1.11) builder (3.2.3) concurrent-ruby (1.0.5) erubi (1.6.0) faraday (0.11.0) multipart-post (>= 1.2, < 3) globalid (0.4.0) activesupport (>= 4.2.0) hashie (3.5.5) i18n (0.8.1) jwt (1.5.6) loofah (2.0.3) nokogiri (>= 1.5.9) mail (2.6.5) mime-types (>= 1.16, < 4) metaclass (0.0.4) method_source (0.8.2) mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) mini_portile2 (2.1.0) minitest (5.10.1) mocha (1.2.1) metaclass (~> 0.0.1) multi_json (1.12.1) multi_xml (0.6.0) multipart-post (2.0.0) nio4r (2.0.0) nokogiri (1.7.1) mini_portile2 (~> 2.1.0) oauth2 (1.3.1) faraday (>= 0.8, < 0.12) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (>= 1.2, < 3) omniauth (1.6.1) hashie (>= 3.4.6, < 3.6.0) rack (>= 1.6.2, < 3) omniauth-facebook (4.0.0) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.4.0) oauth2 (~> 1.0) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) orm_adapter (0.5.0) rack (2.0.1) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.6.3) rack (>= 1.0) rails (5.1.0) actioncable (= 5.1.0) actionmailer (= 5.1.0) actionpack (= 5.1.0) actionview (= 5.1.0) activejob (= 5.1.0) activemodel (= 5.1.0) activerecord (= 5.1.0) activesupport (= 5.1.0) bundler (>= 1.3.0, < 2.0) railties (= 5.1.0) sprockets-rails (>= 2.0.0) rails-controller-testing (1.0.1) actionpack (~> 5.x) actionview (~> 5.x) activesupport (~> 5.x) rails-dom-testing (2.0.2) activesupport (>= 4.2.0, < 6.0) nokogiri (~> 1.6) rails-html-sanitizer (1.0.3) loofah (~> 2.0) railties (5.1.0) actionpack (= 5.1.0) activesupport (= 5.1.0) method_source rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (12.0.0) rdoc (5.1.0) responders (2.4.0) actionpack (>= 4.2.0, < 5.3) railties (>= 4.2.0, < 5.3) ruby-openid (2.7.0) sprockets (3.7.1) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.2.0) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) sqlite3 (1.3.13) thor (0.19.4) thread_safe (0.3.6) tzinfo (1.2.3) thread_safe (~> 0.1) warden (1.2.7) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) websocket-driver (0.6.5) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.2) PLATFORMS ruby DEPENDENCIES activemodel-serializers-xml! activerecord-jdbc-adapter activerecord-jdbcsqlite3-adapter devise! jruby-openssl mocha (~> 1.1) oauth2 omniauth (~> 1.3) omniauth-facebook omniauth-oauth2 omniauth-openid rails (~> 5.1) rails-controller-testing rdoc responders (~> 2.1) sqlite3 webrat (= 0.7.3) BUNDLED WITH 1.16.1 devise-4.4.3/bin/0000755000004100000410000000000013254473005013604 5ustar www-datawww-datadevise-4.4.3/bin/test0000755000004100000410000000041513254473005014511 0ustar www-datawww-data#!/usr/bin/env ruby $: << File.expand_path(File.expand_path('../../test', __FILE__)) require 'bundler/setup' begin require 'rails/test_unit/minitest_plugin' rescue LoadError exec 'rake' end Rails::TestUnitReporter.executable = 'bin/test' exit Minitest.run(ARGV) devise-4.4.3/Gemfile0000644000004100000410000000125113254473005014326 0ustar www-datawww-data# frozen_string_literal: true source "https://rubygems.org" gemspec gem "rails", "~> 5.1" gem "omniauth", "~> 1.3" gem "oauth2" gem "omniauth-oauth2" gem "rdoc" gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml" gem "rails-controller-testing" gem "responders", "~> 2.1" group :test do gem "omniauth-facebook" gem "omniauth-openid" 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 # TODO: # group :mongoid do # gem "mongoid", "~> 4.0.0" # end devise-4.4.3/devise.gemspec0000644000004100000410000000173113254473005015662 0ustar www-datawww-data# -*- encoding: utf-8 -*- # frozen_string_literal: true $:.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 = '>= 2.1.0' s.add_dependency("warden", "~> 1.2.3") s.add_dependency("orm_adapter", "~> 0.1") s.add_dependency("bcrypt", "~> 3.0") s.add_dependency("railties", ">= 4.1.0", "< 6.0") s.add_dependency("responders") end devise-4.4.3/devise.png0000644000004100000410000003201213254473005015017 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-4.4.3/MIT-LICENSE0000644000004100000410000000207713254473005014476 0ustar www-datawww-dataCopyright 2009-2017 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-4.4.3/CODE_OF_CONDUCT.md0000644000004100000410000000377513254473005015647 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-4.4.3/.travis.yml0000644000004100000410000000271613254473005015153 0ustar www-datawww-datalanguage: ruby rvm: - 2.1.10 - 2.2.8 - 2.3.5 - 2.4.2 - 2.5.0 - ruby-head gemfile: - Gemfile - gemfiles/Gemfile.rails-5.2-rc1 - gemfiles/Gemfile.rails-5.0-stable - gemfiles/Gemfile.rails-4.2-stable - gemfiles/Gemfile.rails-4.1-stable matrix: exclude: - rvm: 2.1.10 gemfile: Gemfile - rvm: 2.1.10 gemfile: gemfiles/Gemfile.rails-5.2-rc1 - rvm: 2.5.0 gemfile: gemfiles/Gemfile.rails-4.1-stable - rvm: 2.4.2 gemfile: gemfiles/Gemfile.rails-4.1-stable - rvm: ruby-head gemfile: gemfiles/Gemfile.rails-4.1-stable - rvm: 2.1.10 gemfile: gemfiles/Gemfile.rails-5.0-stable - rvm: 2.1.10 gemfile: Gemfile - env: DEVISE_ORM=mongoid gemfile: Gemfile - env: DEVISE_ORM=mongoid gemfile: gemfiles/Gemfile.rails-5.0-stable - env: DEVISE_ORM=mongoid gemfile: gemfiles/Gemfile.rails-5.2-rc1 allow_failures: - rvm: ruby-head services: - mongodb sudo: false cache: bundler env: matrix: - DEVISE_ORM=active_record - DEVISE_ORM=mongoid before_install: - "rm ${BUNDLE_GEMFILE}.lock" - gem update --system before_script: "bundle update" script: "bin/test" notifications: email: false slack: on_pull_requests: false on_success: change on_failure: always secure: Q3M+kmude3FjisibEeeGe0wSMXgvwLH+vL7Zrx9//q4QtkfnrQ/BBMvY9KXxPEsNF+eys4YopYjTkJ8uRmeboUATW/oQ4Jrv3+u3zkIHK2sFn/Q2cQWpK5w+CbgEnHPjKYnUu34b09njXTgDlr/mqtbPqrKeZ1dLlpKXCB/q4GY= devise-4.4.3/lib/0000755000004100000410000000000013254473005013602 5ustar www-datawww-datadevise-4.4.3/lib/generators/0000755000004100000410000000000013254473005015753 5ustar www-datawww-datadevise-4.4.3/lib/generators/mongoid/0000755000004100000410000000000013254473005017407 5ustar www-datawww-datadevise-4.4.3/lib/generators/mongoid/devise_generator.rb0000644000004100000410000000331213254473005023260 0ustar www-datawww-data# frozen_string_literal: true require '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 <! <% if @resource.try(:unconfirmed_email?) %> We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>. <% else %> We're contacting you to notify you that your email has been changed to <%= @resource.email %>. <% end %> devise-4.4.3/lib/generators/templates/markerb/password_change.markerb0000644000004100000410000000014713254473005026112 0ustar www-datawww-dataHello <%= @resource.email %>! We're contacting you to notify you that your password has been changed. devise-4.4.3/lib/generators/templates/markerb/confirmation_instructions.markerb0000644000004100000410000000024313254473005030254 0ustar www-datawww-dataWelcome <%= @email %>! You can confirm your account through the link below: [Confirm my account](<%= confirmation_url(@resource, confirmation_token: @token) %>) devise-4.4.3/lib/generators/templates/markerb/reset_password_instructions.markerb0000644000004100000410000000054213254473005030632 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-4.4.3/lib/generators/templates/markerb/unlock_instructions.markerb0000644000004100000410000000036013254473005027057 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-4.4.3/lib/generators/templates/controllers/0000755000004100000410000000000013254473005022317 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/controllers/unlocks_controller.rb0000644000004100000410000000112313254473005026562 0ustar www-datawww-data# frozen_string_literal: true class <%= @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-4.4.3/lib/generators/templates/controllers/registrations_controller.rb0000644000004100000410000000265213254473005030011 0ustar www-datawww-data# frozen_string_literal: true class <%= @scope_prefix %>RegistrationsController < Devise::RegistrationsController # before_action :configure_sign_up_params, only: [:create] # before_action :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.permit(:sign_up, keys: [:attribute]) # end # If you have extra params to permit, append them to the sanitizer. # def configure_account_update_params # devise_parameter_sanitizer.permit(:account_update, keys: [: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-4.4.3/lib/generators/templates/controllers/README0000644000004100000410000000067013254473005023202 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-4.4.3/lib/generators/templates/controllers/sessions_controller.rb0000644000004100000410000000105413254473005026755 0ustar www-datawww-data# frozen_string_literal: true class <%= @scope_prefix %>SessionsController < Devise::SessionsController # before_action :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.permit(:sign_in, keys: [:attribute]) # end end devise-4.4.3/lib/generators/templates/controllers/omniauth_callbacks_controller.rb0000644000004100000410000000125313254473005030733 0ustar www-datawww-data# frozen_string_literal: true class <%= @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-4.4.3/lib/generators/templates/controllers/confirmations_controller.rb0000644000004100000410000000124413254473005027763 0ustar www-datawww-data# frozen_string_literal: true class <%= @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-4.4.3/lib/generators/templates/controllers/passwords_controller.rb0000644000004100000410000000122713254473005027136 0ustar www-datawww-data# frozen_string_literal: true class <%= @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-4.4.3/lib/generators/templates/README0000644000004100000410000000175713254473005020643 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. You can copy Devise views (for customization) to your app by running: rails g devise:views =============================================================================== devise-4.4.3/lib/generators/templates/simple_form_for/0000755000004100000410000000000013254473005023133 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/simple_form_for/sessions/0000755000004100000410000000000013254473005025001 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/simple_form_for/sessions/new.html.erb0000644000004100000410000000070713254473005027233 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-4.4.3/lib/generators/templates/simple_form_for/registrations/0000755000004100000410000000000013254473005026030 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/simple_form_for/registrations/new.html.erb0000644000004100000410000000105513254473005030257 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-4.4.3/lib/generators/templates/simple_form_for/registrations/edit.html.erb0000644000004100000410000000204013254473005030406 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-4.4.3/lib/generators/templates/simple_form_for/unlocks/0000755000004100000410000000000013254473005024611 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/simple_form_for/unlocks/new.html.erb0000644000004100000410000000071513254473005027042 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-4.4.3/lib/generators/templates/simple_form_for/passwords/0000755000004100000410000000000013254473005025160 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/simple_form_for/passwords/new.html.erb0000644000004100000410000000065713254473005027416 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-4.4.3/lib/generators/templates/simple_form_for/passwords/edit.html.erb0000644000004100000410000000131313254473005027540 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-4.4.3/lib/generators/templates/simple_form_for/confirmations/0000755000004100000410000000000013254473005026006 5ustar www-datawww-datadevise-4.4.3/lib/generators/templates/simple_form_for/confirmations/new.html.erb0000644000004100000410000000074513254473005030242 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-4.4.3/lib/generators/templates/devise.rb0000755000004100000410000003246613254473005021573 0ustar www-datawww-data# frozen_string_literal: true # 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` as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '<%= SecureRandom.hex(64) %>' # ==> Controller configuration # Configure the parent class to the devise controllers. # config.parent_controller = 'DeviseController' # ==> 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' # Configure the parent class responsible to send e-mails. # config.parent_mailer = 'ActionMailer::Base' # ==> 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 # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. # config.reload_routes = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 11. If # using other algorithms, it sets how many times you want the password to be hashed. # # 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 # algorithm), 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 : 11 # Set up a pepper to generate the hashed password. # config.pepper = '<%= SecureRandom.hex(64) %>' # Send a notification to the original email when the user's email is changed. # config.send_email_changed_notification = false # 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 = 6..128 # 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[^@\s]+@[^@\s]+\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 hashing or encryption algorithm besides bcrypt (default). # You can use :sha1, :sha512 or algorithms 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-4.4.3/lib/generators/active_record/0000755000004100000410000000000013254473005020564 5ustar www-datawww-datadevise-4.4.3/lib/generators/active_record/templates/0000755000004100000410000000000013254473005022562 5ustar www-datawww-datadevise-4.4.3/lib/generators/active_record/templates/migration_existing.rb0000644000004100000410000000174613254473005027022 0ustar www-datawww-data# frozen_string_literal: true class AddDeviseTo<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> 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-4.4.3/lib/generators/active_record/templates/migration.rb0000644000004100000410000000123213254473005025076 0ustar www-datawww-data# frozen_string_literal: true class DeviseCreate<%= table_name.camelize %> < ActiveRecord::Migration<%= migration_version %> def change create_table :<%= table_name %><%= primary_key_type %> 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-4.4.3/lib/generators/active_record/devise_generator.rb0000644000004100000410000000635413254473005024446 0ustar www-datawww-data# frozen_string_literal: true require '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" class_option :primary_key_type, type: :string, desc: "The type for primary key" 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", "#{migration_path}/add_devise_to_#{table_name}.rb", migration_version: migration_version else migration_template "migration.rb", "#{migration_path}/devise_create_#{table_name}.rb", migration_version: migration_version 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 <= '5.0.3' db_migrate_path else @migration_path ||= File.join("db", "migrate") end end def model_path @model_path ||= File.join("app", "models", "#{file_path}.rb") end end end end devise-4.4.3/lib/generators/devise/devise_generator.rb0000644000004100000410000000152513254473005023107 0ustar www-datawww-data# frozen_string_literal: true require 'rails/generators/named_base' module Devise module Generators class DeviseGenerator < Rails::Generators::NamedBase include Rails::Generators::ResourceHelpers namespace "devise" source_root File.expand_path("../templates", __FILE__) desc "Generates a model with the given NAME (if one does not exist) with devise " \ "configuration plus a migration file and devise routes." hook_for :orm class_option :routes, desc: "Generate routes", type: :boolean, default: true def add_devise_routes devise_route = "devise_for :#{plural_name}".dup devise_route << %Q(, class_name: "#{class_name}") if class_name.include?("::") devise_route << %Q(, skip: :all) unless options.routes? route devise_route end end end end devise-4.4.3/lib/generators/devise/views_generator.rb0000644000004100000410000001062613254473005022767 0ustar www-datawww-data# frozen_string_literal: true require 'rails/generators/base' module Devise module Generators # Include this module in your generator to generate Devise views. # `copy_views` is the main method and by default copies all views # with forms. module ViewPathTemplates #:nodoc: extend ActiveSupport::Concern included do argument :scope, required: false, default: nil, desc: "The scope to copy views to" # Le sigh, ensure Thor won't handle opts as args # It should be fixed in future Rails releases class_option :form_builder, aliases: "-b" class_option :markerb class_option :views, aliases: "-v", type: :array, desc: "Select specific view directories to generate (confirmations, passwords, registrations, sessions, unlocks, mailer)" public_task :copy_views end def copy_views if options[:views] options[:views].each do |directory| view_directory directory.to_sym end else view_directory :confirmations view_directory :passwords view_directory :registrations view_directory :sessions view_directory :unlocks end end protected def view_directory(name, _target_path = nil) directory name.to_s, _target_path || "#{target_path}/#{name}" do |content| if scope content.gsub "devise/shared/links", "#{plural_scope}/shared/links" else content end end end def target_path @target_path ||= "app/views/#{plural_scope || :devise}" end def plural_scope @plural_scope ||= scope.presence && scope.underscore.pluralize end end class SharedViewsGenerator < Rails::Generators::Base #:nodoc: include ViewPathTemplates source_root File.expand_path("../../../../app/views/devise", __FILE__) desc "Copies shared Devise views to your application." hide! # Override copy_views to just copy mailer and shared. def copy_views view_directory :shared end end class FormForGenerator < Rails::Generators::Base #:nodoc: include ViewPathTemplates source_root File.expand_path("../../../../app/views/devise", __FILE__) desc "Copies default Devise views to your application." hide! end class SimpleFormForGenerator < Rails::Generators::Base #:nodoc: include ViewPathTemplates source_root File.expand_path("../../templates/simple_form_for", __FILE__) desc "Copies simple form enabled views to your application." hide! def copy_views if options[:views] options[:views].delete('mailer') end super end end class ErbGenerator < Rails::Generators::Base #:nodoc: include ViewPathTemplates source_root File.expand_path("../../../../app/views/devise", __FILE__) desc "Copies Devise mail erb views to your application." hide! def copy_views if !options[:views] || options[:views].include?('mailer') view_directory :mailer end end end class MarkerbGenerator < Rails::Generators::Base #:nodoc: include ViewPathTemplates source_root File.expand_path("../../templates", __FILE__) desc "Copies Devise mail markerb views to your application." hide! def copy_views if !options[:views] || options[:views].include?('mailer') view_directory :markerb, target_path end end def target_path "app/views/#{plural_scope || :devise}/mailer" end end class ViewsGenerator < Rails::Generators::Base desc "Copies Devise views to your application." argument :scope, required: false, default: nil, desc: "The scope to copy views to" invoke SharedViewsGenerator hook_for :form_builder, aliases: "-b", desc: "Form builder to be used", default: defined?(SimpleForm) ? "simple_form_for" : "form_for" hook_for :markerb, desc: "Generate markerb instead of erb mail views", default: defined?(Markerb), type: :boolean hook_for :erb, desc: "Generate erb mail views", default: !defined?(Markerb), type: :boolean end end end devise-4.4.3/lib/generators/devise/controllers_generator.rb0000644000004100000410000000306413254473005024176 0ustar www-datawww-data# frozen_string_literal: true require 'rails/generators/base' module Devise module Generators class ControllersGenerator < Rails::Generators::Base CONTROLLERS = %w(confirmations passwords registrations sessions unlocks omniauth_callbacks).freeze desc <<-DESC.strip_heredoc Create inherited Devise controllers in your app/controllers folder. Use -c to specify which controller you want to overwrite. If you do no specify a controller, all controllers will be created. For example: rails generate devise:controllers users -c=sessions This will create a controller class at app/controllers/users/sessions_controller.rb like this: class Users::ConfirmationsController < Devise::ConfirmationsController content... end DESC source_root File.expand_path("../../templates/controllers", __FILE__) argument :scope, required: true, desc: "The scope to create controllers in, e.g. users, admins" class_option :controllers, aliases: "-c", type: :array, desc: "Select specific controllers to generate (#{CONTROLLERS.join(', ')})" def create_controllers @scope_prefix = scope.blank? ? '' : (scope.camelize + '::') controllers = options[:controllers] || CONTROLLERS controllers.each do |name| template "#{name}_controller.rb", "app/controllers/#{scope}/#{name}_controller.rb" end end def show_readme readme "README" if behavior == :invoke end end end end devise-4.4.3/lib/generators/devise/install_generator.rb0000644000004100000410000000224213254473005023273 0ustar www-datawww-data# frozen_string_literal: true require 'rails/generators/base' require 'securerandom' module Devise module Generators MissingORMError = Class.new(Thor::Error) class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../../templates", __FILE__) desc "Creates a Devise initializer and copy locale files to your application." class_option :orm def copy_initializer unless options[:orm] raise MissingORMError, <<-ERROR.strip_heredoc An ORM must be set to install Devise in your application. Be sure to have an ORM like Active Record or Mongoid loaded in your app or configure your own at `config/application.rb`. config.generators do |g| g.orm :your_orm_gem end ERROR end template "devise.rb", "config/initializers/devise.rb" end def copy_locale copy_file "../../../config/locales/en.yml", "config/locales/devise.en.yml" end def show_readme readme "README" if behavior == :invoke end def rails_4? Rails::VERSION::MAJOR == 4 end end end end devise-4.4.3/lib/devise/0000755000004100000410000000000013254473005015061 5ustar www-datawww-datadevise-4.4.3/lib/devise/secret_key_finder.rb0000644000004100000410000000125113254473005021071 0ustar www-datawww-data# frozen_string_literal: true module Devise class SecretKeyFinder def initialize(application) @application = application end def find if @application.respond_to?(:credentials) && key_exists?(@application.credentials) @application.credentials.secret_key_base elsif @application.respond_to?(:secrets) && key_exists?(@application.secrets) @application.secrets.secret_key_base elsif @application.config.respond_to?(:secret_key_base) && key_exists?(@application.config) @application.config.secret_key_base end end private def key_exists?(object) object.secret_key_base.present? end end end devise-4.4.3/lib/devise/omniauth/0000755000004100000410000000000013254473005016705 5ustar www-datawww-datadevise-4.4.3/lib/devise/omniauth/url_helpers.rb0000644000004100000410000000200613254473005021554 0ustar www-datawww-data# frozen_string_literal: true module Devise module OmniAuth module UrlHelpers def omniauth_authorize_path(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_path", *args) end def omniauth_authorize_url(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_authorize_url", *args) end def omniauth_callback_path(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_callback_path", *args) end def omniauth_callback_url(resource_or_scope, provider, *args) scope = Devise::Mapping.find_scope!(resource_or_scope) _devise_route_context.send("#{scope}_#{provider}_omniauth_callback_url", *args) end end end end devise-4.4.3/lib/devise/omniauth/config.rb0000644000004100000410000000260513254473005020502 0ustar www-datawww-data# frozen_string_literal: true module Devise module OmniAuth class StrategyNotFound < NameError def initialize(strategy) @strategy = strategy super("Could not find a strategy with name `#{strategy}'. " \ "Please ensure it is required or explicitly set it using the :strategy_class option.") end end class Config attr_accessor :strategy attr_reader :args, :options, :provider, :strategy_name def initialize(provider, args) @provider = provider @args = args @options = @args.last.is_a?(Hash) ? @args.last : {} @strategy = nil @strategy_name = options[:name] || @provider @strategy_class = options.delete(:strategy_class) end def strategy_class @strategy_class ||= find_strategy || autoload_strategy end def find_strategy ::OmniAuth.strategies.find do |strategy_class| strategy_class.to_s =~ /#{::OmniAuth::Utils.camelize(strategy_name)}$/ || strategy_class.default_options[:name] == strategy_name end end def autoload_strategy name = ::OmniAuth::Utils.camelize(provider.to_s) if ::OmniAuth::Strategies.const_defined?(name) ::OmniAuth::Strategies.const_get(name) else raise StrategyNotFound, name end end end end end devise-4.4.3/lib/devise/failure_app.rb0000644000004100000410000001660213254473005017702 0ustar www-datawww-data# frozen_string_literal: true require "action_controller/metal" module Devise # Failure application that will be called every time :warden is thrown from # any strategy or hook. It is responsible for redirecting the user to the sign # in page based on current scope and mapping. If no scope is given, it # redirects to the default_url. class FailureApp < ActionController::Metal include ActionController::UrlFor include ActionController::Redirecting include Rails.application.routes.url_helpers include Rails.application.routes.mounted_helpers include Devise::Controllers::StoreLocation delegate :flash, to: :request def self.call(env) @respond ||= action(:respond) @respond.call(env) end # Try retrieving the URL options from the parent controller (usually # ApplicationController). Instance methods are not supported at the moment, # so only the class-level attribute is used. def self.default_url_options(*args) if defined?(Devise.parent_controller.constantize) Devise.parent_controller.constantize.try(:default_url_options) || {} else {} end end def respond if http_auth? http_auth elsif warden_options[:recall] recall else redirect end end def http_auth self.status = 401 self.headers["WWW-Authenticate"] = %(Basic realm=#{Devise.http_authentication_realm.inspect}) if http_auth_header? self.content_type = request.format.to_s self.response_body = http_auth_body end def recall header_info = if relative_url_root? base_path = Pathname.new(relative_url_root) full_path = Pathname.new(attempted_path) { "SCRIPT_NAME" => relative_url_root, "PATH_INFO" => '/' + full_path.relative_path_from(base_path).to_s } else { "PATH_INFO" => attempted_path } end header_info.each do | var, value| if request.respond_to?(:set_header) request.set_header(var, value) else request.env[var] = value end end flash.now[:alert] = i18n_message(:invalid) if is_flashing_format? # self.response = recall_app(warden_options[:recall]).call(env) self.response = recall_app(warden_options[:recall]).call(request.env) end def redirect store_location! if is_flashing_format? if flash[:timedout] && flash[:alert] flash.keep(:timedout) flash.keep(:alert) else flash[:alert] = i18n_message end end redirect_to redirect_url end protected def i18n_options(options) options end def i18n_message(default = nil) message = warden_message || default || :unauthenticated if message.is_a?(Symbol) options = {} options[:resource_name] = scope options[:scope] = "devise.failure" options[:default] = [message] auth_keys = scope_class.authentication_keys keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key| scope_class.human_attribute_name(key) } options[:authentication_keys] = keys.join(I18n.translate(:"support.array.words_connector")) options = i18n_options(options) I18n.t(:"#{scope}.#{message}", options) else message.to_s end end def redirect_url if warden_message == :timeout flash[:timedout] = true if is_flashing_format? path = if request.get? attempted_path else request.referrer end path || scope_url else scope_url end end def route(scope) :"new_#{scope}_session_url" end def scope_url opts = {} # Initialize script_name with nil to prevent infinite loops in # authenticated mounted engines in rails 4.2 and 5.0 opts[:script_name] = nil route = route(scope) opts[:format] = request_format unless skip_format? opts[:script_name] = relative_url_root if relative_url_root? 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 an 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 doesn't 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 request.respond_to?(:get_header) ? request.get_header("warden") : request.env["warden"] end def warden_options request.respond_to?(:get_header) ? request.get_header("warden.options") : request.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 can't use # the 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 def relative_url_root @relative_url_root ||= begin config = Rails.application.config config.try(:relative_url_root) || config.action_controller.try(:relative_url_root) end end def relative_url_root? relative_url_root.present? end end end devise-4.4.3/lib/devise/controllers/0000755000004100000410000000000013254473005017427 5ustar www-datawww-datadevise-4.4.3/lib/devise/controllers/store_location.rb0000644000004100000410000000405213254473005023001 0ustar www-datawww-data# frozen_string_literal: true require "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_facebook_omniauth_authorize_path # def store_location_for(resource_or_scope, location) session_key = stored_location_key_for(resource_or_scope) path = extract_path_from_location(location) session[session_key] = path if path 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 def extract_path_from_location(location) uri = parse_uri(location) if uri path = remove_domain_from_uri(uri) path = add_fragment_back_to_path(uri, path) path end end def remove_domain_from_uri(uri) [uri.path.sub(/\A\/+/, '/'), uri.query].compact.join('?') end def add_fragment_back_to_path(uri, path) [path, uri.fragment].compact.join('#') end end end end devise-4.4.3/lib/devise/controllers/rememberable.rb0000644000004100000410000000364413254473005022405 0ustar www-datawww-data# frozen_string_literal: true module 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 request.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-4.4.3/lib/devise/controllers/scoped_views.rb0000644000004100000410000000056013254473005022447 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/controllers/url_helpers.rb0000644000004100000410000000467313254473005022312 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/controllers/helpers.rb0000644000004100000410000002650113254473005021422 0ustar www-datawww-data# frozen_string_literal: true module 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_action :authenticate_blogger! # Redirects unless either a user or an admin are authenticated # before_action ->{ 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_actions, # 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_action :authenticate_user! # Tell devise to use :user map # before_action :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'] or raise MissingWarden 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_action :my_filter, unless: :devise_controller? def devise_controller? is_a?(::DeviseController) end # Set up 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 ||= Devise::ParameterSanitizer.new(resource_class, resource_name, params) 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_data_after_sign_out! Devise.mappings.each { |_,m| instance_variable_set("@current_#{m.name}", nil) } super end end end class MissingWarden < StandardError def initialize super "Devise could not find the `Warden::Proxy` instance on your request environment.\n" + \ "Make sure that your application is loading Devise and Warden as expected and that " + \ "the `Warden::Manager` middleware is present in your middleware stack.\n" + \ "If you are seeing this on one of your tests, ensure that your tests are either " + \ "executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` " + \ "module to inject the `request.env['warden']` object for you." end end end devise-4.4.3/lib/devise/controllers/sign_in_out.rb0000644000004100000410000001067513254473005022302 0ustar www-datawww-data# frozen_string_literal: true module 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. This will run authentication hooks, which may # cause exceptions to be thrown from this method; if you simply want to check # if a scope has already previously been authenticated without running # authentication hooks, you can directly call `warden.authenticated?(scope: scope)` 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. # # 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) # 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] ActiveSupport::Deprecation.warn(<<-DEPRECATION.strip_heredoc, caller) [Devise] bypass option is deprecated and it will be removed in future version of Devise. Please use bypass_sign_in method instead. Example: bypass_sign_in(user) DEPRECATION 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 in a user bypassing the 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: # # bypass_sign_in @user, scope: :user # bypass_sign_in @user def bypass_sign_in(resource, scope: nil) scope ||= Devise::Mapping.find_scope!(resource) expire_data_after_sign_in! warden.session_serializer.store(resource, scope) 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.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-4.4.3/lib/devise/mailers/0000755000004100000410000000000013254473005016515 5ustar www-datawww-datadevise-4.4.3/lib/devise/mailers/helpers.rb0000644000004100000410000000476113254473005020514 0ustar www-datawww-data# frozen_string_literal: true module Devise module Mailers module Helpers extend ActiveSupport::Concern included do include Devise::Controllers::ScopedViews end protected attr_reader :scope_name, :resource # Configure default email options def devise_mail(record, action, opts = {}, &block) initialize_from_record(record) mail headers_for(action, opts), &block 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 # Set up 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-4.4.3/lib/devise/time_inflector.rb0000644000004100000410000000045313254473005020413 0ustar www-datawww-data# frozen_string_literal: true require "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-4.4.3/lib/devise/omniauth.rb0000644000004100000410000000201013254473005017223 0ustar www-datawww-data# frozen_string_literal: true begin 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-4.4.3/lib/devise/parameter_filter.rb0000644000004100000410000000232013254473005020730 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/test_helpers.rb0000644000004100000410000000073013254473005020107 0ustar www-datawww-data# frozen_string_literal: true module Devise module TestHelpers def self.included(base) base.class_eval do ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] including `Devise::TestHelpers` is deprecated and will be removed from Devise. For controller tests, please include `Devise::Test::ControllerHelpers` instead. DEPRECATION include Devise::Test::ControllerHelpers end end end end devise-4.4.3/lib/devise/encryptor.rb0000644000004100000410000000124313254473005017433 0ustar www-datawww-data# frozen_string_literal: true require '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, hashed_password, password) return false if hashed_password.blank? bcrypt = ::BCrypt::Password.new(hashed_password) if klass.pepper.present? password = "#{password}#{klass.pepper}" end password = ::BCrypt::Engine.hash_secret(password, bcrypt.salt) Devise.secure_compare(password, hashed_password) end end end devise-4.4.3/lib/devise/strategies/0000755000004100000410000000000013254473005017233 5ustar www-datawww-datadevise-4.4.3/lib/devise/strategies/rememberable.rb0000644000004100000410000000366513254473005022214 0ustar www-datawww-data# frozen_string_literal: true require '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) if extend_remember_me?(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?(resource) resource.respond_to?(:extend_remember_period) && resource.extend_remember_period 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-4.4.3/lib/devise/strategies/database_authenticatable.rb0000644000004100000410000000154513254473005024546 0ustar www-datawww-data# frozen_string_literal: true require '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) hashed = false if validate(resource){ hashed = true; resource.valid_password?(password) } remember_me(resource) resource.after_database_authentication success!(resource) end mapping.to.new.password = password if !hashed && Devise.paranoid fail(:not_found_in_database) unless resource end end end end Warden::Strategies.add(:database_authenticatable, Devise::Strategies::DatabaseAuthenticatable) devise-4.4.3/lib/devise/strategies/authenticatable.rb0000644000004100000410000001415313254473005022721 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/lib/devise/strategies/base.rb0000644000004100000410000000117613254473005020477 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/hooks/0000755000004100000410000000000013254473005016204 5ustar www-datawww-datadevise-4.4.3/lib/devise/hooks/timeoutable.rb0000644000004100000410000000246213254473005021047 0ustar www-datawww-data# frozen_string_literal: true # 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-4.4.3/lib/devise/hooks/lockable.rb0000644000004100000410000000072613254473005020312 0ustar www-datawww-data# frozen_string_literal: true # 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]) unless record.failed_attempts.to_i.zero? record.failed_attempts = 0 record.save(validate: false) end end end devise-4.4.3/lib/devise/hooks/forgetable.rb0000644000004100000410000000072013254473005020642 0ustar www-datawww-data# frozen_string_literal: true # 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-4.4.3/lib/devise/hooks/proxy.rb0000644000004100000410000000074613254473005017721 0ustar www-datawww-data# frozen_string_literal: true module 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, :request, to: :warden def initialize(warden) @warden = warden end def session warden.request.session end end end end devise-4.4.3/lib/devise/hooks/rememberable.rb0000644000004100000410000000050413254473005021152 0ustar www-datawww-data# frozen_string_literal: true Warden::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-4.4.3/lib/devise/hooks/trackable.rb0000644000004100000410000000103513254473005020460 0ustar www-datawww-data# frozen_string_literal: true # 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-4.4.3/lib/devise/hooks/csrf_cleaner.rb0000644000004100000410000000057213254473005021163 0ustar www-datawww-data# frozen_string_literal: true Warden::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-4.4.3/lib/devise/hooks/activatable.rb0000644000004100000410000000101013254473005021000 0ustar www-datawww-data# frozen_string_literal: true # 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-4.4.3/lib/devise/mapping.rb0000644000004100000410000001261413254473005017045 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/test/0000755000004100000410000000000013254473005016040 5ustar www-datawww-datadevise-4.4.3/lib/devise/test/integration_helpers.rb0000644000004100000410000000330613254473005022434 0ustar www-datawww-data# frozen_string_literal: true module Devise # Devise::Test::IntegrationHelpers is a helper module for facilitating # authentication on Rails integration tests to bypass the required steps for # signin in or signin out a record. # # Examples # # class PostsTest < ActionDispatch::IntegrationTest # include Devise::Test::IntegrationHelpers # # test 'authenticated users can see posts' do # sign_in users(:bob) # # get '/posts' # assert_response :success # end # end module Test module IntegrationHelpers def self.included(base) base.class_eval do include Warden::Test::Helpers setup :setup_integration_for_devise teardown :teardown_integration_for_devise end end # Signs in a specific resource, mimicking a successfull sign in # operation through +Devise::SessionsController#create+. # # * +resource+ - The resource that should be authenticated # * +scope+ - An optional +Symbol+ with the scope where the resource # should be signed in with. def sign_in(resource, scope: nil) scope ||= Devise::Mapping.find_scope!(resource) login_as(resource, scope: scope) end # Signs out a specific scope from the session. # # * +resource_or_scope+ - The resource or scope that should be signed out. def sign_out(resource_or_scope) scope = Devise::Mapping.find_scope!(resource_or_scope) logout scope end protected def setup_integration_for_devise Warden.test_mode! end def teardown_integration_for_devise Warden.test_reset! end end end end devise-4.4.3/lib/devise/test/controller_helpers.rb0000644000004100000410000001316613254473005022301 0ustar www-datawww-data# frozen_string_literal: true module Devise module Test # `Devise::Test::ControllerHelpers` 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::Test::ControllerHelpers` in integration tests. # # Examples # # class PostsTest < ActionController::TestCase # include Devise::Test::ControllerHelpers # # test 'authenticated users can GET index' do # sign_in users(:bob) # # get :index # assert_response :success # end # end # # Important: you should not test Warden specific behavior (like callbacks) # using `Devise::Test::ControllerHelpers` since it is a stub of the actual # behavior. Such callbacks should be tested in your integration suite instead. module ControllerHelpers extend ActiveSupport::Concern included do setup :setup_controller_for_warden, :warden end # Override process to consider warden. def process(*) _catch_warden { super } @response end # We need to set up 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. # # * +resource+ - The resource that should be authenticated # * +scope+ - An optional +Symbol+ with the scope where the resource # should be signed in with. # Examples: # # sign_in users(:alice) # sign_in users(:alice), scope: :admin def sign_in(resource, deprecated = nil, scope: nil) if deprecated.present? scope = resource resource = deprecated ActiveSupport::Deprecation.warn <<-DEPRECATION.strip_heredoc [Devise] sign_in(:#{scope}, resource) on controller tests is deprecated and will be removed from Devise. Please use sign_in(resource, scope: :#{scope}) instead. DEPRECATION end scope ||= Devise::Mapping.find_scope!(resource) 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 = request.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 request.env["PATH_INFO"] = "/#{options[:action]}" request.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.response.content_type = headers["Content-Type"] unless Rails.version.start_with?('5') @controller.status = status @controller.response.body = response.body 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) status, headers, body = *ret # ensure the controller response is set to our response. @controller.response ||= @response @response.status = status @response.headers.merge!(headers) @response.body = body end ret end end end end devise-4.4.3/lib/devise/delegator.rb0000644000004100000410000000064713254473005017363 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/orm/0000755000004100000410000000000013254473005015656 5ustar www-datawww-datadevise-4.4.3/lib/devise/orm/active_record.rb0000644000004100000410000000022213254473005021010 0ustar www-datawww-data# frozen_string_literal: true require 'orm_adapter/adapters/active_record' ActiveSupport.on_load(:active_record) do extend Devise::Models end devise-4.4.3/lib/devise/orm/mongoid.rb0000644000004100000410000000026013254473005017635 0ustar www-datawww-data# frozen_string_literal: true ActiveSupport.on_load(:mongoid) do require 'orm_adapter/adapters/mongoid' Mongoid::Document::ClassMethods.send :include, Devise::Models end devise-4.4.3/lib/devise/models.rb0000644000004100000410000000673713254473005016706 0ustar www-datawww-data# frozen_string_literal: true module 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::Models::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-4.4.3/lib/devise/version.rb0000644000004100000410000000011413254473005017067 0ustar www-datawww-data# frozen_string_literal: true module Devise VERSION = "4.4.3".freeze end devise-4.4.3/lib/devise/token_generator.rb0000644000004100000410000000131413254473005020573 0ustar www-datawww-data# frozen_string_literal: true require 'openssl' 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 end devise-4.4.3/lib/devise/modules.rb0000644000004100000410000000212313254473005017054 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/lib/devise/rails/0000755000004100000410000000000013254473005016173 5ustar www-datawww-datadevise-4.4.3/lib/devise/rails/routes.rb0000644000004100000410000004726213254473005020054 0ustar www-datawww-data# frozen_string_literal: true require "active_support/core_ext/object/try" require "active_support/core_ext/hash/slice" module Devise module RouteSet def finalize! result = super @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 end end 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. prepend Devise::RouteSet 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: set up 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 set up path name that will be used, as rails routes does. # The following route configuration would set up your route as /accounts instead of /users: # # devise_for :users, path: 'accounts' # # * singular: set up 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_action 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 targeted. # # 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 current_scope = @scope.dup if @scope.respond_to? :new @scope = @scope.new path: nil else @scope[:path] = nil end path_prefix = Devise.omniauth_path_prefix || "/#{mapping.fullpath}/auth".squeeze("/") set_omniauth_path_prefix!(path_prefix) mapping.to.omniauth_providers.each do |provider| match "#{path_prefix}/#{provider}", to: "#{controllers[:omniauth_callbacks]}#passthru", as: "#{provider}_omniauth_authorize", via: [:get, :post] match "#{path_prefix}/#{provider}/callback", to: "#{controllers[:omniauth_callbacks]}##{provider}", as: "#{provider}_omniauth_callback", via: [:get, :post] end ensure @scope = current_scope 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)) if @scope.respond_to? :new @scope = @scope.new exclusive else exclusive.each_pair { |key, value| @scope[key] = value } end 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-4.4.3/lib/devise/rails/warden_compat.rb0000644000004100000410000000035113254473005021342 0ustar www-datawww-data# frozen_string_literal: true module Warden::Mixins::Common def request @request ||= ActionDispatch::Request.new(env) end def reset_session! request.reset_session end def cookies request.cookie_jar end end devise-4.4.3/lib/devise/models/0000755000004100000410000000000013254473005016344 5ustar www-datawww-datadevise-4.4.3/lib/devise/models/timeoutable.rb0000644000004100000410000000212313254473005021201 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/lib/devise/models/registerable.rb0000644000004100000410000000136413254473005021345 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/lib/devise/models/lockable.rb0000644000004100000410000001660413254473005020454 0ustar www-datawww-data# frozen_string_literal: true require "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 set up 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 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 increment_failed_attempts if attempts_exceeded? lock_access! unless access_locked? else save(validate: false) end false end end def increment_failed_attempts self.failed_attempts ||= 0 self.failed_attempts += 1 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 # List of strategies that are enabled/supported if :both is used. BOTH_STRATEGIES = [:time, :email] # 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) self.unlock_strategy == strategy || (self.unlock_strategy == :both && BOTH_STRATEGIES.include?(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-4.4.3/lib/devise/models/recoverable.rb0000644000004100000410000001545613254473005021175 0ustar www-datawww-data# frozen_string_literal: true module 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 :clear_reset_password_token, if: :clear_reset_password_token? 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) if new_password.present? self.password = new_password self.password_confirmation = new_password_confirmation save else errors.add(:password, :blank) false end 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 save(validate: false) raw end def send_reset_password_instructions_notification(token) send_devise_notification(:reset_password_instructions, token, {}) end if Devise.activerecord51? def clear_reset_password_token? encrypted_password_changed = respond_to?(:will_save_change_to_encrypted_password?) && will_save_change_to_encrypted_password? authentication_keys_changed = self.class.authentication_keys.any? do |attribute| respond_to?("will_save_change_to_#{attribute}?") && send("will_save_change_to_#{attribute}?") end authentication_keys_changed || encrypted_password_changed end else def clear_reset_password_token? encrypted_password_changed = respond_to?(:encrypted_password_changed?) && encrypted_password_changed? authentication_keys_changed = self.class.authentication_keys.any? do |attribute| respond_to?("#{attribute}_changed?") && send("#{attribute}_changed?") end authentication_keys_changed || encrypted_password_changed end 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-4.4.3/lib/devise/models/rememberable.rb0000644000004100000410000001300513254473005021312 0ustar www-datawww-data# frozen_string_literal: true require 'devise/strategies/rememberable' require 'devise/hooks/rememberable' require 'devise/hooks/forgetable' module Devise module Models # Rememberable manages generating and clearing token for remembering 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 def self.required_fields(klass) [:remember_created_at] end 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 def remember_expires_at self.class.remember_for.from_now end def extend_remember_period self.class.extend_remember_period end def rememberable_value if respond_to?(:remember_token) remember_token elsif respond_to?(:authenticatable_salt) && (salt = authenticatable_salt.presence) salt else raise "authenticatable_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 Devise::Models.config(self, :remember_for, :extend_remember_period, :rememberable_options, :expire_all_remember_me_on_sign_out) end end end end devise-4.4.3/lib/devise/models/trackable.rb0000644000004100000410000000314113254473005020620 0ustar www-datawww-data# frozen_string_literal: true require '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) # We have to check if the user is already persisted before running # `save` here because invalid users can be saved if we don't. # See https://github.com/plataformatec/devise/issues/4673 for more details. return if new_record? update_tracked_fields(request) save(validate: false) end end end end devise-4.4.3/lib/devise/models/omniauthable.rb0000644000004100000410000000122613254473005021342 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/lib/devise/models/database_authenticatable.rb0000644000004100000410000001547413254473005023665 0ustar www-datawww-data# frozen_string_literal: true require 'devise/strategies/database_authenticatable' module Devise module Models # Authenticatable Module, responsible for hashing the password and # validating the 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 # `rails secret` to generate new keys. # # * +stretches+: the cost given to bcrypt. # # * +send_email_changed_notification+: notify original email when it changes. # # * +send_password_change_notification+: notify email when password changes. # # == Examples # # User.find(1).valid_password?('password123') # returns true/false # module DatabaseAuthenticatable extend ActiveSupport::Concern included do after_update :send_email_changed_notification, if: :send_email_changed_notification? 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 a hashed password based on the given value. # For legacy reasons, we use `encrypted_password` to store # the hashed password. 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 if Devise.activerecord51? # Send notification to user when email changes. def send_email_changed_notification send_devise_notification(:email_changed, to: email_before_last_save) end else # Send notification to user when email changes. def send_email_changed_notification send_devise_notification(:email_changed, to: email_was) end end # Send notification to user when password changes. def send_password_change_notification send_devise_notification(:password_change) end protected # Hashes the password using bcrypt. Custom hash functions should override # this method to apply their own algorithm. # # See https://github.com/plataformatec/devise-encryptable for examples # of other hashing engines. def password_digest(password) Devise::Encryptor.digest(self.class, password) end if Devise.activerecord51? def send_email_changed_notification? self.class.send_email_changed_notification && saved_change_to_email? end else def send_email_changed_notification? self.class.send_email_changed_notification && email_changed? end end if Devise.activerecord51? def send_password_change_notification? self.class.send_password_change_notification && saved_change_to_encrypted_password? end else def send_password_change_notification? self.class.send_password_change_notification && encrypted_password_changed? end end module ClassMethods Devise::Models.config(self, :pepper, :stretches, :send_email_changed_notification, :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-4.4.3/lib/devise/models/validatable.rb0000644000004100000410000000523413254473005021145 0ustar www-datawww-data# frozen_string_literal: true module 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 6..128. # 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? if Devise.activerecord51? validates_uniqueness_of :email, allow_blank: true, if: :will_save_change_to_email? validates_format_of :email, with: email_regexp, allow_blank: true, if: :will_save_change_to_email? else validates_uniqueness_of :email, allow_blank: true, if: :email_changed? validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? end 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-4.4.3/lib/devise/models/authenticatable.rb0000644000004100000410000003002313254473005022024 0ustar www-datawww-data# frozen_string_literal: true require '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.try(:dup) || {} 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 # Redefine inspect using serializable_hash, to ensure we don't accidentally # leak passwords into exceptions. def inspect inspection = serializable_hash.collect do |k,v| "#{k}: #{respond_to?(:attribute_for_inspect) ? attribute_for_inspect(k) : v.inspect}" end "#<#{self.class} #{inspection.join(", ")}>" 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 # 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 # end # # def send_pending_notifications # pending_notifications.each do |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 # # # 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 a 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 = if attributes.respond_to? :permit! attributes.slice(*required_attributes).permit!.to_h.with_indifferent_access else attributes.with_indifferent_access.slice(*required_attributes) end 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-4.4.3/lib/devise/models/confirmable.rb0000644000004100000410000003704713254473005021165 0ustar www-datawww-data# frozen_string_literal: true module 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 set up (t.reconfirmable in migrations). Until confirmed, new email is # stored in unconfirmed email column, and copied to email column on successful # confirmation. Also, when used in conjunction with `send_email_changed_notification`, # the notification is sent to the original email when the change is requested, # not when the unconfirmed email is confirmed. # * +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 included do before_create :generate_confirmation_token, if: :confirmation_required? after_create :skip_reconfirmation_in_callback!, if: :send_confirmation_notification? if defined?(ActiveRecord) && self < ActiveRecord::Base # ActiveRecord after_commit :send_on_create_confirmation_instructions, on: :create, if: :send_confirmation_notification? after_commit :send_reconfirmation_instructions, on: :update, if: :reconfirmation_required? else # Mongoid after_create :send_on_create_confirmation_instructions, if: :send_confirmation_notification? after_update :send_reconfirmation_instructions, if: :reconfirmation_required? end before_update :postpone_email_change_until_confirmation_and_regenerate_confirmation_token, if: :postpone_email_change? end def initialize(*args, &block) @bypass_confirmation_postpone = false @skip_reconfirmation_in_callback = 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 pending_reconfirmation? 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 # 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 # To not require reconfirmation after creating with #save called in a # callback call skip_create_confirmation! def skip_reconfirmation_in_callback! @skip_reconfirmation_in_callback = true end # 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. # allow_unconfirmed_access_for 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.utc > self.confirmation_sent_at.utc + 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 self.confirmation_token = @raw_confirmation_token = Devise.friendly_token self.confirmation_sent_at = Time.now.utc end end def generate_confirmation_token! generate_confirmation_token && save(validate: false) end if Devise.activerecord51? def postpone_email_change_until_confirmation_and_regenerate_confirmation_token @reconfirmation_required = true self.unconfirmed_email = self.email self.email = self.email_in_database self.confirmation_token = nil generate_confirmation_token end else 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 end if Devise.activerecord51? def postpone_email_change? postpone = self.class.reconfirmable && will_save_change_to_email? && !@bypass_confirmation_postpone && self.email.present? && (!@skip_reconfirmation_in_callback || !self.email_in_database.nil?) @bypass_confirmation_postpone = false postpone end else def postpone_email_change? postpone = self.class.reconfirmable && email_changed? && !@bypass_confirmation_postpone && self.email.present? && (!@skip_reconfirmation_in_callback || !self.email_was.nil?) @bypass_confirmation_postpone = false postpone end end def reconfirmation_required? self.class.reconfirmable && @reconfirmation_required && (self.email.present? || self.unconfirmed_email.present?) end def send_confirmation_notification? confirmation_required? && !@skip_confirmation_notification && self.email.present? end # With reconfirmable, notify the original email when the user first # requests the email change, instead of when the change is confirmed. def send_email_changed_notification? if self.class.reconfirmable self.class.send_email_changed_notification && reconfirmation_required? else super end 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 = {}) attributes = attributes.slice(*confirmation_keys).permit!.to_h if attributes.respond_to? :permit 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-4.4.3/lib/devise/rails.rb0000644000004100000410000000252213254473005016521 0ustar www-datawww-data# frozen_string_literal: true require '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 do |app| app.reload_routes! if Devise.reload_routes end 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| Devise.secret_key ||= Devise::SecretKeyFinder.new(app).find Devise.token_generator ||= if secret_key = Devise.secret_key Devise::TokenGenerator.new( ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key)) ) end end end end devise-4.4.3/lib/devise/parameter_sanitizer.rb0000644000004100000410000001255213254473005021463 0ustar www-datawww-data# frozen_string_literal: true module Devise # The +ParameterSanitizer+ deals with permitting specific parameters values # for each +Devise+ scope in the application. # # The sanitizer knows about Devise default parameters (like +password+ and # +password_confirmation+ for the `RegistrationsController`), and you can # extend or change the permitted parameters list on your controllers. # # === Permitting new parameters # # You can add new parameters to the permitted list using the +permit+ method # in a +before_action+ method, for instance. # # class ApplicationController < ActionController::Base # before_action :configure_permitted_parameters, if: :devise_controller? # # protected # # def configure_permitted_parameters # # Permit the `subscribe_newsletter` parameter along with the other # # sign up parameters. # devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) # end # end # # Using a block yields an +ActionController::Parameters+ object so you can # permit nested parameters and have more control over how the parameters are # permitted in your controller. # # def configure_permitted_parameters # devise_parameter_sanitizer.permit(:sign_up) do |user| # user.permit(newsletter_preferences: []) # end # end class ParameterSanitizer DEFAULT_PERMITTED_ATTRIBUTES = { sign_in: [:password, :remember_me], sign_up: [:password, :password_confirmation], account_update: [:password, :password_confirmation, :current_password] } def initialize(resource_class, resource_name, params) @auth_keys = extract_auth_keys(resource_class) @params = params @resource_name = resource_name @permitted = {} DEFAULT_PERMITTED_ATTRIBUTES.each_pair do |action, keys| permit(action, keys: keys) end end # Sanitize the parameters for a specific +action+. # # === Arguments # # * +action+ - A +Symbol+ with the action that the controller is # performing, like +sign_up+, +sign_in+, etc. # # === Examples # # # Inside the `RegistrationsController#create` action. # resource = build_resource(devise_parameter_sanitizer.sanitize(:sign_up)) # resource.save # # Returns an +ActiveSupport::HashWithIndifferentAccess+ with the permitted # attributes. def sanitize(action) permissions = @permitted[action] if permissions.respond_to?(:call) cast_to_hash permissions.call(default_params) elsif permissions.present? cast_to_hash permit_keys(default_params, permissions) else unknown_action!(action) end end # Add or remove new parameters to the permitted list of an +action+. # # === Arguments # # * +action+ - A +Symbol+ with the action that the controller is # performing, like +sign_up+, +sign_in+, etc. # * +keys:+ - An +Array+ of keys that also should be permitted. # * +except:+ - An +Array+ of keys that shouldn't be permitted. # * +block+ - A block that should be used to permit the action # parameters instead of the +Array+ based approach. The block will be # called with an +ActionController::Parameters+ instance. # # === Examples # # # Adding new parameters to be permitted in the `sign_up` action. # devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) # # # Removing the `password` parameter from the `account_update` action. # devise_parameter_sanitizer.permit(:account_update, except: [:password]) # # # Using the block form to completely override how we permit the # # parameters for the `sign_up` action. # devise_parameter_sanitizer.permit(:sign_up) do |user| # user.permit(:email, :password, :password_confirmation) # end # # # Returns nothing. def permit(action, keys: nil, except: nil, &block) if block_given? @permitted[action] = block end if keys.present? @permitted[action] ||= @auth_keys.dup @permitted[action].concat(keys) end if except.present? @permitted[action] ||= @auth_keys.dup @permitted[action] = @permitted[action] - except end end private # Cast a sanitized +ActionController::Parameters+ to a +HashWithIndifferentAccess+ # that can be used elsewhere. # # Returns an +ActiveSupport::HashWithIndifferentAccess+. def cast_to_hash(params) # TODO: Remove the `with_indifferent_access` method call when we only support Rails 5+. params && params.to_h.with_indifferent_access end def default_params @params.fetch(@resource_name, {}) end def permit_keys(parameters, keys) parameters.permit(*keys) end def extract_auth_keys(klass) auth_keys = klass.authentication_keys auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys end def unknown_action!(action) raise NotImplementedError, <<-MESSAGE.strip_heredoc "Devise doesn't know how to sanitize parameters for '#{action}'". If you want to define a new set of parameters to be sanitized use the `permit` method first: devise_parameter_sanitizer.permit(:#{action}, keys: [:param1, :param2, :param3]) MESSAGE end end end devise-4.4.3/lib/devise.rb0000755000004100000410000004044713254473005015422 0ustar www-datawww-data# frozen_string_literal: true require '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 :ParameterSanitizer, 'devise/parameter_sanitizer' autoload :TestHelpers, 'devise/test_helpers' autoload :TimeInflector, 'devise/time_inflector' autoload :TokenGenerator, 'devise/token_generator' autoload :SecretKeyFinder, 'devise/secret_key_finder' 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 module Test autoload :ControllerHelpers, 'devise/test/controller_helpers' autoload :IntegrationHelpers, 'devise/test/integration_helpers' 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 = {} ROUTES = {} STRATEGIES = {} URL_HELPERS = {} # 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 hash the password. mattr_accessor :stretches @@stretches = 11 # 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 = [:email] # 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 asserts that there are no # @ symbols or whitespaces in either the localpart or the domain, and that # there is a single @ symbol separating the localpart and the domain. mattr_accessor :email_regexp @@email_regexp = /\A[^@\s]+@[^@\s]+\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 # 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. mattr_accessor :reconfirmable @@reconfirmable = true # Time interval to timeout the user session without activity. mattr_accessor :timeout_in @@timeout_in = 30.minutes # Used to hash the password. Please generate one with rails secret. mattr_accessor :pepper @@pepper = nil # Used to send notification to the original user email when their email is changed. mattr_accessor :send_email_changed_notification @@send_email_changed_notification = false # 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 = [:http_auth] # 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 = :delete # 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 # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. mattr_accessor :reload_routes @@reload_routes = true # PRIVATE CONFIGURATION # Store scopes mappings. mattr_reader :mappings @@mappings = {} # OmniAuth configurations. mattr_reader :omniauth_configs @@omniauth_configs = {} # 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 def self.rails51? # :nodoc: Rails.gem_version >= Gem::Version.new("5.1.x") end def self.activerecord51? # :nodoc: defined?(ActiveRecord) && ActiveRecord.gem_version >= Gem::Version.new("5.1.x") end # Default way to set up 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) ActiveSupport::Dependencies.reference(arg) Getter.new(arg) 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) 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 |args| 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-4.4.3/gemfiles/0000755000004100000410000000000013254473005014627 5ustar www-datawww-datadevise-4.4.3/gemfiles/Gemfile.rails-5.0-stable0000644000004100000410000000111713254473005021003 0ustar www-datawww-data# frozen_string_literal: true source "https://rubygems.org" gemspec path: ".." gem "rails", '~> 5.0.0' gem "omniauth" gem "omniauth-oauth2" gem "rdoc" gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml" gem "rails-controller-testing" gem "responders", "~> 2.1" group :test do gem "omniauth-facebook" gem "omniauth-openid" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false gem 'test_after_commit', require: false end platforms :ruby do gem "sqlite3" end # TODO: # group :mongoid do # gem "mongoid", "~> 4.0.0" # end devise-4.4.3/gemfiles/Gemfile.rails-5.0-stable.lock0000644000004100000410000001077713254473005021746 0ustar www-datawww-dataGIT remote: git://github.com/rails/activemodel-serializers-xml.git revision: dd9c0acf26aab111ebc647cd8deb99ebc6946531 specs: activemodel-serializers-xml (1.0.1) activemodel (> 5.x) activesupport (> 5.x) builder (~> 3.1) PATH remote: .. specs: devise (4.4.3) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0, < 6.0) responders warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: actioncable (5.0.2) actionpack (= 5.0.2) nio4r (>= 1.2, < 3.0) websocket-driver (~> 0.6.1) actionmailer (5.0.2) actionpack (= 5.0.2) actionview (= 5.0.2) activejob (= 5.0.2) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 2.0) actionpack (5.0.2) actionview (= 5.0.2) activesupport (= 5.0.2) rack (~> 2.0) rack-test (~> 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (5.0.2) activesupport (= 5.0.2) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.3) activejob (5.0.2) activesupport (= 5.0.2) globalid (>= 0.3.6) activemodel (5.0.2) activesupport (= 5.0.2) activerecord (5.0.2) activemodel (= 5.0.2) activesupport (= 5.0.2) arel (~> 7.0) activesupport (5.0.2) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (~> 0.7) minitest (~> 5.1) tzinfo (~> 1.1) arel (7.1.4) bcrypt (3.1.11) builder (3.2.3) concurrent-ruby (1.0.5) erubis (2.7.0) faraday (0.11.0) multipart-post (>= 1.2, < 3) globalid (0.4.0) activesupport (>= 4.2.0) hashie (3.5.5) i18n (0.8.1) jwt (1.5.6) loofah (2.0.3) nokogiri (>= 1.5.9) mail (2.6.5) mime-types (>= 1.16, < 4) metaclass (0.0.4) method_source (0.8.2) mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) mini_portile2 (2.1.0) minitest (5.10.1) mocha (1.2.1) metaclass (~> 0.0.1) multi_json (1.12.1) multi_xml (0.6.0) multipart-post (2.0.0) nio4r (2.0.0) nokogiri (1.7.2) mini_portile2 (~> 2.1.0) oauth2 (1.3.1) faraday (>= 0.8, < 0.12) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (>= 1.2, < 3) omniauth (1.6.1) hashie (>= 3.4.6, < 3.6.0) rack (>= 1.6.2, < 3) omniauth-facebook (4.0.0) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.4.0) oauth2 (~> 1.0) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) orm_adapter (0.5.0) rack (2.0.2) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.6.3) rack (>= 1.0) rails (5.0.2) actioncable (= 5.0.2) actionmailer (= 5.0.2) actionpack (= 5.0.2) actionview (= 5.0.2) activejob (= 5.0.2) activemodel (= 5.0.2) activerecord (= 5.0.2) activesupport (= 5.0.2) bundler (>= 1.3.0, < 2.0) railties (= 5.0.2) sprockets-rails (>= 2.0.0) rails-controller-testing (1.0.1) actionpack (~> 5.x) actionview (~> 5.x) activesupport (~> 5.x) rails-dom-testing (2.0.3) activesupport (>= 4.2.0) nokogiri (>= 1.6) rails-html-sanitizer (1.0.3) loofah (~> 2.0) railties (5.0.2) actionpack (= 5.0.2) activesupport (= 5.0.2) method_source rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (12.0.0) rdoc (5.1.0) responders (2.4.0) actionpack (>= 4.2.0, < 5.3) railties (>= 4.2.0, < 5.3) ruby-openid (2.7.0) sprockets (3.7.1) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.2.0) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) sqlite3 (1.3.13) test_after_commit (1.1.0) activerecord (>= 3.2) thor (0.19.4) thread_safe (0.3.6) tzinfo (1.2.3) thread_safe (~> 0.1) warden (1.2.7) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) websocket-driver (0.6.5) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.2) PLATFORMS ruby DEPENDENCIES activemodel-serializers-xml! devise! mocha (~> 1.1) omniauth omniauth-facebook omniauth-oauth2 omniauth-openid rails (~> 5.0.0) rails-controller-testing rdoc responders (~> 2.1) sqlite3 test_after_commit webrat (= 0.7.3) BUNDLED WITH 1.16.1 devise-4.4.3/gemfiles/Gemfile.rails-4.2-stable.lock0000644000004100000410000001071413254473005021736 0ustar www-datawww-dataGIT remote: git://github.com/rails/rails.git revision: dc3ae21802c316e1639239d28202db7aa7fb7cac branch: 4-2-stable specs: actionmailer (4.2.8) actionpack (= 4.2.8) actionview (= 4.2.8) activejob (= 4.2.8) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 1.0, >= 1.0.5) actionpack (4.2.8) actionview (= 4.2.8) activesupport (= 4.2.8) 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.8) activesupport (= 4.2.8) builder (~> 3.1) erubis (~> 2.7.0) rails-dom-testing (~> 1.0, >= 1.0.5) rails-html-sanitizer (~> 1.0, >= 1.0.3) activejob (4.2.8) activesupport (= 4.2.8) globalid (>= 0.3.0) activemodel (4.2.8) activesupport (= 4.2.8) builder (~> 3.1) activerecord (4.2.8) activemodel (= 4.2.8) activesupport (= 4.2.8) arel (~> 6.0) activesupport (4.2.8) i18n (~> 0.7) minitest (~> 5.1) thread_safe (~> 0.3, >= 0.3.4) tzinfo (~> 1.1) rails (4.2.8) actionmailer (= 4.2.8) actionpack (= 4.2.8) actionview (= 4.2.8) activejob (= 4.2.8) activemodel (= 4.2.8) activerecord (= 4.2.8) activesupport (= 4.2.8) bundler (>= 1.3.0, < 2.0) railties (= 4.2.8) sprockets-rails railties (4.2.8) actionpack (= 4.2.8) activesupport (= 4.2.8) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) PATH remote: .. specs: devise (4.4.3) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0, < 6.0) responders warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: arel (6.0.4) bcrypt (3.1.11) bson (3.2.6) builder (3.2.3) concurrent-ruby (1.0.5) connection_pool (2.2.1) erubis (2.7.0) faraday (0.11.0) multipart-post (>= 1.2, < 3) globalid (0.3.7) activesupport (>= 4.1.0) hashie (3.5.5) i18n (0.8.1) jwt (1.5.6) loofah (2.0.3) nokogiri (>= 1.5.9) mail (2.6.4) mime-types (>= 1.16, < 4) metaclass (0.0.4) mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) mini_portile2 (2.1.0) minitest (5.10.1) mocha (1.2.1) 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.12.1) multi_xml (0.6.0) multipart-post (2.0.0) nokogiri (1.7.0.1) mini_portile2 (~> 2.1.0) oauth2 (1.3.1) faraday (>= 0.8, < 0.12) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (>= 1.2, < 3) omniauth (1.6.1) hashie (>= 3.4.6, < 3.6.0) rack (>= 1.6.2, < 3) omniauth-facebook (4.0.0) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.4.0) 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.3.0) orm_adapter (0.5.0) rack (1.6.5) 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.8) activesupport (>= 4.2.0.beta, < 5.0) nokogiri (~> 1.6) rails-deprecated_sanitizer (>= 1.0.1) rails-html-sanitizer (1.0.3) loofah (~> 2.0) rake (12.0.0) rdoc (5.1.0) responders (2.4.0) actionpack (>= 4.2.0, < 5.3) railties (>= 4.2.0, < 5.3) ruby-openid (2.7.0) sprockets (3.7.1) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.2.0) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) sqlite3 (1.3.13) test_after_commit (1.1.0) activerecord (>= 3.2) thor (0.19.4) thread_safe (0.3.6) tzinfo (1.2.2) thread_safe (~> 0.1) warden (1.2.7) 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 omniauth-facebook omniauth-oauth2 omniauth-openid rails! rdoc (~> 5.1) sqlite3 test_after_commit webrat (= 0.7.3) BUNDLED WITH 1.16.1 devise-4.4.3/gemfiles/Gemfile.rails-4.2-stable0000644000004100000410000000113013254473005020777 0ustar www-datawww-data# frozen_string_literal: true source "https://rubygems.org" gemspec path: ".." gem "rails", github: "rails/rails", branch: "4-2-stable" gem "omniauth" gem "omniauth-oauth2" gem "rdoc", "~> 5.1" group :test do gem "omniauth-facebook" gem "omniauth-openid" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false gem 'test_after_commit', 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-4.4.3/gemfiles/Gemfile.rails-5.2-rc10000644000004100000410000000076313254473005020226 0ustar www-datawww-datasource "https://rubygems.org" gemspec path: ".." gem "rails", '~> 5.2.0.rc1' gem "omniauth" gem "omniauth-oauth2" gem "rdoc" gem "activemodel-serializers-xml", github: "rails/activemodel-serializers-xml" gem "rails-controller-testing" gem "responders", "~> 2.1" group :test do gem "omniauth-facebook" gem "omniauth-openid" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false gem 'test_after_commit', require: false end platforms :ruby do gem "sqlite3" end devise-4.4.3/gemfiles/Gemfile.rails-5.2-rc1.lock0000644000004100000410000001154613254473005021156 0ustar www-datawww-dataGIT remote: git://github.com/rails/activemodel-serializers-xml.git revision: 356edf4dfc38fb1fbfee90c87856e4fe5b73c5e1 specs: activemodel-serializers-xml (1.0.2) activemodel (> 5.x) activesupport (> 5.x) builder (~> 3.1) PATH remote: .. specs: devise (4.4.3) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0, < 6.0) responders warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: actioncable (5.2.0.rc1) actionpack (= 5.2.0.rc1) nio4r (~> 2.0) websocket-driver (>= 0.6.1) actionmailer (5.2.0.rc1) actionpack (= 5.2.0.rc1) actionview (= 5.2.0.rc1) activejob (= 5.2.0.rc1) mail (~> 2.5, >= 2.5.4) rails-dom-testing (~> 2.0) actionpack (5.2.0.rc1) actionview (= 5.2.0.rc1) activesupport (= 5.2.0.rc1) rack (~> 2.0) rack-test (>= 0.6.3) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.2) actionview (5.2.0.rc1) activesupport (= 5.2.0.rc1) builder (~> 3.1) erubi (~> 1.4) rails-dom-testing (~> 2.0) rails-html-sanitizer (~> 1.0, >= 1.0.3) activejob (5.2.0.rc1) activesupport (= 5.2.0.rc1) globalid (>= 0.3.6) activemodel (5.2.0.rc1) activesupport (= 5.2.0.rc1) activerecord (5.2.0.rc1) activemodel (= 5.2.0.rc1) activesupport (= 5.2.0.rc1) arel (>= 9.0) activestorage (5.2.0.rc1) actionpack (= 5.2.0.rc1) activerecord (= 5.2.0.rc1) marcel (~> 0.3.1) activesupport (5.2.0.rc1) concurrent-ruby (~> 1.0, >= 1.0.2) i18n (~> 0.7) minitest (~> 5.1) tzinfo (~> 1.1) arel (9.0.0) bcrypt (3.1.11) builder (3.2.3) concurrent-ruby (1.0.5) crass (1.0.3) erubi (1.7.0) faraday (0.12.2) multipart-post (>= 1.2, < 3) globalid (0.4.1) activesupport (>= 4.2.0) hashie (3.5.7) i18n (0.9.3) concurrent-ruby (~> 1.0) jwt (1.5.6) loofah (2.1.1) crass (~> 1.0.2) nokogiri (>= 1.5.9) mail (2.7.0) mini_mime (>= 0.1.1) marcel (0.3.1) mimemagic (~> 0.3.2) metaclass (0.0.4) method_source (0.9.0) mimemagic (0.3.2) mini_mime (1.0.0) mini_portile2 (2.3.0) minitest (5.11.3) mocha (1.3.0) metaclass (~> 0.0.1) multi_json (1.13.1) multi_xml (0.6.0) multipart-post (2.0.0) nio4r (2.2.0) nokogiri (1.8.2) mini_portile2 (~> 2.3.0) oauth2 (1.4.0) faraday (>= 0.8, < 0.13) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (>= 1.2, < 3) omniauth (1.8.1) hashie (>= 3.4.6, < 3.6.0) rack (>= 1.6.2, < 3) omniauth-facebook (4.0.0) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.5.0) oauth2 (~> 1.1) omniauth (~> 1.2) omniauth-openid (1.0.1) omniauth (~> 1.0) rack-openid (~> 1.3.1) orm_adapter (0.5.0) rack (2.0.4) rack-openid (1.3.1) rack (>= 1.1.0) ruby-openid (>= 2.1.8) rack-test (0.8.2) rack (>= 1.0, < 3) rails (5.2.0.rc1) actioncable (= 5.2.0.rc1) actionmailer (= 5.2.0.rc1) actionpack (= 5.2.0.rc1) actionview (= 5.2.0.rc1) activejob (= 5.2.0.rc1) activemodel (= 5.2.0.rc1) activerecord (= 5.2.0.rc1) activestorage (= 5.2.0.rc1) activesupport (= 5.2.0.rc1) bundler (>= 1.3.0) railties (= 5.2.0.rc1) sprockets-rails (>= 2.0.0) rails-controller-testing (1.0.2) actionpack (~> 5.x, >= 5.0.1) actionview (~> 5.x, >= 5.0.1) activesupport (~> 5.x) rails-dom-testing (2.0.3) activesupport (>= 4.2.0) nokogiri (>= 1.6) rails-html-sanitizer (1.0.3) loofah (~> 2.0) railties (5.2.0.rc1) actionpack (= 5.2.0.rc1) activesupport (= 5.2.0.rc1) method_source rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (12.3.0) rdoc (6.0.1) responders (2.4.0) actionpack (>= 4.2.0, < 5.3) railties (>= 4.2.0, < 5.3) ruby-openid (2.7.0) sprockets (3.7.1) concurrent-ruby (~> 1.0) rack (> 1, < 3) sprockets-rails (3.2.1) actionpack (>= 4.0) activesupport (>= 4.0) sprockets (>= 3.0.0) sqlite3 (1.3.13) test_after_commit (1.1.0) activerecord (>= 3.2) thor (0.20.0) thread_safe (0.3.6) tzinfo (1.2.5) thread_safe (~> 0.1) warden (1.2.7) rack (>= 1.0) webrat (0.7.3) nokogiri (>= 1.2.0) rack (>= 1.0) rack-test (>= 0.5.3) websocket-driver (0.7.0) websocket-extensions (>= 0.1.0) websocket-extensions (0.1.3) PLATFORMS ruby DEPENDENCIES activemodel-serializers-xml! devise! mocha (~> 1.1) omniauth omniauth-facebook omniauth-oauth2 omniauth-openid rails (~> 5.2.0.rc1) rails-controller-testing rdoc responders (~> 2.1) sqlite3 test_after_commit webrat (= 0.7.3) BUNDLED WITH 1.16.1 devise-4.4.3/gemfiles/Gemfile.rails-4.1-stable.lock0000644000004100000410000000747013254473005021742 0ustar www-datawww-dataGIT remote: git://github.com/rails/rails.git revision: 0cad778c2605a5204a05a9f1dbd3344e39f248d8 branch: 4-1-stable specs: actionmailer (4.1.16) actionpack (= 4.1.16) actionview (= 4.1.16) mail (~> 2.5, >= 2.5.4) rails (4.1.16) actionmailer (= 4.1.16) actionpack (= 4.1.16) actionview (= 4.1.16) activemodel (= 4.1.16) activerecord (= 4.1.16) activesupport (= 4.1.16) bundler (>= 1.3.0, < 2.0) railties (= 4.1.16) sprockets-rails (~> 2.0) PATH remote: .. specs: devise (4.4.3) bcrypt (~> 3.0) orm_adapter (~> 0.1) railties (>= 4.1.0, < 6.0) responders warden (~> 1.2.3) GEM remote: https://rubygems.org/ specs: actionpack (4.1.16) actionview (= 4.1.16) activesupport (= 4.1.16) rack (~> 1.5.2) rack-test (~> 0.6.2) actionview (4.1.16) activesupport (= 4.1.16) builder (~> 3.1) erubis (~> 2.7.0) activemodel (4.1.16) activesupport (= 4.1.16) builder (~> 3.1) activerecord (4.1.16) activemodel (= 4.1.16) activesupport (= 4.1.16) arel (~> 5.0.0) activesupport (4.1.16) i18n (~> 0.6, >= 0.6.9) json (~> 1.7, >= 1.7.7) minitest (~> 5.1) thread_safe (~> 0.1) tzinfo (~> 1.1) arel (5.0.1.20140414130214) bcrypt (3.1.11) bson (3.2.6) builder (3.2.3) concurrent-ruby (1.0.5) connection_pool (2.2.1) erubis (2.7.0) faraday (0.11.0) multipart-post (>= 1.2, < 3) hashie (3.5.5) i18n (0.8.1) json (1.8.6) jwt (1.5.6) mail (2.6.4) mime-types (>= 1.16, < 4) metaclass (0.0.4) mime-types (3.1) mime-types-data (~> 3.2015) mime-types-data (3.2016.0521) mini_portile2 (2.1.0) minitest (5.10.1) mocha (1.2.1) 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.12.1) multi_xml (0.6.0) multipart-post (2.0.0) nokogiri (1.7.0.1) mini_portile2 (~> 2.1.0) oauth2 (1.3.1) faraday (>= 0.8, < 0.12) jwt (~> 1.0) multi_json (~> 1.3) multi_xml (~> 0.5) rack (>= 1.2, < 3) omniauth (1.4.2) hashie (>= 1.2, < 4) rack (>= 1.0, < 3) omniauth-facebook (4.0.0) omniauth-oauth2 (~> 1.2) omniauth-oauth2 (1.4.0) 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.3.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) railties (4.1.16) actionpack (= 4.1.16) activesupport (= 4.1.16) rake (>= 0.8.7) thor (>= 0.18.1, < 2.0) rake (12.0.0) rdoc (5.1.0) responders (1.1.2) railties (>= 3.2, < 4.2) ruby-openid (2.7.0) sprockets (3.7.1) 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.13) test_after_commit (1.1.0) activerecord (>= 3.2) thor (0.19.4) thread_safe (0.3.6) tzinfo (1.2.2) thread_safe (~> 0.1) warden (1.2.7) 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 omniauth-facebook omniauth-oauth2 omniauth-openid rails! rdoc (~> 5.1) sqlite3 test_after_commit webrat (= 0.7.3) BUNDLED WITH 1.16.1 devise-4.4.3/gemfiles/Gemfile.rails-4.1-stable0000644000004100000410000000113013254473005020776 0ustar www-datawww-data# frozen_string_literal: true source "https://rubygems.org" gemspec path: ".." gem "rails", github: "rails/rails", branch: "4-1-stable" gem "omniauth" gem "omniauth-oauth2" gem "rdoc", "~> 5.1" group :test do gem "omniauth-facebook" gem "omniauth-openid" gem "webrat", "0.7.3", require: false gem "mocha", "~> 1.1", require: false gem 'test_after_commit', 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-4.4.3/test/0000755000004100000410000000000013254473005014013 5ustar www-datawww-datadevise-4.4.3/test/devise_test.rb0000755000004100000410000000632613254473005016670 0ustar www-datawww-data# frozen_string_literal: true require '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 Devise.add_module(:coconut) assert_equal 1, Devise::ALL.select { |v| v == :coconut }.size refute Devise::STRATEGIES.include?(:coconut) refute defined?(Devise::Models::Coconut) Devise::ALL.delete(:coconut) Devise.add_module(:banana, strategy: :fruits) assert_equal :fruits, Devise::STRATEGIES[:banana] Devise::ALL.delete(:banana) Devise::STRATEGIES.delete(:banana) 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| refute Devise.secure_compare(empty, "something") refute Devise.secure_compare("something", empty) refute Devise.secure_compare(empty, empty) end refute 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", "test@tt", "test@valid---domain.com"] non_valid_emails = ["rex", "test user@example.com", "test_user@example server.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-4.4.3/test/failure_app_test.rb0000644000004100000410000003173713254473005017701 0ustar www-datawww-data# frozen_string_literal: true require '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) # Passing nil for action_dispatch.request.formats prevents the default from being used in Rails 5, need to remove it if env.has_key?('action_dispatch.request.formats') && env['action_dispatch.request.formats'].nil? env.delete 'action_dispatch.request.formats' unless env['action_dispatch.request.formats'] end @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 if Rails.application.config.action_controller.respond_to?(:relative_url_root) test "returns to the default redirect location considering action_controller's relative url root" do swap Rails.application.config.action_controller, 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 action_controller's relative url root and subdomain" do swap Rails.application.config.action_controller, 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 'set up 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-4.4.3/test/omniauth/0000755000004100000410000000000013254473005015637 5ustar www-datawww-datadevise-4.4.3/test/omniauth/url_helpers_test.rb0000644000004100000410000000341513254473005021552 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class OmniAuthRoutesTest < ActionController::TestCase tests ApplicationController def assert_path(action, provider, with_param=true) # Resource param assert_equal @controller.send(action, :user, provider), @controller.send("user_#{provider}_#{action}") # With an object assert_equal @controller.send(action, User.new, provider), @controller.send("user_#{provider}_#{action}") if with_param # Default url params assert_equal @controller.send(action, :user, provider, param: 123), @controller.send("user_#{provider}_#{action}", 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 NoMethodError 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-4.4.3/test/omniauth/config_test.rb0000644000004100000410000000354213254473005020474 0ustar www-datawww-data# frozen_string_literal: true require '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 class NamedTestStrategy include OmniAuth::Strategy option :name, :the_one end test "finds the strategy in OmniAuth's list by name" do config = Devise::OmniAuth::Config.new :the_one, [{}] assert_equal NamedTestStrategy, config.strategy_class end class UnNamedTestStrategy include OmniAuth::Strategy end test "finds the strategy in OmniAuth's list by class name" do 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-4.4.3/test/models_test.rb0000644000004100000410000001120513254473005016661 0ustar www-datawww-data# frozen_string_literal: true require '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| refute 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 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-4.4.3/test/controllers/0000755000004100000410000000000013254473005016361 5ustar www-datawww-datadevise-4.4.3/test/controllers/url_helpers_test.rb0000644000004100000410000000453713254473005022302 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class RoutesTest < Devise::ControllerTestCase 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-4.4.3/test/controllers/custom_registrations_controller_test.rb0000644000004100000410000000273313254473005026504 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class CustomRegistrationsControllerTest < Devise::ControllerTestCase tests Custom::RegistrationsController include Devise::Test::ControllerHelpers 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, params: { 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, params: { 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, params: { 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, params: { 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-4.4.3/test/controllers/load_hooks_controller_test.rb0000644000004100000410000000102713254473005024332 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class LoadHooksControllerTest < Devise::ControllerTestCase 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-4.4.3/test/controllers/passwords_controller_test.rb0000644000004100000410000000203213254473005024232 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class PasswordsControllerTest < Devise::ControllerTestCase tests Devise::PasswordsController include Devise::Test::ControllerHelpers 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, params: { "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-4.4.3/test/controllers/custom_strategy_test.rb0000644000004100000410000000374113254473005023206 0ustar www-datawww-data# frozen_string_literal: true require '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 < Devise::ControllerTestCase tests CustomStrategyController include Devise::Test::ControllerHelpers 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 assert ret.is_a?(ActionDispatch::TestResponse) # 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' assert ret.is_a?(ActionDispatch::TestResponse) # check the saved response headers as well. assert_equal response.headers['X-FOO'], 'BAR' end end devise-4.4.3/test/controllers/helper_methods_test.rb0000644000004100000410000000116413254473005022751 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class ApiController < ActionController::Metal include Devise::Controllers::Helpers end class HelperMethodsTest < Devise::ControllerTestCase tests ApiController test 'includes Devise::Controllers::Helpers' do assert_includes @controller.class.ancestors, Devise::Controllers::Helpers end test 'does not respond_to helper or helper_method' do refute_respond_to @controller.class, :helper refute_respond_to @controller.class, :helper_method end test 'defines methods like current_user' do assert_respond_to @controller, :current_user end end devise-4.4.3/test/controllers/helpers_test.rb0000644000004100000410000003004113254473005021405 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' require 'ostruct' class ControllerAuthenticatableTest < Devise::ControllerTestCase 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) refute @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 'bypass the sign in' do user = User.new @mock_warden.expects(:session_serializer).returns(serializer = mock()) serializer.expects(:store).with(user, :user) @controller.bypass_sign_in(user) 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_nil @controller.instance_variable_get(:@current_user) assert_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_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 refute @controller.devise_controller? end end devise-4.4.3/test/controllers/internal_helpers_test.rb0000644000004100000410000001116713254473005023311 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class MyController < DeviseController end class HelpersTest < Devise::ControllerTestCase 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'} # Stub controller name so strong parameters can filter properly. # DeviseController does not allow any parameters by default. @controller.stubs(:controller_name).returns(:sessions_controller) params = ActionController::Parameters.new({'user' => user_params}) @controller.stubs(:params).returns(params) res_params = @controller.send(:resource_params).permit!.to_h assert_equal user_params, res_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 refute @controller.navigational_formats.include?("*/*") end MyController.send(:protected, :navigational_formats) end end devise-4.4.3/test/controllers/sessions_controller_test.rb0000644000004100000410000000657613254473005024074 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class SessionsControllerTest < Devise::ControllerTestCase tests Devise::SessionsController include Devise::Test::ControllerHelpers test "#create doesn't raise unpermitted params when sign in fails" do begin subscriber = ActiveSupport::Notifications.subscribe %r{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, params: { 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, params: { 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, params: { 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, params: { 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, params: { 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 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-4.4.3/test/controllers/inherited_controller_i18n_messages_test.rb0000644000004100000410000000244613254473005026717 0ustar www-datawww-data# frozen_string_literal: true require '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 < Devise::ControllerTestCase 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 < Devise::ControllerTestCase 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-4.4.3/test/mailers/0000755000004100000410000000000013254473005015447 5ustar www-datawww-datadevise-4.4.3/test/mailers/mailer_test.rb0000644000004100000410000000107013254473005020302 0ustar www-datawww-data# frozen_string_literal: true require "test_helper" class MailerTest < ActionMailer::TestCase test "pass given block to #mail call" do class TestMailer < Devise::Mailer def confirmation_instructions(record, token, opts = {}) @token = token devise_mail(record, :confirmation_instructions, opts) do |format| format.html(content_transfer_encoding: "7bit") end end end mail = TestMailer.confirmation_instructions(create_user, "confirmation-token") assert mail.content_transfer_encoding, "7bit" end end devise-4.4.3/test/mailers/reset_password_instructions_test.rb0000644000004100000410000000526513254473005024733 0ustar www-datawww-data# frozen_string_literal: true require '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 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'set up 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 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'set up 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-4.4.3/test/mailers/email_changed_test.rb0000644000004100000410000000671513254473005021604 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class EmailChangedTest < ActionMailer::TestCase def setup setup_mailer Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'test@example.com' Devise.send_email_changed_notification = true end def teardown Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' Devise.send_email_changed_notification = false end def user @user ||= create_user.tap { |u| @original_user_email = u.email u.update_attributes!(email: 'new-email@example.com') } end def mail @mail ||= begin user ActionMailer::Base.deliveries.last end end test 'email sent after changing the user email' 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 email changed to the original user email' do mail assert_equal [@original_user_email], mail.to end test 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'set up 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 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'set up 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 'set up subject from I18n' do store_translations :en, devise: { mailer: { email_changed: { subject: 'Email Has Changed' } } } do assert_equal 'Email Has Changed', mail.subject end end test 'subject namespaced by model' do store_translations :en, devise: { mailer: { email_changed: { user_subject: 'User Email Has Changed' } } } do assert_equal 'User Email Has Changed', mail.subject end end test 'body should have user info' do body = mail.body.encoded assert_match "Hello #{@original_user_email}", body assert_match "has been changed to #{user.email}", body end end class EmailChangedReconfirmationTest < ActionMailer::TestCase def setup setup_mailer Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'test@example.com' Devise.send_email_changed_notification = true end def teardown Devise.mailer = 'Devise::Mailer' Devise.mailer_sender = 'please-change-me@config-initializers-devise.com' Devise.send_email_changed_notification = false end def admin @admin ||= create_admin.tap { |u| @original_admin_email = u.email u.update_attributes!(email: 'new-email@example.com') } end def mail @mail ||= begin admin ActionMailer::Base.deliveries[-2] end end test 'send email changed to the original user email' do mail assert_equal [@original_admin_email], mail.to end test 'body should have unconfirmed user info' do body = mail.body.encoded assert_match admin.email, body assert_match "is being changed to #{admin.unconfirmed_email}", body end end devise-4.4.3/test/mailers/unlock_instructions_test.rb0000644000004100000410000000465613254473005023165 0ustar www-datawww-data# frozen_string_literal: true require '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 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'set up 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 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'set up 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-4.4.3/test/mailers/confirmation_instructions_test.rb0000644000004100000410000000625513254473005024357 0ustar www-datawww-data# frozen_string_literal: true require '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 'set up sender from configuration' do assert_equal ['test@example.com'], mail.from end test 'set up sender from custom mailer defaults' do Devise.mailer = 'Users::Mailer' assert_equal ['custom@example.com'], mail.from end test 'set up 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 'set up reply to as copy from sender' do assert_equal ['test@example.com'], mail.reply_to end test 'set up 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 'set up 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-4.4.3/test/parameter_sanitizer_test.rb0000644000004100000410000000465613254473005021462 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' require 'devise/parameter_sanitizer' class ParameterSanitizerTest < ActiveSupport::TestCase def sanitizer(params) params = ActionController::Parameters.new(params) Devise::ParameterSanitizer.new(User, :user, params) end test 'permits the default parameters for sign in' do sanitizer = sanitizer('user' => { 'email' => 'jose' }) sanitized = sanitizer.sanitize(:sign_in) assert_equal({ 'email' => 'jose' }, sanitized) end test 'permits the default parameters for sign up' do sanitizer = sanitizer('user' => { 'email' => 'jose', 'role' => 'invalid' }) sanitized = sanitizer.sanitize(:sign_up) assert_equal({ 'email' => 'jose' }, sanitized) end test 'permits the default parameters for account update' do sanitizer = sanitizer('user' => { 'email' => 'jose', 'role' => 'invalid' }) sanitized = sanitizer.sanitize(:account_update) assert_equal({ 'email' => 'jose' }, sanitized) end test 'permits news parameters for an existing action' do sanitizer = sanitizer('user' => { 'username' => 'jose' }) sanitizer.permit(:sign_in, keys: [:username]) sanitized = sanitizer.sanitize(:sign_in) assert_equal({ 'username' => 'jose' }, sanitized) end test 'permits news parameters for an existing action with a block' do sanitizer = sanitizer('user' => { 'username' => 'jose' }) sanitizer.permit(:sign_in) do |user| user.permit(:username) end sanitized = sanitizer.sanitize(:sign_in) assert_equal({ 'username' => 'jose' }, sanitized) end test 'permit parameters for new actions' do sanitizer = sanitizer('user' => { 'email' => 'jose@omglol', 'name' => 'Jose' }) sanitizer.permit(:invite_user, keys: [:email, :name]) sanitized = sanitizer.sanitize(:invite_user) assert_equal({ 'email' => 'jose@omglol', 'name' => 'Jose' }, sanitized) end test 'fails when we do not have any permitted parameters for the action' do sanitizer = sanitizer('user' => { 'email' => 'jose', 'password' => 'invalid' }) assert_raise NotImplementedError do sanitizer.sanitize(:unknown) end end test 'removes permitted parameters' do sanitizer = sanitizer('user' => { 'email' => 'jose@omglol', 'username' => 'jose' }) sanitizer.permit(:sign_in, keys: [:username], except: [:email]) sanitized = sanitizer.sanitize(:sign_in) assert_equal({ 'username' => 'jose' }, sanitized) end end devise-4.4.3/test/test/0000755000004100000410000000000013254473005014772 5ustar www-datawww-datadevise-4.4.3/test/test/controller_helpers_test.rb0000644000004100000410000001134313254473005022265 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class TestControllerHelpersTest < Devise::ControllerTestCase tests UsersController include Devise::Test::ControllerHelpers 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, params: { 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 = 300 end end swap Devise.warden_config, failure_app: custom_failure_app do get :index assert_response 300 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 "returns the content type of a failure app" do get :index, params: { format: :xml } assert response.content_type.include?('application/xml') 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 = if Devise::Test.rails51? || Devise::Test.rails52? ActionController::TestRequest.create(Class.new) # needs a "controller class" elsif Devise::Test.rails5? ActionController::TestRequest.create else ActionController::TestRequest.new end 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-4.4.3/test/test/integration_helpers_test.rb0000644000004100000410000000130213254473005022417 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class TestIntegrationsHelpersTest < Devise::IntegrationTest include Devise::Test::IntegrationHelpers test '#sign_in signs in the resource directly' do sign_in(create_user) visit '/' assert warden.authenticated?(:user) end test '#sign_outs signs out in the resource directly' do user = create_user sign_in user sign_out user visit '/' refute warden.authenticated?(:user) end test '#sign_out does not signs out other scopes' do sign_in(create_user) sign_in(create_admin) sign_out :user visit '/' refute warden.authenticated?(:user) assert warden.authenticated?(:admin) end end devise-4.4.3/test/orm/0000755000004100000410000000000013254473005014610 5ustar www-datawww-datadevise-4.4.3/test/orm/active_record.rb0000644000004100000410000000130313254473005017743 0ustar www-datawww-data# frozen_string_literal: true ActiveRecord::Migration.verbose = false ActiveRecord::Base.logger = Logger.new(nil) ActiveRecord::Base.include_root_in_json = true migrate_path = File.expand_path("../../rails_app/db/migrate/", __FILE__) if Devise::Test.rails52? ActiveRecord::MigrationContext.new(migrate_path).migrate else ActiveRecord::Migrator.migrate(migrate_path) end class ActiveSupport::TestCase if Devise::Test.rails5? self.use_transactional_tests = true else # Let `after_commit` work with transactional fixtures, however this is not needed for Rails 5. require 'test_after_commit' self.use_transactional_fixtures = true end self.use_instantiated_fixtures = false end devise-4.4.3/test/orm/mongoid.rb0000644000004100000410000000043113254473005016567 0ustar www-datawww-data# frozen_string_literal: true require '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.default_session.drop end end devise-4.4.3/test/test_helper.rb0000644000004100000410000000177213254473005016665 0ustar www-datawww-data# frozen_string_literal: true ENV["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-4.4.3/test/rails_app/0000755000004100000410000000000013254473005015765 5ustar www-datawww-datadevise-4.4.3/test/rails_app/Rakefile0000644000004100000410000000037113254473005017433 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-4.4.3/test/rails_app/bin/0000755000004100000410000000000013254473005016535 5ustar www-datawww-datadevise-4.4.3/test/rails_app/bin/rake0000755000004100000410000000013213254473005017401 0ustar www-datawww-data#!/usr/bin/env ruby require_relative '../config/boot' require 'rake' Rake.application.run devise-4.4.3/test/rails_app/bin/rails0000755000004100000410000000022213254473005017571 0ustar www-datawww-data#!/usr/bin/env ruby APP_PATH = File.expand_path('../../config/application', __FILE__) require_relative '../config/boot' require 'rails/commands' devise-4.4.3/test/rails_app/bin/bundle0000755000004100000410000000020113254473005017725 0ustar www-datawww-data#!/usr/bin/env ruby ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) load Gem.bin_path('bundler', 'bundle') devise-4.4.3/test/rails_app/db/0000755000004100000410000000000013254473005016352 5ustar www-datawww-datadevise-4.4.3/test/rails_app/db/schema.rb0000644000004100000410000000414613254473005020144 0ustar www-datawww-data# encoding: UTF-8 # frozen_string_literal: true # 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-4.4.3/test/rails_app/db/migrate/0000755000004100000410000000000013254473005020002 5ustar www-datawww-datadevise-4.4.3/test/rails_app/db/migrate/20100401102949_create_tables.rb0000644000004100000410000000407413254473005024571 0ustar www-datawww-data# frozen_string_literal: true superclass = ActiveRecord::Migration # TODO: Inherit from the 5.0 Migration class directly when we drop support for Rails 4. superclass = ActiveRecord::Migration[5.0] if superclass.respond_to?(:[]) class CreateTables < superclass 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-4.4.3/test/rails_app/public/0000755000004100000410000000000013254473005017243 5ustar www-datawww-datadevise-4.4.3/test/rails_app/public/422.html0000644000004100000410000000130713254473005020441 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-4.4.3/test/rails_app/public/favicon.ico0000644000004100000410000000000013254473005021352 0ustar www-datawww-datadevise-4.4.3/test/rails_app/public/404.html0000644000004100000410000000133013254473005020435 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-4.4.3/test/rails_app/public/500.html0000644000004100000410000000133013254473005020432 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-4.4.3/test/rails_app/lib/0000755000004100000410000000000013254473005016533 5ustar www-datawww-datadevise-4.4.3/test/rails_app/lib/shared_admin.rb0000644000004100000410000000130513254473005021475 0ustar www-datawww-data# frozen_string_literal: true module 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 if Devise::Test.rails51? validates_uniqueness_of :email, allow_blank: true, if: :will_save_change_to_email? else validates_uniqueness_of :email, allow_blank: true, if: :email_changed? end end def raw_confirmation_token @raw_confirmation_token end end devise-4.4.3/test/rails_app/lib/shared_user_without_email.rb0000644000004100000410000000174513254473005024325 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/test/rails_app/lib/shared_user.rb0000644000004100000410000000140713254473005021366 0ustar www-datawww-data# frozen_string_literal: true module SharedUser extend ActiveSupport::Concern included do devise :database_authenticatable, :confirmable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :trackable, :validatable, :omniauthable, password_length: 7..72, reconfirmable: false 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-4.4.3/test/rails_app/lib/shared_user_without_omniauth.rb0000644000004100000410000000055513254473005025060 0ustar www-datawww-data# frozen_string_literal: true module SharedUserWithoutOmniauth extend ActiveSupport::Concern included do devise :database_authenticatable, :confirmable, :lockable, :recoverable, :registerable, :rememberable, :timeoutable, :trackable, :validatable, reconfirmable: false end def raw_confirmation_token @raw_confirmation_token end end devise-4.4.3/test/rails_app/config/0000755000004100000410000000000013254473005017232 5ustar www-datawww-datadevise-4.4.3/test/rails_app/config/application.rb0000644000004100000410000000277013254473005022070 0ustar www-datawww-data# frozen_string_literal: true require 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 } rails_version = Gem::Version.new(Rails.version) if DEVISE_ORM == :active_record && rails_version >= Gem::Version.new('4.2.0') && rails_version < Gem::Version.new('5.1.0') config.active_record.raise_in_transactional_callbacks = true end # This was used to break devise in some situations config.to_prepare do Devise::SessionsController.layout "application" end end end devise-4.4.3/test/rails_app/config/initializers/0000755000004100000410000000000013254473005021740 5ustar www-datawww-datadevise-4.4.3/test/rails_app/config/initializers/secret_token.rb0000644000004100000410000000033613254473005024754 0ustar www-datawww-data# frozen_string_literal: true config = Rails.application.config config.secret_key_base = 'd588e99efff13a86461fd6ab82327823ad2f8feb5dc217ce652cdd9f0dfc5eb4b5a62a92d24d2574d7d51dfb1ea8dd453ea54e00cf672159a13104a135422a10' devise-4.4.3/test/rails_app/config/initializers/session_store.rb0000644000004100000410000000016313254473005025164 0ustar www-datawww-data# frozen_string_literal: true RailsApp::Application.config.session_store :cookie_store, key: '_rails_app_session' devise-4.4.3/test/rails_app/config/initializers/backtrace_silencers.rb0000644000004100000410000000066113254473005026256 0ustar www-datawww-data# frozen_string_literal: true # 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-4.4.3/test/rails_app/config/initializers/devise.rb0000644000004100000410000002044613254473005023552 0ustar www-datawww-data# frozen_string_literal: true require "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 # Set up 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-4.4.3/test/rails_app/config/initializers/inflections.rb0000644000004100000410000000012513254473005024600 0ustar www-datawww-data# frozen_string_literal: true ActiveSupport::Inflector.inflections do |inflect| end devise-4.4.3/test/rails_app/config/boot.rb0000644000004100000410000000116613254473005020526 0ustar www-datawww-data# frozen_string_literal: true unless defined?(DEVISE_ORM) DEVISE_ORM = (ENV["DEVISE_ORM"] || :active_record).to_sym end module Devise module Test # Detection for minor differences between Rails 4 and 5, 5.1, and 5.2 in tests. def self.rails52? Rails.version.start_with? '5.2' end def self.rails51? Rails.version.start_with? '5.1' end def self.rails5? Rails.version.start_with? '5' end end end # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) devise-4.4.3/test/rails_app/config/environments/0000755000004100000410000000000013254473005021761 5ustar www-datawww-datadevise-4.4.3/test/rails_app/config/environments/test.rb0000644000004100000410000000361513254473005023272 0ustar www-datawww-data# frozen_string_literal: true RailsApp::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 >= "5.0.0" config.public_file_server.enabled = true config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'} elsif Rails.version >= "4.2.0" config.serve_static_files = true config.static_cache_control = "public, max-age=3600" else config.serve_static_assets = true config.static_cache_control = "public, max-age=3600" end # 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-4.4.3/test/rails_app/config/environments/production.rb0000644000004100000410000000657013254473005024504 0ustar www-datawww-data# frozen_string_literal: true RailsApp::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 >= "5.0.0" config.public_file_server.enabled = false elsif 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-4.4.3/test/rails_app/config/environments/development.rb0000644000004100000410000000220613254473005024630 0ustar www-datawww-data# frozen_string_literal: true RailsApp::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-4.4.3/test/rails_app/config/database.yml0000644000004100000410000000072613254473005021526 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-4.4.3/test/rails_app/config/routes.rb0000644000004100000410000000764313254473005021112 0ustar www-datawww-data# frozen_string_literal: true Rails.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 :gets, sign_out_via: :get, 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-4.4.3/test/rails_app/config/environment.rb0000644000004100000410000000027113254473005022123 0ustar www-datawww-data# frozen_string_literal: true # Load the rails application. require File.expand_path('../application', __FILE__) # Initialize the rails application. RailsApp::Application.initialize! devise-4.4.3/test/rails_app/app/0000755000004100000410000000000013254473005016545 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/0000755000004100000410000000000013254473005017702 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/home/0000755000004100000410000000000013254473005020632 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/home/index.html.erb0000644000004100000410000000000613254473005023372 0ustar www-datawww-dataHome! devise-4.4.3/test/rails_app/app/views/home/user_dashboard.html.erb0000644000004100000410000000001713254473005025252 0ustar www-datawww-dataUser dashboard devise-4.4.3/test/rails_app/app/views/home/join.html.erb0000644000004100000410000000000513254473005023221 0ustar www-datawww-dataJoin devise-4.4.3/test/rails_app/app/views/home/admin_dashboard.html.erb0000644000004100000410000000002013254473005025356 0ustar www-datawww-dataAdmin dashboard devise-4.4.3/test/rails_app/app/views/home/private.html.erb0000644000004100000410000000001113254473005023731 0ustar www-datawww-dataPrivate! devise-4.4.3/test/rails_app/app/views/layouts/0000755000004100000410000000000013254473005021402 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/layouts/application.html.erb0000644000004100000410000000115313254473005025342 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-4.4.3/test/rails_app/app/views/admins/0000755000004100000410000000000013254473005021155 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/admins/sessions/0000755000004100000410000000000013254473005023023 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/admins/sessions/new.html.erb0000644000004100000410000000011213254473005025243 0ustar www-datawww-dataWelcome to "sessions/new" view! <%= render file: "devise/sessions/new" %> devise-4.4.3/test/rails_app/app/views/admins/index.html.erb0000644000004100000410000000001713254473005023717 0ustar www-datawww-dataWelcome Admin! devise-4.4.3/test/rails_app/app/views/users/0000755000004100000410000000000013254473005021043 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/users/mailer/0000755000004100000410000000000013254473005022314 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/users/mailer/confirmation_instructions.erb0000644000004100000410000000002613254473005030320 0ustar www-datawww-data<%= @resource.email %>devise-4.4.3/test/rails_app/app/views/users/sessions/0000755000004100000410000000000013254473005022711 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/views/users/sessions/new.html.erb0000644000004100000410000000002213254473005025131 0ustar www-datawww-dataSpecial user view devise-4.4.3/test/rails_app/app/views/users/index.html.erb0000644000004100000410000000004613254473005023607 0ustar www-datawww-dataWelcome User #<%= current_user.id %>! devise-4.4.3/test/rails_app/app/views/users/edit_form.html.erb0000644000004100000410000000011613254473005024446 0ustar www-datawww-data<%= button_to 'Update', update_form_user_path(current_user), method: 'put' %> devise-4.4.3/test/rails_app/app/mongoid/0000755000004100000410000000000013254473005020201 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/mongoid/user_without_email.rb0000644000004100000410000000172713254473005024445 0ustar www-datawww-data# frozen_string_literal: true require "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-4.4.3/test/rails_app/app/mongoid/admin.rb0000644000004100000410000000133513254473005021620 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/test/rails_app/app/mongoid/shim.rb0000644000004100000410000000074313254473005021472 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/test/rails_app/app/mongoid/user_with_validations.rb0000644000004100000410000000174413254473005025142 0ustar www-datawww-data# frozen_string_literal: true require "shared_user" class UserWithValidations 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 ## 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 validates :email, presence: true end devise-4.4.3/test/rails_app/app/mongoid/user.rb0000644000004100000410000000262313254473005021507 0ustar www-datawww-data# frozen_string_literal: true require '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 cattr_accessor :validations_performed after_validation :after_validation_callback def after_validation_callback # used to check in our test if the validations were called @@validations_performed = true end end devise-4.4.3/test/rails_app/app/mongoid/user_on_main_app.rb0000644000004100000410000000225613254473005024051 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/test/rails_app/app/mongoid/user_on_engine.rb0000644000004100000410000000225513254473005023531 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/test/rails_app/app/controllers/0000755000004100000410000000000013254473005021113 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/controllers/application_with_fake_engine.rb0000644000004100000410000000116013254473005027307 0ustar www-datawww-data# frozen_string_literal: true class 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-4.4.3/test/rails_app/app/controllers/custom/0000755000004100000410000000000013254473005022425 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/controllers/custom/registrations_controller.rb0000644000004100000410000000105113254473005030107 0ustar www-datawww-data# frozen_string_literal: true class 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-4.4.3/test/rails_app/app/controllers/admins/0000755000004100000410000000000013254473005022366 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/controllers/admins/sessions_controller.rb0000644000004100000410000000030513254473005027022 0ustar www-datawww-data# frozen_string_literal: true class Admins::SessionsController < Devise::SessionsController def new flash[:special] = "Welcome to #{controller_path.inspect} controller!" super end end devise-4.4.3/test/rails_app/app/controllers/users_controller.rb0000644000004100000410000000155013254473005025045 0ustar www-datawww-data# frozen_string_literal: true class UsersController < ApplicationController prepend_before_action :current_user, only: :exhibit before_action :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 (Devise::Test.rails5? ? :body : :text) => 'Update' end def accept @current_user = current_user end def exhibit render (Devise::Test.rails5? ? :body : :text) => current_user ? "User is authenticated" : "User is not authenticated" end def expire user_session['last_request_at'] = 31.minutes.ago.utc render (Devise::Test.rails5? ? :body : :text) => 'User will be expired on next request' end end devise-4.4.3/test/rails_app/app/controllers/publisher/0000755000004100000410000000000013254473005023110 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/controllers/publisher/registrations_controller.rb0000644000004100000410000000014413254473005030574 0ustar www-datawww-data# frozen_string_literal: true class Publisher::RegistrationsController < ApplicationController end devise-4.4.3/test/rails_app/app/controllers/publisher/sessions_controller.rb0000644000004100000410000000013713254473005027547 0ustar www-datawww-data# frozen_string_literal: true class Publisher::SessionsController < ApplicationController end devise-4.4.3/test/rails_app/app/controllers/home_controller.rb0000644000004100000410000000071613254473005024637 0ustar www-datawww-data# frozen_string_literal: true class 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 if Devise::Test.rails5? render body: "unauthenticated", status: :unauthorized else render text: "unauthenticated", status: :unauthorized end end end devise-4.4.3/test/rails_app/app/controllers/application_controller.rb0000644000004100000410000000073613254473005026214 0ustar www-datawww-data# frozen_string_literal: true # 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_action :current_user, unless: :devise_controller? before_action :authenticate_user!, if: :devise_controller? respond_to(*Mime::SET.map(&:to_sym)) devise_group :commenter, contains: [:user, :admin] end devise-4.4.3/test/rails_app/app/controllers/users/0000755000004100000410000000000013254473005022254 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/controllers/users/omniauth_callbacks_controller.rb0000644000004100000410000000102013254473005030660 0ustar www-datawww-data# frozen_string_literal: true class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook data = request.respond_to?(:get_header) ? request.get_header("omniauth.auth") : request.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 (Devise::Test.rails5? ? :body : :text) => "" end end devise-4.4.3/test/rails_app/app/controllers/admins_controller.rb0000644000004100000410000000021213254473005025151 0ustar www-datawww-data# frozen_string_literal: true class AdminsController < ApplicationController before_action :authenticate_admin! def index end end devise-4.4.3/test/rails_app/app/mailers/0000755000004100000410000000000013254473005020201 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/mailers/users/0000755000004100000410000000000013254473005021342 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/mailers/users/from_proc_mailer.rb0000644000004100000410000000017613254473005025212 0ustar www-datawww-data# frozen_string_literal: true class Users::FromProcMailer < Devise::Mailer default from: proc { 'custom@example.com' } end devise-4.4.3/test/rails_app/app/mailers/users/reply_to_mailer.rb0000644000004100000410000000024613254473005025057 0ustar www-datawww-data# frozen_string_literal: true class Users::ReplyToMailer < Devise::Mailer default from: 'custom@example.com' default reply_to: 'custom_reply_to@example.com' end devise-4.4.3/test/rails_app/app/mailers/users/mailer.rb0000644000004100000410000000015513254473005023141 0ustar www-datawww-data# frozen_string_literal: true class Users::Mailer < Devise::Mailer default from: 'custom@example.com' end devise-4.4.3/test/rails_app/app/active_record/0000755000004100000410000000000013254473005021356 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/active_record/user_without_email.rb0000644000004100000410000000030113254473005025605 0ustar www-datawww-data# frozen_string_literal: true require "shared_user_without_email" class UserWithoutEmail < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutEmail end devise-4.4.3/test/rails_app/app/active_record/admin.rb0000644000004100000410000000020113254473005022764 0ustar www-datawww-data# frozen_string_literal: true require 'shared_admin' class Admin < ActiveRecord::Base include Shim include SharedAdmin end devise-4.4.3/test/rails_app/app/active_record/shim.rb0000644000004100000410000000005713254473005022645 0ustar www-datawww-data# frozen_string_literal: true module Shim end devise-4.4.3/test/rails_app/app/active_record/user_with_validations.rb0000644000004100000410000000031613254473005026311 0ustar www-datawww-data# frozen_string_literal: true require 'shared_user' class UserWithValidations < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUser validates :email, presence: true end devise-4.4.3/test/rails_app/app/active_record/user.rb0000644000004100000410000000071313254473005022662 0ustar www-datawww-data# frozen_string_literal: true require 'shared_user' class User < ActiveRecord::Base include Shim include SharedUser include ActiveModel::Serializers::Xml if Devise::Test.rails5? validates :sign_in_count, presence: true cattr_accessor :validations_performed after_validation :after_validation_callback def after_validation_callback # used to check in our test if the validations were called @@validations_performed = true end end devise-4.4.3/test/rails_app/app/active_record/user_on_main_app.rb0000644000004100000410000000030313254473005025215 0ustar www-datawww-data# frozen_string_literal: true require 'shared_user_without_omniauth' class UserOnMainApp < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutOmniauth end devise-4.4.3/test/rails_app/app/active_record/user_on_engine.rb0000644000004100000410000000030213254473005024675 0ustar www-datawww-data# frozen_string_literal: true require 'shared_user_without_omniauth' class UserOnEngine < ActiveRecord::Base self.table_name = 'users' include Shim include SharedUserWithoutOmniauth end devise-4.4.3/test/rails_app/app/helpers/0000755000004100000410000000000013254473005020207 5ustar www-datawww-datadevise-4.4.3/test/rails_app/app/helpers/application_helper.rb0000644000004100000410000000022213254473005024372 0ustar www-datawww-data# frozen_string_literal: true # Methods added to this helper will be available to all templates in the application. module ApplicationHelper end devise-4.4.3/test/rails_app/config.ru0000644000004100000410000000023613254473005017603 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-4.4.3/test/delegator_test.rb0000644000004100000410000000122513254473005017345 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/test/generators/0000755000004100000410000000000013254473005016164 5ustar www-datawww-datadevise-4.4.3/test/generators/mongoid_generator_test.rb0000644000004100000410000000121513254473005023251 0ustar www-datawww-data# frozen_string_literal: true require "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-4.4.3/test/generators/views_generator_test.rb0000644000004100000410000001006613254473005022756 0ustar www-datawww-data# frozen_string_literal: true require "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-4.4.3/test/generators/devise_generator_test.rb0000644000004100000410000000214413254473005023076 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/test/generators/controllers_generator_test.rb0000644000004100000410000000357013254473005024171 0ustar www-datawww-data# frozen_string_literal: true require "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-4.4.3/test/generators/active_record_generator_test.rb0000644000004100000410000001101113254473005024421 0ustar www-datawww-data# frozen_string_literal: true require "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 are properly created with changed db/migrate path in application configuration" do old_paths = Rails.application.config.paths["db/migrate"] Rails.application.config.paths.add "db/migrate", with: "db2/migrate" run_generator %w(monster) if Rails.version >= '5.0.3' assert_migration "db2/migrate/devise_create_monsters.rb", /def change/ else assert_migration "db/migrate/devise_create_monsters.rb", /def change/ end Rails.application.config.paths["db/migrate"] = old_paths 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 "update model migration when model exists with changed db/migrate path in application configuration" do old_paths = Rails.application.config.paths["db/migrate"] Rails.application.config.paths.add "db/migrate", with: "db2/migrate" run_generator %w(monster) assert_file "app/models/monster.rb" run_generator %w(monster) if Rails.version >= '5.0.3' assert_migration "db2/migrate/add_devise_to_monsters.rb" else assert_migration "db/migrate/add_devise_to_monsters.rb" end Rails.application.config.paths["db/migrate"] = old_paths 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 test "do NOT add primary key type when NOT specified in rails generator" do run_generator %w(monster) assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters do/ end test "add primary key type with rails 5 when specified in rails generator" do run_generator ["monster", "--primary_key_type=uuid"] if Rails.version.start_with? '5' assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters, id: :uuid do/ else assert_migration "db/migrate/devise_create_monsters.rb", /create_table :monsters do/ end 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 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 %r{attr_accessible :email}, content end end end end end devise-4.4.3/test/generators/install_generator_test.rb0000644000004100000410000000135213254473005023265 0ustar www-datawww-data# frozen_string_literal: true require "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(["--orm=active_record"]) assert_file "config/initializers/devise.rb", /devise\/orm\/active_record/ assert_file "config/locales/devise.en.yml" end test "fails if no ORM is specified" do stderr = capture(:stderr) do run_generator end assert_match %r{An ORM must be set to install Devise}, stderr assert_no_file "config/initializers/devise.rb" assert_no_file "config/locales/devise.en.yml" end end devise-4.4.3/test/integration/0000755000004100000410000000000013254473005016336 5ustar www-datawww-datadevise-4.4.3/test/integration/http_authenticatable_test.rb0000644000004100000410000001005613254473005024120 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class HttpAuthenticationTest < Devise::IntegrationTest test 'sign in with HTTP should not run model validations' do sign_in_as_new_user_with_http refute User.validations_performed end 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), headers: { "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 swap Devise, skip_session_storage: [] 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 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: { 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: { 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), headers: { "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), headers: { "HTTP_AUTHORIZATION" => "OAuth #{Base64.encode64("#{user.email}:12345678")}" } end end devise-4.4.3/test/integration/trackable_test.rb0000644000004100000410000000466013254473005021660 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class TrackableHooksTest < Devise::IntegrationTest test "trackable should not run model validations" do sign_in_as_user refute User.validations_performed end 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 delete 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 delete 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 delete 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-4.4.3/test/integration/timeoutable_test.rb0000644000004100000410000001141213254473005022233 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class SessionTimeoutTest < Devise::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, headers: { '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, headers: { '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 refute 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 refute warden.authenticated?(:user) refute 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) delete 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' refute 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", params: { 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 refute 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-4.4.3/test/integration/recoverable_test.rb0000644000004100000410000003037413254473005022222 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class PasswordTest < Devise::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 refute 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 %r{Reset password token(.*)invalid} refute 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 "Password confirmation doesn't match Password" refute 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' refute 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 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'), params: { 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'), params: { 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'), params: { 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'), params: { 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'), params: { 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'), params: { 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), params: { 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-4.4.3/test/integration/lockable_test.rb0000644000004100000410000001744713254473005021513 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class LockTest < Devise::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 %r{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.' refute 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'), params: { 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'), params: { 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 a 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 a 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 a 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-4.4.3/test/integration/omniauthable_test.rb0000644000004100000410000001027113254473005022373 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class OmniauthableIntegrationTest < Devise::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 "omniauth sign in should not run model validations" do stub_action!(:sign_in_facebook) do create_user visit "/users/sign_in" click_link "Sign in with FaceBook" assert warden.authenticated?(:user) refute User.validations_performed 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" refute 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-4.4.3/test/integration/confirmable_test.rb0000644000004100000410000003115013254473005022203 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class ConfirmationTest < Devise::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 %r{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) refute user.confirmed? visit_user_confirmation_with_token(user.raw_confirmation_token) assert_have_selector '#error_explanation' assert_contain %r{needs to be confirmed within 3 days} refute 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) refute 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' refute 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' refute 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'), params: { 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'), params: { 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, params: { 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 < Devise::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? refute 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? refute 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-4.4.3/test/integration/rememberable_test.rb0000644000004100000410000001471713254473005022356 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class RememberMeTest < Devise::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 = if Devise::Test.rails51? || Devise::Test.rails52? ActionController::TestRequest.create(Class.new) # needs a "controller class" elsif Devise::Test.rails5? ActionController::TestRequest.create else ActionController::TestRequest.new end 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) refute warden.authenticated?(:user) create_user_and_remember post exhibit_user_url(1) assert_equal "User is not authenticated", response.body refute 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, params: { authenticity_token: "oops", user: { email: "jose.valim@gmail.com", password: "123456", remember_me: "1" } } refute warden.authenticated?(:user) refute 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 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 'extends remember period when extend remember period config is true' do swap Devise, extend_remember_period: true, remember_for: 1.year do create_user_and_remember old_remember_token = nil travel_to 1.day.ago do get root_path old_remember_token = request.cookies['remember_user_token'] end get root_path current_remember_token = request.cookies['remember_user_token'] refute_equal old_remember_token, current_remember_token end end test 'does not extend remember period when extend period config is false' do swap Devise, extend_remember_period: false, remember_for: 1.year do create_user_and_remember old_remember_token = nil travel_to 1.day.ago do get root_path old_remember_token = request.cookies['remember_user_token'] end get root_path current_remember_token = request.cookies['remember_user_token'] assert_equal old_remember_token, current_remember_token end end test 'do not remember other scopes' do create_user_and_remember get root_path assert_response :success assert warden.authenticated?(:user) refute warden.authenticated?(:admin) end test 'do not remember with invalid token' do create_user_and_remember('add') get users_path refute 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 refute 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) delete destroy_user_session_path refute warden.authenticated?(:user) assert_nil warden.cookies['remember_user_token'] get users_path refute 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 refute 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-4.4.3/test/integration/mounted_engine_test.rb0000644000004100000410000000210113254473005022714 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class MyMountableEngine def self.call(env) ['200', { 'Content-Type' => 'text/html' }, ['Rendered content of MyMountableEngine']] end end # If disable_clear_and_finalize is set to true, Rails will not clear other routes when calling # again the draw method. Look at the source code at: # http://www.rubydoc.info/docs/rails/ActionDispatch/Routing/RouteSet:draw Rails.application.routes.disable_clear_and_finalize = true Rails.application.routes.draw do authenticate(:user) do mount MyMountableEngine, at: '/mountable_engine' end end class AuthenticatedMountedEngineTest < Devise::IntegrationTest test 'redirects to the sign in page when not authenticated' do get '/mountable_engine' follow_redirect! assert_response :ok assert_contain 'You need to sign in or sign up before continuing.' end test 'renders the mounted engine when authenticated' do sign_in_as_user get '/mountable_engine' assert_response :success assert_contain 'Rendered content of MyMountableEngine' end end devise-4.4.3/test/integration/authenticatable_test.rb0000644000004100000410000005156213254473005023070 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class AuthenticationSanityTest < Devise::IntegrationTest test 'sign in should not run model validations' do sign_in_as_user refute User.validations_performed end 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) refute warden.authenticated?(:admin) end test 'sign in as admin should not authenticate user scope' do sign_in_as_admin assert warden.authenticated?(:admin) refute 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 delete destroy_user_session_path refute 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 delete destroy_admin_session_path refute 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 delete destroy_user_session_path refute warden.authenticated?(:user) refute 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 delete destroy_admin_session_path refute warden.authenticated?(:admin) refute 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 refute 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) refute 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) refute 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) delete destroy_admin_session_path assert_response :redirect assert_redirected_to root_path get root_path assert_contain 'Signed out successfully' refute warden.authenticated?(:admin) end test 'unauthenticated admin set message on sign out' do delete 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 < Devise::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 refute 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) refute 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) refute 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) refute 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) refute 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) refute 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) refute 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) refute 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) refute 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) refute warden.authenticated?(:admin) assert_raises ActionController::RoutingError do get join_path end end test 'not signed in users should see unauthenticated page (unauthenticated accepted)' do get join_path assert_response :success assert_template 'home/join' assert_contain 'Join' end end class AuthenticationRedirectTest < Devise::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, headers: { '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 < Devise::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 '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 < Devise::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 %r{Special user view}, response.body end end test 'renders the scoped view if turned on in a specific controller' do begin Devise::SessionsController.scoped_views = true assert_raise Webrat::NotFoundError do sign_in_as_user end assert_match %r{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 < Devise::IntegrationTest test 'handles unverified requests gets rid of caches' do swap ApplicationController, allow_forgery_protection: true do post exhibit_user_url(1) refute warden.authenticated?(:user) sign_in_as_user assert warden.authenticated?(:user) post exhibit_user_url(1) refute 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, headers: { "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 %r{.*}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'), params: { 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'), params: { 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 delete destroy_user_session_path assert_response :redirect assert_current_url '/' sign_in_as_user delete 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 delete destroy_user_session_path(format: 'xml') assert_response :no_content refute warden.authenticated?(:user) end test 'sign out with json format returns no content' do sign_in_as_user delete destroy_user_session_path(format: 'json') assert_response :no_content refute 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_admin get destroy_sign_out_via_get_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "application/json,text/javascript,*/*" } # NOTE: Bug is triggered by combination of XHR and */*. assert_response :no_content refute 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 delete destroy_user_session_path, xhr: true, headers: { "HTTP_ACCEPT" => "text/html,*/*" } assert_response :redirect refute warden.authenticated?(:user) end end end class AuthenticationKeysTest < Devise::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." refute 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 < Devise::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 refute 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." refute 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 < Devise::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 refute 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 refute 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 refute 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 refute 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 < Devise::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 < Devise::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-4.4.3/test/integration/registerable_test.rb0000644000004100000410000003173313254473005022401 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class RegistrationTest < Devise::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 "/" refute warden.authenticated?(:user) user = User.to_adapter.find_first(order: [:id, :desc]) assert_equal user.email, 'new_user@test.com' refute 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" refute 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 "Password confirmation doesn't match Password" assert_contain "2 errors prohibited" assert_nil User.to_adapter.find_first refute 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/) refute 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 "Password confirmation doesn't match Password" refute User.to_adapter.find_first.valid_password?('pas123') end test 'a signed in user should see a warning about minimum password length' do sign_in_as_user get edit_user_registration_path assert_contain 'characters minimum' 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'), params: { 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'), params: { 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'), params: { 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'), params: { 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 < Devise::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-4.4.3/test/integration/database_authenticatable_test.rb0000644000004100000410000000542513254473005024711 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class DatabaseAuthenticationTest < Devise::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 refute 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 refute 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 refute 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' refute 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' refute 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-4.4.3/test/routes_test.rb0000644000004100000410000003057513254473005016732 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' ExpectedRoutingError = MiniTest::Assertion 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: :delete}) 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_facebook_omniauth_callback_path # 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_google_omniauth_callback_path 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'}, {path: '/en/accounts/logout', method: :delete }) 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 expected_params = {controller: 'devise/sessions', action: 'new'} expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_in.xml', method: :get}) end end test 'map with format false for passwords' do expected_params = {controller: 'devise/passwords', action: 'create'} expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_admin/password', method: :post}) assert_raise ExpectedRoutingError do assert_recognizes(expected_params, {path: '/htmlonly_admin/password.xml', method: :post}) end end test 'map with format false for registrations' do expected_params = {controller: 'devise/registrations', action: 'new'} expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes(expected_params, {path: '/htmlonly_admin/sign_up.xml', method: :get}) end end test 'map with format false for confirmations' do expected_params = {controller: 'devise/confirmations', action: 'show'} expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes(expected_params, {path: '/htmlonly_users/confirmation.xml', method: :get}) end end test 'map with format false for unlocks' do expected_params = {controller: 'devise/unlocks', action: 'show'} expected_params[:format] = false if Devise::Test.rails5? assert_recognizes(expected_params, {path: '/htmlonly_users/unlock', method: :get}) assert_raise ExpectedRoutingError do assert_recognizes(expected_params, {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-4.4.3/test/models/0000755000004100000410000000000013254473005015276 5ustar www-datawww-datadevise-4.4.3/test/models/trackable_test.rb0000644000004100000410000000334513254473005020617 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class TrackableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do assert_equal 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 test "update_tracked_fields! should not persist invalid records" do user = UserWithValidations.new request = mock request.stubs(:remote_ip).returns("127.0.0.1") assert_not user.update_tracked_fields!(request) assert_not user.persisted? end test "update_tracked_fields! should not run model validations" do user = User.new request = mock request.stubs(:remote_ip).returns("127.0.0.1") user.expects(:after_validation_callback).never assert_not user.update_tracked_fields!(request) end end devise-4.4.3/test/models/timeoutable_test.rb0000644000004100000410000000266213254473005021202 0ustar www-datawww-data# frozen_string_literal: true require '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 refute new_user.timedout?(29.minutes.ago) end test 'should not be expired when params is nil' do refute 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) refute 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 } refute 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) refute user.timedout?(30.seconds.ago) Devise.timeout_in = 5.minutes refute 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_equal 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-4.4.3/test/models/recoverable_test.rb0000644000004100000410000002146213254473005021160 0ustar www-datawww-data# frozen_string_literal: true require '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 refute 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) refute 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") refute 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) refute 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') refute 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: '') refute 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: '') refute 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 return a new record with errors if password is not provided' do user = create_user raw = user.send_reset_password_instructions reset_password_user = User.reset_password_by_token(reset_password_token: raw) refute 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 refute 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) refute 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_equal 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_nil User.with_reset_password_token('random-token') end end devise-4.4.3/test/models/lockable_test.rb0000644000004100000410000002574213254473005020450 0ustar www-datawww-data# frozen_string_literal: true require '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 refute 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! refute 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 refute 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 refute 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 refute 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') refute 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('') refute 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") refute 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) refute 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 refute user.resend_unlock_instructions refute 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 refute user.resend_unlock_instructions refute 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_equal 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_equal 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_equal 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 test 'unlock_strategy_enabled? should return true for both, email, and time strategies if :both is used' do swap Devise, unlock_strategy: :both do user = create_user assert_equal true, user.unlock_strategy_enabled?(:both) assert_equal true, user.unlock_strategy_enabled?(:time) assert_equal true, user.unlock_strategy_enabled?(:email) assert_equal false, user.unlock_strategy_enabled?(:none) assert_equal false, user.unlock_strategy_enabled?(:an_undefined_strategy) end end test 'unlock_strategy_enabled? should return true only for the configured strategy' do swap Devise, unlock_strategy: :email do user = create_user assert_equal false, user.unlock_strategy_enabled?(:both) assert_equal false, user.unlock_strategy_enabled?(:time) assert_equal true, user.unlock_strategy_enabled?(:email) assert_equal false, user.unlock_strategy_enabled?(:none) assert_equal false, user.unlock_strategy_enabled?(:an_undefined_strategy) end end end devise-4.4.3/test/models/omniauthable_test.rb0000644000004100000410000000040013254473005021324 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class OmniauthableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do assert_equal Devise::Models::Omniauthable.required_fields(User), [] end end devise-4.4.3/test/models/confirmable_test.rb0000644000004100000410000004412413254473005021150 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class ConfirmableTest < ActiveSupport::TestCase def setup setup_mailer end test 'should set callbacks to send the mail' do if DEVISE_ORM == :active_record defined_callbacks = User._commit_callbacks.map(&:filter) assert_includes defined_callbacks, :send_on_create_confirmation_instructions assert_includes defined_callbacks, :send_reconfirmation_instructions elsif DEVISE_ORM == :mongoid assert_includes User._create_callbacks.map(&:filter), :send_on_create_confirmation_instructions assert_includes User._update_callbacks.map(&:filter), :send_reconfirmation_instructions end 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 refute new_user.confirmed? user = create_user refute 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] refute 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') refute 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('') refute 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! refute 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") refute 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 refute 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 = create_user user.confirmation_sent_at = 2.days.ago refute 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 refute user.active_for_authentication? end end test 'should be active when already confirmed' do user = create_user refute user.confirmed? refute 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 refute 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 refute 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) refute 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 refute 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 refute 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) refute 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? refute 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 send confirmation instructions by email after changing email from nil' do admin = create_admin(email: nil) 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") refute 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_equal Devise::Models::Confirmable.required_fields(User), [ :confirmation_token, :confirmed_at, :confirmation_sent_at ] end test 'required_fields should also contain unconfirmable when reconfirmable_email is true' do assert_equal Devise::Models::Confirmable.required_fields(Admin), [ :confirmation_token, :confirmed_at, :confirmation_sent_at, :unconfirmed_email ] end test 'should not require reconfirmation after creating a record' do admin = create_admin assert !admin.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 admin = Admin::WithSaveInCallback.create(valid_attributes.except(:username)) assert !admin.pending_reconfirmation? end test 'should require reconfirmation after creating a record and updating the email' do admin = create_admin assert !admin.instance_variable_get(:@bypass_confirmation_postpone) admin.email = "new_test@email.com" admin.save assert admin.pending_reconfirmation? end test 'should notify previous email on email change when configured' do swap Devise, send_email_changed_notification: true do admin = create_admin original_email = admin.email assert_difference 'ActionMailer::Base.deliveries.size', 2 do assert admin.update_attributes(email: 'new-email@example.com') end assert_equal original_email, ActionMailer::Base.deliveries[-2]['to'].to_s assert_equal 'new-email@example.com', ActionMailer::Base.deliveries[-1]['to'].to_s assert_email_not_sent do assert admin.confirm end end end end devise-4.4.3/test/models/serializable_test.rb0000644000004100000410000000373513254473005021340 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/test/models/registerable_test.rb0000644000004100000410000000040013254473005021324 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class RegisterableTest < ActiveSupport::TestCase test 'required_fields should contain the fields that Devise uses' do assert_equal Devise::Models::Registerable.required_fields(User), [] end end devise-4.4.3/test/models/database_authenticatable_test.rb0000644000004100000410000002356313254473005023654 0ustar www-datawww-data# frozen_string_literal: true require '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 a hashed password while setting password' do user = new_user assert_present user.encrypted_password end test 'should support custom hashing methods' do user = UserWithCustomHashing.new(password: '654321') assert_equal user.encrypted_password, '123456' end test 'allow authenticatable_salt to work even with nil hashed password' do user = User.new user.encrypted_password = nil assert_nil user.authenticatable_salt end test 'should not generate a hashed password if password is blank' do assert_blank new_user(password: nil).encrypted_password assert_blank new_user(password: '').encrypted_password end test 'should hash 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') refute 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 = '' refute 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 refute 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 refute 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? refute 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 refute 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 refute 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 refute 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 refute 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 notify previous email on email change when configured' do swap Devise, send_email_changed_notification: true do user = create_user original_email = user.email assert_email_sent original_email do assert user.update_attributes(email: 'new-email@example.com') end assert_match original_email, ActionMailer::Base.deliveries.last.body.encoded end end test 'should notify 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 assert_match user.email, ActionMailer::Base.deliveries.last.body.encoded 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_equal Devise::Models::DatabaseAuthenticatable.required_fields(User), [ :encrypted_password, :email ] 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_equal Devise::Models::DatabaseAuthenticatable.required_fields(User), [ :encrypted_password, :login ] end end end devise-4.4.3/test/helpers/0000755000004100000410000000000013254473005015455 5ustar www-datawww-datadevise-4.4.3/test/helpers/devise_helper_test.rb0000644000004100000410000000300613254473005021656 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class DeviseHelperTest < Devise::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-4.4.3/test/secret_key_finder_test.rb0000644000004100000410000000404213254473005021063 0ustar www-datawww-data# frozen_string_literal: true require 'test_helper' class Rails52Credentials def credentials OpenStruct.new(secret_key_base: 'credentials') end end class Rails52Secrets def credentials OpenStruct.new(secret_key_base: nil) end def secrets OpenStruct.new(secret_key_base: 'secrets') end end class Rails52Config def credentials OpenStruct.new(secret_key_base: nil) end def secrets OpenStruct.new(secret_key_base: nil) end def config OpenStruct.new(secret_key_base: 'config') end end class Rails41Secrets def secrets OpenStruct.new(secret_key_base: 'secrets') end def config OpenStruct.new(secret_key_base: nil) end end class Rails41Config def secrets OpenStruct.new(secret_key_base: nil) end def config OpenStruct.new(secret_key_base: 'config') end end class Rails40Config def config OpenStruct.new(secret_key_base: 'config') end end class SecretKeyFinderTest < ActiveSupport::TestCase test "rails 5.2 uses credentials when they're available" do secret_key_finder = Devise::SecretKeyFinder.new(Rails52Credentials.new) assert_equal 'credentials', secret_key_finder.find end test "rails 5.2 uses secrets when credentials are empty" do secret_key_finder = Devise::SecretKeyFinder.new(Rails52Secrets.new) assert_equal 'secrets', secret_key_finder.find end test "rails 5.2 uses config when secrets are empty" do secret_key_finder = Devise::SecretKeyFinder.new(Rails52Config.new) assert_equal 'config', secret_key_finder.find end test "rails 4.1 uses secrets" do secret_key_finder = Devise::SecretKeyFinder.new(Rails41Secrets.new) assert_equal 'secrets', secret_key_finder.find end test "rails 4.1 uses config when secrets are empty" do secret_key_finder = Devise::SecretKeyFinder.new(Rails41Config.new) assert_equal 'config', secret_key_finder.find end test "rails 4.0 uses config" do secret_key_finder = Devise::SecretKeyFinder.new(Rails40Config.new) assert_equal 'config', secret_key_finder.find end end devise-4.4.3/test/support/0000755000004100000410000000000013254473005015527 5ustar www-datawww-datadevise-4.4.3/test/support/integration.rb0000644000004100000410000000507013254473005020401 0ustar www-datawww-data# frozen_string_literal: true require '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.validations_performed = false 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-4.4.3/test/support/helpers.rb0000644000004100000410000000432413254473005017521 0ustar www-datawww-data# frozen_string_literal: true require '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 def create_user_with_validations(attributes={}) UserWithValidations.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-4.4.3/test/support/webrat/0000755000004100000410000000000013254473005017013 5ustar www-datawww-datadevise-4.4.3/test/support/webrat/integrations/0000755000004100000410000000000013254473005021521 5ustar www-datawww-datadevise-4.4.3/test/support/webrat/integrations/rails.rb0000644000004100000410000000135413254473005023163 0ustar www-datawww-data# frozen_string_literal: true require '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 class RailsAdapter protected def do_request(http_method, url, data, headers) update_protocol(url) integration_session.send(http_method, normalize_url(url), params: data, headers: headers) end end end module ActionDispatch #:nodoc: IntegrationTest.class_eval do include Webrat::Methods include Webrat::Matchers end end devise-4.4.3/test/support/action_controller/0000755000004100000410000000000013254473005021247 5ustar www-datawww-datadevise-4.4.3/test/support/action_controller/record_identifier.rb0000644000004100000410000000051313254473005025253 0ustar www-datawww-data# frozen_string_literal: true # 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-4.4.3/test/support/mongoid.yml0000644000004100000410000000027113254473005017706 0ustar www-datawww-datatest: <%= Mongoid::VERSION.to_i > 4 ? 'clients' : 'sessions' %>: default: database: devise-test-suite hosts: - localhost:<%= ENV['MONGODB_PORT'] || '27017' %> devise-4.4.3/test/support/assertions.rb0000644000004100000410000000150713254473005020251 0ustar www-datawww-data# frozen_string_literal: true require 'active_support/test_case' class ActiveSupport::TestCase 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_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-4.4.3/test/support/http_method_compatibility.rb0000644000004100000410000000307413254473005023330 0ustar www-datawww-data# frozen_string_literal: true module Devise class IntegrationTest < ActionDispatch::IntegrationTest # %w( get post patch put head delete xml_http_request # xhr get_via_redirect post_via_redirect # ).each do |method| %w( get post put ).each do |method| if Rails.version >= '5.0.0' define_method(method) do |url, options={}| if options.empty? super url else super url, options end end else define_method(method) do |url, options={}| if options[:xhr]==true xml_http_request __method__, url, options[:params] || {}, options[:headers] else super url, options[:params] || {}, options[:headers] end end end end end class ControllerTestCase < ActionController::TestCase # %w( get post patch put head delete xml_http_request # xhr get_via_redirect post_via_redirect # ).each do |method| %w( get post put ).each do |method| if Rails.version >= '5.0.0' define_method(method) do |action, options={}| if options.empty? super action else super action, options end end else define_method(method) do |action, options={}| if options[:xhr]==true xml_http_request __method__, action, options[:params] || {}, options[:headers] else super action, options[:params] || {}, options[:headers] end end end end end end devise-4.4.3/test/support/locale/0000755000004100000410000000000013254473005016766 5ustar www-datawww-datadevise-4.4.3/test/support/locale/en.yml0000644000004100000410000000023313254473005020111 0ustar www-datawww-dataen: devise: failure: user: does_not_exist: "User %{name} does not exist" errors: messages: taken: "has already been taken" devise-4.4.3/test/mapping_test.rb0000644000004100000410000001122413254473005017032 0ustar www-datawww-data# frozen_string_literal: true require '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 :delete' do assert_equal :delete, 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? refute 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-4.4.3/test/test_models.rb0000644000004100000410000000154013254473005016662 0ustar www-datawww-data# frozen_string_literal: true class 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 UserWithCustomHashing < 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-4.4.3/test/rails_test.rb0000644000004100000410000000054713254473005016517 0ustar www-datawww-data# frozen_string_literal: true require '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-4.4.3/.gitignore0000644000004100000410000000014413254473005015023 0ustar www-datawww-datatest/rails_app/log/* test/rails_app/tmp/* *~ coverage/* *.sqlite3 .bundle rdoc/* pkg log test/tmp/* devise-4.4.3/config/0000755000004100000410000000000013254473005014301 5ustar www-datawww-datadevise-4.4.3/config/locales/0000755000004100000410000000000013254473005015723 5ustar www-datawww-datadevise-4.4.3/config/locales/en.yml0000644000004100000410000001005213254473005017046 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" email_changed: subject: "Email Changed" 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-4.4.3/.yardopts0000644000004100000410000000015413254473005014702 0ustar www-datawww-data--protected --no-private --embed-mixin ClassMethods - README.md CHANGELOG.rdoc CONTRIBUTING.md MIT-LICENSE devise-4.4.3/CONTRIBUTING.md0000644000004100000410000001037513254473005015273 0ustar www-datawww-data# How to contribute to Devise Thanks for your interest on contributing to Devise! Here are a few general guidelines on contributing and reporting bugs to Devise that we ask you to take a look first. Notice that all of your interactions in the project are expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md). ## Reporting Issues Before reporting a new issue, please be sure that the issue wasn't already reported or fixed by searching on GitHub through our [issues](https://github.com/plataformatec/devise/issues). When creating a new issue, be sure to include a **title and clear description**, as much relevant information as possible, and either a test case example or even better a **sample Rails app that replicates the issue** - Devise has a lot of moving parts and it's functionality can be affected by third party gems, so we need as much context and details as possible to identify what might be broken for you. We have a [test case template](guides/bug_report_templates/integration_test.rb) that can be used to replicate issues with minimal setup. Please do not attempt to translate Devise built in views. The views are meant to be a starting point for fresh apps and not production material - eventually all applications will require custom views where you can write your own copy and translate it if the application requires it . For historical references, please look into closed [Issues/Pull Requests](https://github.com/plataformatec/devise/issues?q=i18n) regarding internationalization. Avoid opening new issues to ask questions in our issues tracker. Please go through the project wiki, documentation and source code first, or try to ask your question on [Stack Overflow](http://stackoverflow.com/questions/tagged/devise). **If you find a security bug, do not report it through GitHub. Please send an e-mail to [opensource@plataformatec.com.br](mailto:opensource@plataformatec.com.br) instead.** ## Sending Pull Requests Before sending a new Pull Request, take a look on existing Pull Requests and Issues to see if the proposed change or fix has been discussed in the past, or if the change was already implemented but not yet released. We expect new Pull Requests to include enough tests for new or changed behavior, and we aim to maintain everything as most backwards compatible as possible, reserving breaking changes to be ship in major releases when necessary - you can wrap the new code path with a setting toggle from the `Devise` module defined as `false` by default to require developers to opt-in for the new behavior. If your Pull Request includes new or changed behavior, be sure that the changes are beneficial to a wide range of use cases or it's an application specific change that might not be so valuable to other applications. Some changes can be introduced as a new `devise-something` gem instead of belonging to the main codebase. When adding new settings, you can take advantage of the [`Devise::Models.config`](https://github.com/plataformatec/devise/blob/245b1f9de0b3386b7913e14b60ea24f43b77feb0/lib/devise/models.rb#L13-L50) method to add class and instance level fallbacks to the new setting. We also welcome Pull Requests that improve our existing documentation (both our `README.md` and the RDoc sections in the source code) or improve existing rough edges in our API that might be blocking existing integrations or 3rd party gems. ## Other ways to contribute We welcome anyone that wants to contribute to Devise to triage and reply to open issues to help troubleshoot and fix existing bugs on Devise. Here is what you can do: * Help ensure that existing issues follows the recommendations from the _[Reporting Issues](#reporting-issues)_ section, providing feeback to the issue's author on what might be missing. * Review and update the existing content of our [Wiki](https://github.com/plataformatec/devise/wiki) with up to date instructions and code samples - the wiki was grown with several different tutorials and references that we can't keep track of everything, so if there is a page that showcases an integration or customization that you are familiar with feel free to update it as necessary. * Review existing Pull Requests, and testing patches against real existing applications that use Devise. Thanks again for your interest on contributing to the project! :heart: devise-4.4.3/guides/0000755000004100000410000000000013254473005014314 5ustar www-datawww-datadevise-4.4.3/guides/bug_report_templates/0000755000004100000410000000000013254473005020542 5ustar www-datawww-datadevise-4.4.3/guides/bug_report_templates/integration_test.rb0000644000004100000410000000430313254473005024451 0ustar www-datawww-data# frozen_string_literal: true begin require 'bundler/inline' rescue LoadError => e $stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler' raise e end gemfile(true) do source 'https://rubygems.org' # Activate the gem you are reporting the issue against. gem 'rails', '~> 4.2.0' gem 'devise', '~> 4.0' gem 'sqlite3' gem 'byebug' end require 'rack/test' require 'action_controller/railtie' require 'active_record' require 'devise/rails/routes' require 'devise/rails/warden_compat' ActiveRecord::Base.establish_connection( adapter: :sqlite3, database: ':memory:') class DeviseCreateUsers < ActiveRecord::Migration def change create_table(:users) do |t| t.string :email, null: false t.string :encrypted_password, null: true t.timestamps null: false end end end Devise.setup do |config| require 'devise/orm/active_record' config.secret_key = 'secret_key_base' end class TestApp < Rails::Application config.root = File.dirname(__FILE__) config.session_store :cookie_store, key: 'cookie_store_key' secrets.secret_token = 'secret_token' secrets.secret_key_base = 'secret_key_base' config.eager_load = false config.middleware.use Warden::Manager do |config| Devise.warden_config = config end config.logger = Logger.new($stdout) Rails.logger = config.logger end Rails.application.initialize! DeviseCreateUsers.migrate(:up) class User < ActiveRecord::Base devise :database_authenticatable end Rails.application.routes.draw do devise_for :users get '/' => 'test#index' end class ApplicationController < ActionController::Base end class TestController < ApplicationController include Rails.application.routes.url_helpers before_filter :authenticate_user! def index render plain: 'Home' end end require 'minitest/autorun' class BugTest < ActionDispatch::IntegrationTest include Rack::Test::Methods include Warden::Test::Helpers def test_returns_success Warden.test_mode! login_as User.create!(email: 'test@test.com', password: 'test123456', password_confirmation: 'test123456') get '/' assert last_response.ok? end private def app Rails.application end end devise-4.4.3/app/0000755000004100000410000000000013254473005013614 5ustar www-datawww-datadevise-4.4.3/app/views/0000755000004100000410000000000013254473005014751 5ustar www-datawww-datadevise-4.4.3/app/views/devise/0000755000004100000410000000000013254473005016230 5ustar www-datawww-datadevise-4.4.3/app/views/devise/mailer/0000755000004100000410000000000013254473005017501 5ustar www-datawww-datadevise-4.4.3/app/views/devise/mailer/unlock_instructions.html.erb0000644000004100000410000000042413254473005025255 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-4.4.3/app/views/devise/mailer/confirmation_instructions.html.erb0000644000004100000410000000030613254473005026451 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-4.4.3/app/views/devise/mailer/password_change.html.erb0000644000004100000410000000016513254473005024307 0ustar www-datawww-data

Hello <%= @resource.email %>!

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

devise-4.4.3/app/views/devise/mailer/reset_password_instructions.html.erb0000644000004100000410000000061113254473005027024 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-4.4.3/app/views/devise/mailer/email_changed.html.erb0000644000004100000410000000047213254473005023701 0ustar www-datawww-data

Hello <%= @email %>!

<% if @resource.try(:unconfirmed_email?) %>

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

<% else %>

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

<% end %> devise-4.4.3/app/views/devise/sessions/0000755000004100000410000000000013254473005020076 5ustar www-datawww-datadevise-4.4.3/app/views/devise/sessions/new.html.erb0000644000004100000410000000117413254473005022327 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, autocomplete: "email" %>
<%= 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-4.4.3/app/views/devise/registrations/0000755000004100000410000000000013254473005021125 5ustar www-datawww-datadevise-4.4.3/app/views/devise/registrations/new.html.erb0000644000004100000410000000142013254473005023350 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, autocomplete: "email" %>
<%= 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-4.4.3/app/views/devise/registrations/edit.html.erb0000644000004100000410000000264413254473005023515 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, autocomplete: "email" %>
<% 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" %> <% if @minimum_password_length %>
<%= @minimum_password_length %> characters minimum <% end %>
<%= 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-4.4.3/app/views/devise/unlocks/0000755000004100000410000000000013254473005017706 5ustar www-datawww-datadevise-4.4.3/app/views/devise/unlocks/new.html.erb0000644000004100000410000000067513254473005022144 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, autocomplete: "email" %>
<%= f.submit "Resend unlock instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.4.3/app/views/devise/shared/0000755000004100000410000000000013254473005017476 5ustar www-datawww-datadevise-4.4.3/app/views/devise/shared/_links.html.erb0000644000004100000410000000217513254473005022417 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-4.4.3/app/views/devise/passwords/0000755000004100000410000000000013254473005020255 5ustar www-datawww-datadevise-4.4.3/app/views/devise/passwords/new.html.erb0000644000004100000410000000070313254473005022503 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, autocomplete: "email" %>
<%= f.submit "Send me reset password instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.4.3/app/views/devise/passwords/edit.html.erb0000644000004100000410000000144313254473005022641 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-4.4.3/app/views/devise/confirmations/0000755000004100000410000000000013254473005021103 5ustar www-datawww-datadevise-4.4.3/app/views/devise/confirmations/new.html.erb0000644000004100000410000000105013254473005023325 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, autocomplete: "email", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %>
<%= f.submit "Resend confirmation instructions" %>
<% end %> <%= render "devise/shared/links" %> devise-4.4.3/app/controllers/0000755000004100000410000000000013254473005016162 5ustar www-datawww-datadevise-4.4.3/app/controllers/devise_controller.rb0000644000004100000410000001425113254473005022234 0ustar www-datawww-data# frozen_string_literal: true # All Devise controllers are inherited from here. class DeviseController < Devise.parent_controller.constantize include Devise::Controllers::ScopedViews if respond_to?(:helper) helper DeviseHelper end if respond_to?(:helper_method) helpers = %w(resource scope_name resource_name signed_in_resource resource_class resource_params devise_mapping) helper_method(*helpers) end prepend_before_action :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_actions where no authentication is required. # # Example: # before_action :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 true end end # Sets the flash message with :key, using I18n. By default you are able # to set up 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 flash message if is_flashing_format? equals true def set_flash_message!(key, kind, options = {}) if is_flashing_format? set_flash_message(key, kind, options) 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-4.4.3/app/controllers/devise/0000755000004100000410000000000013254473005017441 5ustar www-datawww-datadevise-4.4.3/app/controllers/devise/unlocks_controller.rb0000644000004100000410000000262413254473005023713 0ustar www-datawww-data# frozen_string_literal: true class Devise::UnlocksController < DeviseController prepend_before_action :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 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-4.4.3/app/controllers/devise/registrations_controller.rb0000644000004100000410000001143413254473005025131 0ustar www-datawww-data# frozen_string_literal: true class Devise::RegistrationsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create, :cancel] prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy] prepend_before_action :set_minimum_password_length, only: [:new, :edit] # GET /resource/sign_up def new build_resource yield resource if block_given? respond_with 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 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}" 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 bypass_sign_in resource, scope: resource_name respond_with resource, location: after_update_path_for(resource) else clean_up_passwords resource set_minimum_password_length 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 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 = {}) 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-4.4.3/app/controllers/devise/sessions_controller.rb0000644000004100000410000000461413254473005024104 0ustar www-datawww-data# frozen_string_literal: true class Devise::SessionsController < DeviseController prepend_before_action :require_no_authentication, only: [:new, :create] prepend_before_action :allow_params_authentication!, only: :create prepend_before_action :verify_signed_out_user, only: :destroy prepend_before_action(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) 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 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 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-4.4.3/app/controllers/devise/omniauth_callbacks_controller.rb0000644000004100000410000000232313254473005026054 0ustar www-datawww-data# frozen_string_literal: true class Devise::OmniauthCallbacksController < DeviseController prepend_before_action { request.env["devise.skip_timeout"] = true } def passthru render status: 404, plain: "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 request.respond_to?(:get_header) ? request.get_header("omniauth.error.strategy") : request.env["omniauth.error.strategy"] end def failure_message exception = request.respond_to?(:get_header) ? request.get_header("omniauth.error") : request.env["omniauth.error"] error = exception.error_reason if exception.respond_to?(:error_reason) error ||= exception.error if exception.respond_to?(:error) error ||= (request.respond_to?(:get_header) ? request.get_header("omniauth.error.type") : request.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-4.4.3/app/controllers/devise/confirmations_controller.rb0000644000004100000410000000303213254473005025102 0ustar www-datawww-data# frozen_string_literal: true class 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) 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-4.4.3/app/controllers/devise/passwords_controller.rb0000644000004100000410000000516213254473005024262 0ustar www-datawww-data# frozen_string_literal: true class Devise::PasswordsController < DeviseController prepend_before_action :require_no_authentication # Render the #edit only if coming from a reset password email link append_before_action :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) sign_in(resource_name, resource) else set_flash_message!(:notice, :updated_not_active) 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-4.4.3/app/mailers/0000755000004100000410000000000013254473005015250 5ustar www-datawww-datadevise-4.4.3/app/mailers/devise/0000755000004100000410000000000013254473005016527 5ustar www-datawww-datadevise-4.4.3/app/mailers/devise/mailer.rb0000644000004100000410000000143213254473005020325 0ustar www-datawww-data# frozen_string_literal: true if 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 email_changed(record, opts={}) devise_mail(record, :email_changed, opts) end def password_change(record, opts={}) devise_mail(record, :password_change, opts) end end end devise-4.4.3/app/helpers/0000755000004100000410000000000013254473005015256 5ustar www-datawww-datadevise-4.4.3/app/helpers/devise_helper.rb0000644000004100000410000000157113254473005020425 0ustar www-datawww-data# frozen_string_literal: true module 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-4.4.3/ISSUE_TEMPLATE.md0000644000004100000410000000101013254473005015531 0ustar www-datawww-data## Precheck - Do not use the issues tracker for help or support, try Stack Overflow. - For bugs, do a quick search and make sure the bug has not yet been reported - Finally, be nice and have fun! ## Environment - Ruby **[version]** - Rails **[version]** - Devise **[version]** ## Current behavior Include code samples, errors, steps to reproduce the error and stacktraces if appropriate. Will be even more helpful if you provide a sample application or a test case that reproduces the error. ## Expected behavior devise-4.4.3/CHANGELOG.md0000644000004100000410000002611613254473005014653 0ustar www-datawww-data### Unreleased ### 4.4.3 - 2018-03-17 * bug fixes * Fix undefined method `rails5?` for Devise::Test:Module (by @tegon) * Fix: secret key was being required to be set inside credentials on Rails 5.2 (by @tegon) ### 4.4.2 - 2018-03-15 * enhancements * Support for :credentials on Rails v5.2.x. (by @gencer) * Improve documentation about the test suite. (by @tegon) * Test with Rails 5.2.rc1 on Travis. (by @jcoyne) * Allow test with Rails 6. (by @Fudoshiki) * Creating a new section for controller configuration on `devise.rb` template (by @Danilo-Araujo-Silva) * bug fixes * Preserve content_type for unauthenticated tests (by @gmcnaughton) * Check if the resource is persisted in `update_tracked_fields!` instead of performing validations (by @tegon) * Revert "Replace log_process_action to append_info_to_payload" (by @tegon) ### 4.4.1 - 2018-01-23 * bug fixes * Ensure Gemspec is loaded as utf-8. (by @segiddins) * Fix `ActiveRecord` check on `Confirmable`. (by @tegon) * Fix `signed_in?` docs without running auth hooks. by (@machty) ### 4.4.0 - 2017-12-29 * enhancements * Add `frozen_string_literal` pragma comment to all Ruby files. (by @pat) * Use `set_flash_method!` instead of `set_flash_method` in `Devise::OmniauthCallbacksController#failure`. (by @saichander17) * Clarify how `store_location_for` modifies URIs. (by @olivierlacan) * Move `failed_attempts` increment into its own function. by (@mobilutz) * Add `autocomplete="email"` to email fields. by (@MikeRogers0) * Add the ability to change the default migrations path introduced in Rails 5.0.3. (by @alexhifer) * Delete unnecessary condition for helper method. (by @davydovanton) * Support `id: :uuid` option for migrations. (by @filip373) * bug fixes * Fix syntax for MRI 2.5.0. (by @pat) * Validations were being ignored on singup in the `Trackable#update_tracked_fields!` method. (by @AshleyFoster) * Do not modify options for `#serializable_hash`. (by @guigs) * Email confirmations were being sent on sign in/sign out for application using `mongoid` and `mongoid-paperclip` gems. This is because previously we were checking if a model is from Active Record by checking if the method `after_commit` was defined - since `mongoid` doesn' have one - but `mongoid-paperclip` gem does define one, which cause this issue. (by @fjg) ### 4.3.0 - 2017-05-14 * Enhancements * Dependency support added for Rails 5.1.x. ### 4.2.1 - 2017-03-15 * removals * `Devise::Mailer#scope_name` and `Devise::Mailer#resource` are now protected methods instead of public. * bug fixes * Attempt to reset password without the password field in the request now results in a `:blank` validation error. Before this change, Devise would accept the reset password request and log the user in, without validating/changing the password. (by @victor-am) * Confirmation links now expire based on UTC time, working properly when using different timezones. (by @jjuliano) * enhancements * Notify the original email when it is changed with a new `Devise.send_email_changed_notification` setting. When using `reconfirmable`, the notification will be sent right away instead of when the unconfirmed email is confirmed. (original change by @ethirajsrinivasan) ### 4.2.0 - 2016-07-01 * removals * Remove the deprecated `Devise::ParameterSanitizer` API from Devise 3. Please use the `#permit` and `#sanitize` methods over `#for`. * Remove the deprecated OmniAuth URL helpers. Use the fully qualified helpers (`user_facebook_omniauth_authorize_path`) over the scope based helpers ( `user_omniauth_authorize_path(:facebook)`). * Remove the `Devise.bcrypt` method, use `Devise::Encryptor.digest` instead. * Remove the `Devise::Models::Confirmable#confirm!` method, use `confirm` instead. * Remove the `Devise::Models::Recoverable#reset_password!` method, use `reset_password` instead. * Remove the `Devise::Models::Recoverable#after_password_reset` method. * bug fixes * Fix an `ActionDispatch::IllegalStateError` when testing controllers with Rails 5 rc 2(by @hamadata). * Use `ActiveSupport.on_load` hooks to include Devise on `ActiveRecord` and `Mongoid`, avoiding autoloading these constants too soon (by @lucasmazza, @rafaelfranca). * enhancements * Display the minimum password length on `registrations/edit` view (by @Yanchek99). * You can disable Devise's routes reloading on boot by through the `reload_routes = false` config. This can reduce the time taken to boot the application but it might trigger some errors if you application (mostly your controllers) requires that Devise mappings be loaded during boot time (by @sidonath). * Added `Devise::Test::IntegrationHelpers` to bypass the sign in process using Warden test API (by @lucasmazza). * Define `inspect` in `Devise::Models::Authenticatable` to help ensure password hashes aren't included in exceptions or otherwise accidentally serialized (by @tkrajcar). * Add missing support of `Rails.application.config.action_controller.relative_url_root` (by @kosdiamantis). * deprecations * `Devise::TestHelpers` is deprecated in favor of `Devise::Test::ControllerHelpers` (by @lucasmazza). * The `sign_in` test helper has changed to use keyword arguments when passing a scope. `sign_in :admin, users(:alice)` should be rewritten as `sign_in users(:alice), scope: :admin` (by @lucasmazza). * The option `bypass` of `Devise::Controllers::SignInOut#sign_in` method is deprecated in favor of `Devise::Controllers::SignInOut#bypass_sign_in` method (by @ulissesalmeida). ### 4.1.1 - 2016-05-15 * bug fixes * Fix overwriting the remember_token when a valid one already exists (by @ralinchimev). ### 4.1.0 * bug fixes * Fix race condition of sending the confirmation instructions e-mail using background jobs. Using the previous `after_create` callback, the e-mail can be sent before the record be committed on database, generating a `ActiveRecord::NotFound` error. Now the confirmation e-mail will be only sent after the database commit, using the `after_commit` callback. It may break your test suite on Rails 4 if you are testing the sent e-mails or enqueued jobs using transactional fixtures enabled or `DatabaseCleaner` with `transaction` strategy. You can easily fix your test suite using the gem [test_after_commit](https://github.com/grosser/test_after_commit). For example, put in your Gemfile: ```ruby gem 'test_after_commit', :group => :test ``` On Rails 5 `after_commit` callbacks are triggered even using transactional fixtures, then this fix will not break your test suite. If you are using `DatabaseCleaner` with the `deletion` or `truncation` strategies it may not break your tests. (by @allenwq) * Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` and `:undefined` strategies. (by @f3ndot) * features * Humanize authentication keys in failure flash message (by @byzg) When you are configuring the translations of `devise.failure.invalid`, the `authentication_keys` is translated now. * deprecations * Remove code supporting old session serialization format (by @fphilipe). * Now the `email_regexp` default uses a more permissive regex: `/\A[^@\s]+@[^@\s]+\z/` (by @kimgb) * Now the `strip_whitespace_keys` default is `[:email]` (by @ulissesalmeida) * Now the `reconfirmable` default is `true` (by @ulissesalmeida) * Now the `skip_session_storage` default is `[:http_auth]` (by @ulissesalmeida) * Now the `sign_out_via` default is `:delete` (by @ulissesalmeida) * improvements * Avoids extra computation of friendly token for confirmation token (by @sbc100) ### 4.0.3 - 2016-05-15 * bug fixes * Fix overwriting the remember_token when a valid one already exists (by @ralinchimev). ### 4.0.2 - 2016-05-02 * bug fixes * Fix strategy checking in `Lockable#unlock_strategy_enabled?` for `:none` and `:undefined` strategies. (by @f3ndot) ### 4.0.1 - 2016-04-25 * bug fixes * Fix the e-mail confirmation instructions send when a user updates the email address from nil. (by @lmduc) * Remove unnecessary `attribute_will_change!` call. (by @cadejscroggins) * Consistent `permit!` check. (by @ulissesalmeida) ### 4.0.0 - 2016-04-18 * bug fixes * Fix the `extend_remember_period` configuration. When set to `false` it does not update the cookie expiration anymore.(by @ulissesalmeida) * deprecations * Added a warning of default value change in Devise 4.1 for users that uses the the default configuration of the following configurations: (by @ulissesalmeida) * `strip_whitespace_keys` - The default will be `[:email]`. * `skip_session_storage` - The default will be `[:http_auth]`. * `sign_out_via` - The default will be `:delete`. * `reconfirmable` - The default will be `true`. * `email_regexp` - The default will be `/\A[^@\s]+@[^@\s]+\z/`. * Removed deprecated argument of `Devise::Models::Rememberable#remember_me!` (by @ulissesalmeida) * Removed deprecated private method Devise::Controllers::Helpers#expire_session_data_after_sign_in! (by @bogdanvlviv) ### 4.0.0.rc2 - 2016-03-09 * enhancements * Introduced `DeviseController#set_flash_message!` for conditional flash messages setting to reduce complexity. * `rails g devise:install` will fail if the app does not have a ORM configured (by @arjunsharma) * Support to Rails 5 versioned migrations added. * deprecations * omniauth routes are no longer defined with a wildcard `:provider` parameter, and provider specific routes are defined instead, so route helpers like `user_omniauth_authorize_path(:github)` are deprecated in favor of `user_github_omniauth_authorize_path`. You can still use `omniauth_authorize_path(:user, :github)` if you need to call the helpers dynamically. ### 4.0.0.rc1 - 2016-02-01 * Support added to Rails 5 (by @twalpole). * Devise no longer supports Rails 3.2 and 4.0. * Devise no longer supports Ruby 1.9 and 2.0. * deprecations * The `devise_parameter_sanitize` API has changed: The `for` method was deprecated in favor of `permit`: ```ruby def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) << :subscribe_newsletter # Should become the following. devise_parameter_sanitizer.permit(:sign_up, keys: [:subscribe_newsletter]) end ``` The customization through instance methods on the sanitizer implementation should be done through it's `initialize` method: ```ruby class User::ParameterSanitizer < Devise::ParameterSanitizer def sign_up default_params.permit(:username, :email) end end # The `sign_up` method can be a `permit` call on the sanitizer `initialize`. class User::ParameterSanitizer < Devise::ParameterSanitizer def initialize(*) super permit(:sign_up, keys: [:username, :email]) end end ``` You can check more examples and explanations on the [README section](/plataformatec/devise#strong-parameters) and on the [ParameterSanitizer docs](lib/devise/parameter_sanitizer.rb). Please check [3-stable](https://github.com/plataformatec/devise/blob/3-stable/CHANGELOG.md) for previous changes. devise-4.4.3/README.md0000644000004100000410000007204713254473005014325 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) 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): hashes 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/omniauth/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. ## Table of Contents - [Information](#information) - [The Devise wiki](#the-devise-wiki) - [Bug reports](#bug-reports) - [StackOverflow and Mailing List](#stackoverflow-and-mailing-list) - [RDocs](#rdocs) - [Example applications](#example-applications) - [Extensions](#extensions) - [Contributing](#contributing) - [Starting with Rails?](#starting-with-rails) - [Getting started](#getting-started) - [Controller filters and helpers](#controller-filters-and-helpers) - [Configuring Models](#configuring-models) - [Strong Parameters](#strong-parameters) - [Configuring views](#configuring-views) - [Configuring controllers](#configuring-controllers) - [Configuring routes](#configuring-routes) - [I18n](#i18n) - [Test helpers](#test-helpers) - [Controller tests](#controller-tests) - [Integration tests](#integration-tests) - [OmniAuth](#omniauth) - [Configuring multiple models](#configuring-multiple-models) - [Create a migration with the required fields](#create-a-migration-with-the-required-fields) - [Inside your Admin model](#inside-your-admin-model) - [Inside your routes](#inside-your-routes) - [Inside your protected controller](#inside-your-protected-controller) - [Inside your controllers and views](#inside-your-controllers-and-views) - [ActiveJob Integration](#activejob-integration) - [Password reset tokens and Rails logs](#password-reset-tokens-and-rails-logs) - [Other ORMs](#other-orms) - [Additional information](#additional-information) - [Heroku](#heroku) - [Warden](#warden) - [Contributors](#contributors) - [License](#license) ## 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. ### StackOverflow and Mailing List If you have any questions, comments, or concerns, please use StackOverflow instead of the GitHub issue tracker: http://stackoverflow.com/questions/tagged/devise The deprecated mailing list can still be read on 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 `bin/test`. Devise works with multiple Ruby and Rails versions, and ActiveRecord and Mongoid ORMs, which means you can run the test suite with some modifiers: `DEVISE_ORM` and `BUNDLE_GEMFILE`. ### DEVISE_ORM Since Devise support both Mongoid and ActiveRecord, we rely on this variable to run specific code for each ORM. The default value of `DEVISE_ORM` is `active_record`. To run the tests for mongoid, you can pass `mongoid`: ``` DEVISE_ORM=mongoid bin/test ==> Devise.orm = :mongoid ``` When running the tests for Mongoid, you will need to have a MongoDB server (version 2.0 or newer) running on your system. Please note that the command output will show the variable value being used. ### BUNDLE_GEMFILE We can use this variable to tell bundler what Gemfile it should use (instead of the one in the current directory). Inside the [gemfiles](https://github.com/plataformatec/devise/tree/master/gemfiles) directory, we have one for each version of Rails we support. When you send us a pull request, it may happen that the test suite brakes on Travis using some of them. If that's the case, you can simulate the same environment using the `BUNDLE_GEMFILE` variable. For example, if the tests broke using Ruby 2.4.2 and Rails 4.1, you can do the following: ```bash rbenv shell 2.4.2 # or rvm use 2.4.2 BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bundle install BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bin/test ``` You can also combine both of them if the tests broke for Mongoid: ```bash BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable bundle install BUNDLE_GEMFILE=gemfiles/Gemfile.rails-4.1-stable DEVISE_ORM=mongoid bin/test ``` ## 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 4.0 works with Rails 4.1 onwards. You can add it to your Gemfile with: ```ruby gem 'devise' ``` Then run `bundle install` Next, you need to run the generator: ```console $ rails generate devise:install ``` At this point, a number of instructions will appear in the console. Among these instructions, you'll 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 } ``` 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. In the following command you will 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 the default Devise modules. The generator also configures your `config/routes.rb` file to point to the Devise controller. ```console $ rails generate devise MODEL ``` 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 `rails db:migrate` You should restart your application after changing Devise's configuration options (this includes stopping spring). 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! ``` For Rails 5, note that `protect_from_forgery` is no longer prepended to the `before_action` chain, so if you have set `authenticate_user` before `protect_from_forgery`, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use `protect_from_forgery prepend: true`. 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 hashing algorithm with: ```ruby devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 12 ``` 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 ![The Parameter Sanitizer API has changed for Devise 4](http://messages.hellobits.com/warning.svg?message=The%20Parameter%20Sanitizer%20API%20has%20changed%20for%20Devise%204) *For previous Devise versions see https://github.com/plataformatec/devise/tree/3-stable#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 default permitted parameters 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.permit(:sign_up, keys: [: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: ```ruby class ApplicationController < ActionController::Base before_action :configure_permitted_parameters, if: :devise_controller? protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, address_attributes: [:country, :state, :city, :area, :postal_code]]) end end ``` 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.permit(:sign_in) do |user_params| user_params.permit(:username, :email) end 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.permit(:sign_up) do |user_params| user_params.permit({ roles: [] }, :email, :password, :password_confirmation) end 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 initialize(*) super permit(:sign_up, keys: [: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](http://www.rubydoc.info/github/plataformatec/devise/master/ActionDispatch/Routing/Mapper%3Adevise_for) 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. Please note: You will still need to add `devise_for` in your routes in order to use helper methods such as `current_user`. ```ruby devise_for :users, skip: :all ``` ### 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 controller and integration tests. In order to use them, you need to include the respective module in your test cases/specs. ### Controller tests Controller tests require that you include `Devise::Test::ControllerHelpers` on your test case or its parent `ActionController::TestCase` superclass. ```ruby class PostsControllerTest < ActionController::TestCase include Devise::Test::ControllerHelpers 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::Test::ControllerHelpers, type: :controller config.include Devise::Test::ControllerHelpers, type: :view 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 on your controller tests: ```ruby sign_in @user sign_in @user, scope: :admin ``` 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 controller 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 test 'GET new' do # Mimic the router behavior of setting the Devise scope through the env. @request.env['devise.mapping'] = Devise.mappings[:user] # Use the sign_in helper to sign in a fixture `User` record. sign_in users(:alice) get :new # assert something end ``` ### Integration tests Integration test helpers are available by including the `Devise::Test::IntegrationHelpers` module. ```ruby class PostsTests < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers end ``` Now you can use the following `sign_in` and `sign_out` methods in your integration tests: ```ruby sign_in users(:bob) sign_in users(:bob), scope: :admin sign_out :user ``` RSpec users can include the `IntegrationHelpers` module on their `:feature` specs. ```ruby RSpec.configure do |config| config.include Devise::Test::IntegrationHelpers, type: :feature end ``` Unlike controller tests, integration tests do not need to supply the `devise.mapping` `env` value, as the mapping can be inferred by the routes that are executed in your tests. 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_action :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-2018 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.