from functools import wraps
from flask import g, jsonify, request, redirect, url_for


def require_login(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        # todo: avoid using g.
        if g.get("account") is None:
            if "/api" in request.path:
                # kinda ugly but avoid redirecting non-html requests
                return {}, 401
            else:
                return redirect(url_for("account.get_login", location=request.path))
        kwargs["user"] = kwargs.get("user", g.account)
        return f(*args, **kwargs)
    return wrapper
