-
-
Notifications
You must be signed in to change notification settings - Fork 127
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5d2f7e3
commit 384dda5
Showing
3 changed files
with
52 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
''' CSRF Middleware ''' | ||
|
||
from masonite.exceptions import InvalidCSRFToken | ||
|
||
|
||
class CsrfMiddleware: | ||
''' Verify CSRF Token Middleware ''' | ||
|
||
exempt = [] | ||
|
||
def __init__(self, Request, Csrf, ViewClass): | ||
self.request = Request | ||
self.csrf = Csrf | ||
self.view = ViewClass | ||
|
||
def before(self): | ||
token = self.__verify_csrf_token() | ||
|
||
self.view.share({ | ||
'csrf_field': "<input type='hidden' name='csrf_token' value='{0}' />".format(token) | ||
}) | ||
|
||
def after(self): | ||
pass | ||
|
||
def __in_exempt(self): | ||
""" | ||
Determine if the request has a URI that should pass | ||
through CSRF verification. | ||
""" | ||
|
||
if self.request.path in self.exempt: | ||
return True | ||
else: | ||
return False | ||
|
||
def __verify_csrf_token(self): | ||
""" | ||
Verify si csrf token in post is valid. | ||
""" | ||
|
||
if self.request.is_post() and not self.__in_exempt(): | ||
token = self.request.input('csrf_token') | ||
if not self.csrf.verify_csrf_token(token): | ||
raise InvalidCSRFToken("Invalid CSRF token.") | ||
else: | ||
token = self.csrf.generate_csrf_token() | ||
|
||
return token |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters