Exemple #1
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)
Exemple #2
0
def badgeById(badge_id):
    # get the badge
    if (badge_id != None and badge_id != ""):
        cookie, cookie_exists = utils.getCookie()
        badge_content = postgres.__execRequest(
            "Select * from badge where id=%(badge_id)s and badge_status='ACTIVE' ",
            {'badge_id': badge_id})

        if (len(badge_content['data']) > 0):
            logger.info(badge_content)
            if ('output' in request.args):
                if (request.args['output'] == 'json'):
                    return utils.returnResponse(
                        utils.jsonencode(badge_content), 200, cookie,
                        cookie_exists)
            QRCODE_COMPLETE_URL = QRCODE_URL + "'" + APPURL + badge_content[
                'data'][0]['id'] + "?output=json'"
            logger.info(QRCODE_COMPLETE_URL)
            data = render_template(
                BADGE_DATA,
                GuestFirstname=badge_content['data'][0]['guest_firstname'],
                GuestLastname=badge_content['data'][0]['guest_lastname'],
                GuestCompany=badge_content['data'][0]['guest_company'],
                HostFirstname=badge_content['data'][0]['host_firstname'],
                HostLastname=badge_content['data'][0]['host_lastname'],
                ProfilePicture=badge_content['data'][0]['picture_url'],
                QRCode=QRCODE_COMPLETE_URL)

            return utils.returnResponse(data, 200, cookie, cookie_exists)
    return utils.returnResponse(
        ujson.dumps({'Error': 'Unknown or incorrect badge id'}), 404, cookie,
        cookie_exists)
Exemple #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)
Exemple #4
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)
Exemple #5
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)
Exemple #6
0
def bet_vote():
    try:

        if (postgres.__checkHerokuLogsTable()):
            postgres.__saveLogEntry(request)
        logger.debug(utils.get_debug_all(request))

        # trick
        # ?matchid={{ entry.match_id }}&gameactivity__c={{ entry.gameactivity__c }}&vote_winner={{ entry.participant_home_id}}
        is_vote_through_get = False
        if ('matchid' in request.args and 
            'vote_winner' in request.args and
            'gameactivity__c' in request.args):
            is_vote_through_get = True

        if (request.method == 'POST' or is_vote_through_get == True):
            matchid = request.args['matchid']
            gameactivity__c=request.args['gameactivity__c']
            if (is_vote_through_get):
                winner = request.args['vote_winner']
            else:
                winner = request.form['vote_winner']
            useragent = request.headers['User-Agent']
            

            externalid = uuid.uuid4().__str__()
            createddate  = datetime.now()

            sqlRequest = """
                insert into salesforce.bet__c (winner__c, 
                useragent__c, 
                name, 
                externalid__c, 
                match__c,
                createddate) values 
                ( %(winner)s, %(useragent)s, %(externalid)s, %(externalid)s, %(matchid)s, %(createddate)s ) """
            
            postgres.MANUAL_ENGINE_POSTGRES.execute(sqlRequest,
                        {
                        'winner' : winner,
                        'useragent' : useragent,
                        'createddate':createddate,
                        'externalid' : externalid,
                        'matchid':matchid} )   
            logger.info('##### vote taken into account ####')
            return redirect('/matchs?gameactivity__c='+gameactivity__c+"&has_voted=True")
        else:            
            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")
                sqlRequest = """
                    select   
                        salesforce.gameactivity__c.name , 
                        salesforce.gameactivity__c.sfid, 
                        (select count(*) from  salesforce.match__c where salesforce.match__c.gameactivity__c = salesforce.gameactivity__c.sfid) as nbMatchs 
                    from salesforce.gameactivity__c 

                    """
                data_dict = postgres.__execRequest(sqlRequest, None)
                
                data = render_template(RENDER_BETS_MAIN,
                    columns=data_dict['columns'],
                    entries = data_dict['data'])

                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
Exemple #7
0
def badgesmanagement():
    try:
        logger.debug(utils.get_debug_all(request))
        cookie, cookie_exists = utils.getCookie()
        key = {'cookie': cookie}
        tmp_dict = None
        #data_dict = None
        key_fromCanvas = {'cookie': cookie, 'fromCanvas': True}

        tmp_dict = rediscache.__getCache(key)
        tmp_dict_fromCanvas = rediscache.__getCache(key_fromCanvas)
        if (tmp_dict != None):
            pprint.pprint(ujson.loads(tmp_dict))
        logger.debug("############")
        if (tmp_dict_fromCanvas != None):
            pprint.pprint(ujson.loads(tmp_dict_fromCanvas))

        if (((tmp_dict == None) or (tmp_dict == '')) and
            ((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 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
            return utils.returnResponse(data, 200, cookie, cookie_exists)
        else:
            if request.method == 'POST':
                struct_json = ujson.loads(tmp_dict)
                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
                })

                logger.info('actionType={}'.format(actiontype))
                sfinstanceurl = struct_json['instance_url']
                sftoken = struct_json['access_token']
                guest_id = postgres.getBadgeById(
                    actionvalue)['data'][0]['guest_id']
                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)

            logger.info(tmp_dict)
            sqlRequest = "select Id, guest_firstname, guest_lastname, badge_status, creation_date from public.badge order by creation_date"
            sqlResult = postgres.__execRequest(sqlRequest, None)
            data = render_template(BADGE_FILE,
                                   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)