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
<?php
require_once __DIR__ . "\\..\\vendor\\autoload.php";
use sirJuni\Framework\Middleware\Auth;
class AuthController {
// login
public function login($request) {
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");
}
}
?>
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 everythinglogin()
sets.
Other methods supported are
Auth::set_fallback_route('/login')
- This method is used to set the route which points tologin
page. It is used when we useAuth
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)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.
Last updated