Esempio n. 1
0
 def _get_or_create_account(self, domain, userid, username):
     acct_hash = hashlib.sha1("%s#%s" %
                              ((username or '').encode('utf-8'),
                               (userid or '').encode('utf-8'))).hexdigest()
     keys = [k for k in session.get('account_keys', '').split(',') if k]
     # Find or create an account
     for k in keys:
         acct = session[k]
         if acct['domain'] == domain and acct['userid'] == userid:
             metrics.track(request,
                           'account-auth',
                           domain=domain,
                           acct_id=acct_hash)
             break
     else:
         acct = dict(key=str(uuid1()),
                     domain=domain,
                     userid=userid,
                     username=username)
         metrics.track(request,
                       'account-create',
                       domain=domain,
                       acct_id=acct_hash)
         keys.append(acct['key'])
         session['account_keys'] = ','.join(keys)
     return acct
Esempio n. 2
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        session = environ['beaker.session']
        csrf_token = session.get('csrf')
        if not csrf_token:
            csrf_token = session['csrf'] = str(random.getrandbits(128))
            session.save()

        if request.method == 'POST':
            # check to see if we want to process the post at all
            if (self.unprotected_path is not None
                    and request.path_info.startswith(self.unprotected_path)):
                resp = request.get_response(self.app)
                resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
                resp.set_cookie('csrf', csrf_token, max_age=3600)
                return resp(environ, start_response)

            # check incoming token
            try:
                account_data = request.POST.get('account', None)
                request_csrf_token = environ.get('HTTP_X_CSRF',
                                                 request.POST.get('csrftoken'))
                if account_data is None and request_csrf_token != csrf_token:
                    resp = HTTPForbidden(_ERROR_MSG)
                    metrics.track(request, 'invalid-session')
                    resp.headers['X-Error'] = 'CSRF'
                else:
                    resp = request.get_response(self.app)
            except KeyError:
                resp = HTTPForbidden(_ERROR_MSG)
                resp.headers['X-Error'] = 'CSRF'
        # if we're a get, we don't do any checking
        else:
            resp = request.get_response(self.app)

        if resp.status_int != 200:
            return resp(environ, start_response)

        resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
        resp.set_cookie('csrf', csrf_token, max_age=3600)

        if resp.content_type.split(';')[0] in _HTML_TYPES:
            # ensure we don't add the 'id' attribute twice (HTML validity)
            idattributes = itertools.chain(('id="csrfmiddlewaretoken"', ),
                                           itertools.repeat(''))

            def add_csrf_field(match):
                """Returns the matched <form> tag plus the added <input> element"""
                return match.group() + '<div style="display:none;">' + \
                '<input type="hidden" ' + idattributes.next() + \
                ' name="csrftoken" value="' + csrf_token + \
                '" /></div>'

            # Modify any POST forms and fix content-length
            resp.body = _POST_FORM_RE.sub(add_csrf_field, resp.body)

        return resp(environ, start_response)
Esempio n. 3
0
File: csrf.py Progetto: SriramBms/f1
    def __call__(self, environ, start_response):
        request = Request(environ)
        session = environ['beaker.session']
        csrf_token = session.get('csrf')
        if not csrf_token:
            csrf_token = session['csrf'] = str(random.getrandbits(128))
            session.save()

        if request.method == 'POST':
            # check to see if we want to process the post at all
            if (self.unprotected_path is not None
                and request.path_info.startswith(self.unprotected_path)):
                resp = request.get_response(self.app)
                resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
                resp.set_cookie('csrf', csrf_token, max_age=3600)
                return resp(environ, start_response)

            # check incoming token
            try:
                account_data = request.POST.get('account', None)
                request_csrf_token = environ.get('HTTP_X_CSRF', request.POST.get('csrftoken'))
                if account_data is None and request_csrf_token != csrf_token:
                    resp = HTTPForbidden(_ERROR_MSG)
                    metrics.track(request, 'invalid-session')
                    resp.headers['X-Error'] = 'CSRF'
                else:
                    resp = request.get_response(self.app)
            except KeyError:
                resp = HTTPForbidden(_ERROR_MSG)
                resp.headers['X-Error'] = 'CSRF'
        # if we're a get, we don't do any checking
        else:
            resp = request.get_response(self.app)

        if resp.status_int != 200:
            return resp(environ, start_response)

        resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
        resp.set_cookie('csrf', csrf_token, max_age=3600)

        if resp.content_type.split(';')[0] in _HTML_TYPES:
            # ensure we don't add the 'id' attribute twice (HTML validity)
            idattributes = itertools.chain(('id="csrfmiddlewaretoken"',),
                                            itertools.repeat(''))
            def add_csrf_field(match):
                """Returns the matched <form> tag plus the added <input> element"""
                return match.group() + '<div style="display:none;">' + \
                '<input type="hidden" ' + idattributes.next() + \
                ' name="csrftoken" value="' + csrf_token + \
                '" /></div>'

            # Modify any POST forms and fix content-length
            resp.body = _POST_FORM_RE.sub(add_csrf_field, resp.body)

        return resp(environ, start_response)
Esempio n. 4
0
 def _get_or_create_account(self, domain, userid, username):
     acct_hash = hashlib.sha1(
         "%s#%s" % ((username or "").encode("utf-8"), (userid or "").encode("utf-8"))
     ).hexdigest()
     keys = [k for k in session.get("account_keys", "").split(",") if k]
     # Find or create an account
     for k in keys:
         acct = session[k]
         if acct["domain"] == domain and acct["userid"] == userid:
             metrics.track(request, "account-auth", domain=domain, acct_id=acct_hash)
             break
     else:
         acct = dict(key=str(uuid1()), domain=domain, userid=userid, username=username)
         metrics.track(request, "account-create", domain=domain, acct_id=acct_hash)
         keys.append(acct["key"])
         session["account_keys"] = ",".join(keys)
     return acct
Esempio n. 5
0
 def _get_or_create_account(self, domain, userid, username):
     acct_hash = hashlib.sha1("%s#%s" % ((username or '').encode('utf-8'), (userid or '').encode('utf-8'))).hexdigest()
     keys = [k for k in session.get('account_keys', '').split(',') if k]
     # Find or create an account
     for k in keys:
         acct = session[k]
         if acct['domain']==domain and acct['userid']==userid:
             metrics.track(request, 'account-auth', domain=domain,
                           acct_id=acct_hash)
             break
     else:
         acct = dict(key=str(uuid1()), domain=domain, userid=userid,
                     username=username)
         metrics.track(request, 'account-create', domain=domain, acct_id=acct_hash)
         keys.append(acct['key'])
         session['account_keys'] = ','.join(keys)
     return acct
Esempio n. 6
0
def json_exception_response(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except HTTPException:
        raise
    except Exception, e:
        log.exception("%s(%s, %s) failed", func, args, kwargs)
        #pylons = get_pylons(args)
        #pylons.response.status_int = 500
        metrics.track(get_pylons(args).request, 'unhandled-exception',
                      function=func.__name__, error=e.__class__.__name__)
        return {
            'result': None,
            'error': {
                'name': e.__class__.__name__,
                'message': str(e)
            }
        }
Esempio n. 7
0
    def get(self, domain):
        username = request.POST.get('username')
        userid = request.POST.get('userid')
        group = request.POST.get('group', None)
        startIndex = int(request.POST.get('startindex', '0'))
        maxResults = int(request.POST.get('maxresults', '25'))
        keys = session.get('account_keys', '').split(',')
        account_data = request.POST.get('account', None)
        if not keys:
            error = {
                'provider': domain,
                'message': "no user session exists, auth required",
                'status': 401
            }
            metrics.track(request, 'contacts-unauthed', domain=domain)
            return {'result': None, 'error': error}
        provider = get_provider(domain)

        # even if we have a session key, we must have an account for that
        # user for the specified domain.
        if account_data is not None:
            acct = json.loads(account_data)
        else:
            # support for old accounts in the session store
            acct = None
            for k in keys:
                a = session.get(k)
                if a and a.get('domain') == domain and (
                        not username or a.get('username') == username
                        and not userid or a.get('userid') == userid):
                    acct = a
                    break
        if not acct:
            metrics.track(request, 'contacts-noaccount', domain=domain)
            error = {
                'provider': domain,
                'message': "not logged in or no user account for that domain",
                'status': 401
            }
            return {'result': None, 'error': error}

        try:
            result, error = provider.api(acct).getcontacts(
                startIndex, maxResults, group)
        except OAuthKeysException, e:
            # more than likely we're missing oauth tokens for some reason.
            error = {
                'provider': domain,
                'message': "not logged in or no user account for that domain",
                'status': 401
            }
            result = None
            metrics.track(request,
                          'contacts-oauth-keys-missing',
                          domain=domain)
Esempio n. 8
0
    def get(self, domain):
        username = request.POST.get('username')
        userid = request.POST.get('userid')
        group = request.POST.get('group', None)
        startIndex = int(request.POST.get('startindex','0'))
        maxResults = int(request.POST.get('maxresults','25'))
        keys = session.get('account_keys', '').split(',')
        account_data = request.POST.get('account', None)
        if not keys:
            error = {'provider': domain,
                     'message': "no user session exists, auth required",
                     'status': 401
            }
            metrics.track(request, 'contacts-unauthed', domain=domain)
            return {'result': None, 'error': error}
        provider = get_provider(domain)

        # even if we have a session key, we must have an account for that
        # user for the specified domain.
        if account_data is not None:
            acct = json.loads(account_data)
        else:
            # support for old accounts in the session store
            acct = None
            for k in keys:
                a = session.get(k)
                if a and a.get('domain') == domain and (not username or a.get('username')==username and not userid or a.get('userid')==userid):
                    acct = a
                    break
        if not acct:
            metrics.track(request, 'contacts-noaccount', domain=domain)
            error = {'provider': domain,
                     'message': "not logged in or no user account for that domain",
                     'status': 401
            }
            return {'result': None, 'error': error}

        try:
            result, error = provider.api(acct).getcontacts(startIndex, maxResults, group)
        except OAuthKeysException, e:
            # more than likely we're missing oauth tokens for some reason.
            error = {'provider': domain,
                     'message': "not logged in or no user account for that domain",
                     'status': 401
            }
            result = None
            metrics.track(request, 'contacts-oauth-keys-missing', domain=domain)
Esempio n. 9
0
File: send.py Progetto: SriramBms/f1
    def send(self):
        result = {}
        error = None
        # If we don't have a key in our session we bail early with a
        # 401
        domain = request.POST.get('domain')
        message = request.POST.get('message', '')
        username = request.POST.get('username')
        longurl = request.POST.get('link')
        shorten = asbool(request.POST.get('shorten', 0))
        shorturl = request.POST.get('shorturl')
        userid = request.POST.get('userid')
        to = request.POST.get('to')
        account_data = request.POST.get('account', None)
        if not domain:
            error = {
                'message': "'domain' is not optional",
                'code': constants.INVALID_PARAMS
            }
            return {'result': result, 'error': error}
        keys = session.get('account_keys', '').split(',')
        if not keys:
            error = {'provider': domain,
                     'message': "no user session exists, auth required",
                     'status': 401
            }
            metrics.track(request, 'send-unauthed', domain=domain)
            return {'result': result, 'error': error}

        provider = get_provider(domain)
        # even if we have a session key, we must have an account for that
        # user for the specified domain.
        if account_data is not None:
            acct = json.loads(account_data)
        else:
            # support for old account data in session store
            acct = None
            for k in keys:
                a = session.get(k)
                if a and a.get('domain') == domain and (a.get('username')==username or a.get('userid')==userid):
                    acct = a
                    break
        if not acct:
            metrics.track(request, 'send-noaccount', domain=domain)
            error = {'provider': domain,
                     'message': "not logged in or no user account for that domain",
                     'status': 401
            }
            return {'result': result, 'error': error}

        args = copy.copy(request.POST)
        if shorten and not shorturl and longurl:
            link_timer = metrics.start_timer(request, long_url=longurl)
            u = urlparse(longurl)
            if not u.scheme:
                longurl = 'http://' + longurl
            shorturl = shorten_link(longurl)
            link_timer.track('link-shorten', short_url=shorturl)
            args['shorturl'] = shorturl

        acct_hash = hashlib.sha1("%s#%s" % ((username or '').encode('utf-8'), (userid or '').encode('utf-8'))).hexdigest()
        timer = metrics.start_timer(request, domain=domain, message_len=len(message),
                                    long_url=longurl, short_url=shorturl, acct_id=acct_hash)
        # send the item.
        try:
            result, error = provider.api(acct).sendmessage(message, args)
        except OAuthKeysException, e:
            # XXX - I doubt we really want a full exception logged here?
            #log.exception('error providing item to %s: %s', domain, e)
            # XXX we need to handle this better, but if for some reason the
            # oauth values are bad we will get a ValueError raised
            error = {'provider': domain,
                     'message': "not logged in or no user account for that domain",
                     'status': 401
            }
            
            metrics.track(request, 'send-oauth-keys-missing', domain=domain)
            timer.track('send-error', error=error)
            return {'result': result, 'error': error}
Esempio n. 10
0
    def send(self):
        result = {}
        error = None
        # If we don't have a key in our session we bail early with a
        # 401
        domain = request.POST.get('domain')
        message = request.POST.get('message', '')
        username = request.POST.get('username')
        longurl = request.POST.get('link')
        shorten = asbool(request.POST.get('shorten', 0))
        shorturl = request.POST.get('shorturl')
        userid = request.POST.get('userid')
        to = request.POST.get('to')
        account_data = request.POST.get('account', None)
        if not domain:
            error = {
                'message': "'domain' is not optional",
                'code': constants.INVALID_PARAMS
            }
            return {'result': result, 'error': error}
        keys = session.get('account_keys', '').split(',')
        if not keys:
            error = {
                'provider': domain,
                'message': "no user session exists, auth required",
                'status': 401
            }
            metrics.track(request, 'send-unauthed', domain=domain)
            return {'result': result, 'error': error}

        provider = get_provider(domain)
        # even if we have a session key, we must have an account for that
        # user for the specified domain.
        if account_data is not None:
            acct = json.loads(account_data)
        else:
            # support for old account data in session store
            acct = None
            for k in keys:
                a = session.get(k)
                if a and a.get('domain') == domain and (
                        a.get('username') == username
                        or a.get('userid') == userid):
                    acct = a
                    break
        if not acct:
            metrics.track(request, 'send-noaccount', domain=domain)
            error = {
                'provider': domain,
                'message': "not logged in or no user account for that domain",
                'status': 401
            }
            return {'result': result, 'error': error}

        args = copy.copy(request.POST)
        if shorten and not shorturl and longurl:
            link_timer = metrics.start_timer(request, long_url=longurl)
            u = urlparse(longurl)
            if not u.scheme:
                longurl = 'http://' + longurl
            shorturl = shorten_link(longurl)
            link_timer.track('link-shorten', short_url=shorturl)
            args['shorturl'] = shorturl

        acct_hash = hashlib.sha1("%s#%s" %
                                 ((username or '').encode('utf-8'),
                                  (userid or '').encode('utf-8'))).hexdigest()
        timer = metrics.start_timer(request,
                                    domain=domain,
                                    message_len=len(message),
                                    long_url=longurl,
                                    short_url=shorturl,
                                    acct_id=acct_hash)
        # send the item.
        try:
            result, error = provider.api(acct).sendmessage(message, args)
        except OAuthKeysException, e:
            # XXX - I doubt we really want a full exception logged here?
            #log.exception('error providing item to %s: %s', domain, e)
            # XXX we need to handle this better, but if for some reason the
            # oauth values are bad we will get a ValueError raised
            error = {
                'provider': domain,
                'message': "not logged in or no user account for that domain",
                'status': 401
            }

            metrics.track(request, 'send-oauth-keys-missing', domain=domain)
            timer.track('send-error', error=error)
            return {'result': result, 'error': error}