Exemple #1
0
    def __init__(self, paykey, remote_address):
        headers = {
            'X-PAYPAL-SECURITY-USERID': settings.get('paypal').get('userid'),
            'X-PAYPAL-SECURITY-PASSWORD':
            settings.get('paypal').get('password'),
            'X-PAYPAL-SECURITY-SIGNATURE':
            settings.get('paypal').get('signature'),
            'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
            'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
            'X-PAYPAL-APPLICATION-ID': settings.get('paypal').get('app_id'),
            'X-PAYPAL-DEVICE-IPADDRESS': remote_address,
        }

        data = {
            'key': paykey,
            'requestEnvelope': {
                'errorLanguage': 'en_US'
            },
        }

        self.raw_request = json.dumps(data)
        self.raw_response = url_request(
            "%s%s" %
            (settings.get('paypal').get('endpoint'), "GetShippingAddresses"),
            data=self.raw_request,
            headers=headers).content()
        logging.debug("response was: %s" % self.raw_response)
        self.response = json.loads(self.raw_response)
Exemple #2
0
    def __init__(self):
        # Your Account Sid and Auth Token from twilio.com/user/account

        account_sid = settings.get('twilio').get('account_sid')
        auth_token = settings.get('twilio').get('auth_token')

        self.from_number = "+17602784278"
        self.client = TwilioRestClient(account_sid, auth_token)
Exemple #3
0
 def get_key_and_secret(self):
     """Return tuple with Consumer Key and Consumer Secret for current
     service provider. Must return (key, secret), order *must* be respected.
     """
     app = webapp2.get_app()
     from ferris import settings
     #return app.config.get('twitter_consumer_key'), app.config.get('twitter_consumer_secret')
     return settings.get("twitter_consumer_key"), settings.get("twitter_consumer_secret")
Exemple #4
0
    def __init__(self, quantity, amount, return_url, cancel_url, remote_address, secondary_receiver=None, ipn_url=None, shipping=False):
        headers = {
            'X-PAYPAL-SECURITY-USERID': settings.get('paypal').get('userid'),
            'X-PAYPAL-SECURITY-PASSWORD': settings.get('paypal').get('password'),
            'X-PAYPAL-SECURITY-SIGNATURE': settings.get('paypal').get('signature'),
            'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
            'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
            'X-PAYPAL-APPLICATION-ID': settings.get('paypal').get('app_id'),
            'X-PAYPAL-DEVICE-IPADDRESS': remote_address,
        }

        data = {
            # 'version': '93',
            # 'method': 'SetExpressCheckout',
            'currencyCode': 'PHP',
            'returnUrl': return_url,
            'cancelUrl': cancel_url,
            'requestEnvelope': {'errorLanguage': 'en_US'},
        }

        if shipping:
            data['actionType'] = 'CREATE'
        else:
            data['actionType'] = 'PAY'

        if secondary_receiver is None:  # simple payment
            total = quantity * amount * settings.get('paypal').get('commission')
            data['receiverList'] = {'receiver': [
                {'email': settings.get('paypal').get('email'), 'amount': '%0.2f' % total}
            ]
            }
        else:  # chained
            commission = amount * settings.get('paypal').get('commission')
            data['receiverList'] = {'receiver': [
                {'email': settings.PAYPAL_EMAIL, 'amount': '%0.2f' % amount, 'primary': 'true'},
                {'email': secondary_receiver, 'amount': '%0.2f' % (amount - commission), 'primary': 'false'},
            ]
            }

        if ipn_url is not None:
            data['ipnNotificationUrl'] = ipn_url

        self.raw_request = json.dumps(data)
        # request = urllib2.Request( "%s%s" % ( settings.PAYPAL_ENDPOINT, "Pay" ), data=self.raw_request, headers=headers )
        # self.raw_response = urllib2.urlopen( request ).read()
        self.raw_response = url_request("%s%s" % (settings.get('paypal').get('endpoint'), "Pay"), data=self.raw_request, headers=headers).content()
        logging.debug("response was: %s" % self.raw_response)
        self.response = json.loads(self.raw_response)

        if shipping:
            # generate setpaymentoptions request
            options_raw_request = json.dumps({
                'payKey': self.paykey(),
                'senderOptions': {'requireShippingAddressSelection': 'true', 'shareAddress': 'true'},
                'requestEnvelope': {'errorLanguage': 'en_US'}
            })
            options_raw_response = url_request("%s%s" % (settings.get('paypal').get('endpoint'), "SetPaymentOptions"), data=options_raw_request, headers=headers).content()
            logging.debug('SetPaymentOptions response: %s' % options_raw_response)
    def _on_before_render(self, controller, *args, **kwargs):
        chtml = captcha.displayhtml(
            public_key=settings.get('captcha_public_key'),
            use_ssl=(controller.request.scheme == 'https'),
            error=None)
        if settings.get('captcha_public_key') == "PUT_YOUR_RECAPCHA_PUBLIC_KEY_HERE" or \
            settings.get('captcha_private_key') == "PUT_YOUR_RECAPCHA_PUBLIC_KEY_HERE":
            chtml = '<div class="alert alert-danger"><strong>Error</strong>: You have to ' \
                '<a href="http://www.google.com/recaptcha/whyrecaptcha" target="_blank">sign up ' \
                'for API keys</a> in order to use reCAPTCHA.</div>' \
                '<input type="hidden" name="recaptcha_challenge_field" value="manual_challenge" />' \
                '<input type="hidden" name="recaptcha_response_field" value="manual_challenge" />'

        controller.context['captcha_html'] = chtml
Exemple #6
0
    def _on_before_render(self, controller, *args, **kwargs):
        chtml = captcha.displayhtml(
          public_key=settings.get('captcha_public_key'),
          use_ssl=(controller.request.scheme == 'https'),
          error=None)
        if settings.get('captcha_public_key') == "PUT_YOUR_RECAPCHA_PUBLIC_KEY_HERE" or \
            settings.get('captcha_private_key') == "PUT_YOUR_RECAPCHA_PUBLIC_KEY_HERE":
          chtml = '<div class="alert alert-danger"><strong>Error</strong>: You have to ' \
              '<a href="http://www.google.com/recaptcha/whyrecaptcha" target="_blank">sign up ' \
              'for API keys</a> in order to use reCAPTCHA.</div>' \
              '<input type="hidden" name="recaptcha_challenge_field" value="manual_challenge" />' \
              '<input type="hidden" name="recaptcha_response_field" value="manual_challenge" />'

        controller.context['captcha_html'] = chtml
Exemple #7
0
def hashing(plaintext, salt="", sha="512"):
    """ Returns the hashed and encrypted hexdigest of a plaintext and salt"""
    app = webapp2.get_app()

    # Hashing
    if sha == "1":
        phrase = hashlib.sha1()
    elif sha == "256":
        phrase = hashlib.sha256()
    else:
        phrase = hashlib.sha512()
    phrase.update("%s@%s" % (plaintext, salt))
    phrase_digest = phrase.hexdigest()

    # Encryption (PyCrypto)
    # wow... it's so secure :)
    try:
        from Crypto.Cipher import AES

        mode = AES.MODE_CBC

        # We can not generate random initialization vector because is difficult to retrieve them later without knowing
        # a priori the hash to match. We take 16 bytes from the hexdigest to make the vectors different for each hashed
        # plaintext.
        iv = phrase_digest[:16]
        encryptor = AES.new(settings.get('aes_key'), mode, iv)
        ciphertext = [
            encryptor.encrypt(chunk) for chunk in chunks(phrase_digest, 16)
        ]
        return ''.join(ciphertext)
    except Exception, e:
        logging.error("CRYPTO is not running: {}".format(e))
        raise
def get_config():
    from ferris import settings

    config = settings.get("oauth2_service_account")
    if not config["private_key"] or not config["client_email"]:
        raise RuntimeError("OAuth2 Service Account is not configured correctly")
    return config
Exemple #9
0
    def __init__(self, request):
        # verify that the request is paypal's
        self.error = None
        # verify_request = urllib2.Request( "%s?cmd=_notify-validate" % settings.PAYPAL_PAYMENT_HOST, data=urllib.urlencode( request.POST.copy() ) )
        # verify_response = urllib2.urlopen( verify_request)
        verify_response = url_request("%s?cmd=_notify-validate" % settings.get('paypal').get('payment_host'), data=urllib.urlencode(request.POST.copy()))
        # check code
        if verify_response.code() != 200:
            self.error = 'PayPal response code was %i' % verify_response.code()
            return
        # check response
        raw_response = verify_response.content()
        if raw_response != 'VERIFIED':
            self.error = 'PayPal response was "%s"' % raw_response
            return
        # check payment status
        if request.get('status') != 'COMPLETED':
            self.error = 'PayPal status was "%s"' % request.get('status')
            return

        (currency, amount) = request.get("transaction[0].amount").split(' ')
        if currency != 'PHP':
            self.error = 'Incorrect currency %s' % currency
            return

        self.amount = decimal.Decimal(amount)
Exemple #10
0
 def admin(self):
     self.meta.view.template_name = 'angular/admin-index.html'
     active_user = UserSvc.get_current_user()
     user = Account.transform_message(active_user)
     self.context['active_user'] = protojson.encode_message(user)
     self.context['logout_url'] = users.create_logout_url('/')
     self.context['commission'] = settings.get('paypal').get('commission')
Exemple #11
0
def hashing(plaintext, salt="", sha="512"):
    """ Returns the hashed and encrypted hexdigest of a plaintext and salt"""
    app = webapp2.get_app()

    # Hashing
    if sha == "1":
        phrase = hashlib.sha1()
    elif sha == "256":
        phrase = hashlib.sha256()
    else:
        phrase = hashlib.sha512()
    phrase.update("%s@%s" % (plaintext, salt))
    phrase_digest = phrase.hexdigest()

    # Encryption (PyCrypto)
    # wow... it's so secure :)
    try:
        from Crypto.Cipher import AES

        mode = AES.MODE_CBC

        # We can not generate random initialization vector because is difficult to retrieve them later without knowing
        # a priori the hash to match. We take 16 bytes from the hexdigest to make the vectors different for each hashed
        # plaintext.
        iv = phrase_digest[:16]
        encryptor = AES.new(settings.get('aes_key'), mode, iv)
        ciphertext = [encryptor.encrypt(chunk) for chunk in chunks(phrase_digest, 16)]
        return ''.join(ciphertext)
    except Exception, e:
        logging.error("CRYPTO is not running: {}".format(e))
        raise
Exemple #12
0
def get_config():
    config = settings.get('oauth2_service_account')
    if not config['private_key'] or not config['client_email'] or not config[
            'domain']:
        raise RuntimeError(
            "OAuth2 Service Account is not configured correctly")
    return config
Exemple #13
0
    def __init__(self, request):
        # verify that the request is paypal's
        self.error = None
        # verify_request = urllib2.Request( "%s?cmd=_notify-validate" % settings.PAYPAL_PAYMENT_HOST, data=urllib.urlencode( request.POST.copy() ) )
        # verify_response = urllib2.urlopen( verify_request)
        verify_response = url_request(
            "%s?cmd=_notify-validate" %
            settings.get('paypal').get('payment_host'),
            data=urllib.urlencode(request.POST.copy()))
        # check code
        if verify_response.code() != 200:
            self.error = 'PayPal response code was %i' % verify_response.code()
            return
        # check response
        raw_response = verify_response.content()
        if raw_response != 'VERIFIED':
            self.error = 'PayPal response was "%s"' % raw_response
            return
        # check payment status
        if request.get('status') != 'COMPLETED':
            self.error = 'PayPal status was "%s"' % request.get('status')
            return

        (currency, amount) = request.get("transaction[0].amount").split(' ')
        if currency != 'PHP':
            self.error = 'Incorrect currency %s' % currency
            return

        self.amount = decimal.Decimal(amount)
Exemple #14
0
    def start_purchase(self, item):
        account = self.util.decode_key(item.scalper_name).get()
        params = {
            'item': item.key,
            'owner': account.email,
            'purchaser': users.get_current_user(),
            'status': 'NEW',
            'secret': utils.random_alnum(16)
        }
        purchase = Purchase.create(params)
        if settings.get('paypal').get('use_ipn'):
            ipn_url = "%s/ipn/%s/%s/" % (self.request.host_url, purchase.key(), purchase.secret)
        else:
            ipn_url = None
        if settings.get('paypal').get('use_chain'):
            seller_paypal_email = utils.paypal_email(account.email)
        else:
            seller_paypal_email = None

        pay = paypal.Pay(
            item.quantity,
            item.price,
            "%s" % ("http://" + app_identity.get_default_version_hostname()),
            # "%sreturn/%s/%s/" % (self.request.uri, purchase.key, purchase.secret),
            "%s" % ("http://" + app_identity.get_default_version_hostname()),
            # "%scancel/%s/" % (self.request.uri, purchase.key),
            self.request.remote_addr,
            seller_paypal_email,
            ipn_url,
            shipping=settings.get('paypal').get('shipping'))

        purchase.debug_request = pay.raw_request
        purchase.debug_response = pay.raw_response
        purchase.paykey = pay.paykey()
        purchase.put()

        if pay.status() == 'CREATED':
            purchase.status = 'CREATED'
            purchase.put()
            item.sold = True
            item.put()
            return (True, pay)
        else:
            purchase.status = 'ERROR'
            purchase.put()
            return (False, pay)
Exemple #15
0
 def get_social_providers_info(self):
     providers = self.get_social_providers_names()
     result = {'used': [], 'unused': []}
     for k, v in settings.get('social_providers').items():
         if k in providers:
             result['used'].append(v)
         else:
             result['unused'].append(v)
     return result
Exemple #16
0
 def get_social_providers_info(self):
     providers = self.get_social_providers_names()
     result = {'used': [], 'unused': []}
     for k,v in settings.get('social_providers').items():
         if k in providers:
             result['used'].append(v)
         else:
             result['unused'].append(v)
     return result
Exemple #17
0
    def __init__(self, paykey, remote_address):
        headers = {
            'X-PAYPAL-SECURITY-USERID': settings.get('paypal').get('userid'),
            'X-PAYPAL-SECURITY-PASSWORD': settings.get('paypal').get('password'),
            'X-PAYPAL-SECURITY-SIGNATURE': settings.get('paypal').get('signature'),
            'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
            'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
            'X-PAYPAL-APPLICATION-ID': settings.get('paypal').get('app_id'),
            'X-PAYPAL-DEVICE-IPADDRESS': remote_address,
        }

        data = {
            'key': paykey,
            'requestEnvelope': {'errorLanguage': 'en_US'},
        }

        self.raw_request = json.dumps(data)
        self.raw_response = url_request("%s%s" % (settings.get('paypal').get('endpoint'), "GetShippingAddresses"), data=self.raw_request, headers=headers).content()
        logging.debug("response was: %s" % self.raw_response)
        self.response = json.loads(self.raw_response)
Exemple #18
0
def get_all_deleted_users(showDeleted=True):
    result = []
    directory = build('admin', 'directory_v1', http=build_client())
    page_token = None
    param = {
        'maxResults': '100'
    }
    if showDeleted:
        param['showDeleted'] = True
    else:
        param['query'] = 'isSuspended=True'

    directory_settings = settings.get('google_directory', {
        'domain': service_account.get_config()['domain']
    })

    if 'customer' in directory_settings:
        param['customer'] = directory_settings['customer']
    else:
        param['domain'] = directory_settings['domain']

    while True:
        try:
            if page_token:
                param['pageToken'] = page_token

            response = directory.users().list(**param).execute()

            if 'users' in response:
                for user in response['users']:
                    result.append(user['primaryEmail'])

            page_token = response.get('nextPageToken')

            if not page_token:
                break

            del response

        except Exception as error:
            logging.error(error)
            return False

    return result
Exemple #19
0
def get_all_users():
    result = []
    directory = build('admin', 'directory_v1', http=build_client())
    page_token = None
    param = {
        'maxResults': '100',
        'query': 'isSuspended=False'
    }

    directory_settings = settings.get('google_directory', {
        'domain': service_account.get_config()['domain']
    })

    if 'customer' in directory_settings:
        param['customer'] = directory_settings['customer']
    else:
        param['domain'] = directory_settings['domain']

    while True:
        try:
            if page_token:
                param['pageToken'] = page_token

            response = directory.users().list(**param).execute()

            for user in response['users']:
                result.append(dict(
                    (k, v) for k, v in user.iteritems()
                    if k in ('orgUnitPath', 'primaryEmail', 'name', 'thumbnailPhotoUrl', 'id', 'isAdmin', 'suspended', 'lastLoginTime')
                ))

            page_token = response.get('nextPageToken')

            if not page_token:
                break

            del response

        except Exception as error:
            logging.error(error)
            return False

    return result
def require_captcha_for_post(controller):
    """
    Returns True if the request method is POST and the captcha challenge was successful, otherwise returns False.
    """
    if controller.request.method == 'POST' and not controller.request.path.startswith(
            '/taskqueue'):

        # check captcha
        challenge = controller.request.POST.get('recaptcha_challenge_field')
        response = controller.request.POST.get('recaptcha_response_field')
        remoteip = controller.request.remote_addr

        cResponse = captcha.submit(challenge, response,
                                   settings.get('captcha_private_key'),
                                   remoteip)

        if not cResponse.is_valid:
            return (False, 'Wrong image verification code.')

    return True
Exemple #21
0
def get_all_deleted_users(showDeleted=True):
    result = []
    directory = build('admin', 'directory_v1', http=build_client())
    page_token = None
    param = {'maxResults': '100'}
    if showDeleted:
        param['showDeleted'] = True
    else:
        param['query'] = 'isSuspended=True'

    directory_settings = settings.get(
        'google_directory', {'domain': service_account.get_config()['domain']})

    if 'customer' in directory_settings:
        param['customer'] = directory_settings['customer']
    else:
        param['domain'] = directory_settings['domain']

    while True:
        try:
            if page_token:
                param['pageToken'] = page_token

            response = directory.users().list(**param).execute()

            if 'users' in response:
                for user in response['users']:
                    result.append(user['primaryEmail'])

            page_token = response.get('nextPageToken')

            if not page_token:
                break

            del response

        except Exception as error:
            logging.error(error)
            return False

    return result
Exemple #22
0
def require_captcha_for_post(controller):
    """
    Returns True if the request method is POST and the captcha challenge was successful, otherwise returns False.
    """
    if controller.request.method == 'POST' and not controller.request.path.startswith('/taskqueue'):

        # check captcha
        challenge = controller.request.POST.get('recaptcha_challenge_field')
        response = controller.request.POST.get('recaptcha_response_field')
        remoteip = controller.request.remote_addr

        cResponse = captcha.submit(
          challenge,
          response,
          settings.get('captcha_private_key'),
          remoteip)

        if not cResponse.is_valid:
            return (False, 'Wrong image verification code.')

    return True
Exemple #23
0
def get_all_users():
    result = []
    directory = build('admin', 'directory_v1', http=build_client())
    page_token = None
    param = {'maxResults': '100', 'query': 'isSuspended=False'}

    directory_settings = settings.get(
        'google_directory', {'domain': service_account.get_config()['domain']})

    if 'customer' in directory_settings:
        param['customer'] = directory_settings['customer']
    else:
        param['domain'] = directory_settings['domain']

    while True:
        try:
            if page_token:
                param['pageToken'] = page_token

            response = directory.users().list(**param).execute()

            for user in response['users']:
                result.append(
                    dict((k, v) for k, v in user.iteritems()
                         if k in ('orgUnitPath', 'primaryEmail', 'name',
                                  'thumbnailPhotoUrl', 'id', 'isAdmin',
                                  'suspended', 'lastLoginTime')))

            page_token = response.get('nextPageToken')

            if not page_token:
                break

            del response

        except Exception as error:
            logging.error(error)
            return False

    return result
Exemple #24
0
 def next_url(self):
     return '%s?cmd=_ap-payment&paykey=%s' % (settings.get('paypal').get(
         'payment_host'), self.response['payKey'])
Exemple #25
0
 def test_sanity(self):
     print(settings.get('oauth2_service_account'))
Exemple #26
0
from ferris import Controller, route_with, auth, add_authorizations, settings
from ferris.components.cache import Cache
from plugins import google_directory
from google.appengine.api import backends
import functools
import logging
import threading

config = settings.get('google_directory')
USE_BACKENDS = config.get('use_backend')
BACKEND_NAME = config.get('backend_name')
DEFAULT_LIMIT = config.get('limit', 30)


def backend_redirect(f):
    @functools.wraps(f)
    def inner(self, *args, **kwargs):
        if USE_BACKENDS and backends.get_backend() != BACKEND_NAME:
            return self.redirect(
                backends.get_url(BACKEND_NAME) + self.request.path_qs)
        return f(self, *args, **kwargs)

    return inner


require_user = add_authorizations(auth.require_user)

### WARNING: HACK ####
# This is a dangerous optimization.
# This would not be acceptable on a multi-threaded frontend and it's barely
# acceptable on a multithreaded backend. This should be re-worked with some locks
def get_config():
    config = settings.get('oauth2_service_account')
    if not config['private_key'] or not config['client_email'] or not config['domain']:
        raise RuntimeError("OAuth2 Service Account is not configured correctly")
    return config
Exemple #28
0
from google.appengine.ext import deferred
from google.appengine.api import users, app_identity, urlfetch, memcache
from gdata.calendar_resource.client import CalendarResourceClient
from gdata.gauth import OAuth2TokenFromCredentials as CreateToken
from app.etc import build_creds
import xml.etree.ElementTree as ET
import json
import time
import datetime
from plugins import calendar as calendar_api, google_directory, rfc3339
import logging
import urllib2

urlfetch.set_default_fetch_deadline(60)
APP_ID = app_identity.get_application_id()
oauth_config = settings.get('oauth2_service_account')
current_user = users.get_current_user()


class Calendars(Controller):
    class Meta:
        prefixes = ('api',)
        components = (Calendars,)
        View = 'json'

    @route_with(template='/api/calendar/events/<email>', methods=['GET'])
    def api_list_calendar_events(self, email):
        feed = []
        pageToken = None
        while True:
            response, pageToken = calendar_api.get_all_events(email, None, True, pageToken)
from ferris import plugins, settings
from sqlalchemy import create_engine

plugins.register('sqlalchemy')

db = settings.get('database')
engine = create_engine(db.get('connect_string'), **db.get('args'))
from ferris import BasicModel, ndb, settings
from google.appengine.api import mail, app_identity
APP_ID = app_identity.get_application_id()
oauth_config = settings.get('oauth2_service_account')
notifications_recipient = settings.get('notifications_recipient')


class DeprovisionedAccount(BasicModel):
    status = ndb.BooleanProperty()
    email = ndb.StringProperty()

    @classmethod
    def list_all(cls):
        return cls.query()

    @classmethod
    def create(cls, params):
        item = cls()
        item.populate(**params)
        item.put()
        return item

    @classmethod
    def remove(cls):
        ndb.delete_multi(DeprovisionedAccount.query().fetch(keys_only=True))

    @staticmethod
    def remove_owner_failed_notification(selectedEmail, event_summary,
                                         event_link):

        subject = "Arista Inc. - An attempt to remove an Owner of a Calendar Event has failed. "
Exemple #31
0
 def next_url(self):
     return '%s?cmd=_ap-payment&paykey=%s' % (settings.get('paypal').get('payment_host'), self.response['payKey'])
Exemple #32
0
 def test_sanity(self):
     print(settings.get('oauth2_service_account'))
Exemple #33
0
import httplib2
from google.appengine.ext import deferred
from apiclient.discovery import build
from ferris.core.memcache import cached_by_args
from ferris import settings
from plugins import service_account
import logging
import threading
import math
import ndb_cache


config = settings.get('google_directory')
USE_BACKENDS = config.get('use_backend', False)
BACKEND_NAME = config.get('backend_name')
DEFAULT_LIMIT = config.get('limit', 30)


scopes = (
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.group.readonly',
    'https://www.googleapis.com/auth/admin.directory.orgunit.readonly')


def build_client():
    http = httplib2.Http()
    credentials = service_account.build_credentials(scopes)
    credentials.authorize(http)
    return http

Exemple #34
0
    def __init__(self,
                 quantity,
                 amount,
                 return_url,
                 cancel_url,
                 remote_address,
                 secondary_receiver=None,
                 ipn_url=None,
                 shipping=False):
        headers = {
            'X-PAYPAL-SECURITY-USERID': settings.get('paypal').get('userid'),
            'X-PAYPAL-SECURITY-PASSWORD':
            settings.get('paypal').get('password'),
            'X-PAYPAL-SECURITY-SIGNATURE':
            settings.get('paypal').get('signature'),
            'X-PAYPAL-REQUEST-DATA-FORMAT': 'JSON',
            'X-PAYPAL-RESPONSE-DATA-FORMAT': 'JSON',
            'X-PAYPAL-APPLICATION-ID': settings.get('paypal').get('app_id'),
            'X-PAYPAL-DEVICE-IPADDRESS': remote_address,
        }

        data = {
            # 'version': '93',
            # 'method': 'SetExpressCheckout',
            'currencyCode': 'PHP',
            'returnUrl': return_url,
            'cancelUrl': cancel_url,
            'requestEnvelope': {
                'errorLanguage': 'en_US'
            },
        }

        if shipping:
            data['actionType'] = 'CREATE'
        else:
            data['actionType'] = 'PAY'

        if secondary_receiver is None:  # simple payment
            total = quantity * amount * settings.get('paypal').get(
                'commission')
            data['receiverList'] = {
                'receiver': [{
                    'email': settings.get('paypal').get('email'),
                    'amount': '%0.2f' % total
                }]
            }
        else:  # chained
            commission = amount * settings.get('paypal').get('commission')
            data['receiverList'] = {
                'receiver': [
                    {
                        'email': settings.PAYPAL_EMAIL,
                        'amount': '%0.2f' % amount,
                        'primary': 'true'
                    },
                    {
                        'email': secondary_receiver,
                        'amount': '%0.2f' % (amount - commission),
                        'primary': 'false'
                    },
                ]
            }

        if ipn_url is not None:
            data['ipnNotificationUrl'] = ipn_url

        self.raw_request = json.dumps(data)
        # request = urllib2.Request( "%s%s" % ( settings.PAYPAL_ENDPOINT, "Pay" ), data=self.raw_request, headers=headers )
        # self.raw_response = urllib2.urlopen( request ).read()
        self.raw_response = url_request(
            "%s%s" % (settings.get('paypal').get('endpoint'), "Pay"),
            data=self.raw_request,
            headers=headers).content()
        logging.debug("response was: %s" % self.raw_response)
        self.response = json.loads(self.raw_response)

        if shipping:
            # generate setpaymentoptions request
            options_raw_request = json.dumps({
                'payKey': self.paykey(),
                'senderOptions': {
                    'requireShippingAddressSelection': 'true',
                    'shareAddress': 'true'
                },
                'requestEnvelope': {
                    'errorLanguage': 'en_US'
                }
            })
            options_raw_response = url_request(
                "%s%s" %
                (settings.get('paypal').get('endpoint'), "SetPaymentOptions"),
                data=options_raw_request,
                headers=headers).content()
            logging.debug('SetPaymentOptions response: %s' %
                          options_raw_response)
from ferris import BasicModel, ndb, settings
from google.appengine.api import mail, app_identity
APP_ID = app_identity.get_application_id()
oauth_config = settings.get('oauth2_service_account')
notifications_recipient = settings.get('notifications_recipient')


class DeprovisionedAccount(BasicModel):
    status = ndb.BooleanProperty()
    email = ndb.StringProperty()

    @classmethod
    def list_all(cls):
        return cls.query()

    @classmethod
    def create(cls, params):
        item = cls()
        item.populate(**params)
        item.put()
        return item

    @classmethod
    def remove(cls):
        ndb.delete_multi(
            DeprovisionedAccount.query().fetch(keys_only=True)
        )

    @staticmethod
    def remove_owner_failed_notification(selectedEmail, event_summary, event_link):