### 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')
slug = require('slug')
sha1 = require('./helper').hash('sha1')
forms = require("./forms")
config = require('./config')
db = require('./db')

class LoginFormStrategy
    constructor: () ->
        @name = "login_form"

    authenticate: (user, passphrase, callback) =>
        id = "user/#{user}"
        db.get [id], (err, res) =>
            error = err or res[0].error
            return callback(error) if error
            password = res[0].doc?.passphrase
            return callback("wrong-pass") if (passphrase.password !=
                sha1.hash(passphrase.session + password))
            callback(null)

    # connect-auth api

    basic: (option) =>
        (user, password, success, fail) =>
            user = slug(user)
            passphrase =
                session: "basic"
                password: (sha1.hash("basic" + sha1.hash(
                    config.salt.public + user + password)))
            @authenticate user, passphrase, (err) ->
                if err == null then success() else fail(err if option?.error)

    strategy: (redirect_url) =>
        my = this

        validate = (req, res, callback) ->
            passphrase = req.form.clear_data(req)
            my.authenticate passphrase.user, passphrase, (err) =>
                return @fail(callback) if err
                @success({ name:passphrase.user }, callback)

        fail = (req, res) ->
            req.flash('warn', gt._("invalid data"))
            res.redirect(req.query.redirect_url or redirect_url or "/", 303)

        return name:@name, authenticate: (req, res, callback) ->
            req.form = forms.login(req, res).bind(req.body)
            req.form.validate((err) ->)
            req.form.post_validate?()
            if req.form.isValid()
                action = validate
            else
                action = fail
            action.call(this, req, res, callback)



# exports

module.exports = new LoginFormStrategy()
