Example #1
0
 def get_summary(self):
     return dict (
         total_members_active = User.selectBy(active=1).count(),
         loc_members_active = User.selectBy(active=1, homeplace=self.location).count(),
         loc_members_not_active = User.selectBy(active=0, homeplace=self.location).count(),
         new_members = User.select( \
             AND(User.q.active == 1, User.q.homeplaceID == self.location.id, User.q.created >= self.start, User.q.created <= self.end)).count(),
         revenue = sum(ru.effectivecost for ru in self.usages),
         currency = self.location.currency,
         )
Example #2
0
def requestPassword(*args, **kwargs):
    if kwargs.get('submit') == "Get Password":
        mode = "pword"
    else:
        mode = "uname"            
    email = None
    if 'email' in kwargs:
        email = kwargs['email']
    if not email:
        return dict(message=_("Please enter the email address associated with your account"),
                    showform=True)
    result = User.select(User.q.email_address==email)
            
    try:
        if mode == "uname":
            user = result[0]
            mailtext = "Dear %(first_name)s,\n\nYour username is: %(user_name)s\n\nYou can login at:\n\n%(request_url)s/public/login\n\nIf you have any questions, please contact The Hub's hosting team at %(location_name)[email protected] or phone %(telephone)s.\n\nThank you very much.\n\nThe Hosting Team" %({'first_name':user.first_name, 'request_url':cherrypy.request.base, 'user_name':user.user_name, 'location_name':user.homeplace.name.lower().replace(' ', ''), 'telephone':user.homeplace.telephone})
            
            sendmail.sendmail(email, user.homeplace.name.lower().replace(' ', '') +'*****@*****.**','The Hub | username reminder',mailtext,[])
            return dict(message=_("""A confirmation email was sent to you. """),
                        showform=False)
        else:
            user = result[0]
            reminderkey = md5.new(str(random.random())).hexdigest()
            user.reminderkey = reminderkey
            mailtext = "Dear %(first_name)s,\n\nPlease click the link to reset your password:\n\n %(request_url)s/public/resetPassword?key=%(reminderkey)s\n\nIf you have any questions, please contact The Hub's hosting team at %(location_name)[email protected] or phone %(telephone)s.\n\nThank you very much.\n\nThe Hosting Team" %({'first_name':user.first_name, 'request_url':cherrypy.request.base, 'reminderkey':reminderkey, 'location_name':user.homeplace.name.lower().replace(' ', ''), 'telephone':user.homeplace.telephone})
            
            sendmail.sendmail(email, user.homeplace.name.lower().replace(' ', '') +'*****@*****.**','The Hub | password reminder',mailtext,[])
            return dict(message=_("""A confirmation email was sent to you. """),
                        showform=False)
    except IndexError:            
        return dict(message=_("The email was not correct"),
                               showform=True)
Example #3
0
 def validate_python(self, field_dict, state):
     from hubspace.controllers import permission_or_owner
     user_id = field_dict['id']
     user = User.get(user_id)
     if permission_or_owner(user.homeplace, None, 'manage_users'):
         if 'active' not in field_dict or field_dict['active'] == False:
             if identity.current.user.id == user_id:
                 raise Invalid("You Cannot Deactivate Your Own Profile", field_dict, state, error_dict={'active':"You Cannot Deactivate Your Own Profile"})
Example #4
0
def tariff_users(tariff):
    localtime = now(tariff.place)
    if isinstance(tariff, Resource) and tariff.type == 'tariff':
        return User.select(AND(RUsage.q.resourceID == tariff.id,
                               RUsage.q.userID == User.q.id,
                               RUsage.q.start <= localtime,
                               RUsage.q.end_time >= localtime))
        
    raise "input is not a tariff"
Example #5
0
def filter_members(location, text_filter, type, active_only, start, end, override_user=None):

    if type == "member_search":

        text_filter = "%" + " ".join(text_filter.split()).replace("'","\\'") + "%"

        if override_user:
            user_locs = Location.select()
        else:
            user_locs = user_locations(identity.current.user, ['member', 'host'])

        if user_locs:
            if location:
                relevant_groups = location.groups
                relevant_user_ids = tuple((ug.userID for ug in UserGroup.select(IN(UserGroup.q.group, tuple(relevant_groups)))))
                display_name_clause = iLIKE(User.q.display_name, text_filter)
                user_id_clause = IN(User.q.id, relevant_user_ids) # so that we select all members even those with homehub as this hub
                if active_only:
                    user_active_clause = (User.q.active == 1)
                    users = User.select(AND(display_name_clause, user_id_clause, user_active_clause))
                else:
                    users = User.select(AND(display_name_clause, user_id_clause))

            else:
                display_name_clause = iLIKE(User.q.display_name, text_filter)
                if active_only:
                    user_active_clause = (User.q.active == 1)
                    users = User.select(AND(display_name_clause, user_active_clause))
                else:
                    users = User.select(display_name_clause)

            users = users.orderBy('display_name')
        else:
            users = []

    elif type == 'rfid_member_search':
        users = User.select(AND(User.q.rfid == text_filter))

    elif type == 'fulltext_member_search':
        users = hubspace.search.do_search(text_filter)
        if location:
            user_ids = tuple(user.id for user in users)
            if not user_ids:
                users = []
            else:
                users = User.select(AND(IN(User.q.id, user_ids), User.q.homeplaceID==location.id))

    if start != None and end != None:
        users = users[start:end]

    try:
        webapi = User.selectBy(first_name="web", last_name="api")[0]
        if webapi in users and not identity.has_permission("superuser"):
            users.remove(webapi)
    except:
        pass
    return users
Example #6
0
def setup_microsite_spaces(): 
    """Create the microsites spaces object
    """
    from hubspace.model import ObjectReference, Page, ListItem, PublicSpace, Location, MetaData, MicroSiteSpace, PublicPlace, User
    from hubspace.microSite import microsite_pages, microsite_page_types, microsite_left_page_list, microsite_right_page_list, append_existing_item
    Page.createTable(ifNotExists=True)
    ObjectReference.createTable(ifNotExists=True)
    ListItem.createTable(ifNotExists=True)
    PublicSpace.createTable(ifNotExists=True)
    PublicPlace.createTable(ifNotExists=True)
    MetaData.createTable(ifNotExists=True)
    for user in User.select():
        ObjectReference(**{'object': (user.__class__.__name__, user.id)})

    for loc in Location.select():
        if loc.id == 16 or not loc.url:
            continue
       
        try:
            old_space = MicroSiteSpace.select(AND(MicroSiteSpace.q.locationID==loc.id,
                                                  MicroSiteSpace.q.nextID==None))[0]
        except IndexError:
            print `loc.name` + " doesn't have any spaces to migrate"
            old_space = None
            
        next_item = None
        while old_space:
            new_space = PublicSpace(name=old_space.name, description=old_space.description, image=old_space.image)
            object_ref = ObjectReference.selectBy(object_type='PublicSpace', object_id=new_space.id)[0]
            new_list_item = ListItem(next=next_item, location=loc, active=old_space.active, list_name="spaces_list", object_ref=object_ref)
            next_item = new_list_item
            old_space = old_space.previous

        ObjectReference(**{'object': (loc.__class__.__name__, loc.id)})
        for page, type in microsite_pages.items():
            microsite_page_types[type].create_page(page, loc, {})
        
        kwargs = {'location':loc, 'object_type': Page, 'active': 1}
        for page in microsite_left_page_list:
            kwargs.update({'name':page})
            try:
                page = Page.select(AND(Page.q.location == loc,
                                       IN(Page.q.path_name, [page, page + '.html'])))[0]
                append_existing_item('left_tabs', page, **kwargs)
            except IndexError:
                pass
        for page in microsite_right_page_list: 
            kwargs.update({'name':page})
            try:
                page = Page.select(AND(Page.q.location == loc,
                                       IN(Page.q.path_name, [page, page + '.html'])))[0]
                append_existing_item('right_tabs', page, **kwargs)
            except IndexError:
                pass
Example #7
0
def fix_users_without_object_references():
    from hubspace.model import User, ObjectReference, create_object_reference, Location

    for user in User.select():
        try:
            object_ref = ObjectReference.select(
                AND(ObjectReference.q.object_type == user.__class__.__name__, ObjectReference.q.object_id == user.id)
            )[0]
        except IndexError:
            print "giving " + user.username + "an object reference"
            create_object_reference({"class": User, "id": user.id}, None)

    for loc in Location.select():
        try:
            object_ref = ObjectReference.select(
                AND(ObjectReference.q.object_type == loc.__class__.__name__, ObjectReference.q.object_id == loc.id)
            )[0]
        except IndexError:
            create_object_reference({"class": Location, "id": loc.id}, None)
            print "giving " + loc.name + "an object reference"
Example #8
0
def resetPassword(*args,**kwargs):
    key=kwargs['key']
    result = User.selectBy(reminderkey=key)
    if result.count()==0:
        return dict(message=_("The confirmation key is wrong - maybe you need to check your email?"),
                    showform=False)
    else:
        user=result[0]
        user.reminderkey = md5.new(str(random.random())).hexdigest()	    
        newpassword = md5.new(str(random.random())).hexdigest()[:8]
        user.password = newpassword 
        mailtext = """
Dear Member,

Your new password for The Hub is: %(newpassword)s

For your convenience and security please login and change the password at the earliest possible opportunity. To do so click 'edit' on the top section of your profile page and enter a new password in the 'password' and 'confirm password' fields.
You can login at:
%(url)s

The Hub Team
"""%({'newpassword':newpassword, 'url':user.homeplace.url})
    sendmail.sendmail(user.email_address, user.homeplace.name.lower().replace(' ', '') +'*****@*****.**','The Hub | new password',mailtext,[])
    return dict(message=_("""The new password was sent to you."""), showform=False)
Example #9
0
 def get_churn_stats(self):
     """
     -> [((2009, 3), 13, 4), ((2009, 4), 2, 5), ...]
                     ^ members left         ^ members back
     """
     tariff_ids = (resource.id for resource in self.location.resources if resource.type == 'tariff')
     dateptr = get_last_months_limits(self.start)[0]
     tariff_usages = (ru for ru in self.get_usages_for_period(dateptr, self.end) if ru.resourceID in tariff_ids)
     prev_month = get_last_months_limits(dateptr)
     stats = []
     while dateptr <= self.end:
         current_month = get_this_months_limits(dateptr)
         members_then = set(ru.userID for ru in get_usages_for_period(self.location.id, *prev_month))
         members_now = set(ru.userID for ru in get_usages_for_period(self.location.id, *current_month))
         members_left = len(members_then.difference(members_now))
         members_back = len([m_id for m_id in members_now.difference(members_then) if User.get(m_id).created < prev_month[0]])
         stats.append(("%s %s" % (calendar.month_abbr[dateptr.month], dateptr.year), (members_left, members_back)))
         dateptr = current_month[-1] + datetime.timedelta(1)
         prev_month = current_month
     return stats
Example #10
0
 def _get_invoice(self):
     return User.get(self.userID)
Example #11
0
 def _get_user(self):
     return User.get(self.userID)
Example #12
0
def setup_display_name_field(): 
    """Create the microsites spaces object
    """
    from hubspace.model import User
    for user in User.select():
        user.display_name