#!/usr/bin/env python3 """ Validates and handles forms. """ from passlib.hash import argon2 import config async def change_password(request, user_data): """Changes the email account password.""" user_id = int(request.cookies.get('userid')) data = await request.post() current_password = data.get('current_password', '') new_password = data.get('new_password', '') verify_new_password = data.get('verify_new_password', '') if not argon2.verify(current_password, user_data['password']): result = { 'ok': False, 'message': "Current password does not match." } return result if new_password != verify_new_password: result = { 'ok': False, 'message': "New passwords do not match." } return result if len(new_password) > config.max_password: result = { 'ok': False, 'message': "Maximum password length is 1024 characters." } return result if len(new_password) < config.min_password: result = { 'ok': False, 'message': "Minimum password length is 8 characters." } return result pw_hash = argon2.hash(new_password) async with request.app['pool'].acquire() as conn: await conn.fetch( "UPDATE virtual_users SET password = $1 WHERE buckler_id = $2", pw_hash, user_id) result = { 'ok': True, 'message': "Password has been changed." } return result async def new_email(request): """Add a new email address.""" user_id = int(request.cookies.get('userid')) data = await request.post() new_password = data.get('new_password', '') verify_new_password = data.get('verify_new_password', '') if new_password != verify_new_password: result = { 'ok': False, 'message': "New passwords do not match." } return result if len(new_password) > config.max_password: result = { 'ok': False, 'message': "Maximum password length is 1024 characters." } return result if len(new_password) < config.min_password: result = { 'ok': False, 'message': "Minimum password length is 8 characters." } return result pw_hash = argon2.hash(new_password) email = request['meta']['username'] + '@' + config.server_domain async with request.app['pool'].acquire() as conn: await conn.execute( "INSERT INTO virtual_users " "(domain_id, password, email, buckler_id) " "VALUES (1, $1, $2, $3)", pw_hash, email, user_id) result = { 'ok': True, 'message': "New email account has been created." } return result