# -*- coding: utf-8 -*-
import logging

from pylons import url, request, session, tmpl_context as c
from pylons.controllers.util import redirect_to

from {{package}}.lib.base import BaseController, render

log = logging.getLogger(__name__)

from {{package}} import model as model
from {{package}}.lib.helpers import dcmeta
from {{package}}.lib import auth

class LoginController(BaseController):
    
    "A stub example login controller, with login and logout methods"
    
    def __before__(self):
        c.dcmeta = dcmeta(title="Admin")
    
    def index(self):
        # add your login form here
        c.title = "login to {{package}}"
        return render('signin.mak')
    
    def signin(self):
        username = request.params.get('username')
        password = request.params.get('password')
        log.debug("Login form username: %s, password %s" % \
                                            (username, password))
        try:
            log.debug("Authenticating user %s" % username)
            user = model.User.authenticate(username, password)
            if user:
                log.debug("User %s is authenticated" % username)
            else:
                log.debug("User %s is NOT authenticated" % username)
            auth.login(user)
            if session.get('redirect'):
                redir_url = session.pop('redirect')
                session.save()
                redirect_to(**redir_url)
            else:
                redirect_to(controller='dashboard', action='index')
        except model.NotAuthenticated:
            # if the user visiting this controller is not 
            # authenticated the user is routed to the index
            # (above) which presents a login form.
            redirect_to(url.current(action='index'))
    
    def signout(self):
        auth.logout()
        redirect_to(url.current(action='index'))
    
