Exemplo n.º 1
0
    def _try_sign_in(self, username, password, location=None, remember=False):
        # user may have registered in several Ututi
        # networks using same username
        locations = [user.location for user in User.get_all(username)]
        if len(locations) == 0:
            return {'username': _('Incorrect username.')}

        if len(locations) > 1:
            # if there is more than one location,
            # we will want to show it in the form
            c.locations = [(loc.id, loc.title) for loc in locations]
            c.selected_location = location

        if location is None and len(locations) == 1:
            location = locations[0].id

        if location is None:
            # still none! that means that location is not
            # unique and user did not specify it.
            return {'location': _('Please select your network.')}

        user = User.authenticate(location, username, password)
        if user is None:
            return {'password': _('Incorrect password.')}

        sign_in_user(user, long_session=remember)
Exemplo n.º 2
0
    def _send_news(self, period, **kwargs):
        dtstart, dtend = self.range(**kwargs)

        recipient_to_events = {}
        for event in self._all_events(dtstart, dtend):
            recipients = self._recipients(event, period)
            for recipient in recipients:
                events = recipient_to_events.setdefault(recipient.id, [])
                events.append(event)
        for uid, events in recipient_to_events.items():
            user = User.get_byid(uid)
            events = [ev for ev in events
                      if (ev.user is None or
                          (ev.user.id != uid and
                           ev.context not in user.ignored_subjects
                           and not ev.isEmptyFile()))]

            # process moderation events
            events = [ev for ev in events
                      if not isinstance(ev, ModeratedPostCreated) or ev.context.is_admin(user)]

            if not events:
                continue

            sections = self._get_sections(events)
            subject = self._subject(sections, events)
            extra_vars = {'sections': sections,
                          'subject': subject}
            text = render('/emails/news_text.mako',
                          extra_vars=extra_vars)
            html = render('/emails/news_html.mako',
                          extra_vars=extra_vars)
            msg = EmailMessage(subject, text, html)
            log.info("Sent to <%s> to %s" % (subject,  user.fullname))
            user = user.send(msg)
Exemplo n.º 3
0
    def register(self):
        name = request.POST.get('name')
        email = request.POST.get('email')
        location_id = request.POST.get('location_id')
        accept_terms = request.POST.get('accept_terms')
        person = request.POST.get('person')

        c.universities = self._universities(limit=12)
        c.all_universities = self._universities()

        # checks if email, name, person are not empty
        if not email or not name or not person or accept_terms != '1':
            redirect(url('frontpage'))

        # redirect to login if user is already registered
        if User.get_all(email):
            redirect(url(controller='home', action='login', email=email))

        # otherwise we validate the form properly
        try:
            self.form_result = RegistrationForm().to_python(request.POST)
        except validators.Invalid, e:
            return htmlfill.render(self._sign_up_form(),
                                   defaults=request.POST,
                                   errors=e.error_dict,
                                   error_formatters=u_error_formatters)
Exemplo n.º 4
0
    def update_membership(self, group):
        if hasattr(self, 'form_result'):
            user = User.get_byid(self.form_result.get('user_id', None))
            membership = GroupMember.get(user, group)
            if membership is not None:
                role = self.form_result.get('role', 'member')
                if role == 'not-member':
                    meta.Session.delete(membership)
                elif role in ['member', 'administrator']:
                    role = GroupMembershipType.get(role)
                    membership.role = role
                    h.flash(_("The status of the user %(fullname)s was updated.") % {'fullname': user.fullname})
                else:
                    h.flash(_("Problem updating the status of the user."))

                meta.Session.flush()
                meta.Session.expire(group)
                if group.administrators == 0:
                    h.flash(_('The group must have at least one administrator!'))
                    meta.Session.rollback()
                else:
                    meta.Session.commit()
            else:
                h.flash(_("Problem updating the status of the user. Cannot find such user."))
        redirect(url(controller="group", action="members", id=group.group_id))
Exemplo n.º 5
0
def related_users(user_id, location_id, limit=6):
    from ututi.model import User
    users = {}
    counts = {}
    user = User.get(user_id, location_id)
    # group mates
    for group in user.groups:
        for member in group.members:
            id = member.user.id
            counts.setdefault(id, 0)
            counts[id] += 1
            users[id] = member.user
    # subject followers
    for subject in user.watched_subjects:
        for monitor in subject.watching_users:
            id = monitor.user.id
            counts.setdefault(id, 0)
            counts[id] += 1
            users[id] = monitor.user
    # remove self
    if user.id in counts: del counts[user.id]
    if user.id in users: del users[user.id]
    # sort by counts
    pairs = [(counts[id], users[id]) for id in users.keys()]
    pairs.sort()
    pairs.reverse()
    pairs = pairs[:limit]

    return [{'id': user.id,
             'title': user.fullname,
             'url': user.url(),
             'logo_url': user.url(action='logo', width=45),
             'logo_small_url': user.url(action='logo', width=30)}
            for count, user in pairs]
Exemplo n.º 6
0
def find_user(id):
    """Get's user object by specified id or url_name."""
    try:
        id = int(id)
        return User.get_byid(id)
    except ValueError:
        # it may be url_name then
        return meta.Session.query(User).filter_by(url_name=id).first()
Exemplo n.º 7
0
def test_setup(test):
    """Create some models for this test."""
    ututi.tests.setUp(test)

    # The following c&p from model tests. Maybe should be put to base set up.

    #a user needs a university
    uni = LocationTag(u'U-niversity', u'uni', u'', member_policy='PUBLIC')
    meta.Session.add(uni)
    meta.Session.commit()

    #the user
    meta.Session.execute("insert into authors (type, fullname) values ('user', 'Administrator of the university')")
    meta.Session.execute("insert into users (id, location_id, username, password)"
                         " (select authors.id, tags.id, '*****@*****.**', 'xnIVufqLhFFcgX+XjkkwGbrY6kBBk0vvwjA7'"
                         " from tags, authors where title_short = 'uni' and fullname = 'Administrator of the university');")
    meta.Session.execute("insert into emails (id, email, confirmed)"
                         " (select users.id, users.username, true from users where username = '******')")
    meta.Session.commit()

    u = User.get('*****@*****.**', uni)
    user = User(u"a new user", "*****@*****.**", uni, "his password")
    meta.Session.add(user)
    user.emails.append(Email("*****@*****.**"))
    user.phone_number = '+37060000000'
    user.phone_confirmed = False
    meta.Session.commit()

    meta.Session.execute("SET LOCAL ututi.active_user TO %d" % u.id)

    g = Group('moderators', u'Moderatoriai', LocationTag.get(u'vu'), date.today(), u'U2ti moderatoriai.')

    role = GroupMembershipType.get('administrator')
    gm = GroupMember()
    gm.user = u
    gm.group = g
    gm.role = role
    meta.Session.add(g)
    meta.Session.add(gm)
    meta.Session.commit()
    meta.set_active_user(u.id)
Exemplo n.º 8
0
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()

    u = User.get('*****@*****.**', LocationTag.get(u'uni'))
    meta.set_active_user(u.id)
    meta.Session.add(Subject(u'subject', u'Subject',
                             LocationTag.get(u'uni'),
                             u''))
    meta.Session.commit()
    meta.set_active_user(u.id)
Exemplo n.º 9
0
def make_facebook_invitations(fb_ids, inviter, location):
    already = []
    invited = []
    for facebook_id in fb_ids:
        if User.get_byfbid(facebook_id, location):
            already.append(facebook_id)
        else:
            invitee = UserRegistration.create_or_update(
                location, facebook_id=facebook_id)
            invitee.inviter = inviter
            invited.append(facebook_id)

    return invited
Exemplo n.º 10
0
def test_setup(test):
    """Create some models needed for the tests."""
    ututi.tests.setUp(test)
    setUpUser()

    uni = LocationTag.get(u'uni')
    u = User.get('*****@*****.**', uni)
    meta.set_active_user(u.id)
    dept1 = LocationTag(title=u'dept1',
                        title_short=u'dept1',
                        parent=uni,
                        member_policy='PUBLIC')
    dept2 = LocationTag(title=u'dept2',
                        title_short=u'dept2',
                        parent=uni,
                        member_policy='PUBLIC')
    other_uni = LocationTag(title=u'other_uni',
                            title_short=u'other_uni',
                            parent=None,
                            member_policy='PUBLIC')
    meta.Session.add_all([dept1, dept2, other_uni])
    meta.Session.commit()

    meta.set_active_user(u.id)

    subj1 = Subject(u'subject1', u'Subject1', dept1, u'')
    subj2 = Subject(u'subject2', u'Subject2', dept2, u'')
    meta.Session.add_all([subj1, subj2])

    u = User.get('*****@*****.**', uni)
    u.location = LocationTag.get(u'uni/dept2')
    meta.Session.add(u)
    meta.Session.commit()

    meta.Session.commit()
    meta.set_active_user(u.id)
Exemplo n.º 11
0
    def pswrecovery(self):
        if hasattr(self, 'form_result'):
            email = self.form_result.get('email', None)
            # TODO: this needs to be resolved, get_global is wrong here:
            user = User.get_global(email)
            if user is not None:
                if not user.recovery_key:
                    user.gen_recovery_key()
                email_password_reset(user)
                meta.Session.commit()
                h.flash(_('Password recovery email sent. Please check your inbox.'))
            else:
                h.flash(_('User account not found.'))

        return htmlfill.render(self._pswrecovery_form())
Exemplo n.º 12
0
 def link_facebook(self):
     fb_user = facebook.get_user_from_cookie(request.cookies,
                      config['facebook.appid'], config['facebook.secret'])
     if not fb_user:
         h.flash(_("Failed to link Facebook account"))
     else:
         facebook_id = int(fb_user['uid'])
         if not User.get_byfbid(facebook_id):
             c.user.facebook_id = facebook_id
             c.user.update_logo_from_facebook()
             meta.Session.commit()
             h.flash(_("Linked to Facebook account."))
         else:
             h.flash(_('This Facebook account is already linked to another Ututi account.'))
     redirect(url(controller='profile', action='login_settings'))
Exemplo n.º 13
0
    def fromMessageText(cls, message_text, force=False):
        message = cls.parseMessage(message_text)
        message_id = message.getMessageId()
        g = message.getGroup()

        #use the numerical group id
        if g is None:
            return

        group_id = g.id

        if cls.get(message_id, group_id):
            raise MessageAlreadyExists(message_id, group_id)

        mime_message = mimetools.Message(StringIO(message_text))
        author_name, author_address = parseaddr(mime_message['From'])
        author = User.get_global(author_address)
        in_moderation_queue = False

        whitelist = [i.email for i in g.whitelist] + [
            config.get('ututi_email_from', '*****@*****.**')]
        if not (author_address in whitelist or
                author is not None and g.is_member(author)
                or force):
            if g.mailinglist_moderated:
                in_moderation_queue = True
            else:
                return # Bounce

        reply_to_message_id = message.getHeader('in-reply-to')
        reply_to = cls.get(reply_to_message_id, group_id)

        # XXX Hacky way to find messages this message might be a reply to
        if not reply_to:
            sbj = message.getSubject()
            parts = sbj.split(':')
            if len(parts) > 1:
                real_sbj = parts[-1].strip()
                reply_to = meta.Session.query(cls).filter_by(subject=real_sbj,
                                                             group_id=group_id).first()
        return cls(message_text,
                   message_id,
                   group_id,
                   message.getSubject(),
                   message.getDate(),
                   reply_to,
                   in_moderation_queue)
Exemplo n.º 14
0
def make_email_invitations(emails, inviter, location):
    invalid = []
    already = []
    invited = []
    for email in filter(bool, map(strip, emails)):
        try:
            email = TranslatedEmailValidator.to_python(email)
        except Invalid:
            invalid.append(email)
        else:
            if User.get(email, location.root):
                already.append(email)
            else:
                invitee = UserRegistration.create_or_update(location, email)
                invitee.inviter = inviter
                invited.append(invitee)

    return invited, invalid, already
Exemplo n.º 15
0
def current_user():
    from ututi.model import User
    try:
        login = session.get('login', None)
        if login is None:
            return None
        login = int(login)
    except ValueError:
        return None

    session_secret = session.get('cookie_secret', None)
    cookie_secret = request.cookies.get('ututi_session_lifetime', None)

    if session_secret != cookie_secret:
        session.delete()
        response.delete_cookie('ututi_session_lifetime')
        return None

    return User.get_byid(login)
Exemplo n.º 16
0
    def _receive_message(self, message_type):
        msg = ReceivedSMSMessage(message_type, request_url=request.url)
        msg.success = False
        msg.test = bool(request.params.get('test', False))
        msg.sender_phone_number = request.params.get('sender')
        msg.message_text = request.params.get('message')
        msg.sender = User.get_byphone('+' + msg.sender_phone_number)
        meta.Session.add(msg)
        log.info('Fortumo notification "%s" from +%s: text: %s; url: %s' % (
                msg.message_type, msg.sender_phone_number, msg.message_text,
                msg.request_url))
        if not msg.check_fortumo_sig():
            # Something fishy is going on...
            meta.Session.commit()
            raise ValueError('Invalid Fortumo signature!')

        handler = getattr(self, '_handle_%s' % message_type)
        text = handler(msg)
        msg.result = text
        meta.Session.commit()
        return text
Exemplo n.º 17
0
def prepare_logo(obj_type, obj_id, width=None, height=None, default_img_path=None, square=False):
    obj = None
    if obj_id is not None:
        if obj_type == 'user':
            obj = User.get_global(obj_id)
        else:
            obj_types = {
                'group': Group,
                'locationtag': LocationTag,
                'registration': UserRegistration,
                'theme': Theme,
            }
            obj_cls = obj_types[obj_type]
            obj = obj_cls.get(obj_id)

    if obj is not None and obj.has_logo():
        return prepare_image(obj.logo, width, height, square)
    elif default_img_path is not None:
        stream = resource_stream("ututi", default_img_path).read()
        return prepare_image(stream, width, height, square)
    else:
        return None
Exemplo n.º 18
0
    def _send_group_invitations(self, group, emails, message=None):
        invites, invalid, already = make_email_invitations(emails, c.user, group.location)
        # invites are registration objects!

        for email in already:
            user = User.get(email, group.location.root)
            if self._check_handshakes(group, user) == 'request':
                # Automatically accept requests to become group member.
                group.add_member(user)
                self._clear_requests(group, c.user)
                h.flash(_('New member %s added.') % user.fullname)
            else:
                invitation = group.create_pending_invitation(email, c.user)
                send_group_invitation_for_user(invitation, email, message)

        for registration in invites:
            invitation = group.create_pending_invitation(registration.email, c.user)
            send_group_invitation_for_non_user(invitation, registration, message)

        if invites:
            h.flash(_("Users invited."))
        if invalid != []:
            h.flash(_("Invalid email addresses detected: %s") % ', '.join(invalid))
        meta.Session.commit()
Exemplo n.º 19
0
def ftest_setUp(test):
    ututi.tests.setUp(test)

    # U-niversity and D-epartment
    # should be used in writing new functional tests

    uni = LocationTag(u'U-niversity', u'uni', u'', member_policy='PUBLIC')
    dep = LocationTag(u'D-epartment', u'dep', u'', uni, member_policy='PUBLIC')
    meta.Session.add(uni)
    meta.Session.add(dep)
    meta.Session.commit()

    # Admin user, named 'Adminas Adminovix' for backward compatibility
    create_user('Adminas Adminovix', '*****@*****.**', 'xnIVufqLhFFcgX+XjkkwGbrY6kBBk0vvwjA7', 'uni')

    # Below are old locations, users, groups and subjects for backward compatibility
    # Note: objects that didn't have their location specified are now assigned to U-niversity

    vu = LocationTag(u'Vilniaus universitetas', u'vu', u'Seniausias universitetas Lietuvoje.',
                     member_policy='PUBLIC')
    ef = LocationTag(u'Ekonomikos fakultetas', u'ef', u'', vu, member_policy='PUBLIC')
    gf = LocationTag(u'Geografijos fakultetas', u'gf', u'', vu, member_policy='PUBLIC')
    meta.Session.add(vu)
    meta.Session.add(ef)
    meta.Session.add(gf)

    region = Region(u'Mazowieckie', u'lt')
    meta.Session.add(region)

    # Users:

    first = User(u'Alternative user', '*****@*****.**', uni, 'password', True)
    meta.Session.add(first)
    email = Email('*****@*****.**')
    email.confirmed = True
    first.emails.append(email)

    second = User(u'Second user', '*****@*****.**', uni, 'password', True)
    meta.Session.add(second)
    email = Email('*****@*****.**')
    email.confirmed = True
    second.emails.append(email)
    second.phone_number = '+37067412345'
    second.phone_confirmed = True

    admin = User.get('*****@*****.**', uni)
    admin.phone_number = '+37067812375'
    admin.phone_confirmed = True

    # Third user has hist email uncofirmed
    third = User(u'Third user', '*****@*****.**', uni, 'password', True)
    meta.Session.add(third)
    email = Email('*****@*****.**')
    email.confirmed = False
    third.emails.append(email)

    # A verified teacher Benas
    benas = Teacher(fullname=u'Benas',
                    username='******',
                    location=uni,
                    password='******',
                    gen_password=True)
    benas.teacher_verified = True
    meta.Session.add(benas)
    email = Email('*****@*****.**')
    email.confirmed = True
    benas.emails.append(email)

    # Groups:

    meta.Session.execute("SET LOCAL ututi.active_user TO %d" % admin.id)

    moderators = Group('moderators', u'Moderatoriai', uni, date(date.today().year, 1, 1), u'U2ti moderatoriai.')
    meta.Session.add(moderators)

    moderators.add_member(admin, True)
    moderators.add_member(third)

    testgroup = Group('testgroup', u'Testing group', LocationTag.get(u'vu'), date(date.today().year, 1, 1), u'Testing group')
    meta.Session.add(testgroup)
    testgroup.mailinglist_enabled = False
    testgroup.add_member(admin, True)
    testgroup.add_member(second)

    # Subjects:

    math = Subject(u'mat_analize', u'Matematin\u0117 analiz\u0117', LocationTag.get(u'vu'), u'prof. E. Misevi\u010dius')
    meta.Session.add(math)
    third.watchSubject(math)

    # Tags:

    tag = SimpleTag(u'simple_tag')
    meta.Session.add(tag)

    meta.Session.commit()
Exemplo n.º 20
0
 def getAuthor(self):
     author_name, author_address = parseaddr(self.getHeader("from"))
     return User.get_global(author_address)
Exemplo n.º 21
0
 def getAuthor(self):
     author_name, author_address = parseaddr(self.mime_message['From'])
     return User.get_global(author_address)