def login():
    request_args = request.args
    response = Response()

    try:
        if 'username' not in request_args or 'password' not in request_args:
            response.message = 'No username and/or password provided.'
            return jsonify(attr.asdict(response)), 500

        print(request_args.get('password'))
        req = {
            'username': request_args.get('username'),
            'pw': request_args.get('password')
        }

        response = user_login(req)
        return jsonify(attr.asdict(response)), 200

    except Exception as ex:
        response.message = 'Error attempting to login user.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        return jsonify(attr.asdict(response)), 500
def get_user_from_session(username, token):
    valid_user = verify_user(username, None, True)

    if valid_user.error or 'Operation not' in valid_user.message:
        return valid_user

    response = Response()

    if not valid_user.data:
        response.message = 'Invalid user.  Check username and password.'
        response.authorized = False
        return response

    key = 'customer_{}'.format(valid_user.data['custId'])
    customer_info = repository.get_object_by_key(key)
    if ('error' in customer_info
            and customer_info['error']) or ('result' in customer_info
                                            and not customer_info['result']):
        response.message = ''
        response.authorized = False
        response.error = customer_info['error']
        return response

    response.data = {
        'userInfo': {
            'userId': valid_user.data['userId'],
            'username': valid_user.data['username'],
            'token': token
        },
        'customerInfo': customer_info['result']
    }
    response.message = 'Successfully verified and extended session.'
    response.authorized = True

    return response
Exemple #3
0
    def decorated(*args, **kwargs):
        bearer_header = request.headers.get('Authorization', None)
        response = Response()
        if not bearer_header:
            response.message = 'No authorization token provided.'
            response.authorized = False
            g.jwt = {'token': None, 'result': response}
            return f(*args, **kwargs)

        try:
            token = bearer_header.replace('Bearer ', '')
            ext_session_res = extend_session(token)
            g.jwt = {
                'token': None if ext_session_res.error else token,
                'result': ext_session_res
            }
        except Exception as ex:
            response.error = {
                'message': repr(ex),
                'stackTrace': traceback.format_exc()
            }
            response.message
            g.jwt = {'token': None, 'result': response}

        return f(*args, **kwargs)
def search():
    # only used for req/response logging in UI
    req_id = None
    response = Response()
    try:
        request_args = request.args

        if 'requestId' in request_args:
            req_id = int(request_args.get('requestId'))

        if 'product' not in request_args or request_args.get('product') == '':
            response.message = 'No search term provided.'
            return jsonify(attr.asdict(response)), 200

        fuzziness = None
        if 'fuzziness' in request_args:
            fuzziness = int(request_args.get('fuzziness'))

        product = request_args.get('product')
        response = service.product_service.search_products(product, fuzziness)
        response.request_id = req_id

        if response.error:
            return jsonify(attr.asdict(response)), 500

        return jsonify(attr.asdict(response)), 200
    except Exception as ex:
        response.message = 'Error attempting to search for products.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        response.requestId = req_id
        return jsonify(attr.asdict(response)), 500
Exemple #5
0
def register():
    # only used for req/response logging in UI
    req_id = None
    response = Response()
    try:
        request_content = request.get_json()

        if 'requestId' in request_content:
            req_id = int(request_content['requestId'])

        response = service.user_service.register(request_content)
        response.request_id = req_id

        if response.error:
            return jsonify(attr.asdict(response)), 500

        return jsonify(attr.asdict(response)), 200
    except Exception as ex:
        response.message = 'Error attempting to register user.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        response.requestId = req_id
        return jsonify(attr.asdict(response)), 500
Exemple #6
0
def verify_user_session():
    # only used for req/response logging in UI
    req_id = None
    response = Response()
    try:
        request_content = request.get_json()

        if request_content and 'requestId' in request_content:
            req_id = int(request_content['requestId'])

        jwt = g.get('jwt', None)
        if not jwt['token']:
            if jwt['result'].authorized is not None and not jwt[
                    'result'].authorized:
                return jsonify(attr.asdict(jwt['result'])), 401

            return jsonify(attr.asdict(jwt['result'])), 400

        username = jwt['result'].data['username']
        response = service.user_service.get_user_from_session(
            username, jwt['token'])
        response.request_id = req_id

        if response.error:
            return jsonify(attr.asdict(response)), 500

        return jsonify(attr.asdict(response)), 200
    except Exception as ex:
        response.message = 'Error trying to verify user session.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        response.requestId = req_id
        return jsonify(attr.asdict(response)), 500
    def decorated(*args, **kwargs):
        bearer_header = request.headers.get('Authorization', None)
        response = Response(None, None, None, None)
        if not bearer_header:
            response.message = 'No authorization token provided.'
            response.authorized = False
            g.jwt = {
                'token': None,
                'sessionRes': response
            }
            return f(*args, **kwargs)

        try:
            token = bearer_header.replace('Bearer ', '')
            ext_session_res = user_svc.extend_session(token)
            #Couchbase KeyNotFound - unauthorized (i.e. session expired)
            # if response.error:
            #     response.request_id = req_id
            #     if response.authorized is not None and not response.authorized:
            #         return jsonify(response.to_dict()), 401
            #     else:
            #         return jsonify(response.to_dict()), 500
                    
            #https://stackoverflow.com/questions/22256862/flask-how-to-store-and-retrieve-a-value-bound-to-the-request/22256956
            g.jwt = {
                'token': None if ext_session_res.error else token,
                'sessionRes': ext_session_res
            }
            #return f(*args, **kwargs)
        except Exception as err:
            response.error = err
            response.message
            g.jwt = {
                'token': None,
                'sessionRes': response
            }

        return f(*args, **kwargs)
Exemple #8
0
def save_or_update_order():
    # only used for req/response logging in UI
    req_id = None
    response = Response()
    try:
        request_content = request.get_json()

        if 'requestId' in request_content:
            req_id = int(request_content['requestId'])

        jwt = g.get('jwt', None)
        if not jwt['token']:
            if jwt['result'].authorized is not None and not jwt[
                    'result'].authorized:
                return jsonify(attr.asdict(jwt['result'])), 401

            return jsonify(attr.asdict(jwt['result'])), 400

        if 'order' not in request_content:
            response.message = 'No order provided.'
            response.requestId = req_id
            return jsonify(attr.asdict(response)), 400

        req = {
            'order':
            request_content['order'],
            'update':
            request_content['update'] if 'update' in request_content else False
        }

        response = service.user_service.save_or_update_order(req)
        response.requestId = req_id

        if response.error:
            return jsonify(attr.asdict(response)), 500

        return jsonify(attr.asdict(response)), 200

    except Exception as ex:
        response.message = 'Error trying to save/update order.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        response.requestId = req_id
        return jsonify(attr.asdict(response)), 500
Exemple #9
0
def get_new_order():
    # only used for req/response logging in UI
    req_id = None
    response = Response()
    try:
        request_args = request.args

        if 'requestId' in request_args:
            req_id = int(request_args.get('requestId'))

        jwt = g.get('jwt', None)
        if not jwt['token']:
            if jwt['result'].authorized is not None and not jwt[
                    'result'].authorized:
                return jsonify(attr.asdict(jwt['result'])), 401

            return jsonify(attr.asdict(jwt['result'])), 400

        if 'customerId' not in request_args:
            response.message = 'No customerId provided.'
            response.requestId = req_id
            return jsonify(attr.asdict(response)), 400

        customer_id = int(request_args.get('customerId'))

        response = service.user_service.get_new_order(customer_id)
        response.requestId = req_id

        if response.error:
            return jsonify(attr.asdict(response)), 500

        return jsonify(attr.asdict(response)), 200

    except Exception as ex:
        response.message = 'Error trying to retrieve customer orders.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        response.requestId = req_id
        return jsonify(attr.asdict(response)), 500
Exemple #10
0
def login():
    # only used for req/response logging in UI
    req_id = None
    response = Response()
    try:
        request_content = request.get_json()

        if 'requestId' in request_content:
            req_id = int(request_content['requestId'])

        if not ('username' in request_content
                and 'password' in request_content):
            response.message = 'No username and/or password provided.'
            response.requestId = req_id
            return jsonify(attr.asdict(response)), 400

        req = {
            'username': request_content['username'],
            'pw': request_content['password']
        }

        response = service.user_service.login(req)
        response.request_id = req_id

        if response.error:
            return jsonify(attr.asdict(response)), 500

        if response.data and response.authorized:
            return jsonify(attr.asdict(response)), 200

        return jsonify(attr.asdict(response)), 401

    except Exception as ex:
        response.message = 'Error attempting to login user.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        response.requestId = req_id
        return jsonify(attr.asdict(response)), 500
Exemple #11
0
def search_products(product, fuzziness):
    response = Response()
    result = repository.search_products(product, fuzziness)

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error searching for products.'
    else:
        if result == 'NOP':
            return response
        response.data = result['products']
        response.message = 'Successfully searched for products.'

    return response
    def verify_user(self, username, pw, jwt=None):
        result = self.repository.get_user_info(username)
        response = Response(None, 'Operation not built yet.', None, None)
        if 'error' in result:
            response.error = result['error']
            response.message = 'Could not find user.'
            return response

        if result == 'NOP':
            return response

        #no password when using JWT, if user is found, consider valid
        if jwt:
            response.data = result['user_info']
            response.message = 'JWT - no password verification needed.'
            return response

        if bcrypt.checkpw(pw, str.encode(result['user_info']['password'])):
            response.data = result['user_info']
            response.message = 'Password verified.'

        return response
def update_order(order):
    response = Response()
    result = repository.replace_order(order)

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error updating order.'
        return response

    if result == 'NOP':
        return response

    response.data = result['success']
    response.message = 'Successfully updated order.'
    return response
def delete_order(order_id):
    response = Response()
    result = repository.delete_order(order_id)

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error retrieving order.'
        return response

    if result == 'NOP':
        return response

    response.data = result['success']
    response.message = 'Successfully deleted order.'
    return response
def register(req):
    req['password'] = bcrypt.hashpw(str.encode(req['password']),
                                    bcrypt.gensalt()).decode()
    response = Response()
    result = repository.create_account(req)
    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error registering customer/user.'
    else:
        if result == 'NOP':
            return response
        response.data = result['acct']
        response.message = 'Successfully registered customer/user.'

    return response
def get_new_order(id):
    response = Response()
    result = repository.get_new_order(id)

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error retrieving customer new/pending order.'
        return response

    if result == 'NOP':
        return response

    response.data = result['order']
    response.message = 'Successfully retrieved customer new/pending order.'
    return response
def save_order(order):
    response = Response()
    result = repository.save_order(order)

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error saving order.'
        return response

    if result == 'NOP':
        return response

    response.data = result['order']
    response.message = 'Successfully saved order.'
    return response
    def register(self, req):
        req['password'] = bcrypt.hashpw(str.encode(req['password']),
                                        bcrypt.gensalt()).decode()
        response = Response(None, 'Operation not built yet.', None, None)
        result = self.repository.create_account(req)
        if 'error' in result:
            response.error = result['error']
            response.message = 'Error registering customer/user.'
        else:
            if result == 'NOP':
                return response
            response.data = result['acct']
            response.message = 'Successfully registered customer/user.'

        return response
def get_customer(id):
    response = Response()
    customer_id = 'customer_{}'.format(id)
    result = repository.get_customer(customer_id)

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error retrieving customer.'
        return response

    if result == 'NOP':
        return response

    response.data = result['customer']
    response.message = 'Successfully retrieved customer.'
    return response
    def create_session(self, username):
        response = Response(None, 'Operation not built yet.', None, None)

        expiry = int(get_ttl())
        session = self.repository.create_session(username, expiry)

        if 'error' in session:
            response.message = 'Error creating session.'
            response.error = session['error']
            return response

        if 'sessionId' in session:
            response.data = session['sessionId']
            response.message = 'Session created.'

        return response
def ping():
    response = Response()
    try:
        ping_resp = repository.ping()

        if ping_resp['error']:
            response.message = 'Error trying to ping database.'
            response.error = ping_resp['error']
            return jsonify(attr.asdict(response)), 500

        if ping_resp == 'NOP':
            return jsonify(attr.asdict(response)), 200

        response.data = ping_resp['result']
        response.message = 'Successfully pinged database.'
        return jsonify(attr.asdict(response)), 200
    except Exception as ex:
        response.message = 'Error attempting to ping database.'
        response.error = {
            'message': repr(ex),
            'stackTrace': traceback.format_exc()
        }
        return jsonify(attr.asdict(response)), 500
def create_session(username):
    response = Response()

    expiry = int(get_ttl())
    session = repository.create_session(username, expiry)

    if 'error' in session and session['error']:
        response.message = 'Error creating session.'
        response.error = session['error']
        return response

    if 'session_id' in session and session['session_id']:
        response.data = session['session_id']
        response.message = 'Session created.'

    return response
def save_address(req):
    response = Response()
    result = repository.save_address(req['custId'], req['path'],
                                     req['address'])

    if 'error' in result and result['error']:
        response.error = result['error']
        response.message = 'Error saving address.'
        return response

    if result == 'NOP':
        return response

    response.data = result['success']
    response.message = 'Successfully saved address.'
    return response
    def login(self, req):
        valid_user_res = self.verify_user(req['username'],
                                          str.encode(req['pw']))
        if valid_user_res.error or 'Operation not' in valid_user_res.message:
            return valid_user_res

        response = Response(None, 'Operation not built yet.', None, None)

        if not valid_user_res.data:
            response.message = 'Invalid user.  Check username and password.'
            response.authorized = False
            return response

        key = 'customer_{0}'.format(valid_user_res.data['custId'])
        customer_info = self.repository.get_object_by_key(key)

        session_res = self.create_session(req['username'])

        if session_res.error:
            return session_res

        secret = get_secret()
        encoded_jwt = jwt.encode({'id': session_res.data},
                                 secret,
                                 algorithm='HS256')
        response.data = {
            'userInfo': {
                'userId': valid_user_res.data['userId'],
                'username': valid_user_res.data['username'],
                'token': encoded_jwt.decode()
            },
            'customerInfo': customer_info
        }
        response.message = 'Successfully logged in (session created).'
        response.authorized = True

        return response
    def get_user_from_session(self, jwt):
        valid_user_res = self.verify_user(jwt['sessionRes'].data['username'],
                                          None, True)
        if valid_user_res.error or 'Operation not' in valid_user_res.message:
            return valid_user_res

        response = Response(None, 'Operation not built yet.', None, None)

        if not valid_user_res.data:
            response.message = 'Invalid user.  Check username and password.'
            response.authorized = False
            return response

        response.data = {
            'userInfo': {
                'userId': valid_user_res.data['userId'],
                'username': valid_user_res.data['username'],
                'token': jwt['token']
            }
        }
        response.message = 'Successfully verified and extended session.'
        response.authorized = True

        return response
def extend_session(token):
    secret = get_secret()
    response = Response()
    #decoded = None
    try:
        decoded_jwt = jwt.decode(token, secret, algorithms=['HS256'])
    except Exception as ex:
        print(ex)
        response.message = 'Error extending session.  Invalid token.'
        response.error = ex
        return response

    expiry = int(get_ttl())
    session = repository.extend_session(decoded_jwt['id'], expiry)
    if 'error' in session and session['error']:
        if session['error']['message'] == 'Document not found.':
            response.message = 'Unauthorizeed.  Session expired'
            response.authorized = False
        else:
            response.message = "Error trying to verify session."

        response.error = {
            'message': repr(session['error']),
            'stackTrace': traceback.format_exc()
        }
        return response

    if session == 'NOP':
        return response

    response.data = session['session']
    response.message = 'Successfully extended session.'
    response.authorized = True
    return response
    def extend_session(self, token):
        secret = get_secret()
        response = Response(None, 'Operation not built yet.', None, None)
        decoded = None
        try:
            decoded_jwt = jwt.decode(token, secret, algorithms=['HS256'])
        except Exception as ex:
            print(ex)
            response.message = 'Error extending session.  Invalid token.'
            response.error = ex
            return response

        expiry = int(get_ttl())
        session = self.repository.extend_session(decoded_jwt['id'], expiry)
        if 'error' in session:
            if session['error'].CODE == 13:
                response.message = 'Unauthorizeed.  Session expired'
                response.authorized = False
            else:
                response.message = "Error trying to verify session."

            response.error = {
                'message': repr(session['error']),
                'stackTrace': traceback.format_exc()
            }
            return response

        if session == 'NOP':
            return response

        response.data = session
        response.message = 'Successfully extended session.'
        response.authorized = True
        return response