# User Management System - Documentation
[εζδΈζ](https://hackmd.io/@LWCJacky/HybtFi4gJx)
## Overview
This Python-based `UserManagement` class provides a framework for managing user accounts, roles, and permissions within an SQLite database. It allows for operations such as adding users, assigning roles, validating permissions, and managing user information and roles in a scalable and structured manner.
## Features
* **User Management:** Insert, update, or fetch users' data such as name, email, and profile picture.
* **Role Assignment:** Assign roles to users and manage permissions.
* **Permission Validation:** Validate if a user has the required role to perform certain actions.
* **Database Structure:** Automatically creates necessary tables for users, roles, and permissions.
* **Error Handling:** Gracefully handles various SQL errors and exceptions.
## Installation
### Requirements
* Python 3.x
* SQLite (comes pre-installed with Python)
### Setup
1. Download and place the `UserManagement` class in your project folder.
2. Ensure that you have the correct SQLite database file or specify its path during initialization.
3. The necessary tables are automatically created if they do not exist when the `UserManagement` class is instantiated.
### Example of Creating an Instance
```python
# Create an instance of UserManagement
user_mgmt = UserManagement('path_to_your_database.db')
```
## Database Schema
The system creates the following tables:
### 1. Users Table (`users`)
* **`id`**: Auto-incrementing primary key.
* **`sub`**: User's unique identifier (must be unique).
* **`name`**: User's full name.
* **`picture`**: URL of the user's profile picture.
* **`email`**: User's email address.
* **`created_at`**: Timestamp when the user was created.
* **`updated_at`**: Timestamp when the user was last updated.
### 2. Permissions Table (`permissions`)
* **`id`**: Auto-incrementing primary key.
* **`role`**: Role name (e.g., 'admin', 'user').
* **`priority`**: Role's priority level (lower numbers represent higher authority).
* **`created_at`**: Timestamp when the permission was created.
* **`updated_at`**: Timestamp when the permission was last updated.
### 3. Roles Table (`roles`)
* **`id`**: Auto-incrementing primary key.
* **`sub`**: User's unique identifier (foreign key referencing `users` table).
* **`role`**: Role name (foreign key referencing `permissions` table).
* **`created_at`**: Timestamp when the role was assigned to the user.
* **`updated_at`**: Timestamp when the role was last updated.
## Methods
### 1. **`__init__(db_file)`**
Initializes the class and creates the database tables if they don't already exist.
### 2. **`get_connection()`**
Creates and returns a new SQLite database connection.
### 3. **`create_tables()`**
Creates the necessary database tables (`users`, `permissions`, `roles`).
### 4. **`add_permission(role, priority)`**
Adds a new permission/role to the `permissions` table.
* **Parameters**:
* `role` (str): Name of the role.
* `priority` (int): Priority level of the role.
### 5. **`assign_role(sub, role)`**
Assigns a role to a user.
* **Parameters**:
* `sub` (str): User's unique identifier.
* `role` (str): Role to assign.
### 6. **`validate_user_permission(sub, required_role)`**
Validates if a user has a specific role or higher.
* **Parameters**:
* `sub` (str): User's unique identifier.
* `required_role` (str): The role to validate against.
### 7. **`insert_user(sub, name, email, picture=None)`**
Inserts a new user or updates the existing user if changes are detected.
* **Parameters**:
* `sub` (str): User's unique identifier.
* `name` (str): Full name of the user.
* `email` (str): User's email address.
* `picture` (str): URL of the user's profile picture (optional).
### 8. **`get_user_by_id(user_id)`**
Fetches a user's information by their unique identifier.
* **Parameters**:
* `user_id` (str): The unique identifier of the user.
### 9. **`get_user_roles(user_id)`**
Fetches all roles assigned to a user.
* **Parameters**:
* `user_id` (str): The unique identifier of the user.
### 10. **`check_email_exists(email)`**
Checks if an email address already exists in the system.
* **Parameters**:
* `email` (str): The email address to check.
### 11. **`fetch_users()`**
Fetches all user information from the `users` table.
### 12. **`get_fetch_available_roles()`**
Fetches all available roles and their priorities from the `permissions` table.
### 13. **`get_fetch_roles_for_user(sub)`**
Fetches the roles assigned to a specific user.
* **Parameters**:
* `sub` (str): The unique identifier of the user.
### 14. **`remove_role(user_id, role)`**
Removes a specific role from a user.
* **Parameters**:
* `user_id` (str): The unique identifier of the user.
* `role` (str): The role to be removed.
## Example Usage
Here are some examples of how to use the `UserManagement` class:
### Add a Permission
```python
user_mgmt.add_permission('admin', 1)
```
### Insert or Update a User
```python
user_mgmt.insert_user(
sub="U1234567890abcdef",
name="John Doe",
email="john.doe@example.com",
picture="https://example.com/profile.jpg"
)
```
### Assign a Role to a User
```python
user_mgmt.assign_role("U1234567890abcdef", "admin")
```
### Validate User Permission
```python
try:
if user_mgmt.validate_user_permission("U1234567890abcdef", "admin"):
print("User has the required permission.")
except PermissionError:
print("Permission denied.")
```
### Fetch All Users
```python
users = user_mgmt.get_fetch_users()
print(json.dumps(users, indent=4))
```
## Error Handling
The system handles errors such as:
* **IntegrityError**: When a role already exists or a duplicate user is inserted.
* **PermissionError**: When a user lacks the necessary permissions.
Each database connection is closed after the operation to prevent connection leaks.
## Conclusion
This `UserManagement` class is a robust solution for managing users and permissions in applications where role-based access control is required. It is scalable, easy to use, and can be integrated into Flask or other Python-based web applications.