PageRenderTime 135ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/devise.rb

https://github.com/dluxemburg/devise
Ruby | 444 lines | 343 code | 47 blank | 54 comment | 0 complexity | 9d400fa0ddedc3104af829aa551399ab MD5 | raw file
  1. require 'rails'
  2. require 'active_support/core_ext/numeric/time'
  3. require 'active_support/dependencies'
  4. require 'orm_adapter'
  5. require 'set'
  6. require 'securerandom'
  7. module Devise
  8. autoload :Delegator, 'devise/delegator'
  9. autoload :FailureApp, 'devise/failure_app'
  10. autoload :OmniAuth, 'devise/omniauth'
  11. autoload :ParamFilter, 'devise/param_filter'
  12. autoload :TestHelpers, 'devise/test_helpers'
  13. autoload :TimeInflector, 'devise/time_inflector'
  14. module Controllers
  15. autoload :Helpers, 'devise/controllers/helpers'
  16. autoload :Rememberable, 'devise/controllers/rememberable'
  17. autoload :ScopedViews, 'devise/controllers/scoped_views'
  18. autoload :UrlHelpers, 'devise/controllers/url_helpers'
  19. end
  20. module Mailers
  21. autoload :Helpers, 'devise/mailers/helpers'
  22. end
  23. module Strategies
  24. autoload :Base, 'devise/strategies/base'
  25. autoload :Authenticatable, 'devise/strategies/authenticatable'
  26. end
  27. # Constants which holds devise configuration for extensions. Those should
  28. # not be modified by the "end user" (this is why they are constants).
  29. ALL = []
  30. CONTROLLERS = ActiveSupport::OrderedHash.new
  31. ROUTES = ActiveSupport::OrderedHash.new
  32. STRATEGIES = ActiveSupport::OrderedHash.new
  33. URL_HELPERS = ActiveSupport::OrderedHash.new
  34. # Strategies that do not require user input.
  35. NO_INPUT = []
  36. # True values used to check params
  37. TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE']
  38. # Custom domain for cookies. Not set by default
  39. mattr_accessor :rememberable_options
  40. @@rememberable_options = {}
  41. # The number of times to encrypt password.
  42. mattr_accessor :stretches
  43. @@stretches = 10
  44. # Keys used when authenticating a user.
  45. mattr_accessor :authentication_keys
  46. @@authentication_keys = [ :email ]
  47. # Request keys used when authenticating a user.
  48. mattr_accessor :request_keys
  49. @@request_keys = []
  50. # Keys that should be case-insensitive.
  51. mattr_accessor :case_insensitive_keys
  52. @@case_insensitive_keys = [ :email ]
  53. # Keys that should have whitespace stripped.
  54. mattr_accessor :strip_whitespace_keys
  55. @@strip_whitespace_keys = []
  56. # If http authentication is enabled by default.
  57. mattr_accessor :http_authenticatable
  58. @@http_authenticatable = false
  59. # If http headers should be returned for ajax requests. True by default.
  60. mattr_accessor :http_authenticatable_on_xhr
  61. @@http_authenticatable_on_xhr = true
  62. # If params authenticatable is enabled by default.
  63. mattr_accessor :params_authenticatable
  64. @@params_authenticatable = true
  65. # The realm used in Http Basic Authentication.
  66. mattr_accessor :http_authentication_realm
  67. @@http_authentication_realm = "Application"
  68. # Email regex used to validate email formats. It simply asserts that
  69. # an one (and only one) @ exists in the given string. This is mainly
  70. # to give user feedback and not to assert the e-mail validity.
  71. mattr_accessor :email_regexp
  72. @@email_regexp = /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/
  73. # Range validation for password length
  74. mattr_accessor :password_length
  75. @@password_length = 6..128
  76. # The time the user will be remembered without asking for credentials again.
  77. mattr_accessor :remember_for
  78. @@remember_for = 2.weeks
  79. # If true, extends the user's remember period when remembered via cookie.
  80. mattr_accessor :extend_remember_period
  81. @@extend_remember_period = false
  82. # Time interval you can access your account before confirming your account.
  83. mattr_accessor :allow_unconfirmed_access_for
  84. @@allow_unconfirmed_access_for = 0.days
  85. # Time interval the confirmation token is valid. nil = unlimited
  86. mattr_accessor :confirm_within
  87. @@confirm_within = nil
  88. # Defines which key will be used when confirming an account.
  89. mattr_accessor :confirmation_keys
  90. @@confirmation_keys = [ :email ]
  91. # Defines if email should be reconfirmable.
  92. # False by default for backwards compatibility.
  93. mattr_accessor :reconfirmable
  94. @@reconfirmable = false
  95. # Time interval to timeout the user session without activity.
  96. mattr_accessor :timeout_in
  97. @@timeout_in = 30.minutes
  98. # Authentication token expiration on timeout
  99. mattr_accessor :expire_auth_token_on_timeout
  100. @@expire_auth_token_on_timeout = false
  101. # Used to encrypt password. Please generate one with rake secret.
  102. mattr_accessor :pepper
  103. @@pepper = nil
  104. # Scoped views. Since it relies on fallbacks to render default views, it's
  105. # turned off by default.
  106. mattr_accessor :scoped_views
  107. @@scoped_views = false
  108. # Defines which strategy can be used to lock an account.
  109. # Values: :failed_attempts, :none
  110. mattr_accessor :lock_strategy
  111. @@lock_strategy = :failed_attempts
  112. # Defines which key will be used when locking and unlocking an account
  113. mattr_accessor :unlock_keys
  114. @@unlock_keys = [ :email ]
  115. # Defines which strategy can be used to unlock an account.
  116. # Values: :email, :time, :both
  117. mattr_accessor :unlock_strategy
  118. @@unlock_strategy = :both
  119. # Number of authentication tries before locking an account
  120. mattr_accessor :maximum_attempts
  121. @@maximum_attempts = 20
  122. # Time interval to unlock the account if :time is defined as unlock_strategy.
  123. mattr_accessor :unlock_in
  124. @@unlock_in = 1.hour
  125. # Defines which key will be used when recovering the password for an account
  126. mattr_accessor :reset_password_keys
  127. @@reset_password_keys = [ :email ]
  128. # Time interval you can reset your password with a reset password key
  129. mattr_accessor :reset_password_within
  130. @@reset_password_within = 6.hours
  131. # The default scope which is used by warden.
  132. mattr_accessor :default_scope
  133. @@default_scope = nil
  134. # Address which sends Devise e-mails.
  135. mattr_accessor :mailer_sender
  136. @@mailer_sender = nil
  137. # Authentication token params key name of choice. E.g. /users/sign_in?some_key=...
  138. mattr_accessor :token_authentication_key
  139. @@token_authentication_key = :auth_token
  140. # Skip session storage for the following strategies
  141. mattr_accessor :skip_session_storage
  142. @@skip_session_storage = []
  143. # Which formats should be treated as navigational.
  144. mattr_accessor :navigational_formats
  145. @@navigational_formats = ["*/*", :html]
  146. # When set to true, signing out a user signs out all other scopes.
  147. mattr_accessor :sign_out_all_scopes
  148. @@sign_out_all_scopes = true
  149. # The default method used while signing out
  150. mattr_accessor :sign_out_via
  151. @@sign_out_via = :get
  152. # The parent controller all Devise controllers inherits from.
  153. # Defaults to ApplicationController. This should be set early
  154. # in the initialization process and should be set to a string.
  155. mattr_accessor :parent_controller
  156. @@parent_controller = "ApplicationController"
  157. # The router Devise should use to generate routes. Defaults
  158. # to :main_app. Should be overriden by engines in order
  159. # to provide custom routes.
  160. mattr_accessor :router_name
  161. @@router_name = nil
  162. # Set the omniauth path prefix so it can be overriden when
  163. # Devise is used in a mountable engine
  164. mattr_accessor :omniauth_path_prefix
  165. @@omniauth_path_prefix = nil
  166. def self.encryptor=(value)
  167. warn "\n[DEVISE] To select a encryption which isn't bcrypt, you should use devise-encryptable gem.\n"
  168. end
  169. def self.use_salt_as_remember_token=(value)
  170. warn "\n[DEVISE] Devise.use_salt_as_remember_token is deprecated and has no effect. Please remove it.\n"
  171. end
  172. def self.apply_schema=(value)
  173. warn "\n[DEVISE] Devise.apply_schema is deprecated and has no effect. Please remove it.\n"
  174. end
  175. # PRIVATE CONFIGURATION
  176. # Store scopes mappings.
  177. mattr_reader :mappings
  178. @@mappings = ActiveSupport::OrderedHash.new
  179. # Omniauth configurations.
  180. mattr_reader :omniauth_configs
  181. @@omniauth_configs = ActiveSupport::OrderedHash.new
  182. # Define a set of modules that are called when a mapping is added.
  183. mattr_reader :helpers
  184. @@helpers = Set.new
  185. @@helpers << Devise::Controllers::Helpers
  186. # Private methods to interface with Warden.
  187. mattr_accessor :warden_config
  188. @@warden_config = nil
  189. @@warden_config_block = nil
  190. # When true, enter in paranoid mode to avoid user enumeration.
  191. mattr_accessor :paranoid
  192. @@paranoid = false
  193. # Default way to setup Devise. Run rails generate devise_install to create
  194. # a fresh initializer with all configuration values.
  195. def self.setup
  196. yield self
  197. end
  198. class Getter
  199. def initialize name
  200. @name = name
  201. end
  202. def get
  203. ActiveSupport::Dependencies.constantize(@name)
  204. end
  205. end
  206. def self.ref(arg)
  207. if defined?(ActiveSupport::Dependencies::ClassCache)
  208. ActiveSupport::Dependencies::reference(arg)
  209. Getter.new(arg)
  210. else
  211. ActiveSupport::Dependencies.ref(arg)
  212. end
  213. end
  214. def self.available_router_name
  215. router_name || :main_app
  216. end
  217. def self.omniauth_providers
  218. omniauth_configs.keys
  219. end
  220. # Get the mailer class from the mailer reference object.
  221. def self.mailer
  222. @@mailer_ref.get
  223. end
  224. # Set the mailer reference object to access the mailer.
  225. def self.mailer=(class_name)
  226. @@mailer_ref = ref(class_name)
  227. end
  228. self.mailer = "Devise::Mailer"
  229. # Small method that adds a mapping to Devise.
  230. def self.add_mapping(resource, options)
  231. mapping = Devise::Mapping.new(resource, options)
  232. @@mappings[mapping.name] = mapping
  233. @@default_scope ||= mapping.name
  234. @@helpers.each { |h| h.define_helpers(mapping) }
  235. mapping
  236. end
  237. # Make Devise aware of an 3rd party Devise-module (like invitable). For convenience.
  238. #
  239. # == Options:
  240. #
  241. # +model+ - String representing the load path to a custom *model* for this module (to autoload.)
  242. # +controller+ - Symbol representing the name of an exisiting or custom *controller* for this module.
  243. # +route+ - Symbol representing the named *route* helper for this module.
  244. # +strategy+ - Symbol representing if this module got a custom *strategy*.
  245. #
  246. # All values, except :model, accept also a boolean and will have the same name as the given module
  247. # name.
  248. #
  249. # == Examples:
  250. #
  251. # Devise.add_module(:party_module)
  252. # Devise.add_module(:party_module, :strategy => true, :controller => :sessions)
  253. # Devise.add_module(:party_module, :model => 'party_module/model')
  254. #
  255. def self.add_module(module_name, options = {})
  256. ALL << module_name
  257. options.assert_valid_keys(:strategy, :model, :controller, :route, :no_input)
  258. if strategy = options[:strategy]
  259. strategy = (strategy == true ? module_name : strategy)
  260. STRATEGIES[module_name] = strategy
  261. end
  262. if controller = options[:controller]
  263. controller = (controller == true ? module_name : controller)
  264. CONTROLLERS[module_name] = controller
  265. end
  266. NO_INPUT << strategy if options[:no_input]
  267. if route = options[:route]
  268. case route
  269. when TrueClass
  270. key, value = module_name, []
  271. when Symbol
  272. key, value = route, []
  273. when Hash
  274. key, value = route.keys.first, route.values.flatten
  275. else
  276. raise ArgumentError, ":route should be true, a Symbol or a Hash"
  277. end
  278. URL_HELPERS[key] ||= []
  279. URL_HELPERS[key].concat(value)
  280. URL_HELPERS[key].uniq!
  281. ROUTES[module_name] = key
  282. end
  283. if options[:model]
  284. path = (options[:model] == true ? "devise/models/#{module_name}" : options[:model])
  285. camelized = ActiveSupport::Inflector.camelize(module_name.to_s)
  286. Devise::Models.send(:autoload, camelized.to_sym, path)
  287. end
  288. Devise::Mapping.add_module module_name
  289. end
  290. # Sets warden configuration using a block that will be invoked on warden
  291. # initialization.
  292. #
  293. # Devise.initialize do |config|
  294. # config.allow_unconfirmed_access_for = 2.days
  295. #
  296. # config.warden do |manager|
  297. # # Configure warden to use other strategies, like oauth.
  298. # manager.oauth(:twitter)
  299. # end
  300. # end
  301. def self.warden(&block)
  302. @@warden_config_block = block
  303. end
  304. # Specify an omniauth provider.
  305. #
  306. # config.omniauth :github, APP_ID, APP_SECRET
  307. #
  308. def self.omniauth(provider, *args)
  309. @@helpers << Devise::OmniAuth::UrlHelpers
  310. config = Devise::OmniAuth::Config.new(provider, args)
  311. @@omniauth_configs[config.strategy_name.to_sym] = config
  312. end
  313. # Include helpers in the given scope to AC and AV.
  314. def self.include_helpers(scope)
  315. ActiveSupport.on_load(:action_controller) do
  316. include scope::Helpers if defined?(scope::Helpers)
  317. include scope::UrlHelpers
  318. end
  319. ActiveSupport.on_load(:action_view) do
  320. include scope::UrlHelpers
  321. end
  322. end
  323. # Regenerates url helpers considering Devise.mapping
  324. def self.regenerate_helpers!
  325. Devise::Controllers::UrlHelpers.remove_helpers!
  326. Devise::Controllers::UrlHelpers.generate_helpers!
  327. end
  328. # A method used internally to setup warden manager from the Rails initialize
  329. # block.
  330. def self.configure_warden! #:nodoc:
  331. @@warden_configured ||= begin
  332. warden_config.failure_app = Devise::Delegator.new
  333. warden_config.default_scope = Devise.default_scope
  334. warden_config.intercept_401 = false
  335. Devise.mappings.each_value do |mapping|
  336. warden_config.scope_defaults mapping.name, :strategies => mapping.strategies
  337. end
  338. @@warden_config_block.try :call, Devise.warden_config
  339. true
  340. end
  341. end
  342. # Generate a friendly string randomically to be used as token.
  343. def self.friendly_token
  344. SecureRandom.base64(15).tr('+/=lIO0', 'pqrsxyz')
  345. end
  346. # constant-time comparison algorithm to prevent timing attacks
  347. def self.secure_compare(a, b)
  348. return false if a.blank? || b.blank? || a.bytesize != b.bytesize
  349. l = a.unpack "C#{a.bytesize}"
  350. res = 0
  351. b.each_byte { |byte| res |= byte ^ l.shift }
  352. res == 0
  353. end
  354. end
  355. require 'warden'
  356. require 'devise/mapping'
  357. require 'devise/models'
  358. require 'devise/modules'
  359. require 'devise/rails'