Authentication
Overview by Shivang
Register
- Route:
POST ..customers/auth/register - Controller:
RegistrationController - Method:
register - Request:
CustomerRegistrationRequest- Class:
CustomerRegistrationRequest - Extends:
FormRequest
- Class:
- Description: Endpoint for user registration.
The __invoke method in the RegistrationController handles customer registration for the POST /register route. It retrieves customer data from the CustomerRegistrationRequest, creates a new customer with additional attributes like user and siteId, and optionally sets a default branch. After logging the creation, it authenticates the customer and performs additional actions if the customer is new, such as dispatching jobs for mobile user status and promo code issuance. The method concludes by returning a CustomerResource containing the customer’s details.
Login
- Route:
POST ..customers/auth/login - Controller:
LoginController - Method:
login - Request:
CustomerLoginRequest- Class:
CustomerLoginRequest - Extends:
FormRequest
- Class:
- Description: Endpoint for user login.
The login functionality is managed by the __invoke method of the LoginController, processing requests at POST /login. It implements geo-based rate limiting based on the user's location, performs customer lookups, and verifies passwords. The method returns responses through the CustomerResource for successful logins and various HTTP error statuses for failures. Errors and warnings are logged for geo-location, rate limiting, and authentication issues.
Password Email
- Route:
POST ..customers/auth/password/email - Controller:
PasswordResetController - Method:
sendPasswordResetEmail - Request:
SendPasswordResetEmailRequest- Class:
SendPasswordResetEmailRequest
- Class:
- Description: Endpoint to send a password reset email.
The password reset functionality is handled by the PasswordResetController with a POST request to /password/reset/ . The resetPassword method verifies the customer's username through the SendPasswordResetEmailRequest. If the customer is found, a password reset email is sent, and relevant logs are recorded. If the customer is not found, a log entry is made, and a 204 No Content response is returned. Upon successful email dispatch, a 200 OK response with a confirmation message is returned.
Password Reset
- Route:
POST ..customers/auth/password/reset - Controller:
PasswordResetController - Method:
resetPassword - Request:
ResetPasswordRequest- Class:
ResetPasswordRequest
- Class:
- Description: Endpoint to reset the user password.
The resetPassword method in PasswordResetController processes password reset requests using a provided token, username, and new password. It logs the request and attempts to reset the password, updating the customer's password and status upon success. If the customer does not have a trolley cookie, it updates their record if a trolley_token is present. Additionally, contact preferences are updated if provided in the request. The method returns a 200 OK response upon successful reset or a 422 Unprocessable Entity response if the reset fails, along with relevant log entries.
Guest Register
- Route:
POST ..customers/auth/guest/register - Controller:
GuestController - Method:
register - Request:
RegistrationRequest- Class:
RegistrationRequest
- Class:
- Description: Endpoint for guest registration.
For the Guest register method in the controller handles customer registrations using a RegistrationRequest. It checks if the user is a guest; if not, a 403 Forbidden response is returned. Upon successful validation, a new customer is created via the customerService, and relevant log information is recorded. The method then logs the new customer and their primary address ID, and authenticates the user by logging them in. Finally, it returns a CustomerResource containing the newly created customer's details.
Convert Guest to Customer
- Route:
PATCH ..customers/auth/guest/{customerId}/convert-to-customer - Controller:
GuestController - Method:
convertToCustomer - Request:
ConvertToCustomerRequest- Class:
ConvertToCustomerRequest - Directory:
Http/Requests/Guest
- Class:
- Description: Endpoint to convert a guest to a registered customer.
- Parameters:
customerId: The ID of the guest to be converted.
Convert Guest to Customer
- Route:
PATCH ..customers/auth/guest/{customerId}/convert-to-customer - Controller:
GuestController - Method:
convertToCustomer - Request:
ConvertToCustomerRequest- Class:
ConvertToCustomerRequest - Extends:
FormRequest
- Class:
- Description: Endpoint to convert a guest customer to a fully registered customer.
The convertToCustomer method processes the conversion of a guest customer to a registered customer. It retrieves the customer by their ID, ensuring a 404 error is thrown if not found, and checks for proper authorization. The method updates the customer's username, password, contact preferences, and marks them as active. It also removes any guest attributes associated with the customer. Finally, it logs the conversion event and returns a CustomerResource containing the updated customer information.
Overview by Shivam
Overview
This document provides an overview of the authentication-related API endpoints available in the Toolstation E-Comm API. The endpoints are designed to handle various aspects of user authentication, including registration, login, password management, and guest-to-customer conversion.
Route Prefix: /auth
All endpoints under this prefix pertain to authentication.
GET: /auth/_ping
- Method:
GET - Controller:
PingController - Description: Checks if the authentication service is up and running.
Response
Response Code: 200 OK
Response:
{
"data": {
"msg": "OK"
}
}
POST: /auth/register
- Controller:
RegistrationController - Method:
POST - Request:
CustomerRegistrationRequest - Description: Completes the customer registration process.
Controller
Key Points
- Dependencies:
- The controller is located in
App\Http\Controllers\Api\Auth. CustomerService: Manages customer-related operations.CustomerRegistrationRequest: Handles validation of registration requests.CustomerResource: Formats the customer data response.MarkCustomerAsMobileUser: Job for marking a customer as a mobile user.IssueNewAppSignUpPromoCode: Job for issuing a promotional code.Carbon: For handling dates.Auth: For authentication.Log: For logging activities.
- Constructor:
- Injecting
CustomerServiceto manage customer-related operations.
__invokeMethod:
public function __invoke(CustomerLoginRequest $request)
{
// Function implementation goes here
}
Purpose: Handles customer registration
- steps
- Retrieves customer data from the request.
- Creates a new customer using
CustomerService, adding additional data (user,siteId,date). - Sets a default branch for the customer if specified in the request.
- Logs the creation of the new customer, including customer ID and primary address ID.
- Authenticates the new customer by setting the user in the Auth system.
- Handling Mobile App Users:
- Checks if the request is from a mobile app and if the customer is a new mobile app user.
- Dispatches a job to mark the customer as a mobile user.
- Issues a promotional code if enabled.
- Returns the customer information as a
CustomerResource.
isNewAppCustomerMethod:
- Purpose: Determines if the registration request is from a mobile app and if the customer is a new mobile app user.
Logging:
- Utilizes
Log::infoto track key activities, such as new customer creation and branch assignments.
Request Parameters
- Content-Type:
application/json customer_data: An object containing the customer information.title: Customer’s title (string, required).first_name: Customer’s first name (string, required).last_name: Customer’s last name (string, required).mobile: Customer’s mobile number (string, required).email: Customer’s email address (string, required).password: Customer’s chosen password (string, required).company: Customer’s company name (string, optional).address: An object containing the customer's address information.type: Address type (string, required).town: Customer’s town (string, required).postcode: Customer’s postcode (string, required).line_1: Address line 1 (string, required).line_2: Address line 2 (string, optional).line_3: Address line 3 (string, optional).country: Customer’s country (string, required).country_id: Customer’s country ID (string, required).
contact_preferences: An object containing the customer's contact preferences.mobile: Preferred contact method for mobile (boolean, required).email: Preferred contact method for email (boolean, required).sms: Preferred contact method for SMS (boolean, optional).post: Preferred contact method for postal mail (boolean, optional).
terms_accepted: (Optional) Boolean indicating if terms and conditions have been accepted (boolean).
Request Body:
{
"customer_data": {
"title": "string", // Required: Customer's title
"first_name": "string", // Required: Customer's first name
"last_name": "string", // Required: Customer's last name
"mobile": "string", // Required: Customer's mobile number
"email": "string", // Required: Customer's email address
"password": "string", // Required: Customer's chosen password
"company": "string", // Optional: Customer's company name
"address": {
"type": "string", // Required: Address type
"town": "string", // Required: Customer's town
"postcode": "string", // Required: Customer's postcode
"line_1": "string", // Required: Address line 1
"line_2": "string", // Optional: Address line 2
"line_3": "string", // Optional: Address line 3
"country": "string", // Required: Customer's country
"country_id": "string" // Required: Customer's country ID
},
"contact_preferences": {
"mobile": true, // Required: True if contact by mobile is preferred
"email": true, // Required: True if contact by email is preferred
"sms": false, // Optional: True if contact by SMS is preferred
"post": false // Optional: True if contact by postal mail is preferred
},
"terms_accepted": true // Optional: Indicates if terms and conditions are accepted
}
}
Response:
{
"data": {
........
........
........
}
}
POST: /auth/login
- Controller:
LoginController - Method:
POST - Request:
CustomerLoginRequest - Description: Endpoint for completing the Login Process.
Controller
Key Points:
- Dependencies:
CustomerServicefor managing customer-related operations.CustomerLoginRequestfor handling login request validation.CustomerResourcefor formatting the customer data response.MarkCustomerAsMobileUserandIssueNewAppSignUpPromoCodefor processing additional actions related to new mobile app users and promotions.Authfor handling authentication.Logfor logging various actions and issues.
- Constructor:
- Injecting
CustomerServiceto manage customer-related operations.
__invokeMethod:
public function __invoke(CustomerLoginRequest $request)
{
// Function implementation goes here
}
Geo-Rate Limiting:
- If geo-rate limiting is enabled, the method performs several checks to prevent abuse based on the geographical location of the login attempt.
- It uses
geoip()to obtain location data from the request IP and applies rate limiting rules for different regions (e.g., outside the UK, outside the EU).
Customer Authentication::
- Retrieves the customer by username using
CustomerService. - Checks if the customer is active and has a valid password.
- Handles legacy password hashes and updates them to the modern hashing method if necessary.
- Authenticates the customer and sets the user in the Auth system.
Handling Mobile App Users:
- If the login request is from a mobile app and the customer is a new mobile app user, it dispatches jobs to mark the customer as a mobile user and issue a promotional code if enabled.
Logging: -Extensive logging is used to track various stages of the login process, including geo-location checks, customer status, password validation, and successful logins.
isNewAppCustomerMethod:
- Determines if the login request is from a mobile app and whether the customer is a new mobile app user.
compareUsingOldHashingMethodMethod:
- Compares the provided password with the stored password hash using an old hashing method if necessary.
POST: /auth/password/email
- Controller:
PasswordResetController - Method:
POST - Request:
SendPasswordResetEmailRequest - Description: Endpoint to send a Email for reset the password.
The sendPasswordResetEmail method handles password reset requests by first sending a reset email to a customer if they exist, and then processing the password reset by updating the customer's password and related details, ensuring any additional preferences or cookies are updated, while logging all significant actions and returning appropriate responses based on the success or failure of the reset process.
public function sendPasswordResetEmail(SendPasswordResetEmailRequest $request)
{
// Function implementation goes here
}
Key Points:
- Dependencies:
- Retrieving Customer: It first retrieves the customer based on the provided username.
- Checking Existence: If the customer exists, it proceeds to send a password reset email.
- Sending Email: The method utilizes the CustomerService to send a password reset email to the customer.
- Logging: Logs significant actions, including customer retrieval and email sending status.
- Constructor:
- Injecting
CustomerServiceto manage customer-related operations.
Example Request:
Host: example.com
Content-Type: application/json
{
"username": "john.doe"
}
Responses:
- 200 OK: If the email is sent successfully, returns a JSON response with a success message.
- 204 No Content: If the customer does not exist, returns a no content response.
"data": {
"msg": "Reset password email sent"
}
}
POST: /auth/password/reset
- Controller:
PasswordResetController - Method:
POST - Request:
ResetPasswordRequest - Description: Endpoint to reset the password after getting the Reset Email.
The resetPassword method resets the customer's password, updates their details, manages cookies and contact preferences,
logs the result, removes identity tokens, and returns a JSON response.
Functionality:
The resetPassword method processes password reset requests by:
- Logging:
- Logs the details of the password reset attempt, including the reset token.
- Password Reset:
- Utilizes the Password broker to attempt resetting the password.
- If successful, updates the customer's password and other relevant details.
- Customer Update:
Cookie Handling: If the customer does not have a cookie and the request includes atrolley_token, updates the customer's cookie.Contact Preferences: If provided, updates the customer’s contact preferences and ensures their account is active.
- Logging Results:
- Logs the outcome of the password reset attempt, including the result and customer ID.
- Identity Tokens:
- Removes any existing identity tokens for the customer to ensure a clean reset.
- Responses:
200 OK: If the password reset is successful, returns a JSON response with the result.422 Unprocessable Entity: If the password reset fails, returns a JSON response with an error message.
public function resetPassword(ResetPasswordRequest $request)
{
// Function implementation goes here
}
POST: /auth/guest/register
- Controller:
GuestController - Method:
POST - Request:
RegistrationRequest - Description: Guest Registration Endpoints.
The register method processes new customer registrations by verifying the request is from a guest, creating a customer,
logging creation details, authenticating the customer, and returning a CustomerResource.
Functionality:
The resetPassword method processes password reset requests by:
Authorization Check: Ensures the request is made by a GuestCustomer.Customer Creation: Uses theCustomerServiceto create a new customer with the provided data.Logging: Logs the creation of the new guest customer, including their ID and address.Authentication: Logs in the newly created customer to return an authentication token.Response: Returns aCustomerResourcewith the newly created customer’s details.
public function register(RegistrationRequest $request)
{
// Function implementation goes here
}
POST: /auth/guest/{customerId}/convert-to-customer
- Controller:
GuestController - Method:
POST - Request:
ConvertToCustomerRequest - Description: Convert Guest user to Registered Customer.
- Parameters:
customerId(integer): The ID of the guest to be converted.
The convertToCustomer method upgrades a guest user to a registered customer by updating their details,
removing guest attributes, logging the conversion, and returning a CustomerResource.
public function convertToCustomer(ConvertToCustomerRequest $request, $customerId)
{
// Function implementation goes here
}
Functionality:
The convertToCustomer method performs the following actions:
- Fetch Customer:
- Retrieves the customer by
customerId. - Throws a
404error if the customer is not found.
- Authorization:
- Checks if the current user is authorized to convert the specified customer.
- Update Customer Details:
- Sets the customer's username to their email.
- Hashes and updates the customer’s password.
- Marks the customer as active.
- Updates contact preferences and other relevant fields.
- Records the update timestamp and updater information.
- Remove Guest Attributes:
- DELETEs guest-specific attributes from the customer’s record.
- Logging:
- Logs the conversion event with the customer ID.
- Responses:
- Returns a
CustomerResourcerepresenting the updated customer.
=================================================================================
Overview by Atul
Introduction
This Page provides an overview of the routes defined for the authentication purpose endpoints in the Toolstation E-Com Api.
List of Routes for Authentication
/auth/_ping/auth/register/auth/login/auth/password/email/auth/password/reset/auth/guest/register/auth/guest/{customerId}/convert-to-customer
Route Prefix: /auth
All routes within this prefix are related to authentication purpose.
GET: /_ping
- Method:
GET - Controller:
PingController - Description: Endpoint to check if the authentication is valid and running successfully.
Response
Response Code: 200 OK
Response:
{
"data": {
"msg": "OK"
}
}
POST: /register
- Controller:
RegistrationController - Method:
POST - Request:
CustomerRegistrationRequest - Description: Endpoint for Completing the Register Process.
The __invoke function manages the entire customer registration process by receiving a CustomerRegistrationRequest, creating a new customer with additional attributes such as user identifier, site ID, and current date, and then using the CustomerService to handle the creation. It also sets the default branch for the customer if specified, logs details about the newly created customer and their primary address, and authenticates the customer. Additionally, it checks if the registration is from a mobile app and if the customer is a new mobile app user, dispatching jobs to mark them as a mobile user and potentially issue a promotional code based on specific conditions.
public function __invoke(CustomerRegistrationRequest $request)
{
// Function implementation goes here
}
Request Parameters for /register:
- Header :-
Accept-Language:- en-UK,en title: Customer’s title (string, required).first_name: Customer’s first name (string, required).last_name: Customer’s last name (string, required).mobile: Customer’s mobile number (string, required).email: Customer’s email address (string, required).password: Customer’s chosen password (string, required).company: Customer’s company name (string, optional).address: An object containing the customer's address information.type: Address type (integer, required).town: Customer’s town (string, required).postcode: Customer’s postcode (integer, required).line_1: Address line 1 (string, required).line_2: Address line 2 (string, optional).line_3: Address line 3 (string, optional).country: Customer’s country (string, required).country_id: Customer’s country ID (integer, required).
contact_preferences: An object containing the customer's contact preferences.mobile: Preferred contact method for mobile (boolean, required).email: Preferred contact method for email (boolean, required).sms: Preferred contact method for SMS (boolean, optional).post: Preferred contact method for postal mail (boolean, optional).
terms_accepted: (Optional) Boolean indicating if terms and conditions have been accepted (boolean).
POST: /login
- Controller:
LoginController - Method:
POST - Request:
CustomerLoginRequest - Description: Endpoint for completing the Login Process.
The __invoke function processes login requests by implementing geo-location-based rate limiting to manage failed login attempts, verifying customer credentials against the database, updating legacy password hashes to modern standards if necessary, and handling special cases for mobile app users, including dispatching jobs for user status updates and promotional codes, ultimately returning a CustomerResource or appropriate error responses based on the authentication outcome.
public function __invoke(CustomerLoginRequest $request)
{
// Function implementation goes here
}
Request Parameters for /login:
- Header :-
Accept-Language:- en-UK,en username: Customer’s email address (string, required).password: Customer’s chosen password (string, required).
Response
Response Code: 200 OK
Response:
{
"data": {
"id": "CWW02068816",
"title": "Mr",
"first_name": "kulchandraa",
"last_name": "kandel",
"username": "atul-s001@webreinvent.com",
"email": "atul-s001@webreinvent.com",
"telephone": "",
"mobile": "9315582865",
"card_number": "",
"company": "webreinvent",
"vat_number": null,
"account_type": null,
"account_number": null,
"loyalty_club_member": false,
"loyalty_club_member_since": null,
"credit_limit": null,
"remaining_balance": null,
"primary_address": {
"id": "DXX02715004",
"type": 1,
"line_1": "address1",
"line_2": "address2",
"line_3": "address3",
"town": "DELHI",
"county": "",
"postcode": "110037",
"country_id": 1,
"formatted": [
"address1",
"address2",
"address3",
"DELHI",
"110037",
"United Kingdom"
]
},
"contact_preferences": {
"mail_catalogues": false,
"order_query": {
"email": false,
"telephone": false,
"mobile": false,
"sms": false,
"push": false
},
"order_progress": {
"email": false,
"sms": false,
"push": false
},
"offers_info": {
"post": false,
"email": false,
"mobile": false,
"sms": false,
"push": false,
"promo_centre": true
}
},
"default_branch": "h1",
"favourite_branches": [
"h1"
],
"spend_stats": {
"last_month_spend": "0.00",
"this_month_spend": "0.00",
"estimated_savings_last_month": "0.00",
"estimated_savings_this_month": "0.00",
"spend_requirements": null
},
"token": "Token Code",
"one_time_qr_code": null,
"one_time_qr_code_base64": null
}
}
- Error Response:-
Status:401 Unauthorized{ "error": { "code": "401.99", "message": "Unauthorized", "info": "https://developers.example.com", "data": null } }
POST: /password/email
- Controller:
PasswordResetController - Method:
POST - Request:
SendPasswordResetEmailRequest - Description: Endpoint to send a Email for reset the password.
The sendPasswordResetEmail function handles password reset requests by first sending a reset email to a customer if they exist, and then processing the password reset by updating the customer's password and related details, ensuring any additional preferences or cookies are updated, while logging all significant actions and returning appropriate responses based on the success or failure of the reset process.
public function sendPasswordResetEmail(SendPasswordResetEmailRequest $request)
{
// Function implementation goes here
}
Request Parameters for /password/email:
- Header :-
Accept-Language:- en-UK,en username: Customer’s email address (string, required).
Response
Response Code: 200 OK
Response:
{
"data": {
"msg": "Reset password email sent"
}
}
- Error Response:-
Status:204 No Content
POST: /password/reset
- Controller:
PasswordResetController - Method:
POST - Request:
ResetPasswordRequest - Description: Endpoint to reset the password after getting the Reset Email.
The resetPassword function processes password reset requests by first logging the reset attempt and using the Password broker to reset the customer's password, updating their account status and related details if successful; it then checks for and sets additional information such as cookies and contact preferences if applicable, logs the outcome of the reset operation, removes any existing identity tokens, and finally returns a JSON response indicating success or failure based on the result of the password reset process.
public function resetPassword(ResetPasswordRequest $request)
{
// Function implementation goes here
}
Request Parameters for /password/reset:
- Header :-
Accept-Language:- en-UK,en token: Reset token (string, required).username: Customer’s email address (string, required).password: Customer’s chosen password (string, required).password_confirmation: Customer’s chosen password confirmation (string, required).
Response
Response Code: 200 OK
Response:
{
"data": "passwords.reset"
}
- Error Response:-
Status:422 unknown"error": { "code": "422.99", "message": "Unprocessable Entity", "info": "https://developers.example.com", "data": { "message": "Your password reset link expired after 24 hours, or has already been used. To reset your password, please request a new password reset link.", "errors": { "password": [ "Your password reset link expired after 24 hours, or has already been used. To reset your password, please request a new password reset link." ] } } }
POST: /guest/register
- Controller:
GuestController - Method:
POST - Request:
RegistrationRequest - Description: Guest Registration Endpoints.
The register function handles new customer registrations by first ensuring the request is made by a guest user; it then creates a new customer using data from the request, logs the creation details including the customer and address IDs, logs the customer in to update the authentication context, and finally returns a CustomerResource representing the newly registered customer.
public function register(RegistrationRequest $request)
{
// Function implementation goes here
}
POST: /guest/{customerId}/convert-to-customer
- Controller:
GuestController - Method:
POST - Request:
ConvertToCustomerRequest - Description: Convert Guest user to Registered Customer.
- Parameters:
customerId: The customerID of the guest to be converted to a registered customer.
The convertToCustomer function transforms a guest user into a fully registered customer by first fetching and authorizing the specified customer, then updating their account with a new username, hashed password, active status, and contact preferences, removing any guest-specific attributes, logging the conversion event, and finally returning a CustomerResource representing the updated customer.
public function convertToCustomer(ConvertToCustomerRequest $request, $customerId)
{
// Function implementation goes here
}
=================================================================================
OVERVIEW BY SUNIL KUMAR
Registration
- The system is receiving the customer's registration information from a form and request.
- A new customer is getting created using the provided data, along with some additional information like user ID, site ID, and the current date.
- If a default branch is specified in the request, it is set for the new customer.
- Then creating new customers log for keeping record and debugging purposes.
- Then new customer is logged in, making them the currently authenticated user.
- Mobile App User Check:
- The system checks if the registration is from a mobile app and if the customer is a new mobile app user.
- If so, the customer is marked as a mobile app user.
- If a promotion for new app sign-ups is enabled, a promo code is issued to the customer.
- In last system returns the new customer's information as a response.
Route::post('/register', 'RegistrationController');
Details
- Route:
../customers/auth/register - HTTP Request:
POST - Controller:
RegistrationController
Key Points
- Namespace and Dependencies:
- Controller is under
App\Http\Controllers\Api\Auth. - Important dependencies include
CustomerService,CustomerRegistrationRequest,CustomerResource,MarkCustomerAsMobileUser,IssueNewAppSignUpPromoCode,Carbon,Auth, andLog.
- Constructor:
- Injecting
CustomerServiceto manage customer-related operations.
__invokeMethod:
- Collecting customer data from the registration request.
- Uses
CustomerServiceto create a new customer with additional information (user,siteId,date). - Assigning a default branch if specified in the request.
- Logging-in new customer creation with customer ID and primary address ID.
- Logging-in in the newly created customer.
- Handling Mobile App User (if applicable):
- Dispatching job to issue a promo code if a promotion is enabled.
- Then Returning customer information as a
CustomerResource.
isNewAppCustomerMethod:
- Checks if the registration request is from a mobile app and if the customer is a new mobile app user.
- Logs are created using
Log::info.
Tested through Postman
- Endpoint:
https://apis.dev.nl.toolstation.dev/oauth2/v1/customers/auth/register - Access Token: Required
- Request Body:
{ "title": "Mr", "first_name": "Sunil", "last_name": "Kumar", "email": "sunil-k001@webreinvent.com", "mobile": "9560858774", "password": "123456789", "company": "webreinvent", "address":{ "type" : 1, "town": "DELHI", "postcode": "110043", "line_1": "address1", "line_2": "address2", "line_3": "address3", "country": "INDIA", "country_id": 1 }, "contact_preferences" : { "email": false, "mobile": false, "sms": false, "post": false }, "terms_accepted": true } - Response:
{ "title": "Mr", "first_name": "Sunil-new", "last_name": "SingKumarh", "email": "sunil-new@webreinvent.com", "mobile": "9560858774", "password": "123456789", "company": "webreinvent", "address": { "type": 1, "town": "DELHI", "postcode": "110043", "line_1": "address1", "line_2": "address2", "line_3": "address3", "country": "INDIA", "country_id": 1 }, "contact_preferences": { "email": false, "mobile": false, "sms": false, "post": false }, "terms_accepted": true }
login
The login process involves defining a POST route for login, retrieving and validating the customer using a customer service, and rate limiting based on geolocation. The system verifies the customer's status and password, updating to a modern hash if needed. For mobile app customers, it dispatches jobs to mark them as mobile users and issue promo codes. Upon successful authentication, a CustomerResource is returned.
Route::post('/login', 'LoginController');
Details
- Route:
../customers/auth/login - Request:
CustomerLoginRequest - HTTP Request:
POST - Controller:
LoginController
Key Points
- Rate Limiting Based on Geolocation:
- The controller first checks if geolocation rate limiting is enabled.
- It attempts to get the geolocation data of the login attempt.
- Logs any failure in geolocation data retrieval.
- Applies rate limiting based on whether the attempt is from outside the UK or EU.
- Customer Validation:
- Retrieves the customer using the provided username.
- If the customer does not exist, it logs this information and returns an unauthorized response.
- Checks if the customer account is active. If not, it returns a forbidden response with a specific error code.
- Ensures the customer account has a password. If not, it returns a forbidden response indicating account expiration.
- Password Checking and Hashing:
- Logs that the customer was found and checks if the password matches using a legacy hashing method.
- If the password matches the legacy hash, it updates the password to a modern hash and saves it.
- Sets the authenticated user using
Auth::setUser($customer).
- Additional Checks for New App Customers:
- If the customer is using a mobile app and is a new app customer, it dispatches a job to mark the customer as a mobile user.
- If a promotion for new app sign-ups is enabled, it issues a new app sign-up promo code.
- Response:
- Returns the customer resource if the password check is successful.
Tested through Postman
- Endpoint:
https://apis.dev.nl.toolstation.dev/ecom/v1/customers/auth/login - Access Token: Required
- Request Body:
{ "username": "sunil-k001@webreinvent.com", "password": "Admin@1235" } - Response:
{ "data": { "id": "CWW02068807", "title": "Meneer", "first_name": "Sunil", "last_name": "kumar", "username": "sunil-k001@webreinvent.com", "email": "sunil-k001@webreinvent.com", "telephone": "", "mobile": "7894561230", "card_number": "", "company": "", "vat_number": "", "account_type": null, "account_number": null, "loyalty_club_member": false, "loyalty_club_member_since": null, "credit_limit": null, "remaining_balance": null, "primary_address": { "id": "DWW02714985", "type": 1, "line_1": "1100", "line_2": "", "line_3": "De Trompet", "town": "Heemskerk", "county": "", "postcode": "1967 DA", "country_id": 8, "formatted": [ "De Trompet 1100", "1967 DA Heemskerk", "Nederland" ] }, "contact_preferences": { "mail_catalogues": true, "order_query": { "email": true, "telephone": true, "mobile": true, "sms": true, "push": false }, "order_progress": { "email": true, "sms": true, "push": false }, "offers_info": { "post": true, "email": true, "mobile": false, "sms": false, "push": false, "promo_centre": false } }, "default_branch": null, "favourite_branches": [], "spend_stats": { "last_month_spend": "0.00", "this_month_spend": "0.00", "estimated_savings_last_month": "0.00", "estimated_savings_this_month": "0.00", "spend_requirements": null }, "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXN0b21lcl9pZCI6IkNXVzAyMDY4ODA3IiwidXNlcl9hZ2VudCI6IlBvc3RtYW5SdW50aW1lXC83LjQxLjAiLCJuYmYiOjE3MjMxOTE0MjYsImV4cCI6MTcyNTYxMDYyNn0.Ncg4F8LabKLerpKRsoMtQrZtaf2KK2YBEtlG8iT8LJ8", "one_time_qr_code": null, "one_time_qr_code_base64": null } }
Password Reset
The password reset process involves sending a reset email to the customer if they exist, and then resetting their password if they provide a valid token and new password. Throughout the process, actions and errors are logged for monitoring, and appropriate responses are returned to user.
- sendPasswordResetEmail: Route::post('/password/email', 'PasswordResetController@sendPasswordResetEmail');
- resetPassword: Route::post('/password/reset', 'PasswordResetController@resetPassword');
- Controller:
PasswordResetController - HTTP Request:
POST - Method:
- For sendPasswordResetEmail :
SendPasswordResetEmailRequest - For resetPassword:
ResetPasswordRequest
- For sendPasswordResetEmail :
Key Points
- sendPasswordResetEmail():
- Fetches customer by username.
- Sends password reset email if customer exists.
- Logs actions and returns a response.
Tested through Postman
- Endpoint:
https://apis.dev.nl.toolstation.dev/ecom/v1/customers/auth/password/email - Access Token: Required
- Request Body:
{ "username": "sunil-k001@webreinvent.com" } - Response:
{ "data": { "msg": "Reset password email sent" } }
- resetPassword():
- Resets the customer's password using the provided token and new password.
- Updates customer details and handles additional preferences.
- Logs actions and returns a response.
Tested through Postman
- Endpoint:
https://apis.dev.nl.toolstation.dev/ecom/v1/customers/auth/password/reset - Access Token: Required
- Request Body:
{ "token": "1d9eacffed5ae3cd079eae3ca72ff0226a59f55f99349f35462f5cfed5419a7c", "email": "sunil-k001@webreinvent.com", "password": "Admin@1235", "password_confirmation": "Admin@1235" } - Response:
{ "data": "passwords.reset" }
Guest
The GuestController handles two methods:
- The
registerwhen a guest registers, a new guest customer is created, logged, and authenticated. - The
convertToCustomermethod allows for converting a guest to a fully registered customer by updating necessary attributes, authorizing the action, logging the conversion, and returning aCustomerResource
- Route::post('/guest/register', 'GuestController@register');
Details
- Route:
../customers/auth/guest/register - Request:
RegistrationRequest - HTTP Request:
POST - Controller:
GuestController - Method:
register
- Route::patch('/guest/{customerId}/convert-to-customer', 'GuestController@convertToCustomer');
Details
- Route:
../customers/auth/guest/{customerId}/convert-to-customer - Request:
ConvertToCustomerRequest - HTTP Request:
PATCH - Controller:
GuestController - Method:
convertToCustomer