138 lines
3.9 KiB
Python
138 lines
3.9 KiB
Python
# backend/routes/auth.py
|
|
from flask import Blueprint, request, jsonify
|
|
from datetime import datetime, timedelta
|
|
import bcrypt
|
|
import jwt
|
|
|
|
from ..db import get_db_connection, release_db_connection
|
|
from ..middleware import SECRET_KEY, token_required
|
|
|
|
auth_blueprint = Blueprint('auth', __name__)
|
|
|
|
@auth_blueprint.route('/auth/register', methods=['POST'])
|
|
def register():
|
|
"""
|
|
Регистрация нового пользователя
|
|
---
|
|
tags:
|
|
- Auth
|
|
parameters:
|
|
- name: body
|
|
in: body
|
|
required: true
|
|
schema:
|
|
type: object
|
|
properties:
|
|
username:
|
|
type: string
|
|
password:
|
|
type: string
|
|
responses:
|
|
201:
|
|
description: Пользователь успешно зарегистрирован
|
|
"""
|
|
data = request.json
|
|
username = data.get('username')
|
|
password = data.get('password')
|
|
|
|
if not username or not password:
|
|
return jsonify({"error": "Username and password are required"}), 400
|
|
|
|
conn = get_db_connection()
|
|
cur = conn.cursor()
|
|
|
|
# Check if exists
|
|
cur.execute("SELECT id FROM users WHERE username = %s", (username,))
|
|
if cur.fetchone():
|
|
release_db_connection(conn)
|
|
return jsonify({"error": "Username already exists"}), 400
|
|
|
|
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
|
|
|
cur.execute(
|
|
"INSERT INTO users (username, password_hash) VALUES (%s, %s) RETURNING id",
|
|
(username, hashed_password)
|
|
)
|
|
user_id = cur.fetchone()[0]
|
|
conn.commit()
|
|
release_db_connection(conn)
|
|
|
|
return jsonify({"message": "User registered successfully", "user_id": user_id}), 201
|
|
|
|
@auth_blueprint.route('/auth/login', methods=['POST'])
|
|
def login():
|
|
"""
|
|
Вход в систему
|
|
---
|
|
tags:
|
|
- Auth
|
|
parameters:
|
|
- name: body
|
|
in: body
|
|
required: true
|
|
schema:
|
|
type: object
|
|
properties:
|
|
username:
|
|
type: string
|
|
password:
|
|
type: string
|
|
responses:
|
|
200:
|
|
description: Токен успешно сгенерирован
|
|
schema:
|
|
properties:
|
|
token:
|
|
type: string
|
|
"""
|
|
data = request.json
|
|
username = data.get('username')
|
|
password = data.get('password')
|
|
|
|
conn = get_db_connection()
|
|
cur = conn.cursor()
|
|
cur.execute("SELECT id, password_hash FROM users WHERE username = %s", (username,))
|
|
user = cur.fetchone()
|
|
release_db_connection(conn)
|
|
|
|
if not user or not bcrypt.checkpw(password.encode('utf-8'), user[1].encode('utf-8')):
|
|
return jsonify({"error": "Invalid credentials"}), 401
|
|
|
|
token = jwt.encode({
|
|
'user_id': user[0],
|
|
'exp': datetime.utcnow() + timedelta(days=7)
|
|
}, SECRET_KEY, algorithm="HS256")
|
|
|
|
# --- AUDIT LOG ---
|
|
from ..utils.audit_utils import log_action
|
|
log_action(user[0], 'LOGIN', {'ip': request.remote_addr})
|
|
# -----------------
|
|
|
|
return jsonify({"token": token})
|
|
|
|
@auth_blueprint.route('/auth/me', methods=['GET'])
|
|
@token_required
|
|
def get_me(current_user_id):
|
|
conn = get_db_connection()
|
|
cur = conn.cursor()
|
|
cur.execute("SELECT id, username, plan FROM users WHERE id = %s", (current_user_id,))
|
|
user = cur.fetchone()
|
|
release_db_connection(conn)
|
|
|
|
if not user:
|
|
return jsonify({"error": "User not found"}), 404
|
|
|
|
return jsonify({"id": user[0], "username": user[1], "plan": user[2]})
|
|
|
|
@auth_blueprint.route('/auth/upgrade', methods=['POST'])
|
|
@token_required
|
|
def upgrade_plan(current_user_id):
|
|
"""Simulates payment success and upgrades to PRO."""
|
|
conn = get_db_connection()
|
|
cur = conn.cursor()
|
|
cur.execute("UPDATE users SET plan = 'pro' WHERE id = %s", (current_user_id,))
|
|
conn.commit()
|
|
release_db_connection(conn)
|
|
|
|
return jsonify({"message": "Successfully upgraded to PRO"}), 200
|