#!/usr/bin/env python3

import logging

from flask import current_app, flash, redirect
from tentacles.globals import ctx


log = logging.getLogger(__name__)


def is_logged_in() -> bool:
    return ctx.uid is not None


def salt(password: str) -> str:
    return "$SALT$" + current_app.config["SECRET_KEY"] + password


def requires_admin(f):
    def _helper(*args, **kwargs):
        if not ctx.is_admin:
            flash("Sorry, admins only", category="error")
            return redirect("/")
        else:
            return f(*args, **kwargs)

    _helper.__name__ = f.__name__
    return _helper


def requires_auth(f):
    def _helper(*args, **kwargs):
        if not ctx.uid:
            flash("Please log in first", category="error")
            return redirect("/")
        else:
            return f(*args, **kwargs)

    _helper.__name__ = f.__name__
    return _helper
