1
0

devise.rb 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. Warden::Manager.after_set_user except: :fetch do |user, warden|
  2. if user.session_active?(warden.cookies.signed['_session_id'] || warden.raw_session['auth_id'])
  3. session_id = warden.cookies.signed['_session_id'] || warden.raw_session['auth_id']
  4. else
  5. session_id = user.activate_session(warden.request)
  6. end
  7. warden.cookies.signed['_session_id'] = {
  8. value: session_id,
  9. expires: 1.year.from_now,
  10. httponly: true,
  11. secure: (Rails.env.production? || ENV['LOCAL_HTTPS'] == 'true'),
  12. same_site: :lax,
  13. }
  14. end
  15. Warden::Manager.after_fetch do |user, warden|
  16. if user.session_active?(warden.cookies.signed['_session_id'] || warden.raw_session['auth_id'])
  17. warden.cookies.signed['_session_id'] = {
  18. value: warden.cookies.signed['_session_id'] || warden.raw_session['auth_id'],
  19. expires: 1.year.from_now,
  20. httponly: true,
  21. secure: (Rails.env.production? || ENV['LOCAL_HTTPS'] == 'true'),
  22. same_site: :lax,
  23. }
  24. else
  25. warden.logout
  26. throw :warden, message: :unauthenticated
  27. end
  28. end
  29. Warden::Manager.before_logout do |_, warden|
  30. SessionActivation.deactivate warden.cookies.signed['_session_id']
  31. warden.cookies.delete('_session_id')
  32. end
  33. module Devise
  34. mattr_accessor :pam_authentication
  35. @@pam_authentication = false
  36. mattr_accessor :pam_controlled_service
  37. @@pam_controlled_service = nil
  38. mattr_accessor :check_at_sign
  39. @@check_at_sign = false
  40. mattr_accessor :ldap_authentication
  41. @@ldap_authentication = false
  42. mattr_accessor :ldap_host
  43. @@ldap_host = nil
  44. mattr_accessor :ldap_port
  45. @@ldap_port = nil
  46. mattr_accessor :ldap_method
  47. @@ldap_method = nil
  48. mattr_accessor :ldap_base
  49. @@ldap_base = nil
  50. mattr_accessor :ldap_uid
  51. @@ldap_uid = nil
  52. mattr_accessor :ldap_bind_dn
  53. @@ldap_bind_dn = nil
  54. mattr_accessor :ldap_password
  55. @@ldap_password = nil
  56. mattr_accessor :ldap_tls_no_verify
  57. @@ldap_tls_no_verify = false
  58. mattr_accessor :ldap_search_filter
  59. @@ldap_search_filter = nil
  60. class Strategies::PamAuthenticatable
  61. def valid?
  62. super && ::Devise.pam_authentication
  63. end
  64. end
  65. end
  66. Devise.setup do |config|
  67. config.warden do |manager|
  68. manager.default_strategies(scope: :user).unshift :ldap_authenticatable if Devise.ldap_authentication
  69. manager.default_strategies(scope: :user).unshift :pam_authenticatable if Devise.pam_authentication
  70. manager.default_strategies(scope: :user).unshift :two_factor_authenticatable
  71. manager.default_strategies(scope: :user).unshift :two_factor_backupable
  72. end
  73. # The secret key used by Devise. Devise uses this key to generate
  74. # random tokens. Changing this key will render invalid all existing
  75. # confirmation, reset password and unlock tokens in the database.
  76. # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key`
  77. # by default. You can change it below and use your own secret key.
  78. # config.secret_key = '2f86974c4dd7735170fd70fbf399f7a477ffd635ef240d07a22cf4bd7cd13dbae17c4383a2996d0c1e79a991ec18a91a17424c53e4771adb75a8b21904bd1403'
  79. # ==> Mailer Configuration
  80. # Configure the e-mail address which will be shown in Devise::Mailer,
  81. # note that it will be overwritten if you use your own mailer class
  82. # with default "from" parameter.
  83. # config.mailer_sender = ENV['SMTP_FROM_ADDRESS'] || 'notifications@localhost'
  84. # Configure the class responsible to send e-mails.
  85. config.mailer = 'UserMailer'
  86. # ==> ORM configuration
  87. # Load and configure the ORM. Supports :active_record (default) and
  88. # :mongoid (bson_ext recommended) by default. Other ORMs may be
  89. # available as additional gems.
  90. require 'devise/orm/active_record'
  91. # ==> Configuration for any authentication mechanism
  92. # Configure which keys are used when authenticating a user. The default is
  93. # just :email. You can configure it to use [:username, :subdomain], so for
  94. # authenticating a user, both parameters are required. Remember that those
  95. # parameters are used only when authenticating and not when retrieving from
  96. # session. If you need permissions, you should implement that in a before filter.
  97. # You can also supply a hash where the value is a boolean determining whether
  98. # or not authentication should be aborted when the value is not present.
  99. # config.authentication_keys = [:email]
  100. # Configure parameters from the request object used for authentication. Each entry
  101. # given should be a request method and it will automatically be passed to the
  102. # find_for_authentication method and considered in your model lookup. For instance,
  103. # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  104. # The same considerations mentioned for authentication_keys also apply to request_keys.
  105. # config.request_keys = []
  106. # Configure which authentication keys should be case-insensitive.
  107. # These keys will be downcased upon creating or modifying a user and when used
  108. # to authenticate or find a user. Default is :email.
  109. config.case_insensitive_keys = [:email]
  110. # Configure which authentication keys should have whitespace stripped.
  111. # These keys will have whitespace before and after removed upon creating or
  112. # modifying a user and when used to authenticate or find a user. Default is :email.
  113. config.strip_whitespace_keys = [:email]
  114. # Tell if authentication through request.params is enabled. True by default.
  115. # It can be set to an array that will enable params authentication only for the
  116. # given strategies, for example, `config.params_authenticatable = [:database]` will
  117. # enable it only for database (email + password) authentication.
  118. # config.params_authenticatable = true
  119. # Tell if authentication through HTTP Auth is enabled. False by default.
  120. # It can be set to an array that will enable http authentication only for the
  121. # given strategies, for example, `config.http_authenticatable = [:database]` will
  122. # enable it only for database authentication. The supported strategies are:
  123. # :database = Support basic authentication with authentication key + password
  124. config.http_authenticatable = [:pam, :database]
  125. # If 401 status code should be returned for AJAX requests. True by default.
  126. # config.http_authenticatable_on_xhr = true
  127. # The realm used in Http Basic Authentication. 'Application' by default.
  128. # config.http_authentication_realm = 'Application'
  129. # It will change confirmation, password recovery and other workflows
  130. # to behave the same regardless if the e-mail provided was right or wrong.
  131. # Does not affect registerable.
  132. # See : https://github.com/plataformatec/devise/wiki/How-To:-Using-paranoid-mode,-avoid-user-enumeration-on-registerable
  133. config.paranoid = true
  134. # By default Devise will store the user in session. You can skip storage for
  135. # particular strategies by setting this option.
  136. # Notice that if you are skipping storage for all authentication paths, you
  137. # may want to disable generating routes to Devise's sessions controller by
  138. # passing skip: :sessions to `devise_for` in your config/routes.rb
  139. config.skip_session_storage = [:http_auth]
  140. # By default, Devise cleans up the CSRF token on authentication to
  141. # avoid CSRF token fixation attacks. This means that, when using AJAX
  142. # requests for sign in and sign up, you need to get a new CSRF token
  143. # from the server. You can disable this option at your own risk.
  144. # config.clean_up_csrf_token_on_authentication = true
  145. # ==> Configuration for :database_authenticatable
  146. # For bcrypt, this is the cost for hashing the password and defaults to 10. If
  147. # using other encryptors, it sets how many times you want the password re-encrypted.
  148. #
  149. # Limiting the stretches to just one in testing will increase the performance of
  150. # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  151. # a value less than 10 in other environments. Note that, for bcrypt (the default
  152. # encryptor), the cost increases exponentially with the number of stretches (e.g.
  153. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
  154. config.stretches = Rails.env.test? ? 1 : 10
  155. # Setup a pepper to generate the encrypted password.
  156. # config.pepper = '104d16705f794923e77c5e5167b52452d00646dc952a2d30b541c24086e647012c7b9625f253c51912e455981e503446772973d5f1638631196c819d7137fad4'
  157. # Send a notification to the original email when the user's email is changed.
  158. config.send_email_changed_notification = true
  159. # Send a notification email when the user's password is changed
  160. config.send_password_change_notification = true
  161. # ==> Configuration for :confirmable
  162. # A period that the user is allowed to access the website even without
  163. # confirming their account. For instance, if set to 2.days, the user will be
  164. # able to access the website for two days without confirming their account,
  165. # access will be blocked just in the third day. Default is 0.days, meaning
  166. # the user cannot access the website without confirming their account.
  167. # config.allow_unconfirmed_access_for = 2.days
  168. # A period that the user is allowed to confirm their account before their
  169. # token becomes invalid. For example, if set to 3.days, the user can confirm
  170. # their account within 3 days after the mail was sent, but on the fourth day
  171. # their account can't be confirmed with the token any more.
  172. # Default is nil, meaning there is no restriction on how long a user can take
  173. # before confirming their account.
  174. config.confirm_within = 2.days
  175. # If true, requires any email changes to be confirmed (exactly the same way as
  176. # initial account confirmation) to be applied. Requires additional unconfirmed_email
  177. # db field (see migrations). Until confirmed, new email is stored in
  178. # unconfirmed_email column, and copied to email column on successful confirmation.
  179. config.reconfirmable = true
  180. # Defines which key will be used when confirming an account
  181. # config.confirmation_keys = [:email]
  182. # ==> Configuration for :rememberable
  183. # The time the user will be remembered without asking for credentials again.
  184. config.remember_for = 1.year
  185. # Invalidates all the remember me tokens when the user signs out.
  186. config.expire_all_remember_me_on_sign_out = true
  187. # If true, extends the user's remember period when remembered via cookie.
  188. # config.extend_remember_period = false
  189. # Options to be passed to the created cookie. For instance, you can set
  190. # secure: true in order to force SSL only cookies.
  191. config.rememberable_options = { secure: true }
  192. # ==> Configuration for :validatable
  193. # Range for password length.
  194. config.password_length = 8..72
  195. # Email regex used to validate email formats. It simply asserts that
  196. # one (and only one) @ exists in the given string. This is mainly
  197. # to give user feedback and not to assert the e-mail validity.
  198. # config.email_regexp = /\A[^@]+@[^@]+\z/
  199. # ==> Configuration for :timeoutable
  200. # The time you want to timeout the user session without activity. After this
  201. # time the user will be asked for credentials again. Default is 30 minutes.
  202. # config.timeout_in = 30.minutes
  203. # ==> Configuration for :lockable
  204. # Defines which strategy will be used to lock an account.
  205. # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  206. # :none = No lock strategy. You should handle locking by yourself.
  207. # config.lock_strategy = :failed_attempts
  208. # Defines which key will be used when locking and unlocking an account
  209. # config.unlock_keys = [:email]
  210. # Defines which strategy will be used to unlock an account.
  211. # :email = Sends an unlock link to the user email
  212. # :time = Re-enables login after a certain amount of time (see :unlock_in below)
  213. # :both = Enables both strategies
  214. # :none = No unlock strategy. You should handle unlocking by yourself.
  215. # config.unlock_strategy = :both
  216. # Number of authentication tries before locking an account if lock_strategy
  217. # is failed attempts.
  218. # config.maximum_attempts = 20
  219. # Time interval to unlock the account if :time is enabled as unlock_strategy.
  220. # config.unlock_in = 1.hour
  221. # Warn on the last attempt before the account is locked.
  222. # config.last_attempt_warning = true
  223. # ==> Configuration for :recoverable
  224. #
  225. # Defines which key will be used when recovering the password for an account
  226. # config.reset_password_keys = [:email]
  227. # Time interval you can reset your password with a reset password key.
  228. # Don't put a too small interval or your users won't have the time to
  229. # change their passwords.
  230. config.reset_password_within = 6.hours
  231. # When set to false, does not sign a user in automatically after their password is
  232. # reset. Defaults to true, so a user is signed in automatically after a reset.
  233. config.sign_in_after_reset_password = false
  234. # ==> Configuration for :encryptable
  235. # Allow you to use another encryption algorithm besides bcrypt (default). You can use
  236. # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
  237. # :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
  238. # and :restful_authentication_sha1 (then you should set stretches to 10, and copy
  239. # REST_AUTH_SITE_KEY to pepper).
  240. #
  241. # Require the `devise-encryptable` gem when using anything other than bcrypt
  242. # config.encryptor = :sha512
  243. # ==> Scopes configuration
  244. # Turn scoped views on. Before rendering "sessions/new", it will first check for
  245. # "users/sessions/new". It's turned off by default because it's slower if you
  246. # are using only default views.
  247. # config.scoped_views = false
  248. # Configure the default scope given to Warden. By default it's the first
  249. # devise role declared in your routes (usually :user).
  250. # config.default_scope = :user
  251. # Set this configuration to false if you want /users/sign_out to sign out
  252. # only the current scope. By default, Devise signs out all scopes.
  253. # config.sign_out_all_scopes = true
  254. # ==> Navigation configuration
  255. # Lists the formats that should be treated as navigational. Formats like
  256. # :html, should redirect to the sign in page when the user does not have
  257. # access, but formats like :xml or :json, should return 401.
  258. #
  259. # If you have any extra navigational formats, like :iphone or :mobile, you
  260. # should add them to the navigational formats lists.
  261. #
  262. # The "*/*" below is required to match Internet Explorer requests.
  263. # config.navigational_formats = ['*/*', :html]
  264. # The default HTTP method used to sign out a resource. Default is :delete.
  265. config.sign_out_via = :delete
  266. # ==> OmniAuth
  267. # Add a new OmniAuth provider. Check the wiki for more information on setting
  268. # up on your models and hooks.
  269. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
  270. # ==> Warden configuration
  271. # If you want to use other strategies, that are not supported by Devise, or
  272. # change the failure app, you can configure them inside the config.warden block.
  273. #
  274. # config.warden do |manager|
  275. # manager.intercept_401 = false
  276. # manager.default_strategies(scope: :user).unshift :some_external_strategy
  277. # end
  278. # ==> Mountable engine configurations
  279. # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  280. # is mountable, there are some extra configurations to be taken into account.
  281. # The following options are available, assuming the engine is mounted as:
  282. #
  283. # mount MyEngine, at: '/my_engine'
  284. #
  285. # The router that invoked `devise_for`, in the example above, would be:
  286. # config.router_name = :my_engine
  287. #
  288. # When using OmniAuth, Devise cannot automatically set OmniAuth path,
  289. # so you need to do it manually. For the users scope, it would be:
  290. # config.omniauth_path_prefix = '/my_engine/users/auth'
  291. if ENV['PAM_ENABLED'] == 'true'
  292. config.pam_authentication = true
  293. config.usernamefield = nil
  294. config.emailfield = 'email'
  295. config.check_at_sign = true
  296. config.pam_default_suffix = ENV.fetch('PAM_EMAIL_DOMAIN') { ENV['LOCAL_DOMAIN'] }
  297. config.pam_default_service = ENV.fetch('PAM_DEFAULT_SERVICE') { 'rpam' }
  298. config.pam_controlled_service = ENV.fetch('PAM_CONTROLLED_SERVICE') { nil }
  299. end
  300. if ENV['LDAP_ENABLED'] == 'true'
  301. config.ldap_authentication = true
  302. config.check_at_sign = true
  303. config.ldap_host = ENV.fetch('LDAP_HOST', 'localhost')
  304. config.ldap_port = ENV.fetch('LDAP_PORT', 389).to_i
  305. config.ldap_method = ENV.fetch('LDAP_METHOD', :simple_tls).to_sym
  306. config.ldap_base = ENV.fetch('LDAP_BASE')
  307. config.ldap_bind_dn = ENV.fetch('LDAP_BIND_DN')
  308. config.ldap_password = ENV.fetch('LDAP_PASSWORD')
  309. config.ldap_uid = ENV.fetch('LDAP_UID', 'cn')
  310. config.ldap_tls_no_verify = ENV['LDAP_TLS_NO_VERIFY'] == 'true'
  311. config.ldap_search_filter = ENV.fetch('LDAP_SEARCH_FILTER', '%{uid}=%{email}')
  312. end
  313. end