73 lines
No EOL
2.4 KiB
Python
73 lines
No EOL
2.4 KiB
Python
from flask import Blueprint, request, jsonify, session
|
|
from extensions import db
|
|
from models.user import User
|
|
from models.banned_ip import BannedIP
|
|
|
|
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')
|
|
|
|
@auth_bp.route('/register', methods=['POST'])
|
|
def register():
|
|
data = request.get_json()
|
|
email = data.get('email')
|
|
ip_address = request.remote_addr
|
|
|
|
if BannedIP.query.filter_by(ip_address=ip_address).first():
|
|
return jsonify({'error': 'Registration blocked from this IP address.'}), 403
|
|
|
|
password = data.get('password')
|
|
first_name = data.get('first_name')
|
|
last_name = data.get('last_name')
|
|
|
|
if not email or not password or not first_name or not last_name:
|
|
return jsonify({'error': 'All fields are required'}), 400
|
|
|
|
if User.query.filter_by(email=email).first():
|
|
return jsonify({'error': 'Email already exists'}), 400
|
|
|
|
new_user = User(email=email, first_name=first_name, last_name=last_name, last_ip=ip_address)
|
|
new_user.set_password(password)
|
|
|
|
db.session.add(new_user)
|
|
db.session.commit()
|
|
|
|
return jsonify({'message': 'User registered successfully'}), 201
|
|
|
|
@auth_bp.route('/login', methods=['POST'])
|
|
def login():
|
|
data = request.get_json()
|
|
email = data.get('email')
|
|
password = data.get('password')
|
|
ip_address = request.remote_addr
|
|
|
|
if BannedIP.query.filter_by(ip_address=ip_address).first():
|
|
return jsonify({'error': 'Login blocked from this IP address.'}), 403
|
|
|
|
user = User.query.filter_by(email=email).first()
|
|
|
|
if user and user.check_password(password):
|
|
if user.is_banned:
|
|
return jsonify({'error': 'This account has been banned.'}), 403
|
|
|
|
user.last_ip = ip_address
|
|
db.session.commit()
|
|
session.permanent = True
|
|
session['user_id'] = user.id
|
|
return jsonify({'message': 'Login successful', 'user': user.to_dict()}), 200
|
|
|
|
return jsonify({'error': 'Invalid username or password'}), 401
|
|
|
|
@auth_bp.route('/logout', methods=['POST'])
|
|
def logout():
|
|
session.pop('user_id', None)
|
|
return jsonify({'message': 'Logged out'}), 200
|
|
|
|
@auth_bp.route('/me', methods=['GET'])
|
|
def get_current_user():
|
|
user_id = session.get('user_id')
|
|
if not user_id:
|
|
return jsonify({'authenticated': False}), 200
|
|
|
|
user = User.query.get(user_id)
|
|
if user:
|
|
return jsonify({'authenticated': True, 'user': user.to_dict()}), 200
|
|
return jsonify({'authenticated': False}), 200 |