
from pyramid.view import view_config
from pyramid.security import remember, forget
from pyramid.httpexceptions import HTTPFound
from .models import User

@view_config(route_name='auth', match_param="action=login", renderer="jm2l:templates/login.mako")
def login(request):
    return {}

@view_config(route_name='bymail', renderer="string")    
def bymail(request):
    myhash = request.matchdict.get('hash', "")
    user = User.by_hash(myhash)
    if user:
        headers = remember(request, user.uid)
        return HTTPFound(location=request.route_url('jm2l'),
                            headers=headers)
    else:
        headers = forget(request)
    return HTTPFound(location=request.route_url('auth', action='login'),
                     headers=headers)

@view_config(route_name='auth', match_param="action=in", renderer="string",
             request_method="POST")
@view_config(route_name='auth', match_param="action=out", renderer="string")
def sign_in_out(request):
    username = request.POST.get('username')
    if username:
        user = User.by_name(username)
        if user and user.verify_password(request.POST.get('password')):
            headers = remember(request, user.uid)
            return HTTPFound(location=request.route_url('jm2l'),
                             headers=headers)
        else:
            headers = forget(request)
    else:
        headers = forget(request)
    return HTTPFound(location=request.route_url('home'),
                     headers=headers)


