CodingNic

Final Capstone Project

User Authentication System

Final Capstone Project 55 min read

User Authentication System

User Authentication System

Now you will build the first real feature of your application: user accounts.

This allows users to:

  • register
  • log in
  • store personal data

All future features (tasks, expenses) will be linked to a user.


Goal of This Lesson

By the end of this lesson, you will:

  • create user registration
  • create login functionality
  • store users in the database
  • validate user input

Step 1: Create User Service File

Create:

text
app/services/user_service.py

Step 2: Import Database Connection

python
from app.services.database import connect

Step 3: Create Register Function

python
def register_user(username, password):
    conn = connect()
    cursor = conn.cursor()

    try:
        cursor.execute(
            "INSERT INTO users (username, password) VALUES (?, ?)",
            (username, password)
        )
        conn.commit()
        return True
    except:
        return False
    finally:
        conn.close()

What This Does

  • inserts a new user
  • prevents duplicate usernames (because of UNIQUE constraint)
  • returns True if successful
  • returns False if user already exists

Step 4: Create Login Function

python
def login_user(username, password):
    conn = connect()
    cursor = conn.cursor()

    cursor.execute(
        "SELECT id FROM users WHERE username = ? AND password = ?",
        (username, password)
    )

    result = cursor.fetchone()
    conn.close()

    if result:
        return result[0]  # user_id
    else:
        return None

What This Does

  • checks if username/password match
  • returns user id if valid
  • returns None if invalid

Step 5: Test in main.py

Update main.py:

python
from app.services.database import create_tables
from app.services.user_service import register_user, login_user

def main():
    create_tables()

    # test register
    print(register_user("tom", "123"))

    # test login
    user_id = login_user("tom", "123")
    print("Logged in user:", user_id)

if __name__ == "__main__":
    main()

Expected Output

text
True
Logged in user: 1

Important Behavior

Duplicate User

python
register_user("tom", "123")

Second attempt returns:

text
False

Important Notes

  • Passwords are stored as plain text (for now)
  • This is okay for learning, but not secure for real apps
  • You will improve this later if needed

Why This Step Matters

User authentication is the base of your system.

Everything else will depend on:

text
user_id

Tasks and expenses will belong to a user.


Clean Structure So Far

text
app/
    services/
        database.py
        user_service.py

Summary

You built a working user system with registration and login, connected to your database.

Your app can now identify and manage users.