Authentication
Masonite makes authentication really simply.
Authentication Scaffold Command
Masonite comes with a command to scaffold out a basic authentication system. You may use this as a great starting point for adding authentication to your application. This command will create controllers, views, and mailables for you.
If you would like to implement your own authentication from scratch you can skip to the sections below.
First run the command to add the news files:
Then add the authentication routes to your routes file:
You may then go to the /login
or /register
route to implement your authentication.
Configuration
The configuration for Masonite's authentication is quite simple:
The default key here is the guard to use for authentication. The web
dictionary is the configuration for the web guard.
Login Attempts
You can attempt a login by using the Auth
class and using the attempt
method:
If the attempt succeeds, the user will now be authenticated and the result of the attempt will be the authenticated model.
If the attempt fails then the result will be None
.
If you know the primary key of the model, you can attempt by the id:
You can logout the current user:
User
You can get the current authenticated user:
If the user is not authenticated, this will return None
.
Routes
You can register several routes quickly using the auth class:
This will register the following routes:
URI | Description |
---|---|
GET /login | Displays a login form for the user |
POST /login | Attempts a login for the user |
GET /home | A home page for the user after a login attempt succeeds |
GET /register | Displays a registration form for the user |
POST /register | Saved the posted information and creates a new user |
GET /password_reset | Displays a password reset form |
POST /password_reset | Attempts to reset the users password |
GET /change_password | Displays a form to request a new password |
POST /change_password | Requests a new password |
Guards
Guards are encapsulated logic for logging in, registering and fetching users. The web guard uses a cookie
driver which sets a token
cookie which is used later to fetch the user.
You can switch the guard on the fly to attempt authentication on different guards:
Last updated