Ejemplo n.º 1
0
def majAddress():
    try:
        if (request.method =='POST'):
            logger.error(utils.get_debug_all(request))
            # gets inseeid
            Siren__c = request.args.get('Siren__c')
            # gets new city
            city = request.args.get('city') 
            if (city == '' or city == None):
                return utils.returnResponse("Please provide a city", 403, None, None) 
            #check if siren__c exits
            if (postgres.__checkAccountBySiren(Siren__c) == False):
                return utils.returnResponse("Please provide a Siren", 403, None, None) 
            # check if city exist   
            # updates
            postgres.__updateCityInAccountBySiren(city, Siren__c)

            return "ok"
        elif (request.method == 'GET'):
            logger.error(utils.get_debug_all(request))
            cookie, cookie_exists =  utils.getCookie()
            # gets inseeid
            Siren__c = request.args.get('Siren__c')
            data = postgres.__getAccountBySiren(Siren__c)
            kafka_utils.sendToKafka_EDF(ujson.dumps(data))
            return utils.returnResponse(ujson.dumps(data), 200, cookie, cookie_exists) 

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists =  utils.getCookie()
        return utils.returnResponse("An error occured, check logDNA for more information", 403, cookie, cookie_exists) 
Ejemplo n.º 2
0
def homepage():
    cookie, cookie_exists = utils.getCookie()
    logger.debug(utils.get_debug_all(request))

    key = {'cookie': cookie}
    tmp_dict = None
    #data_dict = None
    tmp_dict = rediscache.__getCache(key)
    if ((tmp_dict == None) or (tmp_dict == '')):
        logger.info("Data not found in cache")
        logger.debug(utils.get_debug_all(request))
        text = 'User is not authenticated, please log in ! <a href="%s">Authenticate with Salesforce</a>'

        state = str(uuid4())
        save_created_state(state)
        params = {
            "client_id": APP_CLIENT_ID,
            "response_type": "code",
            "state": state,
            "redirect_uri": REDIRECT_URI_CODE,
            "scope": "full refresh_token"
        }

        url = SF_AUTHORIZE_TOKEN_URL + urllib.parse.urlencode(params)
        logger.info(url)
        data = text % url
    else:
        data = tmp_dict

    return utils.returnResponse(data, 200, cookie, cookie_exists)
Ejemplo n.º 3
0
def badges():
    try:
        if (request.method == 'POST'):
            logger.error(utils.get_debug_all(request))
            # gets all the data required to save the badge object
            guest_id = request.args.get('guest_id')
            guest_firstname = request.args.get('guest_firstname')
            guest_lastname = request.args.get('guest_lastname')
            guest_company = request.args.get('guest_company')
            host_firstname = request.args.get('host_firstname')
            host_lastname = request.args.get('host_lastname')
            picture_url = request.args.get('picture_url')
            # id is auto generated
            uid = uuid.uuid4().__str__()
            badge_status = 'ACTIVE'
            badge_url = APPURL + uid
            # status is set to default -> INACTIVE (status are inactive / active )
            # url will be calculated

            # gets new city

            if (guest_id == '' or guest_id == None):
                return utils.returnResponse("Please provide a guest_id", 403,
                                            None, None)
            # check if siren__c exits

            postgres.__insertBadge(uid, guest_id, guest_firstname,
                                   guest_lastname, guest_company,
                                   host_firstname, host_lastname, badge_status,
                                   badge_url, picture_url)

            # generates now the data
            #data = render_template(BADGE_DATA, GuestFirstname=guest_firstname,
            #GuestLastname = guest_lastname, GuestCompany=guest_company, HostFirstname=host_firstname, HostLastname=host_lastname,
            #ProfilePicture=picture_url, QRCode="")

            return "{'Result':'Ok'}"
        elif (request.method == 'GET'):
            logger.error(utils.get_debug_all(request))
            cookie, cookie_exists = utils.getCookie()
            sqlRequest = sqlRequest = "select * from public.badge"
            attributes = None
            if ('badge_id' in request.args):
                sqlRequest += " where id = %(badge_id)s"
                attributes = {"badge_id": request.args.get('badge_id')}
            data = postgres.__execRequest(sqlRequest, attributes)
            return utils.returnResponse(ujson.dumps(data), 200, cookie,
                                        cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 403, cookie,
            cookie_exists)
Ejemplo n.º 4
0
def votes_placevote():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            #gameactivity__c = request.args['gameactivity__c']
            match_id = request.args['match_id']
            resultMatch = postgres.__getMatchById(match_id)
            if (resultMatch['data'][0]['question__c'] == None):
                resultMatch['data'][0]['question__c'] = ""
            data = render_template(RENDER_PLACE_BET,
                                   entry=resultMatch['data'][0],
                                   FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                                   userid=cookie,
                                   PUSHER_KEY=notification.PUSHER_KEY)
            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 5
0
def tables():
    try:
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)

        logger.debug(utils.get_debug_all(request))
        rediscache.__display_RedisContent()
        """
        key = {'url' : request.url}
        tmp_dict = None
        data_dict = None
        tmp_dict = __getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data_dict  = __getTables()
            __setCache(key, ujson.dumps(data_dict), 300)
        else:
            logger.info("Data found in redis, using it directly")
            data_dict = ujson.loads(tmp_dict)
        """
        data_dict = postgres.__getTables()

        return render_template(RENDER_TABLES, entries=data_dict['data'])

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 6
0
def tables():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        logger.debug(utils.get_debug_all(request))
        #rediscache.__display_RedisContent()
        data_dict = postgres.__getTables()
        output = 'html'
        if 'output' in request.args:
            output = request.args['output'].lower()

        if (output == 'html'):
            data = render_template(RENDER_TABLES,
                                   entries=data_dict['data'],
                                   FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                                   userid=cookie,
                                   PUSHER_KEY=notification.PUSHER_KEY)
        else:
            logger.info(
                "Treating request as an API request, output to Json only")
            data = ujson.dumps(data_dict)
        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 7
0
def genericGetPost(uri, isAdmin):
    try:
        logs.logger.debug(utils.get_debug_all(request))
        # check method type
        properClass = functionLoader[uri]['class']
        properClassName = functionLoader[uri]['classname']
        return functionLoader[uri][request.method](properClass,
                                                   properClassName, uri,
                                                   isAdmin)
        """
        if request.method == 'GET':
            if ('GET' in functionLoader[uri]):
                return functionLoader[uri]['GET'](properClass, properClassName, uri, isAdmin)
            return __GET__Generic(properClass, properClassName, uri, isAdmin)
        else:
            if ('POST' in functionLoader[uri]):
                return functionLoader[uri]['POST'](properClass, properClassName, uri, isAdmin)
            return __POST__Generic(properClass, properClassName, uri, isAdmin)
        """
    except werkzeug.exceptions.NotFound as e:
        traceback.print_exc()
        return utils.returnResponse("Requested resource does not exist", 404)
    except Exception as e:
        traceback.print_exc()
        return utils.returnResponse(
            "The server encountered an error while processing your request",
            500)
Ejemplo n.º 8
0
def subscribtionStatus():
    try:
        logs.logger.debug(utils.get_debug_all(request))
        #gets attributes
        received_request = request.json
        if (received_request == None):
            received_request = []
        received_args = request.args
        if ('Device-Serial-Number' not in received_request
                and 'Device-Serial-Number' not in received_args):
            return utils.returnResponse(
                "Error, missing Device-Serial-Number data", 404)

        # gets the value of the attribute, priority is given to request.body
        DeviceSN = ""
        if ('Device-Serial-Number' in received_request):
            DeviceSN = received_request['Device-Serial-Number']
        else:  #must be in the request.args
            DeviceSN = received_args['Device-Serial-Number']

        # calls the functions with the proper param
        data = postgres.subscriptionStatus(DeviceSN)
        if (
                len(data) >= 1
        ):  #only sends the first entry within the array .. should have only one  ..
            return utils.returnResponse(data[0], 200)
        # nothing was found sending back an empty result
        return utils.returnResponse({}, 200)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return utils.returnResponse("An Error Occured.", 200)
Ejemplo n.º 9
0
def root_photo():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data = render_template(RENDER_ROOT_PHOTO,
                                   FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                                   userid=cookie,
                                   PUSHER_KEY=notification.PUSHER_KEY)
            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 10
0
def form():
    try:
        cookie, cookie_exists =  utils.getCookie()
        logger.debug(utils.get_debug_all(request))

        form = ReusableForm(request.form)
 
        print(form.errors)
        if request.method == 'POST':
            name=request.form['name']
            formvalue=request.form['formvalue']
            email=request.form['email']
            postgres.__saveLeadEntry(name, email, formvalue)
            data = render_template('form.html', form=form, registered=True)
            return utils.returnResponse(data, 200, cookie, cookie_exists)
        
        print(form)
        if form.validate():
            # Save the comment here.
            flash('Hello ' + name)
        else:
            flash('All the form fields are required. ')
        
        data = render_template('form.html', form=form)
        
        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists =  utils.getCookie()
        return utils.returnResponse("An error occured, check logDNA for more information", 200, cookie, cookie_exists)

        
Ejemplo n.º 11
0
def getObjects():
    try:
        cookie, cookie_exists = utils.getCookie()
        logger.debug(utils.get_debug_all(request))
        if (not checkAuthorization(request)):
            return utils.returnResponse("Unauthorized access", 401, cookie,
                                        cookie_exists)

        # gets object name
        describe = False
        if ('describe' in request.args):
            describe = True

        object_name = ''
        if ('name' in request.args):
            object_name = request.args['name']
        else:
            return "Error, must specify a object name with ?name=xxx", 404

        data_dict = None
        data_dict = postgres.__getObjectsDescribe(object_name, describe)
        data = ujson.dumps(data_dict)  #{'columns':data_dict['columns']})
        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logs for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 12
0
def votes_placevote():
    try:
        if (postgres.__checkHerokuLogsTable()):
                postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        key = {'url' : request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            #gameactivity__c = request.args['gameactivity__c']            
            match_id = request.args['match_id']            
            resultMatch = postgres.__getMatchById(match_id)
            if (resultMatch['data'][0]['question__c'] == None):
                resultMatch['data'][0]['question__c'] = ""
            data = render_template(RENDER_PLACE_BET,
                entry = resultMatch['data'][0]
                )
            rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict
            

        return data, 200

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 13
0
def root():
    try:
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")

            data = render_template(RENDER_ROOT)

            rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return data, 200
    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 14
0
def photo_display():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        output = 'html'
        if 'output' in request.args:
            output = request.args['output'].lower()

        # logs all attributes received
        logger.debug(utils.get_debug_all(request))
        # gets object name
        object_name = 'ImageAnalysis__c'

        name = request.args['name']
        key = {'url': request.url, 'output': output}
        tmp_dict = None
        data_dict = None

        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data_dict = postgres.__getImageAnalysis(object_name, name)

            if (output == 'html'):
                logger.info(
                    "Treating request as a web request, output to Web page")
                if ('image__c' in data_dict['columns']):
                    data = render_template(RENDER_PHOTO_DISPLAY,
                                           columns=data_dict['columns'],
                                           object_name=object_name,
                                           entries=data_dict['data'])
            else:
                logger.info(
                    "Treating request as an API request, output to Json only")
                data = ujson.dumps(data_dict)

            #if (postgres.HEROKU_LOGS_TABLE not in request.url): # we don't want to cache these logs
            #    rediscache.__setCache(key, data.encode('utf-8'), 60)

        else:
            logger.info("Data found in redis, using it directly")
            #logger.info(tmp_dict)
            if (output == 'html'):
                #data_dict = ujson.loads(tmp_dict)
                data = tmp_dict.decode('utf-8')
            else:
                #data = ujson.loads(tmp_dict)
                data = tmp_dict

        logger.info("returning data")
        return data, 200

    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 15
0
def error():
    if (postgres.__checkHerokuLogsTable()):
        postgres.__saveLogEntry(request)

    logger.debug(utils.get_debug_all(request))
    logger.error("Generating Error")
    error_code = 500
    if ('error_code' in request.args):
        error_code = int(request.args['error_code'])
    return "Error !!!!!!", error_code
Ejemplo n.º 16
0
def error():
    cookie, cookie_exists = utils.getCookie()

    if (postgres.__checkHerokuLogsTable()):
        postgres.__saveLogEntry(request, cookie)

    logger.debug(utils.get_debug_all(request))
    logger.error("Generating Error")
    error_code = 500
    if ('error_code' in request.args):
        error_code = int(request.args['error_code'])
    return utils.returnResponse("Error !! ", error_code, cookie, cookie_exists)
Ejemplo n.º 17
0
def createTicket():
    try:
        cookie, cookie_exists =  utils.getCookie()

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        logger.debug(utils.get_debug_all(request))

        form = TicketForm(request.form)
        
        hosts = postgres.__getSFUsers()
        key = {'url' : MAIN_URL, 'cookie' : cookie}
        tmp_dict = rediscache.__getCache(key)
        data = ""
        if (request.method=="GET"):
            if ((tmp_dict != None) and (tmp_dict != '')):    
                #means user has already registered, forwarding him to the guest thanks
                data = render_template(CREATETICKETS, registered=True, form=form, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
            else:
                # means it has to register
                return redirect("/",code=302)
        elif request.method == 'POST':
            if ((tmp_dict != None) and (tmp_dict != '')):    
                #means user has already registered, accepting this 
                Reason=request.form['Reason']
                Subject=request.form['Subject']
                Description=request.form['Description']
                postgres.__insertCase(cookie, Subject, Description, "Self Service", Reason)
                #postgres.__saveGuestEntry(Firstname, Lastname, Email, Company, PhoneNumber, Host, cookie, Picture)
                data = render_template(GUESTTHANKS, registered=True, userid=cookie, PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)
                #rediscache.__setCache(key, data.encode('utf-8'), 3600)
                return utils.returnResponse(data, 200, cookie, cookie_exists)
            else:
                # means user has not registered and is trying to post, .. 
                # so returning him the registration page first
                return redirect("/",code=302)
        else:
            # trying to hack someting ?
            return redirect("/",code=302)

        
        data = render_template(CREATETICKETS, form=form, hosts=hosts['data'],userid=cookie,PUSHER_KEY=notification.PUSHER_KEY, PUSHER_CLUSTER=notification.CLUSTER)

        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists =  utils.getCookie()
        return utils.returnResponse("An error occured, check logDNA for more information", 200, cookie, cookie_exists)
Ejemplo n.º 18
0
def root_photo():
    try:
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        data = render_template(RENDER_ROOT_PHOTO,
                               imageid=uuid.uuid4().__str__())

        return data, 200
    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 19
0
def canvas_main():
    try:
        logger.debug(utils.get_debug_all(request))
        cookie, cookie_exists = utils.getCookie()
        logger.info("CookieExists={} - Cookie ={}".format(
            cookie_exists, cookie))
        key = {'cookie': cookie, 'fromCanvas': True}
        tmp_dict = None

        if ('signed_request' not in request.form):
            return utils.returnResponse(
                "This application is only accessible through Salesforce Canvas App technology. Please access it through Salesforce",
                200, cookie, cookie_exists)
        consumer_secret = os.getenv("APP_CLIENT_SECRET", "ChangeMe")
        signed_request = request.form['signed_request']
        sr = signedrequest.SignedRequest(consumer_secret, signed_request)
        request_json = sr.verifyAndDecode()
        struct_json = ujson.loads(request_json)

        rediscache.__setCache(key, ujson.dumps(struct_json), 180)

        # test for chatter api
        #sf_getProducts(struct_json['client']['instanceUrl'] , struct_json['client']['oauthToken'])

        pprint.pprint(struct_json)
        if ('record' in struct_json['context']['environment']['parameters']):
            sqlRequest = "select Id, guest_id, guest_firstname, guest_lastname, badge_status, creation_date from public.badge where guest_id = %(guest_id)s order by creation_date"
            sqlResult = postgres.__execRequest(
                sqlRequest, {
                    'guest_id':
                    struct_json['context']['environment']['parameters']
                    ['record']
                })
        else:
            sqlRequest = "select Id, guest_id,guest_firstname, guest_lastname, badge_status, creation_date from public.badge order by creation_date"
            sqlResult = postgres.__execRequest(sqlRequest, {})
        data = render_template(CANVAS_FILE,
                               request_json=ujson.dumps(struct_json),
                               columns=sqlResult['columns'],
                               entries=sqlResult['data'])

        #return render_template()
        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse("An Error Occured, please check LogDNA",
                                    200, cookie, cookie_exists)
Ejemplo n.º 20
0
def bets_bygameactivity__c():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        has_voted = False
        if ('has_voted' in request.args):
            has_voted = bool(request.args['has_voted'])
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")

            gameactivity__c = request.args['gameactivity__c']
            resultActivityName = postgres.__getGameActivityById(
                gameactivity__c)
            result = postgres.__getMatchsByGameActivityId(gameactivity__c)

            data = render_template(
                RENDER_BETS_MATCHS,
                columns=result['columns'],
                entries=result['data'],
                category_name=resultActivityName['data'][0]['activityname'],
                category_id=gameactivity__c,
                hasvoted=has_voted,
                FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                userid=cookie,
                PUSHER_KEY=notification.PUSHER_KEY)

            #rediscache.__setCache(key, data, 60)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 21
0
def customerPassions():
    try:
        logs.logger.debug(utils.get_debug_all(request))

        #gets attributes
        received_request = request.json
        if (received_request == None):
            received_request = []
        received_args = request.args
        if ('Customer-Number' not in received_request
                and 'Customer-Number' not in received_args):
            return utils.returnResponse("Error, missing Customer-Number data",
                                        404)
        if ('Current-Decade' not in received_request
                and 'Current-Decade' not in received_args):
            return utils.returnResponse("Error, missing Current-Decade data",
                                        404)

        # gets the value of the attribute, priority is given to request.body
        CustomerNumber = ""
        if ('Customer-Number' in received_request):
            CustomerNumber = received_request['Customer-Number']
        else:  #must be in the request.args
            CustomerNumber = received_args['Customer-Number']
        currentDecade = ""
        if ('Current-Decade' in received_request):
            currentDecade = received_request['Current-Decade']
        else:  #must be in the request.args
            currentDecade = received_args['Current-Decade']

        # calls the functions with the proper param
        data = postgres.customerPassion(CustomerNumber, currentDecade)
        #ok now rework the structure as this one is different
        # waiting for some data

        if (
                len(data) >= 1
        ):  #only sends the first entry within the array .. should have only one  ..
            return utils.returnResponse(data, 200)
        # nothing was found sending back an empty result
        return utils.returnResponse({}, 200)

    except Exception as e:
        import traceback
        traceback.print_exc()
        return utils.returnResponse("An Error Occured.", 200)
Ejemplo n.º 22
0
def sfconnectedapp():
    logger.error(utils.get_debug_all(request))
    error = request.args.get('error', '')
    if error:
        return "Error: " + error
    state = request.args.get('state', '')
    if not is_valid_state(state):
        # Uh-oh, this request wasn't started by us!
        abort(403)
    code = request.args.get('code')
    print(code)

    data = {
        'client_id': APP_CLIENT_ID,
        'client_secret': APP_CLIENT_SECRET,
        "redirect_uri": REDIRECT_URI_CODE,
        "code": code,
        'grant_type': 'authorization_code'
    }
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    req = requests.post(SF_REQUEST_TOKEN_URL, data=data, headers=headers)
    response = req.json()
    logger.error(response)

    #result = requests.post(url=url, data=data)
    access_token = response['access_token']
    instance_url = response['instance_url']

    url = instance_url + API_URL
    headers = {
        'Authorization': "Bearer " + access_token,
        "X-Prettylogger.debug": "1"
    }
    result = requests.get(url, headers=headers)
    logger.info("Result Code : {}".format(result.status_code))
    logger.info("Header : {}".format(result.headers))
    logger.info("Content : {}".format(result.json()))

    #now stores everything in redis
    rediscache.__delCache(state)
    cookie, cookie_exists = utils.getCookie()
    key = {'cookie': cookie}
    rediscache.__setCache(key, ujson.dumps(response), 3600)

    return "got a code! %s" % response
Ejemplo n.º 23
0
def tables():
    try:
        cookie, cookie_exists = utils.getCookie()
        logger.debug(utils.get_debug_all(request))
        if (not checkAuthorization(request)):
            return utils.returnResponse("Unauthorized access", 401, cookie,
                                        cookie_exists)
        data_dict = postgres.__getTables()
        data = ujson.dumps(data_dict)
        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logs for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 24
0
def tables():
    try:
        cookie, cookie_exists = utils.getCookie()
        logger.debug(utils.get_debug_all(request))
        if (not checkAuthorization(request)):
            return utils.returnResponse("Unauthorized access", 401, cookie,
                                        cookie_exists)
        #Postgres part
        data_dict = postgres.__getTables()
        data = ujson.dumps(data_dict)
        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "The server encountered an error while processing your request",
            500, cookie, cookie_exists)
Ejemplo n.º 25
0
def image():
    try:
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))
        imageid = request.args['id']
        i = request.files['fileToUpload']  # get the image
        f = ('%s.jpeg' % (imageid))
        i.save('%s/%s' % (PATH_TO_TEST_IMAGES_DIR, f))
        completeFilename = '%s/%s' % (PATH_TO_TEST_IMAGES_DIR, f)
        # now upload
        logger.debug(completeFilename)
        awsFilename = aws.uploadData(completeFilename, f)

        return "File received, thanks for sharing!  : You can review it here : " + awsFilename, 200
    except Exception as e:
        import traceback
        traceback.print_exc()
        return "An error occured, check logDNA for more information", 200
Ejemplo n.º 26
0
def genericGetPutDelById(uri, isAdmin, id_):
    try:
        logs.logger.debug(utils.get_debug_all(request))
        # use the end of the route to know which class the call is meant for
        properClass = functionLoader[uri]['class']
        properClassName = functionLoader[uri]['classname']
        logs.logger.debug("properclass={}".format(properClassName))
        return functionLoader[uri][request.method](properClass,
                                                   properClassName, uri,
                                                   isAdmin, id_)

    except werkzeug.exceptions.NotFound as e:
        traceback.print_exc()
        return utils.returnResponse("Requested resource does not exist", 404)
    except Exception as e:
        traceback.print_exc()
        return utils.returnResponse(
            "The server encountered an error while processing your request",
            500)
Ejemplo n.º 27
0
def login():
    logs.logger.debug(utils.get_debug_all(request))

    if current_user.is_authenticated:
        return utils.returnResponse(jsonify({"Error" : "You are already authenticated, logout first"}), 404)        

    hasAuthorizationHeader, decodedHeader = utils.checkAuthorization(request)
    if (not hasAuthorizationHeader ):
      return utils.returnResponse("Unauthorized access", 401)

    #U/P are given in the authorization header
    decodedHeaderSplitted=decodedHeader.decode('utf-8').split(':')

    user = User.query.filter_by(username=decodedHeaderSplitted[0]).first()
    if user is None or not user.check_password(decodedHeaderSplitted[1]):
        return utils.returnResponse(jsonify({"Error" : "incorrect login or password"}), 404) 

    login_user(user)
    return utils.returnResponse(jsonify("Welcome to the matrix neo"), 200)
    
Ejemplo n.º 28
0
def contact():
    try:
        cookie, cookie_exists = utils.getCookie()

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)
        logger.debug(utils.get_debug_all(request))
        if ('phone' not in request.args):
            return utils.returnResponse("Please provide a phone number", 403,
                                        cookie, cookie_exists)
        entry_phone = request.args['phone']
        if (entry_phone == '' or entry_phone == None):
            return utils.returnResponse("Please provide a phone number", 403,
                                        cookie, cookie_exists)

        key = {'url': request.url}
        tmp_dict = None
        #data_dict = None
        tmp_dict = rediscache.__getCache(key)
        if ((tmp_dict == None) or (tmp_dict == '')):
            logger.info("Data not found in cache")
            data_dict = postgres.__execRequest(
                'select name, mobilephone, phone, email, sfid from salesforce.contact where phone = %(phone)s or mobilephone=%(phone)s',
                {'phone': entry_phone})
            logger.info(data_dict)
            rediscache.__setCache(key, data_dict, 60)

            data = ujson.dumps(data_dict)
        else:
            logger.info("Data found in redis, using it directly")
            data = tmp_dict

        return utils.returnResponse(data, 200, cookie, cookie_exists)
    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 403, cookie,
            cookie_exists)
Ejemplo n.º 29
0
def tables():
    try:
        cookie, cookie_exists = utils.getCookie()
        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request, cookie)

        logger.debug(utils.get_debug_all(request))
        #rediscache.__display_RedisContent()
        data_dict = postgres.__getTables()

        data = render_template(RENDER_TABLES,
                               entries=data_dict['data'],
                               FA_APIKEY=utils.FOLLOWANALYTICS_API_KEY,
                               userid=cookie,
                               PUSHER_KEY=notification.PUSHER_KEY)
        return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)
Ejemplo n.º 30
0
def singleguestbadgemanagement():
    try:
        logger.debug(utils.get_debug_all(request))
        cookie, cookie_exists = utils.getCookie()
        #data_dict = None
        key_fromCanvas = {'cookie': cookie, 'fromCanvas': True}
        tmp_dict_fromCanvas = rediscache.__getCache(key_fromCanvas)

        if ((tmp_dict_fromCanvas == None) or (tmp_dict_fromCanvas == '')):
            logger.info("Data not found in cache")
            logger.debug(utils.get_debug_all(request))
            text = 'User is not coming from canvas app !'
            return utils.returnResponse(text, 200, cookie, cookie_exists)
        else:
            struct_json = ujson.loads(tmp_dict_fromCanvas)
            guest_id = request.args['guest_id']

            # gest the record id

            if request.method == 'POST':
                logger.info("post detected")
                actionform = request.form['action']
                actiontype = actionform.split('.')[0]
                actionvalue = actionform.split('.')[1]
                sqlUpdate = "update public.badge set badge_status=%(status)s where id=%(id)s"
                postgres.__execRequestWithNoResult(sqlUpdate, {
                    'status': actiontype,
                    'id': actionvalue
                })

                # now updates the guest status
                # sf_getProducts(struct_json['client']['instanceUrl'] , struct_json['client']['oauthToken'])
                #def sf_updateBadge(sfurl, sftoken, guest, status)
                logger.info('actionType={}'.format(actiontype))
                sfinstanceurl = struct_json['client']['instanceUrl']
                sftoken = struct_json['client']['oauthToken']
                host_id = sf.sf_getGuestHost(sfinstanceurl, sftoken, guest_id)

                if (actiontype == 'INACTIVE'):
                    sf.sf_updateBadge(sfinstanceurl, sftoken, guest_id,
                                      'SECURITY RISK')
                elif (actiontype == 'ACTIVE'):
                    sf.sf_updateBadge(sfinstanceurl, sftoken, guest_id,
                                      'BADGE ISSUED')

                sf.sf_ChatterPost(sfinstanceurl, sftoken, guest_id, host_id,
                                  actiontype)

            sqlRequest = "select Id, guest_id, guest_firstname, guest_lastname, badge_status, creation_date from public.badge where guest_id = %(guest_id)s order by creation_date"
            sqlResult = postgres.__execRequest(sqlRequest,
                                               {'guest_id': guest_id})
            data = render_template(CANVAS_FILE,
                                   request_json=ujson.dumps(struct_json),
                                   columns=sqlResult['columns'],
                                   entries=sqlResult['data'])
            return utils.returnResponse(data, 200, cookie, cookie_exists)

    except Exception as e:
        import traceback
        traceback.print_exc()
        cookie, cookie_exists = utils.getCookie()
        return utils.returnResponse(
            "An error occured, check logDNA for more information", 200, cookie,
            cookie_exists)