import ldap
import kerberos
import flask
import flask_wtf

from webapp import app, context, config
from webapp.auth import login_required

bp = flask.Blueprint('passwd', __name__)

@bp.route('/passwd', methods=["GET"])
@login_required
def passwd_form():
    return flask.render_template('passwd.html')

def _passwd_kadmin(current, new):
    username = flask.session.get('username')
    try:
        principal_name = config.kadmin_principal_map.format(username)
        return kerberos.changePassword(principal_name, current, new)
    except Exception as e:
        print('Kerberos error:', e)
        logging.exception('kpasswd failed')
        return False

@bp.route('/passwd', methods=["POST"])
@login_required
def passwd_action():
    current, new, confirm = (flask.request.form[n] for n in ('current', 'new', 'confirm'))
    if new != confirm:
        flask.flash("New passwords don't match", category='danger')
        return flask.render_template('passwd.html')

    if _passwd_kadmin(current, new):
        flask.flash('Password changed', category='info')
    else:
        flask.flash('Wrong password', category='danger')
    return flask.render_template('passwd.html')
