Coverage for yaptide/routes/utils/decorators.py: 83%

24 statements  

« prev     ^ index     » next       coverage.py v7.6.4, created at 2024-11-22 07:31 +0000

1from functools import wraps 

2from typing import Union 

3 

4from flask import request 

5from werkzeug.exceptions import Forbidden, Unauthorized 

6 

7from yaptide.persistence.db_methods import fetch_user_by_id 

8from yaptide.routes.utils.tokens import decode_auth_token 

9 

10 

11def requires_auth(is_refresh: bool = False): 

12 """Decorator for auth requirements""" 

13 def decorator(f): 

14 """Determines if the access or refresh token is valid""" 

15 @wraps(f) 

16 def wrapper(*args, **kwargs): 

17 token: str = request.cookies.get('refresh_token' if is_refresh else 'access_token') 

18 if not token: 

19 raise Unauthorized(description="No token provided") 

20 resp: Union[int, str] = decode_auth_token(token=token, is_refresh=is_refresh) 

21 if isinstance(resp, int): 

22 user = fetch_user_by_id(user_id=resp) 

23 if user: 

24 return f(user, *args, **kwargs) 

25 raise Forbidden(description="User not found") 

26 if is_refresh: 

27 raise Forbidden(description=f"Log in again. {resp}") 

28 raise Forbidden(description=f"Refresh access token. {resp}") 

29 return wrapper 

30 return decorator