Permalink
Browse files

Merge pull request #19 from miraage/master

CSRF protection
  • Loading branch information...
2 parents 0fd2f83 + 3a87d80 commit cb0e3b1706549eff655b0b460c84bd2558d0e695 @silentworks silentworks committed Jun 8, 2012
Showing with 77 additions and 0 deletions.
  1. +77 −0 Middleware/CsrfGuard.php
View
77 Middleware/CsrfGuard.php
@@ -0,0 +1,77 @@
+<?php
+
+/**
+ * CsrfGuard
+ *
+ * This middleware provides protection from CSRF attacks
+
+ * USAGE
+ *
+ * // Adding middleware
+ * $app = new Slim();
+ * $app->add(new CsrfGuard());
+ *
+ * // Setting token in view
+ * <input type="hidden" name="<?=$csrf_key?>" value="<?=$csrf_token?>">
+ *
+ * @author Mikhail Osher, https://github.com/miraage
+ * @version 1.0
+ */
+class CsrfGuard extends Slim_Middleware {
+ /**
+ * Request key
+ *
+ * @var string
+ */
+ protected $key;
+
+ /**
+ * Constructor
+ *
+ * @param string $key Request key
+ */
+ public function __construct( $key = 'csrf_token' ) {
+ // Validate key (i won't use htmlspecialchars)
+ if ( !is_string($key) || empty($key) || preg_match('/[^a-zA-Z0-9\-\_]/', $key) ) {
+ throw new OutOfBoundsException('Invalid key' . $key);
+ }
+
+ $this->key = $key;
+ }
+
+ /**
+ * Call middleware
+ */
+ public function call() {
+ // Attach as hook
+ $this->app->hook('slim.before', array($this, 'check'));
+
+ // Call next middleware
+ $this->next->call();
+ }
+
+ /**
+ * Check token
+ */
+ public function check() {
+ // Create token
+ $env = $this->app->environment();
+ $token = sha1($env['REMOTE_ADDR'] . '|' . $env['USER_AGENT']);
+
+ // Validate
+ if ( in_array($this->app->request()->getMethod(), array('POST', 'PUT', 'DELETE')) ) {
+ $usertoken = $this->app->request()->post($this->key);
+ if ( $token !== $usertoken ) {
+ $this->app->halt(400, 'Missing token');
+ }
+ }
+
+ // Assign to view
+ $this->app->view()->setData(array(
+ 'csrf_key' => $this->key,
+ 'csrf_token' => $token,
+ ));
+ }
+}
+
+?>

0 comments on commit cb0e3b1

Please sign in to comment.