# Path: apps/core/backends/sudo.py
# def sudo_password_needed(session: SessionBase) -> bool:
#     """
#     Check whether password reentry is necessary for sudo actions
#     """
#     timestamp = int(session.get(SUDO_SESSION_KEY, '0'))
#     time_diff = time.time() - timestamp
#     return time_diff >= SUDO_TIMEOUT_SEC or time_diff < 0
# 
# def sudo_renew(request) -> None:
#     """
#     Renew sudo session timeout
#     """
#     request.session[SUDO_SESSION_KEY] = time.time()


import logging
from functools import wraps
from django.contrib.auth.hashers import check_password
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect, render
from apps.core.backends.sudo import sudo_password_needed, sudo_renew




def _user_required(test_func, raise_error=False, redirect_to=''):
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            elif raise_error:
                raise PermissionDenied
            elif redirect_to:
                return redirect(redirect_to)
            return redirect('/')
        return _wrapped_view
    return decorator


# developer or sysop user is required; raise 403
def dev_required(view_func):
    return _user_required(
        lambda u: u.profile.flags['dev'],
        raise_error=True,

# Path: apps/core/backends/sudo.py
# def sudo_password_needed(session: SessionBase) -> bool:
#     """
#     Check whether password reentry is necessary for sudo actions
#     """
#     timestamp = int(session.get(SUDO_SESSION_KEY, '0'))
#     time_diff = time.time() - timestamp
#     return time_diff >= SUDO_TIMEOUT_SEC or time_diff < 0
# 
# def sudo_renew(request) -> None:
#     """
#     Renew sudo session timeout
#     """
#     request.session[SUDO_SESSION_KEY] = time.time()


# Path: apps/core/backends/decorator.py
import logging
from functools import wraps
from django.contrib.auth.hashers import check_password
from django.core.exceptions import PermissionDenied
from django.shortcuts import redirect, render
from apps.core.backends.sudo import sudo_password_needed, sudo_renew





def _user_required(test_func, raise_error=False, redirect_to=''):
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            elif raise_error:
                raise PermissionDenied
            elif redirect_to:
                return redirect(redirect_to)
            return redirect('/')
        return _wrapped_view
    return decorator


# developer or sysop user is required; raise 403
def dev_required(view_func):
    return _user_required(
        lambda u: u.profile.flags['dev'],
        raise_error=True,

    )(view_func)