Esempio n. 1
0
    def add(self, fp, asset_id=None, **kw):
        """add a new file to the store

        :param fp: the file pointer to the file to be stored
        :param asset_id: An optional asset id. If not given, an asset id will be generated. Needs to be a string
        :param kw: optional keyword arguments simply passed back
        :return: A dictionary containing ``asset_id``, the filesystem ``path`` and the ``content_length``
        """
        if asset_id is None:
            asset_id = unicode(uuid.uuid4())

        path = self._get_path(asset_id)
        dirpath = os.path.split(path)[0]
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)

        dest_fp = open(path, "wb")
        shutil.copyfileobj(fp, dest_fp)
        dest_fp.close()

        content_length = os.path.getsize(path)

        res = AttributeMapper(asset_id=asset_id,
                              path=path,
                              content_length=content_length)
        res.update(kw)
        return res
Esempio n. 2
0
def test_dotted_update_first_missing():
    am = AttributeMapper({'a': AttributeMapper({
        'b': 9,
        'c': 10,
    })})

    pytest.raises(ValueError, am.update, {'foo': 'bar', 'e.b': 13})
Esempio n. 3
0
def test_nested():
    am = AttributeMapper({'a': AttributeMapper({
        'b': 9,
        'c': 10,
    })})

    assert am.a.b == 9
Esempio n. 4
0
    def add(self, fp, asset_id = None, **kw):
        """add a new file to the store

        :param fp: the file pointer to the file to be stored
        :param asset_id: An optional asset id. If not given, an asset id will be generated. Needs to be a string
        :param kw: optional keyword arguments simply passed back
        :return: A dictionary containing ``asset_id``, the filesystem ``path`` and the ``content_length``
        """
        if asset_id is None:
            asset_id = unicode(uuid.uuid4())

        path = self._get_path(asset_id)
        dirpath = os.path.split(path)[0]
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)

        dest_fp = open(path, "wb")
        shutil.copyfileobj(fp, dest_fp)
        dest_fp.close()

        content_length = os.path.getsize(path)

        res = AttributeMapper(
            asset_id = asset_id, 
            path = path,
            content_length = content_length
        )
        res.update(kw)
        return res
Esempio n. 5
0
def test_nested_update():
    am = AttributeMapper({'a': AttributeMapper({
        'b': 9,
        'c': 10,
    })})
    am.update({'foo': 'bar', 'a': {'b': 13}})

    assert am.a.b == 13
    assert am.a.c == 10
    assert am.foo == "bar"
Esempio n. 6
0
def test_dotted_update_no_dict():
    am = AttributeMapper({
        'a': AttributeMapper({
            'b': 9,
            'c': 10,
        }),
        'e': "foobar"
    })

    pytest.raises(ValueError, am.update, {'foo': 'bar', 'e.foo': 'bar'})
Esempio n. 7
0
def test_dotted_update_last_missing():
    am = AttributeMapper({'a': AttributeMapper({
        'b': 9,
        'c': 10,
    })})

    am.update({'foo': 'bar', 'a.e': 13})

    assert am.a.e == 13
    assert am.a.c == 10
    assert am.foo == "bar"
Esempio n. 8
0
def pytest_funcarg__config(request):
    """create a config with all the collections we need""" 
    db = request.getfuncargvalue("db")
    config = AttributeMapper()
    config.dbs = AttributeMapper()
    mydb = config.dbs.db = db
    config.dbs.barcamps = Barcamps(mydb.barcamps, app=None, config=config)
    config.dbs.sessions = Sessions(mydb.sessions, app=None, config=config)
    config.dbs.pages = Pages(mydb.pages, app=None, config=config)
    config.dbs.session_comments = Comments(mydb.session_comments, app=None, config=config)
    return config
Esempio n. 9
0
def pytest_funcarg__config(request):
    """create a config with all the collections we need"""
    db = request.getfuncargvalue("db")
    config = AttributeMapper()
    config.dbs = AttributeMapper()
    mydb = config.dbs.db = db
    config.dbs.barcamps = Barcamps(mydb.barcamps, app=None, config=config)
    config.dbs.sessions = Sessions(mydb.sessions, app=None, config=config)
    config.dbs.pages = Pages(mydb.pages, app=None, config=config)
    config.dbs.session_comments = Comments(mydb.session_comments,
                                           app=None,
                                           config=config)
    return config
Esempio n. 10
0
def test_dotted_update_last_missing():
    am = AttributeMapper({
        'a' : AttributeMapper({
            'b' : 9,
            'c' : 10,
        })
    })

    am.update({
        'foo' : 'bar',
        'a.e' : 13
    })
    
    assert am.a.e == 13
    assert am.a.c == 10
    assert am.foo == "bar"
Esempio n. 11
0
File: app.py Progetto: cryu/camper
    def finalize_setup(self):
        """do our own configuration stuff"""
        self.config.dbs = AttributeMapper()
        mydb = self.config.dbs.db = pymongo.Connection(
            self.config.mongodb_host,
            self.config.mongodb_port)[self.config.mongodb_name]
        self.config.dbs.barcamps = db.Barcamps(mydb.barcamps,
                                               app=self,
                                               config=self.config)
        self.config.dbs.sessions = db.Sessions(mydb.sessions,
                                               app=self,
                                               config=self.config)
        self.config.dbs.pages = db.Pages(mydb.pages,
                                         app=self,
                                         config=self.config)
        self.config.dbs.session_comments = db.Comments(mydb.session_comments,
                                                       app=self,
                                                       config=self.config)
        self.module_map.uploader.config.assets = Assets(mydb.assets,
                                                        app=self,
                                                        config=self.config)

        # etherpad connection
        self.config.etherpad = EtherpadLiteClient(
            base_params={'apikey': self.config.ep_api_key},
            base_url=self.config.ep_endpoint)
Esempio n. 12
0
def test_nested_update():
    am = AttributeMapper({
        'a' : AttributeMapper({
            'b' : 9,
            'c' : 10,
        })
    })
    am.update({
        'foo' : 'bar',
        'a' : {
            'b' : 13
        }
    })
    
    assert am.a.b == 13
    assert am.a.c == 10
    assert am.foo == "bar"
Esempio n. 13
0
File: base.py Progetto: cryu/camper
 def short_location(self):
     """properly format the location of the barcamp if given"""
     bc = self.barcamp
     location = AttributeMapper(bc.location)
     if location.name and location.city:
         return "%s, %s" %(location.name, location.city)
     else:
         return self.handler._("location to be announced")
Esempio n. 14
0
def app(request, config):
    app = camper.app.test_app({},**config)

    app.testdata = AttributeMapper() # for testing purposes
    app.testdata.users = AttributeMapper()
    app.testdata.users.admin = create_user(app, "admin") # TODO: actually make this user an admin
    app.testdata.users.user = create_user(app, "user")
    def fin():
        """finalizer to delete the database again"""
        app.config.dbs.db.users.remove()
        app.config.dbs.db.barcamps.remove()
        app.config.dbs.db.sessions.remove()
        app.config.dbs.db.pages.remove()
        app.config.dbs.db.session_comments.remove()
        app.config.dbs.db.assets.remove()
    request.addfinalizer(fin)
    return app
Esempio n. 15
0
def test_dotted_update2():
    am = AttributeMapper({
        'a' : AttributeMapper({
            'b' : 9,
            'c' : AttributeMapper({
                'd' : 19
            }),
        })
    })

    am.update({
        'foo' : 'bar',
        'a.b' : 13,
        'a.c.d' : 21
    })
    
    assert am.a.b == 13
    assert am.a.c.d == 21
    assert am.foo == "bar"
Esempio n. 16
0
def test_dotted_update2():
    am = AttributeMapper(
        {'a': AttributeMapper({
            'b': 9,
            'c': AttributeMapper({'d': 19}),
        })})

    am.update({'foo': 'bar', 'a.b': 13, 'a.c.d': 21})

    assert am.a.b == 13
    assert am.a.c.d == 21
    assert am.foo == "bar"
Esempio n. 17
0
File: app.py Progetto: sk1p/camper
    def finalize_setup(self):
        """do our own configuration stuff"""
        self.config.dbs = AttributeMapper()
        mydb = self.config.dbs.db = pymongo.MongoClient(self.config.mongodb_url)[self.config.mongodb_name]
        self.config.dbs.barcamps = db.Barcamps(mydb.barcamps, app=self, config=self.config)
        self.config.dbs.sessions = db.Sessions(mydb.sessions, app=self, config=self.config)
        self.config.dbs.pages = db.Pages(mydb.pages, app=self, config=self.config)
        self.config.dbs.blog = db.BlogEntries(mydb.blog, app=self, config=self.config)
        self.config.dbs.galleries = db.ImageGalleries(mydb.galleries, app=self, config=self.config)
        self.config.dbs.session_comments = db.Comments(mydb.session_comments, app=self, config=self.config)
        self.config.dbs.participant_data = db.DataForms(mydb.participant_data, app=self, config=self.config)
        self.config.dbs.tickets = db.Tickets(mydb.tickets, app=self, config=self.config)
        self.config.dbs.userfavs = db.UserFavs(mydb.userfavs, app=self, config=self.config)
        self.module_map.uploader.config.assets = Assets(mydb.assets, app=self, config=self.config)

        # etherpad connection
        self.config.etherpad = EtherpadLiteClient(
            base_params={'apikey': self.config.ep_api_key},
            base_url=self.config.ep_endpoint
        )
Esempio n. 18
0
 def get(self, slug=None):
     """render the view"""
     obj = AttributeMapper(self.barcamp.mail_templates)
     if self.barcamp.ticketmode_enabled:
         form = TicketMailsEditForm(self.request.form,
                                    obj=obj,
                                    config=self.config)
     else:
         form = MailsEditForm(self.request.form,
                              obj=obj,
                              config=self.config)
     if self.request.method == 'POST' and form.validate():
         self.barcamp.mail_templates = form.data
         self.barcamp.put()
         self.flash("Barcamp E-Mails aktualisiert", category="info")
         return redirect(
             self.url_for("barcamps.admin_wizard", slug=self.barcamp.slug))
     return self.render(view=self.barcamp_view,
                        barcamp=self.barcamp,
                        title=self.barcamp.name,
                        form=form,
                        **self.barcamp)
Esempio n. 19
0
File: um.py Progetto: cryu/userbase
class BaseUserModule(Module):
    """a module for implementing the user manager"""

    name = "userbase"

    routes = []

    defaults = {
        'login_view'            : 'users.login',
        'logout_view'           : 'users.logout',
        'verification_view'     : 'users.verification',
        'pw_forgotten_view'     : 'users.pw_forgotten',
        'pw_forgotten_code_view' : 'users.pw_forgotten_code',
        'use_remember'          : True, # whether the remember function/cookie is used
        'cookie_secret'         : None,
        'cookie_name'           : "r", # this cookie name is used as the remember cookie
        'cookie_domain'         : None, # means to use the domain from the app
        'cookie_lifetime'       : datetime.timedelta(days=365),
        'master_template'       : "master.html",
        'pw_salt'               : "CHANGE ME!",

        # database related
        'mongodb_url'           : "mongodb://localhost",
        'mongodb_host'          : "localhost",
        'mongodb_port'          : 27017,
        'mongodb_name'          : "userbase",                   # name of database to use
        'mongodb_collection'    : "users",                      # name of the collection to use
        'mongodb_kwargs'        : {},                           
        'user_class'            : db.User,                      # the db class we use for the user
        'collection_class'      : db.Users,                     # the collection class to use
        'user_id_field'         : 'email',                      # the field in the class and form with the id (email or username)

        # endpoints for redirects
        'urls'                  : AttributeMapper({
            'activation'            : {'endpoint' : 'userbase.activate'},
            'activation_success'    : {'endpoint' : 'root'},
            'activation_code_sent'  : {'endpoint' : 'root'},
            'login_success'         : {'endpoint' : 'root'},
            'registration_success'  : {'endpoint' : 'root'},
            'logout_success'        : {'endpoint' : 'userbase.login'},
            'double_opt_in_pending' : {'endpoint' : 'root'},
            'pw_code_success'       : {'endpoint' : 'userbase.login'},          # url to which to redirect after user has entered email address
            'pw_set_success'        : {'endpoint' : 'root'},                    # url to which to redirect after user has entered a new pw
            'pw_code_enter'         : {'endpoint' : 'userbase.pw_code_enter'},  # url to be sent via mail where the user can set the new password
        }),

        # in case you want your own handlers define them here. They will be set on finalize
        'handler:login'             : handlers.LoginHandler,
        'handler:logout'            : handlers.LogoutHandler,
        'handler:pw_forgot'         : handlers.PasswordForgotHandler,
        'handler:pw_code_enter'     : handlers.PasswordCodeHandler,
        'handler:pw_set'            : handlers.PasswordSetHandler,
        'handler:register'          : handlers.RegistrationHandler,     
        'handler:activate'          : handlers.ActivationHandler,      
        'handler:activation_code'   : handlers.ActivationCodeHandler,

        # form related
        'login_form'                : handlers.EMailLoginForm,          # the login form to use
        'registration_form'         : handlers.EMailRegistrationForm,   # the registration form to use
        'edit_form'                 : handlers.UserEditForm,            # the registration form to use
        'add_form'                  : handlers.UserAddForm,             # the registration form to use
        'pw_forgot_form'            : handlers.PWEMailForm,             # pw forgot form to use
        'pw_change_form'            : handlers.PasswordChangeForm,      # for setting a new password
        
        # further settings
        'enable_registration'       : False,                            # global switch for allowing new users or not
        'enable_usereditor'         : True,                             # global switch for registering the handlers for the user management
        'use_double_opt_in'         : True,                             # use double opt-in?
        'use_html_mail'             : True,                             # use HTML mail? If False, only text mail will be used
        'login_after_registration'  : False,                            # directly log in (even without activation)?
        'email_sender_name'         : "Your System",                    # which is the user who sends out codes etc.?
        'email_sender_address'      : "*****@*****.**",            # which is the user who sends out codes etc.?
        'subjects'                  : AttributeMapper({
            'registration'          : 'Your registration is nearly finished',
            'welcome'               : 'Welcome to our system',
            'password'              : 'Password reminder',
            'pw_code'               : 'Your password reset code',
        }),
        'emails'                    : AttributeMapper({
            'activation_code'       : '_m/userbase/emails/activation_code',
            'welcome'               : '_m/userbase/emails/welcome',
            'pw_code'               : '_m/userbase/emails/pw_code',
        }),
            
        # hooks
        'hooks'                     : hooks.Hooks,

        'permissions'               : AttributeMapper({
            'userbase:admin'        : "manage users",
        })
    }


    ####
    #### hooks
    ####

    # module hook
    def finalize(self):
        """finalize the configuration"""

        # database setup
        conn = self.connection = pymongo.MongoClient(self.config.mongodb_url)
        self.db = conn[self.config.mongodb_name]
        self.users = self.config.collection_class(self.db[self.config.mongodb_collection])
        self.users.SALT = self.config.pw_salt
        self.users.data_class = self.config.user_class # set the correct (custom) user class for it


        # URL setup
        self.add_url_rule(URL("/login", "login", self.config['handler:login']))
        self.add_url_rule(URL("/logout", "logout", self.config['handler:logout']))
        self.add_url_rule(URL("/pw_forgot", "pw_forgot", self.config['handler:pw_forgot']))
        self.add_url_rule(URL("/pw_code_enter", "pw_code_enter", self.config['handler:pw_code_enter']))
        self.add_url_rule(URL("/pw_set", "pw_set", self.config['handler:pw_set']))
        if self.config.enable_registration:
            self.add_url_rule(URL("/register", "register", self.config['handler:register']))
            if self.config.use_double_opt_in:
                self.add_url_rule(URL("/activate", "activate", self.config['handler:activate']))
                self.add_url_rule(URL("/activation_code", "activation_code", self.config['handler:activation_code']))
        if self.config.enable_usereditor:
            self.add_url_rule(URL("/admin/", "userlist", handlers.UserList))
            self.add_url_rule(URL("/admin/new", "useradd", handlers.UserAdd))
            self.add_url_rule(URL("/admin/<uid>", "useredit", handlers.UserEdit))
            self.add_url_rule(URL("/admin/<uid>/activate", "useractivate", handlers.UserActivate))

        # attach the global hooks
        self.hooks = self.config.hooks(self)

    # handler hooks
    def get_render_context(self, handler):
        """inject something into the render context"""
        p = {}
        user = self.get_user(handler)
        if user is not None and user.active:
            p['user'] = user
            p['user_id'] = str(user._id)
            p['logged_in'] = True
        return p

    def before_handler(self, handler):
        """check if we have a logged in user in the session. If not, check the remember cookie
        and maybe re-login the user
        """
        handler.user = None
        handler.user_id = None
        user = self.get_user_by_id(handler.session.get("userid", None))
        if user is not None:
            handler.user = user
            handler.user_id = str(user._id)
            return
        if self.config.cookie_name in handler.request.cookies and "userid" not in handler.session:
            cookie = self.app.load_cookie(handler.request, self.config.cookie_name)
        else:
            return
        if "userid" not in cookie and "hash" not in cookie:
            return

        # now try to set the token again
        user = self.get_user_by_id(cookie['userid'])
        if user is None:
            return
        if not user.active:
            return
        if cookie['hash'] != user.get_token():
            return
        handler.session['userid'] = user.get_id()
        handler.user = user

        # TODO: now reset the remember cookie
        # this means to move save_session from handler to module, better anyway
    
    def after_handler(self, handler, response):
        """check if we need to do a logout"""
        if handler.session.has_key("remember"):
            expires = datetime.datetime.utcnow() + self.config.cookie_lifetime
            self.app.set_cookie(response, self.config.cookie_name, handler.session['remember'], expires = expires)
            del handler.session['remember']
        if handler.session.has_key("remember_forget"):
            self.app.delete_cookie(response, self.config.cookie_name)
            del handler.session['remember_forget']
    ###
    ### user related
    ###

    def user_class(self):
        """return the user class"""
        return self.config.user_class

    def new_user(self, *args, **kwargs):
        """return an empty new user """
        return self.config.user_class(*args, **kwargs)

    def get_user(self, handler):
        """retrieve the user from the handler session or None"""
        return self.get_user_by_id(handler.session.get("userid", None))

    def get_user_by_credential(self, cred):
        """try to retrieve the user by the configured credential field"""
        return self.users.find_one({self.config.user_id_field : cred})

    def get_user_by_activation_code(self, code):
        """try to retrieve the user by the configured credential field"""
        if code is None:
            return None
        return self.users.find_one({'activation_code': code})

    def get_user_by_pw_code(self, code):
        """try to retrieve the user by the given password code"""
        if code is None:
            return None
        return self.users.find_one({'pw_code': code})

    def get_user_by_email(self, email):
        """try to retrieve the user by the email address"""
        return self.users.find_one({'email': email})

    def get_user_by_username(self, username):
        """try to retrieve the user by the username"""
        return self.users.find_one({'username': username})

    def get_users_by(self, key, value):
        """return a list of users which field ``key`` matches ``value``"""
        return self.users.find({key: value})

    def get_user_by_id(self, user_id):
        """returns the user or None if no user was found"""
        if not isinstance(user_id, bson.ObjectId):
            try:
                user_id = bson.ObjectId(user_id)
            except pymongo.errors.InvalidId:
                return None
        try:
            return self.users.get(user_id)
        except ObjectNotFound, e:
            return None
Esempio n. 20
0
def test_basics():
    am = AttributeMapper({'a': 3})

    assert am.a == 3
    assert am['a'] == 3
Esempio n. 21
0
class CamperApp(Application):
    """application"""

    defaults = {
        'hide_from_crawlers': False,
        'log_name': "camper",
        'script_virtual_host': "http://*****:*****@example.org",
        'from_name': "Barcamp-Tool",
        'new_bc_notification_addr':
        None,  # which email address to notify about newly created and published barcamps
        'sponsor_bc_notification_addr':
        None,  # which email address to notify about sponsorship requests 
        'ep_api_key': "please fill in from APIKEY.txt",
        'ep_endpoint': "http://localhost:9001/api",
        'ga': 'none',  #GA key
        'base_asset_path': '/tmp',  # where to store assets
        'fb_app_id': 'PLEASE FILL IN',  # get this from developers.facebook.com
        'log_filename': "/tmp/camper.log",
    }

    modules = [
        babel_module(locale_selector_func=get_locale, ),
        userbase.email_userbase(
            url_prefix="/users",
            mongodb_name="camper",
            master_template="master.html",
            login_after_registration=True,
            double_opt_in=True,
            enable_registration=True,
            enable_usereditor=True,
            user_class=db.CamperUser,
            use_remember=True,
            login_form=login.EMailLoginForm,
            urls={
                'activation': {
                    'endpoint': 'activation'
                },  # we use our own activation handler 
                'activation_success': {
                    'endpoint': 'index'
                },
                'activation_code_sent': {
                    'endpoint': 'userbase.activate'
                },
                'login_success': {
                    'endpoint': 'login_success'
                },
                'logout_success': {
                    'endpoint': 'userbase.login'
                },
                'registration_success': {
                    'endpoint': 'userbase.login'
                },
            },
            messages=AttributeMapper({
                'user_unknown':
                T('User unknown'),
                'email_unknown':
                T('This email address cannot not be found in our user database'
                  ),
                'password_incorrect':
                T('Your password is not correct'),
                'user_not_active':
                T(
                    'Your user has not yet been activated.'
                ),  # maybe provide link here? Needs to be constructed in handler
                'login_failed':
                T('Login failed'),
                'login_success':
                T('Welcome, %(fullname)s'),
                'logout_success':
                T('Your are now logged out'),
                'double_opt_in_pending':
                T('To finish the registration process please check your email with instructions on how to activate your account.'
                  ),
                'registration_success':
                T('Your user registration has been successful'),
                'activation_success':
                T('Your account has been activated'),
                'activation_failed':
                T('The activation code is not valid. Please try again or click <a href="%(url)s">here</a> to get a new one.'
                  ),
                'activation_code_sent':
                T('A new activation code has been sent out, please check your email'
                  ),
                'already_active':
                T('The user is already active. Please log in.'),
                'pw_code_sent':
                T('A link to set a new password has been sent to you'),
                'pw_changed':
                T('Your password has been changed'),

                # for user manager
                'user_edited':
                T('The user has been updated.'),
                'user_added':
                T('The user has been added.'),
                'user_deleted':
                T('The user has been deleted.'),
                'user_activated':
                T('The user has been activated.'),
                'user_deactivated':
                T('The user has been deactivated.'),
            }),
            permissions=AttributeMapper({
                'userbase:admin': T("can manage users"),
                'admin': T("main administrator"),
            })),
        mail_module(debug=True),
        barcamps.barcamp_module(url_prefix="/"),
        blog.blog_module(url_prefix="/"),
        pages.pages_module(url_prefix="/"),
    ]

    jinja_filters = {
        'nl2br': nl2br,
        'currency': do_currency,
        'tojson': _tojson_filter,
        'md': markdownify,
        'textify': textify,
    }

    jinja_options = {'autoescape': True}

    routes = [
        URL('/', 'index', handlers.index.IndexView),
        URL('/past', 'past_barcamps', handlers.index.PastBarcampsView),
        URL('/own', 'own_barcamps', handlers.index.OwnBarcampsView),
        URL('/login_success', 'login_success', handlers.index.LoginSuccess),
        #URL('/robots.txt', 'robots', RobotsTXT),
        URL('/impressum.html', 'impressum', handlers.index.Impressum),
        URL('/', 'root', handlers.index.IndexView),
        URL('/', 'login', handlers.index.IndexView),
        URL('/assets/', 'asset_upload', handlers.images.AssetUploadView),
        URL('/assets/<asset_id>', 'asset', handlers.images.AssetView),

        # sponsoring
        URL('/sponsoring', 'sponsoring', handlers.sponsor.SponsorContactView),

        # user stuff
        URL('/u/<username>', 'profile', handlers.users.profile.ProfileView),
        URL('/u/image_upload', 'profile_image_upload',
            handlers.users.ProfileImageAssetUploadView),
        URL('/u/image_delete', 'profile_image_delete',
            handlers.users.edit.ProfileImageDeleteView),
        URL('/u/user_delete', 'user_delete',
            handlers.users.delete_user.DeleteView),
        URL('/u/edit', 'profile_edit', handlers.users.edit.ProfileEditView),
        URL('/u/change_email', 'email_edit',
            handlers.users.change_email.EMailEditView),
        URL('/u/confirm_email', 'confirm_email',
            handlers.users.change_email.ConfirmEMail),
        URL('/u/activate', 'activation',
            handlers.users.activation.ActivationHandler),

        # admin area
        URL('/admin/', "admin_index", handlers.admin.index.IndexView),
    ]

    def finalize_setup(self):
        """do our own configuration stuff"""
        self.config.dbs = AttributeMapper()
        mydb = self.config.dbs.db = pymongo.MongoClient(
            self.config.mongodb_url)[self.config.mongodb_name]
        self.config.dbs.barcamps = db.Barcamps(mydb.barcamps,
                                               app=self,
                                               config=self.config)
        self.config.dbs.sessions = db.Sessions(mydb.sessions,
                                               app=self,
                                               config=self.config)
        self.config.dbs.pages = db.Pages(mydb.pages,
                                         app=self,
                                         config=self.config)
        self.config.dbs.blog = db.BlogEntries(mydb.blog,
                                              app=self,
                                              config=self.config)
        self.config.dbs.galleries = db.ImageGalleries(mydb.galleries,
                                                      app=self,
                                                      config=self.config)
        self.config.dbs.session_comments = db.Comments(mydb.session_comments,
                                                       app=self,
                                                       config=self.config)
        self.config.dbs.participant_data = db.DataForms(mydb.participant_data,
                                                        app=self,
                                                        config=self.config)
        self.config.dbs.tickets = db.Tickets(mydb.tickets,
                                             app=self,
                                             config=self.config)
        self.config.dbs.userfavs = db.UserFavs(mydb.userfavs,
                                               app=self,
                                               config=self.config)
        self.module_map.uploader.config.assets = Assets(mydb.assets,
                                                        app=self,
                                                        config=self.config)

        # etherpad connection
        self.config.etherpad = EtherpadLiteClient(
            base_params={'apikey': self.config.ep_api_key},
            base_url=self.config.ep_endpoint)

    def finalize_modules(self):
        """finalize all modules"""
        fsstore = FilesystemStore(base_path=self.config.base_asset_path)
        self.modules.append(
            upload_module(
                store=fsstore,
                processors=[
                    ImageSizeProcessor({
                        'thumb': "50x50!",
                        'small': "100x",
                        'logo_full': "1140x",
                        'medium_user': "******",
                        'userlist': '80x80!',
                        'fullwidth': "850x",
                        'gallery': "700x300!",
                        'facebook': "1200x630",
                    })
                ],
            ))

    def setup_logger(self):
        format_string = '[{record.time:%Y-%m-%d %H:%M:%S.%f%z}] {record.level_name} {record.channel} : {record.message} (in {record.filename}:{record.lineno}), args: {record.kwargs})'

        handler = logbook.FileHandler(self.config.log_filename,
                                      format_string=format_string,
                                      bubble=True)
        return logbook.NestedSetup([
            handler,
        ])

    def handle_http_exception(self, request, e):
        """handle http exceptions"""

        logger = logbook.Logger("error")
        if e.code != 404:
            logger.warn("http error", code=e.code, url=request.path)

        # setup the request properly for handlers to use
        urls = self.create_url_adapter(request)
        request.url_adapter = urls

        # we return a 404 now for every exception which probably is not good
        handler = NotFound(self, request)

        resp = handler()
        resp.status_code = e.code  # take code from exception
        return resp

    def get_barcamp(self, slug):
        """return a barcamp by it's slug

        :param slug: slug of the barcamp to retrieve
        :returns: barcamp object or
        """
        barcamp = self.config.dbs.barcamps.by_slug(slug)
        if barcamp is None:
            raise BarcampNotFound(slug=slug)
        return barcamp
Esempio n. 22
0
File: app.py Progetto: cryu/camper
class CamperApp(Application):
    """application"""

    defaults = {
        'log_name': "camper",
        'script_virtual_host': "http://*****:*****@example.org",
        'from_name': "Barcamp-Tool",
        'ep_api_key': "please fill in from APIKEY.txt",
        'ep_endpoint': "http://localhost:9001/api",
        'ga': 'none',  #GA key
        'base_asset_path': '/tmp',  # where to store assets
        'fb_app_id': 'PLEASE FILL IN',  # get this from developers.facebook.com
    }

    modules = [
        babel_module(locale_selector_func=get_locale, ),
        userbase.username_userbase(
            url_prefix="/users",
            mongodb_name="camper",
            master_template="master.html",
            login_after_registration=True,
            double_opt_in=True,
            enable_registration=True,
            enable_usereditor=True,
            user_class=db.CamperUser,
            use_remember=True,
            login_form=login.UsernameLoginForm,
            urls={
                'activation': {
                    'endpoint': 'userbase.activate'
                },
                'activation_success': {
                    'endpoint': 'index'
                },
                'activation_code_sent': {
                    'endpoint': 'userbase.activate'
                },
                'login_success': {
                    'endpoint': 'index'
                },
                'logout_success': {
                    'endpoint': 'userbase.login'
                },
                'registration_success': {
                    'endpoint': 'userbase.login'
                },
            },
            messages=AttributeMapper({
                'user_unknown':
                T('User unknown'),
                'email_unknown':
                T('This email address cannot not be found in our user database'
                  ),
                'password_incorrect':
                T('Your password is not correct'),
                'user_not_active':
                T(
                    'Your user has not yet been activated.'
                ),  # maybe provide link here? Needs to be constructed in handler
                'login_failed':
                T('Login failed'),
                'login_success':
                T('Welcome, %(fullname)s'),
                'logout_success':
                T('Your are now logged out'),
                'double_opt_in_pending':
                T('To finish the registration process please check your email with instructions on how to activate your account.'
                  ),
                'registration_success':
                T('Your user registration has been successful'),
                'activation_success':
                T('Your account has been activated'),
                'activation_failed':
                T('The activation code is not valid. Please try again or click <a href="%(url)s">here</a> to get a new one.'
                  ),
                'activation_code_sent':
                T('A new activation code has been sent out, please check your email'
                  ),
                'already_active':
                T('The user is already active. Please log in.'),
                'pw_code_sent':
                T('A link to set a new password has been sent to you'),
                'pw_changed':
                T('Your password has been changed'),

                # for user manager
                'user_edited':
                T('The user has been updated.'),
                'user_added':
                T('The user has been added.'),
                'user_deleted':
                T('The user has been deleted.'),
                'user_activated':
                T('The user has been activated.'),
                'user_deactivated':
                T('The user has been deactivated.'),
            }),
            permissions=AttributeMapper({
                'userbase:admin': T("can manage users"),
                'admin': T("main administrator"),
            })),
        mail_module(debug=True),
    ]

    jinja_filters = {
        'nl2br': nl2br,
        'currency': do_currency,
        'tojson': _tojson_filter,
        'md': markdownify,
    }

    routes = [
        URL('/', 'index', handlers.index.IndexView),
        URL('/impressum.html', 'impressum', handlers.index.Impressum),
        URL('/', 'root', handlers.index.IndexView),
        URL('/', 'login', handlers.index.IndexView),
        URL('/assets/', 'asset_upload', handlers.images.AssetUploadView),
        URL('/assets/<asset_id>', 'asset', handlers.images.AssetView),

        # admin area
        URL('/admin/', "admin_index", handlers.admin.index.IndexView),
        URL('/admin/pages', "admin_pages", handlers.admin.pages.PagesView),
        URL('/admin/pages/<slot>/add', 'admin_pages_add',
            handlers.pages.add.AddView),
        URL('/s/<page_slug>', 'page', handlers.pages.view.View),

        # user stuff
        URL('/u/<username>', 'profile', handlers.users.profile.ProfileView),
        URL('/u/image_delete', 'profile_image_delete',
            handlers.users.edit.ProfileImageDeleteView),
        URL('/u/edit', 'profile_edit', handlers.users.edit.ProfileEditView),

        # barcamp stuff
        URL('/b/add', 'barcamp_add', handlers.barcamp.add.AddView),
        URL('/b/validate',
            'barcamp_validate',
            handlers.barcamp.add.ValidateView,
            defaults={'slug': None}),
        URL('/<slug>', 'barcamp', handlers.barcamp.index.View),
        URL('/<slug>/validate', 'barcamp_validate',
            handlers.barcamp.add.ValidateView),
        URL('/<slug>/delete', 'barcamp_delete',
            handlers.barcamp.delete.DeleteConfirmView),
        URL('/<slug>/edit', 'barcamp_edit', handlers.barcamp.edit.EditView),
        URL('/<slug>/participants_edit', 'barcamp_participants_edit',
            handlers.barcamp.edit.ParticipantsEditView),
        URL('/<slug>/sponsors', 'barcamp_sponsors',
            handlers.barcamp.index.BarcampSponsors),
        URL('/<slug>/location', 'barcamp_location',
            handlers.barcamp.location.LocationView),
        URL('/<slug>/subscribe', 'barcamp_subscribe',
            handlers.barcamp.registration.BarcampSubscribe),
        URL('/<slug>/register', 'barcamp_register',
            handlers.barcamp.registration.BarcampRegister),
        URL('/<slug>/unregister', 'barcamp_unregister',
            handlers.barcamp.registration.BarcampUnregister),
        URL('/<slug>/planning', 'barcamp_planning_pad',
            handlers.barcamp.pads.PlanningPadView),
        URL('/<slug>/planning/toggle', 'barcamp_planning_pad_toggle',
            handlers.barcamp.pads.PadPublicToggleView),
        URL('/<slug>/docpad', 'barcamp_documentation_pad',
            handlers.barcamp.pads.DocumentationPadView),
        URL('/<slug>/lists', 'barcamp_userlist',
            handlers.barcamp.userlist.UserLists),
        URL('/<slug>/tweetwally', 'barcamp_tweetwally',
            handlers.barcamp.tweetwally.TweetWallyView),
        URL('/<slug>/permissions', 'barcamp_permissions',
            handlers.barcamp.permissions.Permissions),
        URL('/<slug>/permissions/admin', 'barcamp_admin',
            handlers.barcamp.permissions.Admin),
        URL('/<slug>/sessions', 'barcamp_sessions',
            handlers.barcamp.sessions.SessionList),
        URL('/<slug>/sessions.xls', 'barcamp_session_export',
            handlers.barcamp.sessions.SessionExport),
        URL('/<slug>/sessions/<sid>', 'barcamp_session',
            handlers.barcamp.sessions.SessionHandler),
        URL('/<slug>/sessions/<sid>/vote', 'barcamp_session_vote',
            handlers.barcamp.sessions.Vote),
        URL('/<slug>/sessions/<sid>/comments', 'barcamp_session_comments',
            handlers.barcamp.sessions.CommentHandler),
        URL('/<slug>/logo/upload', 'barcamp_logo_upload',
            handlers.barcamp.images.LogoUpload),
        URL('/<slug>/logo/delete', 'barcamp_logo_delete',
            handlers.barcamp.images.LogoDelete),
        URL('/<slug>/logo', 'barcamp_logo', handlers.barcamp.images.Logo),

        # pages for barcamps
        URL('/<slug>/page_add/<slot>', 'barcamp_page_add',
            handlers.pages.add.AddView),
        URL('/<slug>/<page_slug>', 'barcamp_page', handlers.pages.view.View),
        URL('/<slug>/<page_slug>/upload', 'page_image_upload',
            handlers.pages.images.ImageUpload),
        URL('/<slug>/<page_slug>/layout', 'page_layout',
            handlers.pages.edit.LayoutView),
        URL('/<slug>/<page_slug>/edit', 'page_edit',
            handlers.pages.edit.EditView),
        URL('/<slug>/<page_slug>/partial_edit', 'page_edit_partial',
            handlers.pages.edit.PartialEditView),
        URL('/<slug>/<page_slug>/delete', 'page_image_delete',
            handlers.pages.images.ImageDelete),
        URL('/<slug>/<page_slug>/image', 'page_image',
            handlers.pages.images.Image),
    ]

    def finalize_setup(self):
        """do our own configuration stuff"""
        self.config.dbs = AttributeMapper()
        mydb = self.config.dbs.db = pymongo.Connection(
            self.config.mongodb_host,
            self.config.mongodb_port)[self.config.mongodb_name]
        self.config.dbs.barcamps = db.Barcamps(mydb.barcamps,
                                               app=self,
                                               config=self.config)
        self.config.dbs.sessions = db.Sessions(mydb.sessions,
                                               app=self,
                                               config=self.config)
        self.config.dbs.pages = db.Pages(mydb.pages,
                                         app=self,
                                         config=self.config)
        self.config.dbs.session_comments = db.Comments(mydb.session_comments,
                                                       app=self,
                                                       config=self.config)
        self.module_map.uploader.config.assets = Assets(mydb.assets,
                                                        app=self,
                                                        config=self.config)

        # etherpad connection
        self.config.etherpad = EtherpadLiteClient(
            base_params={'apikey': self.config.ep_api_key},
            base_url=self.config.ep_endpoint)

    def finalize_modules(self):
        """finalize all modules"""
        fsstore = FilesystemStore(base_path=self.config.base_asset_path)
        self.modules.append(
            upload_module(
                store=fsstore,
                processors=[
                    ImageSizeProcessor({
                        'thumb': "50x50!",
                        'small': "100x",
                        'logo_full': "940x",
                        'medium_user': "******",
                        'large': "1200x",
                    })
                ],
            ))