Beispiel #1
0
 def facebook(self):
     """Get a facebook object, if pyfacebook is present, the user is logged
     in and is a facebook connect user. Otherwise this is None."""
     try:
         from facebook import Facebook
     except ImportError:
         log.warning("PyFacebook is not installed!")
     else:
         if self.user and self.user.profile.uses_facebook_connect:
             # This implies, that the correct cookies must be set. We don't
             # double check for that.
             api_key = get_app().cfg['facebook/api_key']
             secret_key = get_app().cfg['facebook/secret_key']
             facebook = Facebook(api_key, secret_key)
             # Setting the cookie values
             # It's so cool to have no private attributes. (;
             facebook.uid = self.session['fb_user_id']
             facebook.session_key = self.session['fb_session_id']
             return facebook
Beispiel #2
0
    def _set_password(self, password):
        """encrypts password on the fly."""
        self._password = self.__encrypt_password(password)
        
        # Check if digest save is enabled for digest auth (RFC 2617)
        auth_realm = get_app().cfg['general/auth_realm']
        if auth_realm:
            pw_digest = md5(u"%s:%s:%s" %
                           (self.user_name,
                            auth_realm,
                            password)
                          ).hexdigest()

            # Enforce UTF-8
            if not isinstance(pw_digest, unicode):
                self._password_digest = pw_digest.decode('UTF-8')
            else:
                self._password_digest = pw_digest
Beispiel #3
0
    def __encrypt_password(self, password):
        """Hash the given password with SHA1."""
        
        if isinstance(password, unicode):
            password_8bit = password.encode('UTF-8')

        else:
            password_8bit = password

        app = get_app()

        hashed_password = sha1()
        hashed_password.update(password_8bit)
        hashed_password.update(app.cfg['sessions/secret'])
        hashed_password = hashed_password.hexdigest()

        # make sure the hased password is an UTF-8 object at the end of the
        # process because SQLAlchemy _wants_ a unicode object for Unicode columns
        if not isinstance(hashed_password, unicode):
            hashed_password = hashed_password.decode('UTF-8')

        return hashed_password
Beispiel #4
0
    def __init__(self, namespace, cache_args=None, **kwargs):
        """
        Creates a new cache decorator overriding the default expire and
        namespace values specified in the config.ini.

        Example use::

            @CachedView("my_cache", cache_args=('user_id',), expire=60*5)
            def user_profile(self, req, user_id):
                ...

        :param namespace: `thing` to cache. Keep for invaliation.
        :param cache_args: function arguments used to generate the key from.
        Accepts a list of argument names. String representation of arguments
        is used, so make sure you properly implemented __str__.

        Additional arguments are passed to :class:`beaker.Cache`.
        """

        self.namespace = namespace
        self.cache_args = cache_args
        self.extra_kwargs = kwargs
        self.app = get_app()
Beispiel #5
0
def list_api_methods():
    """List all API methods."""
    result = []
    application = get_app()
    for rule in application.map.iter_rules():
        if rule.build_only:
            continue
        view = application.view_finder.find(rule.endpoint)
        if not getattr(view, "is_api_method", False):
            continue
        handler = view.__name__
        if handler.startswith("api_"):
            handler = handler[4:]
        result.append(
            dict(
                handler=handler,
                valid_methods=view.valid_methods,
                doc=format_rst((inspect.getdoc(view) or "").decode("utf-8")),
                url=unicode(rule),
            )
        )
    result.sort(key=lambda x: (x["url"], x["handler"]))
    return result
Beispiel #6
0
from babel import Locale, UnknownLocaleError
from werkzeug.exceptions import MethodNotAllowed, BadRequest
from werkzeug import Response, escape, Request

from glashammer.utils.local import get_app
from glashammer.utils.wrappers import render_template
from glashammer.utils.lazystring import make_lazy_string

from glashammer.bundles.i18n2 import _, has_section
from .remoting import remote_export_primitive
from .rst_formatting import format_rst
from .decorators import on_method


# If this is included too early, eager loading raises a KeyError.
XML_NS = make_lazy_string(lambda: get_app().cfg["api/xml_ns"])


_escaped_newline_re = re.compile(r"(?:(?:\\r)?\\n)")
log = logging.getLogger("rdreilib.api")


def debug_dump(obj):
    """Dumps the data into a HTML page for debugging."""
    dump = _escaped_newline_re.sub("\n", simplejson.dumps(obj, ensure_ascii=False, indent=2))
    return render_template("api/debug_dump.html", dump=dump)


def dump_xml(obj):
    """Dumps data into a simple XML format."""