-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.py
More file actions
58 lines (43 loc) · 1.79 KB
/
auth.py
File metadata and controls
58 lines (43 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import os
from functools import wraps
from flask import request
import models # Import the module, not the variable
def check_token():
"""Helper function to check if the token is valid"""
# Get the token from environment variable
expected_token = os.environ.get('TODO_TOKEN')
if not expected_token:
return False, {'message': 'Server configuration error: TOKEN not set'}, 500
# Get the token from the Authorization header
auth_header = request.headers.get('Authorization')
if not auth_header:
return False, {'message': 'Authorization header is missing'}, 401
# Check if the header format is correct (Bearer token)
parts = auth_header.split()
if len(parts) != 2 or parts[0].lower() != 'bearer':
return False, {'message': 'Authorization header must be in format: Bearer TOKEN'}, 401
token = parts[1]
# Verify the token
if token != expected_token:
return False, {'message': 'Invalid token'}, 401
return True, None, None
def token_required(f):
"""Decorator for endpoints that require authentication only in private mode"""
@wraps(f)
def decorated(*args, **kwargs):
# If private mode is enabled, check authentication
if models.private_mode: # Access the variable through the module
is_valid, error_message, error_code = check_token()
if not is_valid:
return error_message, error_code
return f(*args, **kwargs)
return decorated
def auth_required(f):
"""Decorator for endpoints that always require authentication"""
@wraps(f)
def decorated(*args, **kwargs):
is_valid, error_message, error_code = check_token()
if not is_valid:
return error_message, error_code
return f(*args, **kwargs)
return decorated