9 |
10 |
--------------------------------------------------------------------------------
/.idea/tokens-validation.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | hichem.tab2002@gmail.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to TokensValidation
2 |
3 | We're thrilled that you're interested in contributing to TokensValidation! By following these guidelines, you can help ensure a smooth and collaborative contribution process.
4 |
5 | ## How to Contribute
6 |
7 | 1- Fork the repository on GitHub.
8 |
9 | 2- Clone your forked repository to your local machine:
10 |
11 | ```bash
12 |
13 | git clone https://github.com/HichemTab-tech/tokens-validation.git
14 |
15 | ```
16 |
17 | 3- Create a new branch for your contribution:
18 |
19 | ```bash
20 |
21 | git checkout -b feature/your-feature-name
22 |
23 | ```
24 |
25 | 4- Make your changes and commit them:
26 |
27 | ```bash
28 |
29 | git commit -m "Add your descriptive commit message here"
30 |
31 | ```
32 |
33 | 5- Push your changes to your forked repository:
34 |
35 | ```bash
36 |
37 | git push origin feature/your-feature-name
38 |
39 | ```
40 |
41 | 6- Open a pull request (PR) on GitHub. Provide a clear and descriptive title, and include details about the changes you've made in the PR description.
42 |
43 | ## Code Style and Standards
44 | Please ensure that your code adheres to the coding standards and style guidelines used in the project. If there are existing code conventions, follow them consistently to maintain code consistency across the project.
45 |
46 | ## Testing
47 | Before submitting your changes, make sure that your new features are tested.
48 |
49 | ## Issues and Bug Reports
50 | If you find a bug or have an issue, please check the existing issues on GitHub to see if it has already been reported. If not, feel free to open a new issue with a clear description and steps to reproduce the problem.
51 |
52 | ## Feature Requests
53 | We welcome new ideas and feature requests! If you have a feature you'd like to propose, open a new issue on GitHub and provide a detailed explanation of the feature's purpose and benefits.
54 |
55 | ## Licensing
56 | By contributing to this project, you agree that your contributions will be licensed under the project's [LICENSE](https://github.com/HichemTab-tech/tokens-validation/blob/master/LICENSE).
57 |
58 | ## Contact
59 | If you have any questions or need further assistance, you can reach out to the maintainers at hichem.tab2002@gmail.com.
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 HichemTab
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 
3 |
4 |
5 | # TokensValidation
6 |
7 | TokensValidation is a PHP library designed to generate and verify authentication and confirmation tokens dynamically. It is ideal for web applications and software that require secure user authentication and authorization. The library generates authentication and confirmation tokens that can be used to log in users, reset passwords, and confirm email addresses.
8 |
9 | ## Table of Contents
10 |
11 | 1. [Installation](#installation)
12 | 2. [Features](#features)
13 | 3. [Usage](#usage)
14 | 1. [Authentication Tokens](#authentication-tokens)
15 | 1. [Using Cookies](#1-using-cookies)
16 | 2. [Handling the Token Yourself](#2-handling-the-token-yourself)
17 | 3. [Overriding the Cookie Handler Methods](#3-overriding-the-cookie-handler-methods)
18 | 2. [Fingerprint](#fingerprint)
19 | 3. [Confirmation Tokens](#confirmation-tokens)
20 | 1. [By URL](#1--by-url)
21 | 2. [By Typing](#2--by-typing)
22 | 3. [WhatFor Field](#whatfor-field)
23 | 4. [Delete after check](#delete-after-check)
24 | 5. [Single Token Per Period](#single-token-per-period)
25 | 4. [Tokens Generator](#tokens-generator)
26 | 5. [Token Expiration](#token-expiration)
27 | 6. [Invitations](#invitations)
28 | 7. [In Laravel](#in-laravel)
29 | 8. [Errors Identification](#errors-identification)
30 | 4. [License](#license)
31 |
32 |
33 | ## Installation
34 |
35 | > ℹ️ **INFO**: This version is compatible with PHP 8 and above. If you are using PHP 7, you must install version [3.2.2](https://github.com/HichemTab-tech/tokens-validation/tree/3.2.2) of this library.
36 |
37 | The TokensValidation library can be installed via Composer by running the following command:
38 |
39 | ```bash
40 | composer require hichemtab-tech/tokens-validation
41 | ```
42 |
43 |
44 | ## Features
45 |
46 | - Authenticate the user after the browser closed without a password
47 | - Generate custom confirmation codes with expiration delay.
48 | - Create invitation tokens to do some actions.
49 | - Flexibility of usage
50 | - Security & Encryption
51 |
52 |
53 | ## Usage
54 |
55 |
56 | To use the library, you first need to set up the database connection parameters by calling the following methods:
57 |
58 | ```PHP
59 | isValidationSucceed()) {
106 | // log in the user automatically,
107 | //for example :
108 | autoLogin($result->getUserId());
109 | }
110 | else{
111 | //throw an error or redirect to log in
112 | }
113 |
114 | ```
115 |
116 | **TokensValidation::checkAuthToken()** checks the authentication token in the cookie and returns the result. If the validation is successful, a new token is generated and replaced in the cookie.
117 |
118 | ##### check the token without regenerating a new one:
119 |
120 | ```PHP
121 | $result = TokensValidation::checkAuthTokenWithoutRegenerate();
122 | ```
123 | This line of code executes a function called TokensValidation::checkAuthTokenWithoutRegenerate() which performs a check on the token to ensure that it is valid, but it does not regenerate a new token to replace the old one. The purpose of this check is to verify that the token is still valid and has not been tampered with. If the token is still valid, the function will return a successful result, which will be stored in the variable "$result".
124 |
125 | It is important to note that this function only checks the token's validity without regenerating it. If the token is invalid or has expired, the function will return an error or failure message, indicating that the user must log in again to obtain a new token. Therefore, this function provides an additional layer of security by ensuring that the token is still valid before proceeding with any further actions that require it.
126 |
127 | ###
128 |
129 | #### 2-Handling the token yourself
130 |
131 | To generate an authentication token and handle it yourself, call the following method:
132 |
133 | ```PHP
134 | $authToken = TokensValidation::createNewAuthToken(
135 | userId: $uid,
136 | usingCookies: false
137 | );
138 |
139 | echo $authToken->getUserId();
140 | echo $authToken->getContent();
141 | ```
142 |
143 | This method generates a new authentication token for the given user ID and returns the token object without saving the token anywhere to let you handle it as you like.
144 |
145 | To check the authentication token, call the following method and pass the token as argument:
146 |
147 | ```PHP
148 | $result = TokensValidation::checkAuthToken(authToken: $authToken);
149 | if ($result->isValidationSucceed()) {
150 | // log in the user automatically,
151 | //for example :
152 | echo $result->getUserId();
153 | echo $result->getNewToken()->getContent();// save it in cookies or whatever you want
154 | autoLogin($result->getUserId());
155 | }
156 | else{
157 | //throw an error or redirect to log in
158 | }
159 | ```
160 |
161 | ###
162 |
163 | #### 3-Overriding the cookie handler methods:
164 |
165 | To override the cookies handler methods, create a class that extends the **AuthTokenCookiesHandler** class and implements the **save()**, **get()**, and **delete()** methods. Then, set the **$AuthTokenCookiesHandler** property to the name of your new class. Here's an example:
166 |
167 | ```PHP
168 | use HichemtabTech\TokensValidation\Actions\Authentication\AuthTokenCookiesHandler;
169 |
170 | class MyAuthTokenCookiesHandler extends AuthTokenCookiesHandler
171 | {
172 | public function save(AuthToken $authToken): void
173 | {
174 | //save the $authToken in cookies or what ever you want
175 | }
176 |
177 | public function get(): ?string
178 | {
179 | //get it
180 | }
181 |
182 | public function delete(): void
183 | {
184 | //delete it
185 | }
186 | }
187 |
188 | TokensValidation::$AuthTokenCookiesHandler = MyAuthTokenCookiesHandler::class;
189 |
190 | // this should be called after preparation
191 |
192 | ```
193 |
194 |
195 | ## Fingerprint
196 | You can add an extra layer of security to authentication tokens by using a browser fingerprint. The library supports fingerprinting by passing a fingerprint string to the createNewAuthToken() method.
197 |
198 | ```PHP
199 | $authToken = TokensValidation::createNewAuthToken(
200 | userId: $uid,
201 | fingerPrint: $somefingerprint
202 | );
203 | ```
204 | To check the authentication token with a fingerprint, call the **checkAuthToken()** method with the fingerprint argument.
205 |
206 | ```PHP
207 | $result = TokensValidation::checkAuthToken(authToken: $authToken, fingerPrint: $somefingerprint);
208 | ```
209 |
210 | - *to generate the fingerprint, you can use for example https://github.com/Valve/fingerprintjs2*
211 |
212 |
213 |
214 | ### Confirmation tokens
215 |
216 | Confirmation tokens are unique codes that can be generated by **TokensValidation** to verify the identity of a user or to confirm their authorization for a specific action. In general, confirmation tokens are used for email verification or password reset purposes, although they can be used for other purposes as well.
217 |
218 | Confirmation processes can be classified into two types: those that require the user to click on a confirmation link *(by URL)* and those that require the user to manually enter a confirmation code *(by typing)*.
219 |
220 | #### 1- By Url
221 | In this case, the library generates a lengthy token that includes an encrypted user ID and is designed to be included in URL parameters.
222 |
223 | ```PHP
224 | $confirmationToken = TokensValidation::createNewConfirmationToken(
225 | userId: $uid,
226 | confirmationType: ConfirmationsTokenTypes::IN_URL
227 | );
228 |
229 | echo $confirmationToken->getContent();// if you want to view the long confirmation token
230 | echo $confirmationToken->getUrl("http://localhost/email-check");// to get the full prepared url with the base url, http://localhost/email-check
231 |
232 | //you will get the url like this:
233 | //http://localhost/email-check?u=def5020080134ecc82ee1c1c2536ccdb0ec3c50161a9b6ab6f0f24c34730b73174327d2990ef8f583cec5f86ba7c3d44c5a5c0adae17313d09d5479fbe83c33e91f00d3902699507fc16266931be4e0f90382e4614aba6d8&c=nkyZDxMqbnS2oPs
234 | ```
235 |
236 | You can utilize these lines of code to verify the contents of a URL.
237 |
238 | ```PHP
239 | $result = TokensValidation::checkConfirmationUrl(url: $url);
240 | if ($result->isValidationSucceed()) {
241 | //for example :
242 | echo $result->getUserId();
243 | //continue the request
244 | }
245 | else{
246 | //throw an error
247 | }
248 | ```
249 |
250 | Or you can inject **$_GET** directly:
251 |
252 | ```PHP
253 | $result = TokensValidation::checkConfirmationUrlParamsFromGET(_GET_ARRAY: $_GET);
254 | ```
255 |
256 | To override the ConfirmationUrl builder methods, create a class that extends the **ConfirmationUrlBuilder** class and implements the **getUrl(ConfirmationToken $confirmationToken, string $baseUrl)**, **getUserIdAndTokenFromUrl(string $url)**, and **getUserIdAndTokenFromGET(array $_GET_ARRAY)** methods. Then, set the $ConfirmationUrlBuilder property to the name of your new class. Here's an example:
257 |
258 | ```PHP
259 | use HichemtabTech\TokensValidation\Actions\Confirmation\ConfirmationUrlBuilder;
260 | use HichemtabTech\TokensValidation\Actions\Confirmation\UserIdAndToken;
261 | use HichemtabTech\TokensValidation\Model\Confirmation\ConfirmationToken;
262 | use Purl\Url;
263 |
264 | class MyConfirmationUrlBuilder extends ConfirmationUrlBuilder
265 | {
266 | public function getUrl(ConfirmationToken $confirmationToken, string $baseUrl): string
267 | {
268 | $url = new Url($baseUrl);
269 | $url->query->set("uid", $confirmationToken->getUserId());// for userId
270 | $url->query->set("token", $confirmationToken->getContent());// for Code
271 | return $url->getUrl();
272 | }
273 |
274 | public function getUserIdAndTokenFromUrl(string $url): UserIdAndToken
275 | {
276 | $url = new Url($url);
277 | return UserIdAndToken::builder()
278 | ->setUserId($url->query->get("uid"))
279 | ->setToken($url->query->get("token"))
280 | ->build();
281 | }
282 |
283 | public function getUserIdAndTokenFromGET(array $_GET_ARRAY): UserIdAndToken
284 | {
285 | return UserIdAndToken::builder()
286 | ->setUserId($_GET_ARRAY["uid"]??"")
287 | ->setToken($_GET_ARRAY["token"]??"")
288 | ->build();
289 | }
290 | }
291 |
292 | TokensValidation::$ConfirmationUrlBuilder = MyConfirmationUrlBuilder::class;
293 |
294 | // this should be called after preparation
295 | ```
296 | #### 2- By typing
297 |
298 | In this case, the user needs to enter the confirmation token generated by the library into a form field. The library can generate a short confirmation token for convenience:
299 |
300 | ```PHP
301 | $confirmationToken = TokensValidation::createNewConfirmationToken(
302 | userId: $uid,
303 | confirmationType: ConfirmationsTokenTypes::SMALL_CODE
304 | );
305 |
306 | echo $confirmationToken->getContent();
307 |
308 |
309 | $result = TokensValidation::checkConfirmationCode(code: $token);
310 | if ($result->isValidationSucceed()) {
311 | //for example :
312 | echo $result->getUserId();
313 | //continue the request
314 | }
315 | else{
316 | //throw an error
317 | }
318 | ```
319 |
320 | #### WhatFor field:
321 | To ensure that each confirmation code is used for its intended purpose, you can include a "**whatFor**" parameter when calling the **createNewConfirmationToken** function. This parameter allows you to specify the purpose of the confirmation code, providing an additional layer of security and accuracy.
322 |
323 | ```PHP
324 | $confirmationToken = TokensValidation::createNewConfirmationToken(
325 | userId: $uid,
326 | confirmationType: ConfirmationsTokenTypes::SMALL_CODE,
327 | whatFor: "email-confirmation"
328 | );
329 | ```
330 |
331 |
332 | To check it :
333 | ```PHP
334 | $result = TokensValidation::checkConfirmationCode(code: $token, whatFor: "email-confirmation");
335 | ```
336 |
337 | If the "whatFor" parameter does not match the intended purpose of the confirmation code, the validation process will fail.
338 |
339 | #### Delete after check:
340 | In some cases, you may only want to check the token and keep it active like for examples (middleware checks)
341 | you want just to check the token if its valid, then check it later in another position.
342 | This parameter allows you to specify whether the token will be deleted after the validation succeeded or not.
343 |
344 | ```PHP
345 | $confirmationToken = TokensValidation::checkConfirmationCode(
346 | userId: $uid,
347 | confirmationType: ConfirmationsTokenTypes::SMALL_CODE,
348 | whatFor: "email-confirmation",
349 | deleteAfterCheck: false, //true by default
350 | );
351 | ```
352 |
353 | #### Single Token Per Period:
354 | To avoid creating multiple confirmation code at the same moment (before expiration),
355 | you can set "**singleTokenPerTime**" parameter to true when calling the **createNewConfirmationToken** function.
356 | This parameter allows TokensValidation to create only one confirmation code per time,
357 | and in case the user requests another code with the same purpose (same whatFor value)
358 | the library returns the existed token only with different expiration date.
359 |
360 | ```PHP
361 | $confirmationToken = TokensValidation::createNewConfirmationToken(
362 | userId: $uid,
363 | confirmationType: ConfirmationsTokenTypes::SMALL_CODE,
364 | whatFor: "email-confirmation",
365 | singleTokenPerTime: true
366 | );
367 | ```
368 |
369 | ### Tokens generator
370 |
371 | You can modify the behavior of the token and confirmation code generator by creating a new class that extends the **AuthTokenGenerator::class** and **ConfirmationCodeGenerator::class**. This allows you to customize the functionality of the generator to meet the specific needs of your project.
372 |
373 | ```PHP
374 | TokensValidation::$AuthTokenGenerator = MyAuthTokenGenerator::class;
375 | TokensValidation::$ConfirmationCodeGenerator = MyConfirmationCodeGenerator::class;
376 | TokensValidation::$InvitationTokenGenerator = MyInvitationTokenGenerator::class;
377 | ```
378 |
379 | ### Token expiration
380 |
381 | By default, tokens generated by the library expire after a period of time (7 days for authentication tokens and 10 minutes for confirmation tokens). You can customize these expiration periods using the **setAuthTokenExpirationDelay()** and **setConfirmationTokenExpirationDelay()** methods, respectively:
382 |
383 | ```PHP
384 | // Set authentication token expiration period to 2 days
385 | TokensValidation::setAuthTokenExpirationDelay(2 * 24 * 60 * 60); // seconds
386 |
387 | // Set confirmation token expiration period to 1 hour
388 | TokensValidation::setConfirmationTokenExpirationDelay(60 * 60); // seconds
389 |
390 | //these lines should be called after preparation.
391 | ```
392 |
393 | You have the option to provide a custom expiration delay by passing the "expirationDelay" parameter to the function which generates the token for either the confirmation token or authentication token. You can accomplish this by using the following code:
394 | ```PHP
395 | $confirmationToken = TokensValidation::createNewConfirmationToken(
396 | userId: $uid,
397 | expirationDelay: 60*60 // seconds
398 | );
399 | ```
400 |
401 | ### Invitations
402 |
403 | The library offers a feature to create an invitation with a token, which can be sent to users via email to authorize them to perform certain actions, such as joining a project or becoming an admin.
404 | In order to utilize this functionality, it is necessary to enable the feature prior to calling the prepare() method. By default, the library includes two enabled features, namely AuthToken and ConfirmationToken. To activate additional features, you should call this before **prepare()**:
405 |
406 | ```PHP
407 | ...
408 | TokensValidation::setFeatures([
409 | 'AuthTokens',
410 | 'ConfirmationToken',
411 | 'InvitationsTokens'
412 | ]);
413 | ...
414 | TokensValidation::prepare();
415 | ```
416 |
417 | Or using config file:
418 |
419 | ```PHP
420 | [
427 | 'AuthTokens',
428 | 'ConfirmationToken',
429 | 'InvitationsTokens'
430 | ]
431 | ...
432 | ];
433 | ```
434 |
435 | #### Create the invitation:
436 |
437 | you can create an invitation by calling this code:
438 |
439 | ```PHP
440 | $invitation = TokensValidation::createInvitation(
441 | userId: $uid,
442 | target_email: "user@example.com",
443 | whatFor: "become-admin",
444 | );
445 |
446 | echo $invitation->getUrl();
447 |
448 | ```
449 |
450 | To adjust the default parameters of the invitation feature in the library, you will need to modify the configuration settings or by calling this code:
451 |
452 | ```PHP
453 | TokensValidation::setInvitationTokenExpirationDelay(60*60*24);
454 | TokensValidation::$InvitationBaseUrl = "http://localhost/invitations";
455 | TokensValidation::$InvitationTokenGenerator = MyInvitationTokenGenerator::class;
456 | TokensValidation::$InvitationUrlBuilder = MyInvitationUrlBuilder::class;
457 | ```
458 |
459 | #### Check the invitation:
460 |
461 | Typically, when using the invitation feature for actions such as sign up, the user is required to provide some information. In order to facilitate this process, the library allows for checking of the invitation, which enables the user to access the input page for providing the required information.
462 |
463 | ```PHP
464 |
465 | isValidationSucceed()) {
473 | redirectTo("/errors/invalid-invitation.html");
474 | }
475 |
476 | ?>
477 |
478 |