Example #1
0
def update_profile_fb(request, passenger_id, next):
    """
    Callback after passenger approved us to get his data from fb
    """
    logging.info("update facebook profile for passenger[%s]" % passenger_id)

    from ordering.models import Passenger
    passenger = Passenger.by_id(passenger_id)
    if passenger and request.GET.get('code'):
        args = {
            'client_id': settings.FACEBOOK_APP_ID,
            # redirect_uri MUST match the one passed in step1 (redirecting to fb)
            'redirect_uri': "http://%s%s" % (DEFAULT_DOMAIN, reverse(update_profile_fb, args=[passenger.id, next])),
            'client_secret': settings.FACEBOOK_APP_SECRET,
            'code': request.GET['code'],
            }

        url = 'https://graph.facebook.com/oauth/access_token?' +\
              urllib.urlencode(args)

        try:
            response = cgi.parse_qs(urllib.urlopen(url).read())
            logging.info("FB query: %s" % url)
            logging.info("FB response: %s" % response)

            access_token = response['access_token'][0]

            facebook_session = FacebookSession(access_token=access_token)
            profile = facebook_session.query('me', fields=['id', 'email', 'first_name', 'last_name', 'picture'])
            passenger.picture_url = profile['picture']['data']['url']
            passenger.fb_id = profile['id']
            passenger.save()
            logging.info("passenger picture updated: %s" % passenger.picture_url)
        except Exception, e:
            pass
Example #2
0
def do_invoice_passenger_action(passenger, action_payload):
    payload = {
#        "ReplyURL": "ReturnPage.asp",
        "TransType"						: "",
        "Username"						: INVOICE_INFO["invoice_username"],
        "CompanyCode"                   : "",
        "CompanyName"                   : passenger.full_name,
        "CompanyAddress"                : "",
        "CompanyCity"                   : "",
        "CompanyState"                  : "",
        "CompanyZipcode"                : "",
        "CompanyTel1"                   : passenger.phone,
        "CompanyTel2"                   : "",
        "CompanyCell"                   : "",
        "CompanyFax"                    : "",
        "CompanyEmail"                  : passenger.user.email,
        "CompanyWebsite"                : "",
        "CompanyComments"               : "",
        }

    payload.update(action_payload)
    url = INVOICE_INFO["invoice_url"]
    payload = dict([(k,v.encode('iso8859_8', 'ignore') if type(v) is types.UnicodeType else v) for (k,v) in payload.items()])
    payload = urlencode(payload)
    result = safe_fetch(url, method="POST", payload=payload, deadline=50, headers={'Content-Type': 'application/x-www-form-urlencoded'})

    return result
Example #3
0
    def authenticate(self, request, user=None):
        cookie = facebook.get_user_from_cookie(request.COOKIES, FACEBOOK_APP_ID, FACEBOOK_SECRET_KEY)

        if cookie:
            uid = cookie['uid']
            access_token = cookie['access_token']
        else:
            # if cookie does not exist
            # assume logging in normal way
            params = {}
            params["client_id"] = FACEBOOK_APP_ID
            params["client_secret"] = FACEBOOK_SECRET_KEY
            params["redirect_uri"] = reverse("socialauth_facebook_login_done")[1:] 
            params["code"] = request.GET.get('code', '')

            url = "https://graph.facebook.com/oauth/access_token?"+urllib.urlencode(params)
            from cgi import parse_qs
            userdata = urllib.urlopen(url).read()
            res_parse_qs = parse_qs(userdata)
            # Could be a bot query
            if not res_parse_qs.has_key('access_token'):
                return None
                
            parse_data = res_parse_qs['access_token']
            uid = parse_data['uid'][-1]
            access_token = parse_data['access_token'][-1]
            
        try:
            fb_user = FacebookUserProfile.objects.get(facebook_uid=uid)
            return fb_user.user

        except FacebookUserProfile.DoesNotExist:
            
            # create new FacebookUserProfile
            graph = facebook.GraphAPI(access_token) 
            fb_data = graph.get_object("me")

            if not fb_data:
                return None

            username = uid
            if not user:
                user = User.objects.create(username=username)
                user.first_name = fb_data['first_name']
                user.last_name = fb_data['last_name']
                user.save()
                
            fb_profile = FacebookUserProfile(facebook_uid=uid, user=user)
            fb_profile.save()
            
            auth_meta = AuthMeta(user=user, provider='Facebook').save()
                
            return user
Example #4
0
def facebook_login(request):
    from sharing.passenger_controller import post_login_redirect

    error = None
    redirect = reverse(post_login_redirect)

    if request.user.is_authenticated():
        return HttpResponseRedirect(redirect)

    if request.GET:
        if 'code' in request.GET:
            args = {
                'client_id': settings.FACEBOOK_APP_ID,
                'redirect_uri': settings.FACEBOOK_REDIRECT_URI,
                'client_secret': settings.FACEBOOK_APP_SECRET,
                'code': request.GET['code'],
                }

            url = 'https://graph.facebook.com/oauth/access_token?' +\
                  urllib.urlencode(args)
            response = cgi.parse_qs(urllib.urlopen(url).read())

            logging.info("FB query: %s" % url)
            logging.info("FB response: %s" % response)

            access_token = response['access_token'][0]
            expires = response['expires'][0]

            facebook_session = FacebookSession.objects.get_or_create(
                access_token=access_token,
            )[0]

            facebook_session.expires = expires
            facebook_session.save()

            #            logging.info("saved facebook_session id=%s" % facebook_session.id)

            user = auth.authenticate(token=access_token)
            if user:
                if user.is_active:
                    auth.login(request, user)
                    return HttpResponseRedirect(redirect)
                else:
                    error = 'AUTH_DISABLED'
            else:
                error = 'AUTH_FAILED'
        elif 'error_reason' in request.GET:
            error = 'AUTH_DENIED'

    template_context = {'settings': settings, 'error': error}
    return render_to_response('facebook_login.html', template_context, context_instance=RequestContext(request))
Example #5
0
def get_user_info(api_key, api_secret, cookies):
    user_info_params = {
                                        'method': 'Users.getInfo',
                                        'api_key': api_key,
                                        'call_id': time.time(),
                                        'v': '1.0',
                                        'uids': cookies[api_key + '_user'],
                                        'fields': 'uid,first_name,last_name,pic_small, name, current_location',
                                        'format': 'json',
                                    }

    user_info_hash = get_facebook_signature(api_key, api_secret, user_info_params)
    user_info_params['sig'] = user_info_hash            
    user_info_params = urllib.urlencode(user_info_params)
    user_info_response  = simplejson.load(urllib.urlopen(REST_SERVER, user_info_params))
    return user_info_response
Example #6
0
def send_invoices_passenger(billing_transactions):
    trx = billing_transactions[0]

    if not all([_trx.passenger.id == trx.passenger.id for _trx in billing_transactions]):
        logging.error("all transactions should belong to the same passenger")
        return False

    if not trx.passenger.invoice_id:
        logging.error("failed sending invoices to passenger_id %s: passenger has no invoice_id" % trx.passenger_id)
        return False

    payload = {
        "TransType"						: "IR:CREATE101",
        "Username"						: INVOICE_INFO["invoice_username"],
        "Key"	    					: INVOICE_INFO["invoice_key"],
        "InvoiceSubject"				: "%s %s" %(_("Ride Summary for month"), trx.charge_date.strftime("%m/%Y")),
        "InvoiceItemCode"				: "|".join([str(trx.order.id) for trx in billing_transactions]),
        "InvoiceItemDescription"		: "|".join([trx.order.invoice_description for trx in billing_transactions]),
        "InvoiceItemQuantity"			: "|".join(["1" for trx in billing_transactions]),
        "InvoiceItemPrice"				: "|".join([str(trx.amount) for trx in billing_transactions]),
        "MailTo"						: trx.passenger.user.email,
        "CompanyCode"					: trx.passenger.invoice_id,
        "ItemPriceIsWithTax"			: 1,
        }

    url = INVOICE_INFO["invoice_url"]

    payload = dict([(k,v.encode('iso8859_8', 'ignore') if type(v) is types.UnicodeType else v) for (k,v) in payload.items()])
    payload = urlencode(payload)

    result = safe_fetch(url, method="POST", payload=payload, deadline=50, headers={'Content-Type': 'application/x-www-form-urlencoded'})
    response_code = re.findall(r"ResponseCode:(\d+)", result.content)
    if response_code and response_code[0] == "100":
        for tx in billing_transactions:
            tx.invoice_sent = True
            tx.save()
        logging.info("invoices sent to passenger %s" % trx.passenger_id)
        return True
    else:
        logging.error("failed sending invoices to passenger_id %s: response_code=%s" % (trx.passenger_id, response_code))
        return False
Example #7
0
def talk_to_fb(api_key, api_secret, params):
    sig = get_facebook_signature(api_key, api_secret, params)
    params['sig'] = sig
    data = urllib.urlencode(params)
    response = simplejson.load(urllib.urlopen(REST_SERVER, data))
    return response