Create Admin User
Function: CreateAdminUser
Type: API Endpoint (POST)
Purpose:
This function is used to create a new administrator user with the provided details, ensuring unique email addresses and securely storing user credentials.
URL:
POST /api/admin/create/
Request Example:
{
"user_name": "<user_name>", // Administrator's full name
"email": "<email>", // Administrator's email
"mobile": "<mobile>", // Administrator's mobile number
"password": "<password>", // Password for the new user
"active": <active>, // User status (1 for active, 0 for inactive)
"lscode": "<lscode>" // LSCode for the administrator
}
Steps:
-
Email Check:
The function first checks if an administrator with the provided email already exists in the system. If the email is already in use, the function raises an HTTP exception with a status code of 400, indicating a conflict. -
User Code & LSCode Generation:
The function then generates a unique user_code and lscode for the new user using the code_generator function. These codes ensure each user has distinct identification values. -
Password Hashing:
The provided password is securely hashed using a hashing function before being stored in the database. -
User Creation:
A new LSAPIUserCredential entry is created with the provided details, including the generated codes, email, mobile number, hashed password, and the current user's email as the creator. -
Database Commit:
The new user is added to the database, committed, and the newly created user's details are refreshed for further use if needed.
Response: If the user is successfully created, the response contains a success message and the details of the newly created user.
Response Example:
{
"message": "Administrator user created successfully",
"user": {
"user_code": "<user_code>",
"LSCode": "<LSCode>",
"user_name": "<user_name>",
"email": "<email>",
"mobile": "<mobile>",
"active": 0 | 1,
"date_of_creation": "<date_of_creation>",
"created_user": "<created_user>",
"date_of_modification": "<date_of_modification>",
"modified_user": "<modified_user>"
}
}
Security:
- This function ensures that only authenticated users can create new administrator accounts by depending on get_current_user.
- Passwords are securely hashed before being stored in the database, preventing plaintext passwords from being exposed.
Error Handling:
- If a user with the provided email already exists, the function raises an HTTPException with a 400 status code and an error message.
- If any other error occurs during database operations, appropriate rollback mechanisms should be applied.
Notes:
- The user and LS codes are generated using the code_generator function, ensuring uniqueness and adherence to the required format.
- The current_user is captured from the session to ensure that only authorized users perform administrative actions.
Request body
Response
Successful Response