from pylons import request, session
from pylons.controllers.util import redirect_to
from {{package}} import model as model

_login_url = '/login'
_auth_user_environ_key = 'AUTH_USER'
_auth_user_session_key = 'AUTH_USER_ID'

def get_user():
    if _auth_user_environ_key not in request.environ:
        user_id = session.get(_auth_user_session_key)
        if user_id:
            # Get by URIRef'ing the string value of user_id.
            # The resulting URI is matched directly in the graph.
            # No need to match ids across multiple tables.
            request.environ[_auth_user_environ_key] = \
                                    User(URIRef(user_id))
        else:
            request.environ[_auth_user_environ_key] = None
    return request.environ[_auth_user_environ_key]

def login(user):
    session[_auth_user_session_key] = str(user.resUri)
    session.save()

def logout():
    session.pop(_auth_user_session_key, None)
    session.clear()
    session.delete()

def redirect_to_login():
    redirect_to(controller=_login_url)

