> For the complete documentation index, see [llms.txt](https://shoaib-1.gitbook.io/sirjuni/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://shoaib-1.gitbook.io/sirjuni/middleware.md).

# Middleware

Components that provide additional checks on requests

## Auth

The Auth middleware can be found at `sirJuni\Framework\Middleware\Auth` and it abstracts login, logout implementation. We can use its methods to login a user and also logout a user. We can also use this middleware to put routes behind `Authentication`.

A simple controller that logs in a user using `Auth` would be

<pre class="language-php"><code class="lang-php"><strong>&#x3C;?php
</strong><strong>require_once __DIR__ . "\\..\\vendor\\autoload.php";
</strong><strong>use sirJuni\Framework\Middleware\Auth;
</strong><strong>
</strong><strong>class AuthController {
</strong><strong>        // login
</strong><strong>        public function login($request) {
</strong>            if ($request->formData('login')) {
                $email = $request->formData('username');
                $pass = $request->formData('password');
    
                $db = new DB();
    
                $user = $db->getUser($email);
                if ($user['password'] == $pass) {
                    Auth::login($user);  // login the user by creating session and storing data there
                    VIEW::init('profile.html', $user);
                }
                else {
                    HelperFuncs::redirect("/mypro/auth?message=wrong");
                }
            }
            else {
                HelperFuncs::redirect("/mypro");
            }
        }
        
        // logout
        public function logout($request) {
            Auth::logout();
            HelperFuncs::redirect("/mypro/auth");
        }
}
?>
</code></pre>

* `Auth::login($user);` - takes in an associative array containing user details and internally creates a session and stores these details there.
* `Auth::logout()` - It destroys the session and unset everything `login()` sets.

**Other methods supported are**

1. `Auth::set_fallback_route('/login')` - This method is used to set the route which points to `login` page. It is used when we use `Auth` as middleware to protect a route. When we visit that route unauthenticated, it redirects the user to the url that is set using this method (here : /login)
2. `Auth::check()` - It returns true if user is logged in and false otherwise.

In the above code `HelperFuncs::redirect` is a function that causes redirect to the given path. It is contained in the `sirJuni\Framework\Helper\HelperFuncs` class.
