from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import search  
import forms
import views

# decorator TODO Find out where these should go normally.
def login_required(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user:
            return func(request, *args, **kw)
        else:
            return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

    return _wrapper

def authorized(role):
    """
    A decorator to enforce user roles, currently 'user' (logged in) 
    'admin' and owner of the object.
    """
    def _wrapper(func):

      def check_login(*args, **kwargs):
        user = users.get_current_user()
        is_admin = users.is_current_user_admin()
        roles = [x.strip() for x in role.split(",")]
        obj = args[0]
        request = args[1]
        if not user:
          return views.HttpResponseRedirect(users.create_login_url(request.get_full_path()))
        else:
          if "admin" in roles:
            if (is_admin):
              return func(*args, **kwargs)
          if "owner" in roles:
            if (user == obj.owner):
              return func(*args, **kwargs)
          if "user" in roles:
            return func(*args, **kwargs)
          else:
            return views.HttpResponseRedirect("/403")

      return check_login
    return _wrapper

