feat: implement user management with roles and last login tracking

This commit is contained in:
Manuel Weiser 2024-09-02 10:32:26 +02:00
parent 58254c4973
commit 069b318f0b
4 changed files with 52 additions and 1 deletions

View File

@ -2,6 +2,7 @@ from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from database import init_db
from models import db, Game
from user_management import user_bp
import os
from datetime import datetime
@ -42,6 +43,8 @@ def get_games():
'owned': game.owned
} for game in games])
app.register_blueprint(user_bp) # Register the user management blueprint
if __name__ == '__main__':
with app.app_context():
init_db() # Ensure the database is initialized when the app starts

View File

@ -24,7 +24,9 @@ def init_db():
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
password TEXT NOT NULL,
role TEXT NOT NULL CHECK(role IN ('user', 'admin')),
last_login TEXT
)
''')

View File

@ -10,3 +10,11 @@ class Game(db.Model):
date = db.Column(db.String(10), nullable=False) # Ensure date is not nullable
buyer = db.Column(db.String(100))
owned = db.Column(db.Boolean, nullable=False)
class User(db.Model):
__tablename__ = 'users' # Ensure the table name is set to 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False, unique=True)
password = db.Column(db.String(100), nullable=False)
role = db.Column(db.String(10), nullable=False) # 'user' or 'admin'
last_login = db.Column(db.String(20), nullable=True) # Last login timestamp

View File

@ -0,0 +1,38 @@
from flask import Blueprint, request, jsonify
from models import db, User
from datetime import datetime
user_bp = Blueprint('user', __name__)
@user_bp.route('/users', methods=['POST'])
def create_user():
data = request.json
new_user = User(
username=data['username'],
password=data['password'],
role=data.get('role', 'user'), # Default role is 'user'
last_login=None
)
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'User created!'}), 201
@user_bp.route('/users/login', methods=['POST'])
def login_user():
data = request.json
user = User.query.filter_by(username=data['username'], password=data['password']).first()
if user:
user.last_login = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
db.session.commit()
return jsonify({'message': 'Login successful!', 'role': user.role}), 200
return jsonify({'message': 'Invalid credentials!'}), 401
@user_bp.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{
'id': user.id,
'username': user.username,
'role': user.role,
'last_login': user.last_login
} for user in users])