Skip to content

Commit 23f7f2a

Browse files
committed
feat: add base auth docs
1 parent ccd1c00 commit 23f7f2a

File tree

7 files changed

+711
-8
lines changed

7 files changed

+711
-8
lines changed

.vitepress/config/sidebar.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,17 +95,17 @@ const sidebar = [
9595
// collapsed: true,
9696
items: [
9797
{ text: 'Introduction', link: '/docs/auth/' },
98-
{ text: 'MVC Support', link: '/docs/auth/mvc' },
99-
{ text: 'Auth Config', link: '/docs/auth/config' },
98+
// { text: 'MVC Support', link: '/docs/auth/mvc' },
99+
// { text: 'Auth Config', link: '/docs/auth/config' },
100100
{ text: 'User Login', link: '/docs/auth/login' },
101101
{ text: 'User Sign Up', link: '/docs/auth/signup' },
102-
{ text: 'Auth Session', link: '/docs/auth/session' },
102+
// { text: 'Auth Session', link: '/docs/auth/session' },
103103
{
104-
text: 'Protected Routes',
104+
text: 'Protecting your routes',
105105
link: '/docs/auth/protected-routes',
106106
},
107107
{ text: 'Updating logged-in user', link: '/docs/auth/update' },
108-
{ text: 'Helper methods', link: '/docs/auth/helpers' },
108+
{ text: 'Build your own auth library', link: '/docs/auth/helpers' },
109109
],
110110
},
111111
{

src/docs/auth/config.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,73 @@
11
# Auth Config
2+
3+
We understand that every application is different and may require a different level of control over the authentication system. Whether you want to use tokens, sessions, or your own custom setup, you can configure it without any hassle.
4+
5+
Leaf Auth is flexible enough to adapt to whatever system works best for you.
6+
7+
If you are using Leaf MVC, we have already created a config file available at `config/auth.php`. You can follow this documentation to update your config file.
8+
9+
## Specifying the table to use
10+
11+
Leaf assumes that you will save your users in a table named `users`. If you want to use a different table, you can configure Leaf Auth using `db.table`:
12+
13+
```php:no-line-numbers
14+
auth()->config('db.table', 'admins');
15+
```
16+
17+
## Specifying the primary key
18+
19+
Most databases use `id` as the primary key. If you are using a different field as the primary key, you can configure Leaf Auth using `id.key`:
20+
21+
```php:no-line-numbers
22+
auth()->config('id.key', 'admin_id');
23+
```
24+
25+
If you are using UUIDs as your primary key, you can configure Leaf Auth to use them:
26+
27+
```php:no-line-numbers
28+
auth()->config('id.uuid', UUID::v4());
29+
```
30+
31+
## Using timestamps
32+
33+
Leaf will always try to set the `created_at` and `updated_at` fields in your database. If you want to turn this off, you can set `timestamps` to `false`:
34+
35+
```php:no-line-numbers
36+
auth()->config('timestamps', false);
37+
```
38+
39+
Different databases have different ways of handling timestamps. If you get an error concerning the format of the timestamp, you can configure Leaf Auth to use a different format:
40+
41+
```php:no-line-numbers
42+
auth()->config('timestamps.format', 'YYYY-MM-DD HH:MM:SS');
43+
```
44+
45+
You can find the date format documentation [here](/docs/utils/date#formatting-dates).
46+
47+
## Create session on registration
48+
49+
Leaf will require a user to manually login after registration. If you want to automatically log in a user after registration, you can configure Leaf Auth to do that:
50+
51+
```php:no-line-numbers
52+
auth()->config('session.register', true);
53+
```
54+
55+
You can also set the redirect URL after registration:
56+
57+
```php:no-line-numbers
58+
auth()->config('session.registerRedirect', '/dashboard');
59+
```
60+
61+
## Auth with tokens
62+
63+
This is the default way Leaf handles authentication. There are a few things you can configure to make your token authentication more secure like the token lifetime:
64+
65+
```php:no-line-numbers
66+
auth()->config('token.lifetime', 3600); // 1 hour
67+
```
68+
69+
You can also set the secret key for your tokens:
70+
71+
```php:no-line-numbers
72+
auth()->config('token.secret', 'your-secret-key');
73+
```

src/docs/auth/helpers.md

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,137 @@
1-
# Helper Methods
1+
# Build your own auth library
2+
3+
Leaf Auth already provides everything you need to get a full authentication system up and running. However, if you want to build your own custom authentication system from the ground up, Leaf provides you with the tools to do that.
4+
5+
## Working with JWTs
6+
7+
According to the JWT docs, JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
8+
9+
In authentication, you can use JWTs as an identifier that a user has successfully logged in. The JWT usually also contains information about the authenticated user, usually the user's id. Leaf auth has helpers for interacting with JWTs. We'll take a look at them in this document.
10+
11+
## Generating JWTs
12+
13+
Leaf provides multiple ways for generating JWTs.
14+
15+
- ### Using the `generateSimpleToken` method
16+
17+
The simplest method is to use the `generateSimpleToken` method on the `Leaf\Helpers\Authentication` class. This method takes in 3 parameters:
18+
19+
- The user id of the currently authenticated user
20+
- The jwt secret string
21+
- The jwt expiry time in seconds
22+
23+
```php
24+
use Leaf\Helpers\Authentication;
25+
26+
// ... your application code
27+
28+
Authentication::generateSimpleToken(
29+
$userId,
30+
'MY_JWT_SECRET_STRING',
31+
time() + 3600
32+
);
33+
```
34+
35+
- ### Using the `generateToken` method
36+
37+
The `generateToken` method on the `Leaf\Helpers\Authentication` class is a more advanced method for generating JWTs. It takes in 2 parameters:
38+
39+
- An array of claims to be added to the JWT
40+
- The JWT secret string
41+
42+
```php
43+
use Leaf\Helpers\Authentication;
44+
45+
// ... your application code
46+
47+
Authentication::generateToken(
48+
[
49+
'user_id' => $userId,
50+
'iat' => time(),
51+
'iss' => 'localhost',
52+
'exp' => time() + 3600,
53+
],
54+
'MY_JWT_SECRET_STRING'
55+
);
56+
```
57+
58+
## Getting JWTs from the request
59+
60+
Tokens from authenticated requests are usually sent in the `Authorization` header. Leaf Auth provides helpers that allow you directly pull in tokens from the request header.
61+
62+
### Using the `getAuthorizationHeader` method
63+
64+
Leaf Auth provides the `getAuthorizationHeader` helper method for getting the token from the request header. It returns null if no authorization header is found.
65+
66+
```php
67+
use Leaf\Helpers\Authentication;
68+
69+
$header = Authentication::getAuthorizationHeader();
70+
```
71+
72+
### Using the `getBearerToken` method
73+
74+
Leaf Auth provides the `getBearerToken` helper method for getting the token from the request header. It returns null if no bearer token is found.
75+
76+
```php
77+
use Leaf\Helpers\Authentication;
78+
79+
$token = Authentication::getBearerToken();
80+
```
81+
82+
## Verifying JWTs
83+
84+
Verifying JWTs is a very important step in the authentication process. Tokens can be tampered with, they can also expire, or be issued by an untrusted source. For this reason, you should always verify the token before using it.
85+
86+
Leaf Auth provides 2 methods for verifying JWTs.
87+
88+
- ### Using the `validateToken` method
89+
90+
This method automatically checks if there is a token in the request header, and if there is, it verifies the token. It returns the decoded token if the token is valid, and returns false if the token is invalid.
91+
92+
It takes in a single parameter, which is the JWT secret string. This secret string should be the same as the one used to generate the token.
93+
94+
```php
95+
use Leaf\Helpers\Authentication;
96+
97+
$data = Authentication::validateToken($secret);
98+
```
99+
100+
Note that this method will automatically return false if there is no token in the request header. You can use the `errors` method to get the error message which is why the token validation failed.
101+
102+
```php
103+
use Leaf\Helpers\Authentication;
104+
105+
$data = Authentication::validateToken($secret);
106+
107+
if (!$data) {
108+
$errors = Authentication::errors();
109+
}
110+
```
111+
112+
- ### Using the `validate` method
113+
114+
Unlike the `validateToken` method, this method does not automatically check for a token in the request header. It takes in 2 parameters:
115+
116+
- The token to be validated
117+
- The JWT secret string
118+
119+
```php
120+
use Leaf\Helpers\Authentication;
121+
122+
$token = Authentication::getBearerToken();
123+
$data = Authentication::validate($token, $secret);
124+
```
125+
126+
Just like the `validateToken` method, this method returns the decoded token if the token is valid, and returns false if the token is invalid. You can use the `errors` method to get the error message which is why the token validation failed.
127+
128+
```php
129+
use Leaf\Helpers\Authentication;
130+
131+
$token = Authentication::getBearerToken();
132+
$data = Authentication::validate($token, $secret);
133+
134+
if (!$data) {
135+
$errors = Authentication::errors();
136+
}
137+
```

src/docs/auth/index.md

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,97 @@
11
# Authentication
2+
3+
<!-- markdownlint-disable no-inline-html -->
4+
5+
Numerous web applications offer their users a means to authenticate and access the application by "logging in." Adding this functionality to web applications can be a challenging and potentially dangerous task.
6+
7+
Leaf provides a lightweight but very powerful authentication system to handle all the complexities of authentication in a few lines of code. We understand that authentication is a critical part of your application, so we've made it as simple and secure as possible.
8+
9+
## Setting up
10+
11+
You can install Leaf Auth using the Leaf CLI:
12+
13+
::: code-group
14+
15+
```bash:no-line-numbers [Leaf CLI]
16+
leaf install auth
17+
```
18+
19+
```bash:no-line-numbers [Composer]
20+
composer require leafs/auth
21+
```
22+
23+
:::
24+
25+
The next step is to link your database and start signing users in.
26+
27+
## Connecting to a database
28+
29+
To do any kind of authentication, you need to connect to some kind of database which will store your users' data. If you are already using Leaf DB or Leaf MVC, then your database connection will automatically be used by Leaf Auth, so you don't need to connect to your database again.
30+
31+
If you are not using Leaf DB or Leaf MVC, you can connect to your database manually:
32+
33+
```php
34+
auth()->connect([
35+
'dbtype' => '...',
36+
'charset' => '...',
37+
'port' => '...',
38+
'host' => '...',
39+
'dbname' => '...',
40+
'user' => '...',
41+
'password' => '...'
42+
]);
43+
```
44+
45+
If you have an existing PDO connection, you can pass it to Leaf Auth:
46+
47+
```php
48+
$db = new PDO('mysql:dbname=test;host=127.0.0.1', 'root', '');
49+
50+
auth()->dbConnection($db);
51+
52+
// you can use leaf auth the same way you always have
53+
```
54+
55+
## Auth + Leaf MVC
56+
57+
If you are using Leaf MVC, you can set up Leaf Auth to work with your default database connection by heading over to the `public/index.php` file and uncommenting the line that connects to the database:
58+
59+
```php
60+
/*
61+
|--------------------------------------------------------------------------
62+
| Sync Leaf Db with ORM and connect
63+
|--------------------------------------------------------------------------
64+
|
65+
| Sync Leaf Db with ORM and connect to the database
66+
| This allows you to use Leaf Db without having
67+
| to initialize it in your controllers.
68+
|
69+
| If you want to use a different connection from those
70+
| used in your models, you can remove the line below and
71+
| add your own connection with:
72+
| db()->connect(...)
73+
|
74+
| **Uncomment the line below to use Leaf Db**
75+
| **You don't need this line to use Leaf Auth**
76+
*/
77+
// \Leaf\Database::initDb(); [!code --]
78+
\Leaf\Database::initDb(); // [!code ++]
79+
```
80+
81+
That's all you need to do. Leaf Auth will automatically connect to your database using the details in your environment file. The auth configuration for your project can be found in the `config/auth.php` file. You can edit this file to change the configuration of Leaf Auth.
82+
83+
## Database Considerations
84+
85+
Leaf Auth doesn't give you any structure for your database, with that, you can structure your database in any way you prefer. However, there are some things you should note:
86+
87+
1. By default, Leaf Auth assumes that your database primary key is `id`. If you have a database where you are using another field, say `admin_id` as the primary key, you will need to tell Leaf the name of your primary key. You can do this using the `ID_KEY` config:
88+
89+
```php:no-line-numbers
90+
auth()->config('id.key', 'admin_id');
91+
```
92+
93+
2. Leaf Auth assumes that you will save your users in a database table named `users`, this might however not be the case for your application. If you want to use a different table, you can configure Leaf Auth using `db.table`:
94+
95+
```php:no-line-numbers
96+
auth()->config('db.table', 'admins');
97+
```

0 commit comments

Comments
 (0)