Create auth/authentication.py
Browse files- auth/authentication.py +79 -0
auth/authentication.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import jwt
|
| 2 |
+
import datetime
|
| 3 |
+
from werkzeug.security import generate_password_hash, check_password_hash
|
| 4 |
+
from flask import request, jsonify, current_app
|
| 5 |
+
from functools import wraps
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
class Authentication:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.secret_key = os.getenv('JWT_SECRET_KEY', 'your-secret-key-here')
|
| 11 |
+
self.algorithm = 'HS256'
|
| 12 |
+
|
| 13 |
+
def generate_token(self, user_id, username, role='student'):
|
| 14 |
+
"""تولید توکن JWT"""
|
| 15 |
+
try:
|
| 16 |
+
payload = {
|
| 17 |
+
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7),
|
| 18 |
+
'iat': datetime.datetime.utcnow(),
|
| 19 |
+
'sub': user_id,
|
| 20 |
+
'username': username,
|
| 21 |
+
'role': role
|
| 22 |
+
}
|
| 23 |
+
return jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Token generation error: {e}")
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
def verify_token(self, token):
|
| 29 |
+
"""اعتبارسنجی توکن JWT"""
|
| 30 |
+
try:
|
| 31 |
+
payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
|
| 32 |
+
return payload
|
| 33 |
+
except jwt.ExpiredSignatureError:
|
| 34 |
+
print("Token expired")
|
| 35 |
+
return None
|
| 36 |
+
except jwt.InvalidTokenError:
|
| 37 |
+
print("Invalid token")
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
def hash_password(self, password):
|
| 41 |
+
"""هش کردن رمز عبور"""
|
| 42 |
+
return generate_password_hash(password)
|
| 43 |
+
|
| 44 |
+
def check_password(self, hashed_password, password):
|
| 45 |
+
"""بررسی تطابق رمز عبور"""
|
| 46 |
+
return check_password_hash(hashed_password, password)
|
| 47 |
+
|
| 48 |
+
def login_required(self, f):
|
| 49 |
+
"""دکوراتور برای نیاز به احراز هویت"""
|
| 50 |
+
@wraps(f)
|
| 51 |
+
def decorated(*args, **kwargs):
|
| 52 |
+
token = None
|
| 53 |
+
|
| 54 |
+
# دریافت توکن از هدر
|
| 55 |
+
if 'Authorization' in request.headers:
|
| 56 |
+
auth_header = request.headers['Authorization']
|
| 57 |
+
try:
|
| 58 |
+
token = auth_header.split(" ")[1]
|
| 59 |
+
except IndexError:
|
| 60 |
+
return jsonify({'message': 'Invalid token format'}), 401
|
| 61 |
+
|
| 62 |
+
if not token:
|
| 63 |
+
return jsonify({'message': 'Token is missing'}), 401
|
| 64 |
+
|
| 65 |
+
# اعتبارسنجی توکن
|
| 66 |
+
payload = self.verify_token(token)
|
| 67 |
+
if not payload:
|
| 68 |
+
return jsonify({'message': 'Invalid token'}), 401
|
| 69 |
+
|
| 70 |
+
# ذخیره اطلاعات کاربر در request
|
| 71 |
+
request.user_id = payload['sub']
|
| 72 |
+
request.username = payload['username']
|
| 73 |
+
request.user_role = payload['role']
|
| 74 |
+
|
| 75 |
+
return f(*args, **kwargs)
|
| 76 |
+
return decorated
|
| 77 |
+
|
| 78 |
+
# نمونه singleton
|
| 79 |
+
auth_manager = Authentication()
|