### codetube
    Copyright (C) 2011 payload payload@lavabit.com
    Copyright (C) 2011 dodo dodo.the.last@gmail.com

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
###

gt = require('gettext')
appconfig = require('../appconfig')
HelperRoutes = require('./main')
config = require('../config')
Controller = require('./skeleton')
forms = require('../forms')

router = null
process.nextTick ->
    router = require('../routes')

class Authentications extends Controller

    constructor: () ->
        super
        @registration = config.users.registration

    register: (req, res) =>
        unless @registration
            req.flash('warn', gt._("registration disabled"))
            return @home(req, res)
        if @logged_in(req, gt._("already registered"))
            return @home(req, res)
        req.form or= forms.register(req, res).bind()
        req.form.action = router.controller.authentication.register.url()
        @render req, res, 'register', form: req.form

    login: (req, res) =>
        if @logged_in(req)
            return @home(req, res)
        req.form or= forms.login(req, res).bind()
        req.form.action = router.controller.authentication.login.url()
        @render req, res, 'login', form: req.form

    login_post: (req, res) =>
        req.authenticate ['login_form'], (err, authed) =>
            # XXX should be debug print? cause login failed is enough as answer
            req.flash('error', err) if err
            if authed
                req.flash('ok', gt._("login successful"))
                res.redirect(@home.url())
            else
                req.flash('error', gt._("login failed"))
                @login(req, res)

    logout: (req, res) =>
        if req.user
            req.logout()
            req.flash('ok', gt._("logout successful"))
        else
            req.flash('warn', gt._("not logged in"))
        res.redirect(@home.url())

# exports

module.exports = Authentications

