# Path: rhizi/crypt_util.py
# def hash_pw(pw_str, salt_str):
#     salt = hashlib.sha512(salt_str.encode('utf-8')).hexdigest()
#     ret = hashlib.sha512((pw_str + salt).encode('utf-8')).hexdigest()
#     return ret
# 
# Path: rhizi/rz_mail.py
# def send_email__flask_ctx(recipients, subject, body, attachments=[]):
#     """
#     Flask context dependent email sending utility
#     """
# 
#     send_from = current_app.rz_config.mail_default_sender
#     mta_host = current_app.rz_config.mta_host
#     mta_port = current_app.rz_config.mta_port
# 
#     send_email(mta_host,
#                         mta_port,
#                         send_from=send_from,
#                         recipients=recipients,
#                         subject=subject,
#                         attachments=attachments,
#                         body=body)
# 
#     log.info('email sent: recipients: %s: subject: %s, attachment-count: %d' % (recipients, subject, len(attachments)))
# 
# Path: rhizi/rz_req_handling.py
# def make_response__json(status=200, data={}):
#     """
#     Construct a json response with proper content-type header
# 
#     @param data: must be serializable via json.dumps
#     """
#     data_str = json.dumps(data)
#     resp = make_response(data_str)
#     resp.headers['Content-Type'] = "application/json"
#     resp.status = str(status)
# 
#     return resp
# 
# def make_response__json__html(status=200, html_str=''):
#     """
#     Construct a json response with HTML payload
#     """
#     return make_response__json(status=status, data={'response__html': html_str })
# 
# HTTP_STATUS__400_BAD_REQUEST = 400
# 
# HTTP_STATUS__500_INTERNAL_SERVER_ERROR = 500
# 
# HTTP_STATUS__200_OK = 200
# 
# HTTP_STATUS__401_UNAUTORIZED = 401


from datetime import datetime
from datetime import timedelta
from flask import current_app
from flask import make_response
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from .crypt_util import hash_pw
from .rz_api_common import API_Exception__bad_request
from .rz_mail import send_email__flask_ctx
from .rz_req_handling import (make_response__json, make_response__json__html,
    HTTP_STATUS__400_BAD_REQUEST, HTTP_STATUS__500_INTERNAL_SERVER_ERROR,
    HTTP_STATUS__200_OK, HTTP_STATUS__401_UNAUTORIZED)
import logging
import re
import uuid

def rest__login():

    def sanitize_input(req):
        req_json = request.get_json()
        email_address = req_json['email_address']
        p = req_json['password']
        return email_address, p

    if request.method == 'POST':
        try:
            email_address, p = sanitize_input(request)
        except:
            log.warn('failed to sanitize inputs. request: %s' % request)
            return make_response__json(status=HTTP_STATUS__401_UNAUTORIZED)  # return empty response

        u_account = None
        try:
            _uid, u_account = current_app.user_db.lookup_user__by_email_address(email_address)
        except:
            log.warn('login: login attempt to unknown account: email_address: \'%s\'' % (email_address))
            return make_response__json(status=HTTP_STATUS__401_UNAUTORIZED)  # return empty response

        try:
            salt = current_app.rz_config.secret_key
            pw_hash = hash_pw(p, salt)
            current_app.user_db.validate_login(email_address=u_account.email_address, pw_hash=pw_hash)
        except Exception as e:
            # login failed
            log.warn('login: unauthorized: user: %s' % (email_address))

# Path: rhizi/crypt_util.py
# def hash_pw(pw_str, salt_str):
#     salt = hashlib.sha512(salt_str.encode('utf-8')).hexdigest()
#     ret = hashlib.sha512((pw_str + salt).encode('utf-8')).hexdigest()
#     return ret
# 
# Path: rhizi/rz_mail.py
# def send_email__flask_ctx(recipients, subject, body, attachments=[]):
#     """
#     Flask context dependent email sending utility
#     """
# 
#     send_from = current_app.rz_config.mail_default_sender
#     mta_host = current_app.rz_config.mta_host
#     mta_port = current_app.rz_config.mta_port
# 
#     send_email(mta_host,
#                         mta_port,
#                         send_from=send_from,
#                         recipients=recipients,
#                         subject=subject,
#                         attachments=attachments,
#                         body=body)
# 
#     log.info('email sent: recipients: %s: subject: %s, attachment-count: %d' % (recipients, subject, len(attachments)))
# 
# Path: rhizi/rz_req_handling.py
# def make_response__json(status=200, data={}):
#     """
#     Construct a json response with proper content-type header
# 
#     @param data: must be serializable via json.dumps
#     """
#     data_str = json.dumps(data)
#     resp = make_response(data_str)
#     resp.headers['Content-Type'] = "application/json"
#     resp.status = str(status)
# 
#     return resp
# 
# def make_response__json__html(status=200, html_str=''):
#     """
#     Construct a json response with HTML payload
#     """
#     return make_response__json(status=status, data={'response__html': html_str })
# 
# HTTP_STATUS__400_BAD_REQUEST = 400
# 
# HTTP_STATUS__500_INTERNAL_SERVER_ERROR = 500
# 
# HTTP_STATUS__200_OK = 200
# 
# HTTP_STATUS__401_UNAUTORIZED = 401


# Path: rhizi/rz_user.py
from datetime import datetime
from datetime import timedelta
from flask import current_app
from flask import make_response
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from .crypt_util import hash_pw
from .rz_api_common import API_Exception__bad_request
from .rz_mail import send_email__flask_ctx
from .rz_req_handling import (make_response__json, make_response__json__html,
    HTTP_STATUS__400_BAD_REQUEST, HTTP_STATUS__500_INTERNAL_SERVER_ERROR,
    HTTP_STATUS__200_OK, HTTP_STATUS__401_UNAUTORIZED)
import logging
import re
import uuid


def rest__login():

    def sanitize_input(req):
        req_json = request.get_json()
        email_address = req_json['email_address']
        p = req_json['password']
        return email_address, p

    if request.method == 'POST':
        try:
            email_address, p = sanitize_input(request)
        except:
            log.warn('failed to sanitize inputs. request: %s' % request)
            return make_response__json(status=HTTP_STATUS__401_UNAUTORIZED)  # return empty response

        u_account = None
        try:
            _uid, u_account = current_app.user_db.lookup_user__by_email_address(email_address)
        except:
            log.warn('login: login attempt to unknown account: email_address: \'%s\'' % (email_address))
            return make_response__json(status=HTTP_STATUS__401_UNAUTORIZED)  # return empty response

        try:
            salt = current_app.rz_config.secret_key
            pw_hash = hash_pw(p, salt)
            current_app.user_db.validate_login(email_address=u_account.email_address, pw_hash=pw_hash)
        except Exception as e:
            # login failed
            log.warn('login: unauthorized: user: %s' % (email_address))

            return make_response__json(status=HTTP_STATUS__401_UNAUTORIZED)  # return empty response