<nephtali>

A simple, flexible, fast, and security-focused PHP framework
Nephtali documentation

Simple auth

Simple auth implementation that protects a directory of PHP files.

Code

The markup and PHP below protects the directory youradmin. Any unauthorized attempts to view a PHP file within the directory will result in the visitor being redirected to the login page.

Of note, this simple example does not ensure that credentials are exchanged over a secure connection.

Markup in login.php

<h2>Login</h2>
<!--pipe:login-->
<!--view:invalid-->
<p>Your login was invalid</p>
<!--view:invalid-->
<!--view:feedback-->
<h2>Some of data was invalid:</h2>
<ul class="standard_list">
   <!--data-->
   <li>{message}</li>
   <!--data-->
</ul>
<!--view:feedback-->
<!--view:error-->
<p>Error, please try again.</p>
<!--view:error-->
<!--pipe:login-->
<form action="login.php" method="post">
   <ul>
      <li>
         <label for="user_name">User name</label>
         <input type="text" id="user_name" name="user_name" />
      </li>
      <li>
         <label for="pw">Password</label>
         <input type="password" id="pw" name="pw" />
      </li>
      <li>
         <input type="submit" value="Login" />
      </li>
   </ul>
</form>

Authorization PHP in nregister.php

// protects http://yourwebsite.com/youradmin/
if (n\url\current_path($paths = array('/youradmin'))) {
   if (!isset($_SESSION)) session_start();
			
   if (!isset($_SESSION['is_logged_in']))
      n\url\redirect('/login.php');
}

Authentication PHP in nsite/login.php

n\port\register(
   $name = 'user_name',
   $opts = array(
      'max_length' => 40,
      'filter' => n\constant\FILTER_TEXT
   )
);
n\port\register(
   $name = 'pw',
   $opts = array(
      'max_length' => 300,
      'formatter' => function($val)
      {
         // hash and return base 64'd to restrict charset
         return base64_encode(
            hash_hmac(
               'sha256',
               $val,
               $key = n\config\get('encryption_salt'),
               true
            )
         );
      },
      'filter' => n\constant\FILTER_TEXT
   )
);
n\val(
   $name = 'attempt_login',
   $value = array('user_name','pw')
);
n\pipe\register_action(
   $name = 'login',
   $actions = array(
      n\port\signature(n\val('attempt_login')) => function($markup)
      {
         if (count($rows = n\port\validate(n\val('attempt_login')))) {
            return n\view\render($view = 'feedback', $markup, $rows);
         }

         if (
            n\port\get('user_name') == n\config\get('user_name')
            && 
            n\port\get('pw') === n\config\get('pw')
         ) {
            $_SESSION['is_logged_in'] = true;
            // avoid session hijacking
            session_regenerate_id();
            n\url\redirect('/youradmin/index.php');
         }

         return n\view\render($view = 'invalid', $markup);
      }
   )
);
blog comments powered by Disqus