Tibamwenda
5 min readJul 10, 2023
from flask import Flask, request, jsonify
import jwt
import datetime

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'

# Dummy user data
users = []


# Token validation function
def validate_token(token):
try:
jwt.decode(token, app.config['SECRET_KEY'])
return True
except jwt.ExpiredSignatureError:
return False
except jwt.InvalidTokenError:
return False


def get_user_by_email(email):
# Find a user by email in the dummy user data
for user in users:
if user['email'] == email:
return user
return None


def get_user_by_id(user_id):
# Find a user by ID in the dummy user data
for user in users:
if user['id'] == user_id:
return user
return None


def authenticate(email, password):
# Authenticate a user based on email and password
user = get_user_by_email(email)
if user and user['password'] == password:
return user
return None


def is_admin(user_id):
# Check if a user has admin privileges
user = get_user_by_id(user_id)
if user and user['admin']:
return True
return False


@app.route('/v1/api/register', methods=['POST'])
def register():
# Endpoint for user registration
data = request.get_json()
email = data.get('email')
password = data.get('password')
name = data.get('name')

if not email or not password or not name:
return jsonify({'error': 'Missing required fields'}), 400

if get_user_by_email(email):
return jsonify({'error': 'Email already exists'}), 400

# Generate a new user ID
new_user_id = len(users) + 1

# Create a new user record
new_user = {
'id': new_user_id,
'name': name,
'email': email,
'password': password,
'admin': False
}
users.append(new_user)

return jsonify({'message': 'User registered successfully'}), 201


@app.route('/v1/api/login', methods=['POST'])
def login():
# Endpoint for user login
data = request.get_json()
email = data.get('email')
password = data.get('password')

if not email or not password:
return jsonify({'error': 'Missing email or password'}), 400

user = authenticate(email, password)
if not user:
return jsonify({'error': 'Invalid credentials'}), 401

# Generate the token
token = jwt.encode({
'user_id': user['id'],
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1)
}, app.config['SECRET_KEY'])

return jsonify({'message': 'Login successful', 'token': token}), 200


@app.route('/v1/api/logout', methods=['POST'])
def logout():
# Endpoint for user logout
# Token-based authentication implementation goes here
return jsonify({'message': 'Logout successful'}), 200


@app.route('/v1/api/reset_password', methods=['POST'])
def request_password_reset():
# Endpoint for requesting a password reset
data = request.get_json()
email = data.get('email')

if not email:
return jsonify({'error': 'Missing email'}), 400

user = get_user_by_email(email)
if not user:
return jsonify({'error': 'User not found'}), 404

# Generate and send password reset token
# Implementation goes here

return jsonify({'message': 'Password reset token sent'}), 200


@app.route('/v1/api/reset_password/<token>', methods=['POST'])
def reset_password(token):
# Endpoint for resetting a user's password
data = request.get_json()
password = data.get('password')

if not password:
return jsonify({'error': 'Missing password'}), 400

# Verify the password reset token
# Implementation goes here

# Update the user's password
# Implementation goes here

return jsonify({'message': 'Password reset successful'}), 200


# Endpoint for retrieving the currently authenticated user's profile
@app.route('/v1/api/user', methods=['GET'])
def get_user_profile():
token = request.headers.get('Authorization')
if not token or not validate_token(token):
return jsonify({'error': 'Invalid token'}), 401

# Get the user ID from the token
user_id = jwt.decode(token, app.config['SECRET_KEY'])['user_id']

user = get_user_by_id(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404

return jsonify({'user': user}), 200


# Endpoint for updating the currently authenticated user's profile
@app.route('/v1/api/user', methods=['PUT'])
def update_user_profile():
token = request.headers.get('Authorization')
if not token or not validate_token(token):
return jsonify({'error': 'Invalid token'}), 401

data = request.get_json()
name = data.get('name')
email = data.get('email')

if not name or not email:
return jsonify({'error': 'Missing name or email'}), 400

# Get the user ID from the token
user_id = jwt.decode(token, app.config['SECRET_KEY'])['user_id']

user = get_user_by_id(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404

user['name'] = name
user['email'] = email

return jsonify({'message': 'User profile updated successfully'}), 200


# Endpoint for deleting the currently authenticated user's profile
@app.route('/v1/api/user', methods=['DELETE'])
def delete_user_profile():
token = request.headers.get('Authorization')
if not token or not validate_token(token):
return jsonify({'error': 'Invalid token'}), 401

# Get the user ID from the token
user_id = jwt.decode(token, app.config['SECRET_KEY'])['user_id']

user = get_user_by_id(user_id)
if not user:
return jsonify({'error': 'User not found'}), 404

users.remove(user)

return jsonify({'message': 'User profile deleted successfully'}), 200


# Endpoint for retrieving a list of all users (requires admin access)
@app.route('/v1/api/users', methods=['GET'])
def get_all_users():
token = request.headers.get('Authorization')
if not token or not validate_token(token):
return jsonify({'error': 'Invalid token'}), 401

# Get the user ID from the token
user_id = jwt.decode(token, app.config['SECRET_KEY'])['user_id']

if not is_admin(user_id):
return jsonify({'error': 'Admin access required'}), 403

return jsonify({'users': users}), 200


if __name__ == '__main__':
app.run(port=8080)

API Documentation: User Management

Introduction: Welcome to the API documentation for the User Management system. This document provides an overview of the routes available in the API, along with their requirements and functionalities. The User Management API allows you to register new users, authenticate users, manage user profiles, and perform administrative tasks. By following this documentation, developers can integrate the API into their applications and leverage its features for user management.

API Routes:

  1. User Registration: Register a new user by providing the required information.
  2. User Login: Authenticate a user and obtain an access token for subsequent requests.
  3. User Logout: Log out the currently authenticated user.
  4. Request Password Reset: Initiate a password reset process by providing the user’s email address.
  5. Reset Password: Reset the password for a user using a password reset token.
  6. Get User Profile: Retrieve the profile of the currently authenticated user.
  7. Update User Profile: Update the profile of the currently authenticated user.
  8. Delete User Profile: Delete the profile of the currently authenticated user.
  9. Get All Users (Admin Access Required): Retrieve a list of all users (requires admin privileges).

Authentication: To access routes that require authentication, include the access token in the Authorization header of the request. The token should be provided in the format Bearer <token>, where <token> is obtained from the login endpoint.

Error Handling: In case of errors, the API will respond with appropriate error messages and status codes. Developers should handle these errors gracefully in their applications.

Security Considerations: Ensure that the API endpoints are accessed securely over HTTPS to protect sensitive user information. Safeguard the secret key used for token encoding and decoding. Implement additional security measures as per your application’s requirements.

User Registration

Endpoint: /v1/api/register
Method: POST
Description: Register a new user
Request Body:

  • email (string, required): The email address of the user.
  • password (string, required): The password for the user.
  • name (string, required): The name of the user.

User Login

Endpoint: /v1/api/login
Method: POST
Description: Authenticate a user and obtain an access token
Request Body:

  • email (string, required): The email address of the user.
  • password (string, required): The password for the user.

User Logout

Endpoint: /v1/api/logout
Method: POST
Description: Log out the currently authenticated user
Authorization Header: Bearer Token (obtained from successful login)

Request Password Reset

Endpoint: /v1/api/reset_password
Method: POST
Description: Request a password reset for a user
Request Body:

  • email (string, required): The email address of the user.

Reset Password

Endpoint: /v1/api/reset_password/<token>
Method: POST
Description: Reset the password for a user using a password reset token
Request Body:

  • password (string, required): The new password for the user.

Get User Profile

Endpoint: /v1/api/user
Method: GET
Description: Retrieve the profile of the currently authenticated user
Authorization Header: Bearer Token (obtained from successful login)

Update User Profile

Endpoint: /v1/api/user
Method: PUT
Description: Update the profile of the currently authenticated user
Authorization Header: Bearer Token (obtained from successful login)
Request Body:

  • name (string, required): The updated name of the user.
  • email (string, required): The updated email address of the user.

Delete User Profile

Endpoint: /v1/api/user
Method: DELETE
Description: Delete the profile of the currently authenticated user
Authorization Header: Bearer Token (obtained from successful login)

Get All Users (Admin Access Required)

Endpoint: /v1/api/users
Method: GET
Description: Retrieve a list of all users (requires admin access)
Authorization Header: Bearer Token (obtained from successful login with admin privileges)

Please note that for routes that require authentication, the Authorization header should be included in the request with the format Bearer <token>, where <token> is the access token obtained from the login endpoint.

Conclusion: The User Management API provides a set of routes to handle user registration, authentication, profile management, and administrative tasks. By following this documentation, developers can effectively utilize the API’s functionalities and integrate them into their applications. Please refer to the detailed route descriptions and requirements to interact with the API successfully.