Class: Karst::Web::Csrf
- Inherits:
-
Object
- Object
- Karst::Web::Csrf
- Defined in:
- lib/karst/web/csrf.rb
Overview
Synchronizer-token protection for state-changing forms served directly from Karst's Rack middleware, where Action Controller CSRF is unavailable.
Defined Under Namespace
Classes: InvalidToken
Constant Summary collapse
- TOKEN_KEY =
"karst.csrf_token"
Instance Method Summary collapse
-
#initialize(request) ⇒ Csrf
constructor
A new instance of Csrf.
- #rotate! ⇒ Object
- #token ⇒ Object
- #verify!(submitted) ⇒ Object
Constructor Details
#initialize(request) ⇒ Csrf
Returns a new instance of Csrf.
15 16 17 |
# File 'lib/karst/web/csrf.rb', line 15 def initialize(request) @request = request end |
Instance Method Details
#rotate! ⇒ Object
30 31 32 |
# File 'lib/karst/web/csrf.rb', line 30 def rotate! session[TOKEN_KEY] = SecureRandom.hex(32) end |
#token ⇒ Object
19 20 21 |
# File 'lib/karst/web/csrf.rb', line 19 def token session[TOKEN_KEY] ||= SecureRandom.hex(32) end |
#verify!(submitted) ⇒ Object
23 24 25 26 27 28 |
# File 'lib/karst/web/csrf.rb', line 23 def verify!(submitted) expected = session[TOKEN_KEY] valid = expected && submitted && expected.bytesize == submitted.bytesize && ActiveSupport::SecurityUtils.secure_compare(expected, submitted) raise InvalidToken, "invalid Karst CSRF token" unless valid end |