#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import falcon
import config as cf
import hashlib
import json

class AuthMiddleware(object):

    def process_request(self, req, resp):
        token = req.get_header('Authorization')
        account_id = req.get_header('Account-ID')
        #print token
        #print account_id
        if token is None:
            description = ('Please provide an auth token '
                           'as part of the request.')

            raise  falcon.HTTPUnauthorized('Auth token required',description,)
                                          
                                          
        if not self._token_is_valid(token, account_id):
            description = ('The provided auth token is not valid. '
                           'Please request a new token and try again.')

            raise falcon.HTTPUnauthorized('Authentication required',description,)
            

    def _token_is_valid(self, token, account_id):
        skey = cf.skey
        md5 = hashlib.md5()
        md5.update(skey + token)
        if md5.hexdigest() == account_id:
            print "auth ok,request token is %s,account_id is %s" %(token,account_id)
            return True
        else:
            print "auth fail,request token is %s,account_id is %s" %(token,account_id)
            return False
        
        
class RequireJSON(object):

    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',)

        if req.method in ('POST', 'PUT'):
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',)


class JSONTranslator(object):

    def process_request(self, req, resp):
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333
        if req.content_length in (None, 0):
            # Nothing to do
            return

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                                        'A valid JSON document is required.')

        try:
            req.context['doc'] = json.loads(body.decode('utf-8'))

        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect or not encoded as '
                                   'UTF-8.')

    def process_response(self, req, resp, resource):
        if 'result' not in req.context:
            return

        resp.body = json.dumps(req.context['result'])