Activity 42: Documentation of Python Flask hash

Documentation of Activity 41: Python Flask Hash

Introduction to Hashing

In this activity, I explored the critical concept of hashing, a fundamental practice for securing sensitive information, particularly passwords. Hashing is a process that transforms data into a fixed-size string of characters, which serves as a hash code.

This ensures that even if someone gains unauthorized access to hashed data, they cannot easily retrieve the original information. The use of hashes is essential for maintaining user security and data integrity in applications that handle login credentials.

Importance of Hashing

  • Security: Hashing protects user passwords, ensuring that even if a database is compromised, attackers cannot retrieve original passwords from their hashes.

  • Data Integrity: Hashes can be used to verify that data has not been altered. If the hash of data changes, it indicates that the data has been modified.

  • Efficiency: Hashing allows for quick data retrieval, enhancing the speed of verifying passwords during login attempts.

Activity 41: Python Flask Hash Implementation

In this activity, I set up a Flask application to manage hashing for user registration and login. Below is a step-by-step guide detailing my implementation process.

Step 1: Set Up Your Flask Project

  1. Create a New Project Folder:

      mkdir nicolas_python_flask_hash
      cd nicolas_python_flask_hash
    
  2. Set Up a Virtual Environment and Install Flask:

      python -m venv venv
      venv\Scripts\activate     # For Windows
      pip install Flask
    
  3. Install Additional Libraries: To handle password hashing, I installed the werkzeug library, which is included with Flask but may require an update:

      pip install -U Werkzeug
    

Step 2: Create the Main Application File

  1. Create a File Named app.py: This file contains the necessary code for the Flask application.

  2. Import Required Modules: At the beginning of app.py, I imported the necessary modules to handle HTTP requests and password hashing.

      from flask import Flask, request, jsonify
      from werkzeug.security import generate_password_hash, check_password_hash
    
  3. Initialize the Flask App: I created an instance of the Flask application.

      app = Flask(__name__)
    
  4. Simulate a Database: For demonstration purposes, I created a dictionary called users_db to simulate a database for storing usernames and hashed passwords.

      users_db = {}
    

Step 3: Define the Routes

  1. Define the /sethash Route: This route allows users to register by hashing their password.

      @app.route('/sethash', methods=['POST'])
      def set_hash():
          username = request.json.get('username')
          password = request.json.get('password')
          hashed_password = generate_password_hash(password)
          users_db[username] = hashed_password
          return jsonify({"message": f"User {username} registered successfully with hashed password!"}), 201
    
  2. Define the /gethash Route: This route retrieves the hashed password for a given username.

      @app.route('/gethash', methods=['GET'])
      def get_hash():
          username = request.args.get('username')
          if username in users_db:
              return jsonify({"username": username, "hashed_password": users_db[username]}), 200
          return jsonify({"message": "User not found!"}), 404
    
  3. Define the /register Route: This route provides instructions for user registration.

      @app.route('/register', methods=['GET'])
      def register():
          return jsonify({"message": "Please use POST /sethash with a username and password to register."})
    
  4. Define the /login Route: This route allows users to log in by verifying their credentials.

      @app.route('/login', methods=['GET'])
      def login():
          username = request.args.get('username')
          password = request.args.get('password')
          if username in users_db and check_password_hash(users_db[username], password):
              return jsonify({"message": f"Welcome, {username}!"}), 200
          return jsonify({"message": "Invalid username or password!"}), 401
    

Step 4: Run the Application

At the end of the app.py file, I included code to run the Flask application with debug mode enabled.

if __name__ == '__main__':
    app.run(debug=True)

Step 5: Explanation of Routes

  • POST /sethash: Accepts a JSON payload to register a user with a hashed password.

  • GET /gethash: Retrieves the hashed password for a specified username.

  • GET /register: Provides instructions on how to register using the /sethash route.

  • GET /login: Verifies user credentials against the stored hashed password.

Step 6: Testing the Application

  1. Run the Flask Application:

      python app.py
    
  2. Use Postman to Test the Endpoints:

    • Register a New User:

          POST http://127.0.0.1:5000/sethash
          Content-Type: application/json
          Body: {"username": "testuser", "password": "testpassword"}
      

    • Retrieve the Hash for a User:

          GET http://127.0.0.1:5000/gethash?username=testuser
      

    • Log In as a User:

          GET http://127.0.0.1:5000/login?username=testuser&password=testpassword
      

Step 7: Initialize Git and Push to GitHub

To finalize my project, I initialized a Git repository and pushed my code to GitHub:

bashCopy codegit init
git add .
git commit -m "Initial commit for Python Flask hash implementation"
git remote add origin https://github.com/MonetForProgrammingPurposes/nicolas_python_flask_hash.git
git branch -M master
git push -u origin master

This documentation reflects my work on implementing hashing in a Flask application.