Пример #1
0
  def post(self):

    g = Group(
      name=cgi.escape(self.request.get('name')),
      owner=users.get_current_user()
      )
    g.put()
    self.redirect('/groups')
Пример #2
0
def createGroup(groupname):
    if not groupname.isalnum():
        raise UserError("Invalid Groupname, Must Be Alphanumeric")
    elif GROUPS.groupnameExists(groupname):
        raise UserError("Group Exists")

    group = Group(groupname)
    GROUPS.addGroup(group)
    return group.serialize()
Пример #3
0
 def createGroupAndInsertMember(self, gname):
     user = users.get_current_user()
     count = Membership.gql("WHERE user = :1 AND alias = :2", user, gname).count()
     if count > 0:
         return None
     group = Group(name=gname)
     group.put()
     
     self.insertUserInGroup(group)
     return group
Пример #4
0
def add_group(**kwargs):
    form = AddGroupForm(csrf_enabled=False);
    if form.validate_on_submit():
        group_tmp = Group(userid=current_user.id,\
                              groupname=form.groupname.data)
        db.session.add(group_tmp)
        db.session.commit()
        group_tmp.bind();
        reDict=group_tmp.get_dict();
        reDict["success"]=1;
        return reDict
    else:
        return dict(fail=1)
Пример #5
0
def test_delete_group_by_name(app, db, checkUI):
    group = Group(name="New_01")
    if not app.group.is_group_exist(group.name):
        app.group.add_new_contacts_group(group)
    old_groups = db.database.get_groups_list()
    # Запоминаем идентификатор удаленной группы
    group.id = app.group.delete_contacts_group_by_name(group.name)
    #  Получаем новый список групп
    new_groups = db.database.get_groups_list()
    #  group.name = "Select ("+ group.name +")"
    old_groups.remove(group)  # Удаляем  правильную группу
    # cравниваем
    assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
    if checkUI:
        assert app.group.get_groups_list().sort() == new_groups.sort()
Пример #6
0
def nightly_task():
    log.info("batch started")
    hub.threadingLocal = threading_local()
    hub.begin()

    last = BatchRecord.select(orderBy=BatchRecord.q.last_handled).reversed()
    if last.count():
        last_rec = last[0]
        from_when = last_rec.last_handled
    else:
        from_when = datetime.date.today()

    last_handled = datetime.datetime.now()
    current = BatchRecord(first_handled=from_when, last_handled=last_handled)
    hub.commit()

    try:
        current.artists_updated = update_artists(queries_per_run)
        current.venues_updated = update_venues()
        cleanup_db()
        current.email_sent, current.artist_pings, current.venue_pings = send_email(from_when, last_handled)

        current.finished = datetime.datetime.now()
        hub.commit()
    except Exception, inst:
        import traceback

        hub.rollback()
        for admin in Group.by_group_name("admin").users:
            util.email(
                admin.email_address,
                "BandRadar <*****@*****.**>",
                "batch error",
                "Batch failed, Andy is on it!\n\n" + traceback.format_exc(),
            )
Пример #7
0
    def post(self):
        if not userIsLoggedIn(self):
            return
        
        user = users.get_current_user()
        lang = getLanguage(self, user)
        
        groupKey = self.request.get('group').strip()
        
        if groupKey == "":
            error = _('Group is required', lang)
            alertMessage(self,error)
            return
        
        group = Group.get(groupKey)
        memberships = Membership.gql("WHERE group = :1 AND user = :2", group, user)

        if memberships.count() <> 1:
            error = _('You don\'t belong to this group.', lang)
            alertMessage(self,error)
            return
        
        membership = memberships.get()
        if not abs(membership.balance) <= 1e-07:
            error = _('You cannot leave this group, your balance must be zero.', lang)
            alertMessage(self,error)
            return
        
        membership.delete()
        if Membership.gql("WHERE group = :1", group).count() == 0:
            group.delete()
        
        msg = _('You have been succesfully unsubscribed from the group %s!', lang) % escape(group.name)
        location = '/?msg=' + msg
        redirectPage(self,location)
Пример #8
0
    def addGroup(self, name):
        """Create a Group

        @param name: group name
        @rtype: Group
        @return: newly created Group"""
        return Group.create(self.pm_getUserManager().addGroup(name), self._modelDataManager)
Пример #9
0
	def get(self):
		page = self.request.get('p');
		if page is None or page == '':
			page = 1
		else:
			page = int(page)
			
		offset = (page - 1) * 10
		
		if page != 1:
			self.response.out.write("<a href=\"?p=%s\">Previous</a> | " % (page - 1))
			
		self.response.out.write(" &nbsp; %s &nbsp; " % page)
			
		self.response.out.write(" | <a href=\"?p=%s\">Next</a>" % (page + 1))
		
		self.response.out.write("<br/><br/>")
		
		for group in Group.gql("LIMIT %s, %s" % (offset, 10)):
			self.response.out.write("<b>%s</b>" % group.name)
			
			self.response.out.write("<ul>")
			for membership in group.memberships:
				self.response.out.write("<li>%s (%s): $%s</li>" % (membership.userNick, membership.user.email(), membership.balance))
			self.response.out.write("</ul>")
Пример #10
0
 def get(self):
     # Get user, group and user membership
     user = users.get_current_user()
     lang = getLanguage(self, user)
     group = Group.get(self.request.get("group"))   
     groupMemberships = group.memberships
     userMembership = findMembershipForUser(groupMemberships, user)
     
     # Go to homepage if someone is trying to acces this group
     # without being a member
     if not userMembership:
         self.redirect('/')
         return
     
     # Get memberships of the current user
     userMemberships = membershipsOfUser(user)
     userMemberships.sort(cmp = compareMembershipsByGroupNick)
     
     hasUserMemberships = len(userMemberships) > 0
     
     # Get user balance in this group
     [balanceSign, balance] = self.getBalance(userMembership, groupMemberships, lang)
     
     # Get user's transaction history for the "History" tab
     try:
         transactionCount = int(self.request.get('transactionCount', default_value=10))
         transactions = self.getTransactionHistory(transactionCount, userMembership, lang)
         transactionCount = len(transactions)
         validationError = False
         validationMessage = ''
     except BaseException, e:
         transactionCount = 0
         transactions = []
         validationError = True
         validationMessage = '(' + _('This should be a number', lang) + ')'
Пример #11
0
    def listUserGroups(self, user):
        """Return a list of current groups joined by this user

        @param user: user name, or User object
        @rtype: Group list
        @return: list of Groups user belongs to"""
        return tuple(Group.create(name, self._modelDataManager) for name in self.pm_getUserManager().listUserGroups(self._unbox(user)))
Пример #12
0
 def get(self, id):
     g = Group.get(group_id=id)
     if not g:
         raise HTTPError(404)
     add_group(id, self.current_user.id)
     uri = self.request.path 
     print uri
     return self.redirect('/group/%s'%id)
Пример #13
0
    def get(self):
        groupKey = self.request.get("key")
        group = Group.get(groupKey)

        self.response.out.write("<h1>Transactions in %s</h1>" % group.name)

        balances = {}

        transactions = Transaction.gql("WHERE group = :1 ORDER BY date ASC", group)

        self.response.out.write("<ul>")
        for tr in transactions:
            try:
                self.response.out.write("<li>")
                self.response.out.write(
                    "Creator: %s, From: <b>%s</b>, To: <b>%s</b>, Type: <b>%s</b>, Amount: %s, Reason: %s, Date: %s"
                    % (
                        tr.creatorMember.user.nickname(),
                        tr.fromMember.user.nickname(),
                        tr.toMember.user.nickname(),
                        tr.type,
                        tr.amount,
                        tr.reason,
                        tr.date,
                    )
                )

                if tr.type == "debt":
                    fromBalance = -tr.amount
                    toBalance = tr.amount
                else:
                    fromBalance = tr.amount
                    toBalance = -tr.amount

                if not tr.fromMember.user in balances:
                    balances[tr.fromMember.user] = fromBalance
                else:
                    balances[tr.fromMember.user] += fromBalance

                if not tr.toMember.user in balances:
                    balances[tr.toMember.user] = toBalance
                else:
                    balances[tr.toMember.user] += toBalance

                totalBalance = 0.0

                self.response.out.write("<ul>")
                for member, balance in balances.items():
                    totalBalance += balance
                    self.response.out.write("<li>%s: %s</li>" % (member, balance))
                if abs(totalBalance - 0) > 1e7:
                    self.response.out.write('<li style="color:red">Total Balance: %s</li>' % totalBalance)
                self.response.out.write("</ul>")

                self.response.out.write("</li>")
            except:
                foo = True
        self.response.out.write("</ul>")
Пример #14
0
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		rejectPath = UrlBuilder(self.request).buildUrl('/reject')
		
		user = users.get_current_user()
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("cow")
		members = group.memberships
		
		parser = CowParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
		
		result = transaction.getResult()
		
		# Update balance and send mails
		for member, balance in result.balanceChange.iteritems():
			balanceBefore = member.balance
			balanceNow = member.balance + balance
			
			# Balance
			member.balance += balance
			member.put()
			
			# Send mail, but not to the creator of this mail
			if member.user != creatorMember.user:
				message = createCowMail(creatorMember, transaction, result, member, balanceBefore, balanceNow, lang)
				sendEmail(message)
			
		# Create transactions
		for debt in result.debts:
			for singleDebt in debt.singleDebts:
				tr = Transaction(
					group = group,
					creatorMember = creatorMember, 
					fromMember = debt.fromMember,
					toMember = singleDebt.toMember,
					type = 'debt',
					amount = singleDebt.money, 
					reason = transaction.reason,
					isRejected = False
				)
				tr.put()
				
		location = '/group?group=%s&msg=%s' % (group.key(), _('Debts saved!', lang))
		redirectPage(self,location)
Пример #15
0
	def groupUpdate(self, **kw):
		user = User.get(int(cherrypy.session['current_user']))
		group = Group.selectBy(group_name=str(kw['name']))[0]
		if kw['value'] == 'true':
			user.addGroup(group.id)
		else:
			user.removeGroup(group.id)

		return dict()
Пример #16
0
def test_edit_random_contacts_group(app, db, checkUI):
    # Параметры группы контактов
    group = Group(name="New_045456661")
    if app.group.count == 0:
        # групп нет - надо создать
        app.group.add_new_contacts_group(Group(name="New_01"))
    # Запoминаем список групп
    old_groups = db.database.get_groups_list()
    # случайно выбираем группу
    index = randrange(len(old_groups))
    group.id = old_groups[index].id
    # редактирование группы контактов
    app.group.edit_contacts_group_by_position(index=index,groups = group)
    #  Получаем норвый список групп
    new_groups = db.database.get_groups_list()
    # Сравниваем списки по содержимому
    assert old_groups.sort() == new_groups.sort()
    if (checkUI):
      assert app.group.get_groups_list().sort() == new_groups.sort()
Пример #17
0
def fake_db():
    userMap={}
    groupMap={}
    for i in range(10):
        user = User("user%s"%i,"*****@*****.**"%i)
        user.password="******"
        db.session.add(user)
        db.session.commit()
        userMap[user.id]=user;
        
    for i in range(5):
        userid = random.choice(userMap.keys())
        group = Group(userid, "group%s"%i)
        group.describe = "".join([chr(random.choice(range(65,90))) for i in range(10)])
        db.session.add(group)
        db.session.commit()
        groupMap[group.id]=group

    db.session.commit()

    for userid,user in userMap.items():
        group=random.choice(groupMap.values());
        group.add_member(userid)

    for groupid,group in groupMap.items():
        user=random.choice(userMap.values());
        group.add_member(user.id)
            
    return dict();
Пример #18
0
def test_edit_group_by_name(app, db, checkUI):
    # Параметры групп контактов
    group = Group(name="New_06661", header="664464664", footer= None)
    editgroup = Group(name="New_01")
    if not app.group.is_group_exist(editgroup.name):
        # группы нет - надо создать
        app.group.add_new_contacts_group(editgroup)
    # Запoминаем список групп
    old_groups = db.database.get_groups_list()
    # редактирование группы контактов по имени
    editgroup.id = app.group.edit_contacts_group_by_name(name = "New_01", groups = group)
    # Сравниваем размер списков
    if (checkUI):
        assert len(old_groups) == app.group.count()
    #  Получаем норвый список групп
    new_groups = db.database.get_groups_list()
    old_groups.remove(editgroup) # Удаляем отредактирорванную группу
    # записываем в списoк исправленную группу
    group.id = editgroup.id
    old_groups.append(group)
    # cравниваем
    assert old_groups.sort() == new_groups.sort()
Пример #19
0
def test_edit_first_contacts_group(app, db, checkUI):
    # Параметры группы контактов
    group = Group(name="New_045456661")
    if app.group.is_group_exist():
        # групп нет - надо создать
        app.group.add_new_contacts_group(Group(name="New_01"))
    # Запoминаем список групп
    old_groups = db.database.get_groups_list()
    group.id = old_groups[0].id
    # редактирование группы контактов
    app.group.edit_first_contacts_group(groups = group)
    # Сравниваем размер списков
    if (checkUI):
        assert len(old_groups) == app.group.count()
    #  Получаем норвый список групп
    new_groups = db.database.get_groups_list()
    # Сравниваем списки по содержимому
    old_groups[0]= group
  #  old_groups[0].name = "Select " + "(%s)" % group.name
  #  assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
    assert old_groups.sort() == new_groups.sort()
    if (checkUI):
      assert app.group.get_groups_list().sort() == new_groups.sort()
Пример #20
0
  def get(self):

    g_key = ''
    g_name = ''

    if self.request.get('g') == None or self.request.get('g') == '':
      opinions = Opinion.all()
    else:
      g = Group.get(self.request.get('g'))
      opinions = Opinion.gql('WHERE group = :1', g)
      g_key = g.key()
      g_name = g.name

    template_values = { 'opinions' : opinions, 'g_key' : g_key, 'g_name' : g_name }
    template = jinja2_environment.get_template('html/opinion.html')
    t = template.render(template_values)
    self.response.out.write(t)
Пример #21
0
def hourly_task():
    hub.threadingLocal = threading_local()
    hub.begin()
    # notify admins of pending events added by users
    events_pending = Event.select(Event.q.approved == None)
    pending_count = events_pending.count()
    unnotified = events_pending.filter(Event.q.admin_notified == False)
    if unnotified.count():
        for event in unnotified:
            event.admin_notified = True
        for admin in Group.by_group_name("admin").users:
            util.email(
                admin.email_address,
                "BandRadar <*****@*****.**>",
                "%d events in queue" % pending_count,
                "There are events in the pending queue.",
            )
    hub.commit()
Пример #22
0
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		user = users.get_current_user();
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("command")
		members = group.memberships
		
		parser = OrderParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
		
		elems = {}
		total = 0.0
		
		for debt in transaction.debts:
			total += debt.money
			razon = debt.reason
			comidas = razon.split(',')
			for comida in comidas:
				comida = comida.strip()
				[cantidad, comida2] = quantity(comida)
				elems[comida2] = elems.get(comida2, 0) + cantidad
				
		result = ''
		for comida, cantidad in elems.items():
			result += ' - %s %s\\n' % (cantidad, comida)
			
		result += '\\n';
		result += _('Total', lang)
		result += ': $%s'% total;
		
		alertMessage(self, result)
Пример #23
0
 def get(self, id):
     gi = GroupInfo.get(id=id)
     if not gi:
         raise HTTPError(404)
     group_name = gi.name
     creater = User.get(gi.create_id)
     description = gi.description
     groups = Group.where(group_id=id)
     user_ids = groups.col_list(col='user_id')
     users = User.get_list(id=user_ids)
     for user_id in user_ids:
         if user_id not in CACHE:
             for user in users:
                 if user_id == user.id:
                     CACHE[user_id] = user
     blogs = Blog.where('user_id in (%s)'%','.join(user_ids))
     for blog in blogs:
         blog.user = CACHE[blog.user_id]
     return self.render('group.html', gi=gi, creater=creater, groups=groups, users=users, blogs=blogs)
Пример #24
0
 def post(self):
     if not userIsLoggedIn(self):
         return
     
     user = users.get_current_user()
     lang = getLanguage(self, user)
     groupKey = self.request.get('group')
     group = Group.get(groupKey)
     invitationText = self.request.get('invitationText')
     emails = self.request.get('emails')
     emails = emails.split(',')
     urlBuilder = UrlBuilder(self.request)
     
     # Check that all emails are valid
     for email in emails:
     	if not mail.is_email_valid(email.strip()):
     		alertMessage(self, _('%s is not a valid email address', lang) % email)
     		return
     
     for email in emails:
         self.sendInvitation(user, email.strip(), group, invitationText, urlBuilder, lang)
         
     redirectPage(self, "/group?group=%s&msg=%s" % (groupKey, escape(_('Your invite has been sent!', lang))))
Пример #25
0
 def get(self):
   template = jinja2_environment.get_template('html/group.html')
   gs = Group.all()
   template_values = { 'groups' : gs }
   t = template.render(template_values)
   self.response.out.write(t)
Пример #26
0
from model import Group

test_data = [
    Group(name="name1", header="header1", footer="footer1"),
    Group(name="name2", header="header2", footer="footer2")
]
Пример #27
0
def create_group():
    """Handle submission of new group form"""

    # form inputs
    group_name = request.form.get("group_name")
    group_descrip = request.form.get("group_descrip")
    hashtag = request.form.get("hashtag")

    # If a hashtag was entered append makealong tag to beginning of value
    if hashtag != "":
        hashtag = '#makealong' + hashtag
    else:
        hashtag = None

    # If upload your own photo radio button was selected save the photo from
    # request files to the photo folder and save the photo path in database.
    # If one of the default photos was selected, set group_image to the photo
    # path for the default photo selected.

    if request.form.get("group_image") == " ":
        filename = photos.save(request.files['photo'])
        group_image = str(photos.path(filename))

    else:
        group_image = request.form.get("group_image")

    # New group object if pattern poll was created, use vote days field as poll
    # indicator. Using pattern helper function that instantiates poll patterns in
    # the database.

    if request.form.get("vote_days"):
        vote_days = request.form.get("vote_days")
        vote_timestamp = datetime.now()

        group = Group(group_name=group_name,
                      group_descrip=group_descrip,
                      group_image=group_image,
                      admin_id=session["user_id"],
                      vote_days=vote_days,
                      vote_timestamp=vote_timestamp,
                      hashtag=hashtag)
        # disabled for demo
        # db.session.add(group)
        # db.session.commit()

        helper.create_patterns_for_poll(group.group_id)

    # New group without pattern poll.
    else:
        group = Group(group_name=group_name,
                      group_descrip=group_descrip,
                      group_image=group_image,
                      admin_id=session["user_id"],
                      hashtag=hashtag)
        # disabled for demo
        # db.session.add(group)
        # db.session.commit()

        # If pattern name was entered in form, call helper function to instantiate
        # pattern in database.

        if request.form.get("pattern_name"):
            helper.add_chosen_pattern("pattern_name", "pattern_link",
                                      "pattern_pdf", group.group_id)

    # Instantiate a new UserGroup object and save it to usergroups which is an
    # association table for groups and users.

    user_group = UserGroup(group_id=group.group_id, user_id=session["user_id"])
    # disabled for demo
    # db.session.add(user_group)
    # db.session.commit()

    return redirect("/group_home/%d" % (group.group_id))
Пример #28
0
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		user = users.get_current_user();
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("cow")
		members = group.memberships
		
		parser = CowParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
		
		result = transaction.getResult()
		
		msg = ''
		msg += _('Total', lang)
		msg += ': $%s\\n'% result.total;
		msg += _('Each', lang)
		msg += ': $%s\\n\\n'% round(result.each, 2);
		
		for debt in result.debts:
			i = 0
			msg += ' - '
			for singleDebt in debt.singleDebts:
				tuple = { 'from': debt.fromMember.userNick, 'to': singleDebt.toMember.userNick, 'amount': round(singleDebt.money, 2) }
				if i == 0:
					if debt.fromMember.user == creatorMember.user:
						msg += _('You owe %(to)s $%(amount)s', lang) % tuple
					elif singleDebt.toMember.user == creatorMember.user:
						msg += _('%(from)s owes you $%(amount)s', lang) % tuple
					else:
						msg += _('%(from)s owes %(to)s $%(amount)s', lang) % tuple
				elif i < len(debt.singleDebts) - 1:
					msg += ', '
					if singleDebt.toMember.user == creatorMember.user:
						msg += _('you $%(amount)s', lang) % tuple
					else:
						msg += _('%(to)s $%(amount)s', lang) % tuple
				else:
					msg += ' '
					msg += _('and', lang)
					msg += ' '
					if singleDebt.toMember.user == creatorMember.user:
						msg += _('you $%(amount)s', lang) % tuple
					else:
						msg += _('%(to)s $%(amount)s', lang) % tuple
				i = i + 1
			msg += '\\n'
		
		alertMessage(self, msg)
Пример #29
0
def create_group(group_name):
    Group.create(group_name)
    resp = jsonify(status="OK", group_name=group_name)
    resp.status_code = 201
    return resp
Пример #30
0
    def post(self, login):
        """
        ---
        summary: Create a new user
        description: |
            Creates new user account

            Requires `manage_users` capability.
        security:
            - bearerAuth: []
        tags:
            - user
        parameters:
            - in: path
              name: login
              schema:
                type: string
              description: New user login
        requestBody:
            description: User information
            content:
              application/json:
                schema: UserProfileManageInfoSchema
        responses:
            200:
                description: When user was created successfully
                content:
                  application/json:
                    schema: UserSuccessSchema
            400:
                description: When request body is invalid
            403:
                description: When user doesn't have `manage_users` capability.
            409:
                description: When user or group with provided name already exists.
            500:
                description: When SMTP server is unavailable or not properly configured on the server.
        """
        schema = UserProfileManageInfoSchema()

        obj = schema.loads(request.get_data(as_text=True))
        if obj.errors:
            return {"errors": obj.errors}, 400

        user_login_obj = UserLoginSchemaBase().load({"login": login})
        if user_login_obj.errors:
            return {"errors": user_login_obj.errors}, 400

        if db.session.query(exists().where(User.login == login)).scalar():
            raise Conflict("User exists yet")

        if db.session.query(exists().where(Group.name == login)).scalar():
            raise Conflict("Group exists yet")

        user = User()
        user.login = login
        user.email = obj.data.get("email")
        user.additional_info = obj.data.get("additional_info")
        user.feed_quality = obj.data.get("feed_quality")
        user.disabled = False
        user.pending = False
        user.registered_by = g.auth_user.id
        user.registered_on = datetime.datetime.now()
        user.groups.append(Group.public_group())
        user.reset_sessions()
        db.session.add(user)

        group = Group()
        group.name = login
        group.private = True
        group.users.append(user)
        db.session.add(group)

        if obj.data.get("send_email", False):
            try:
                send_email_notification(
                    "register",
                    "New account registered in Malwarecage",
                    user.email,
                    base_url=app_config.malwarecage.base_url,
                    login=user.login,
                    set_password_token=user.generate_set_password_token(
                    ).decode("utf-8"))
            except MailError:
                logger.exception("Can't send e-mail notification")
                raise InternalServerError(
                    "SMTP server needed to fulfill this request is"
                    " not configured or unavailable.")

        db.session.commit()

        logger.info('User created', extra={'user': user.login})
        schema = UserSuccessSchema()
        return schema.dump({"login": user.login})
Пример #31
0
    def listGroups(self):
        """Return a list of available groups

        @rtype: Group List
        @return: list of available Groups"""
        return tuple(Group.create(groupName, self._modelDataManager) for groupName in self.pm_getUserManager().listGroups())
Пример #32
0
    def getGroup(self, name):
        """Return a Group object

        @param name: group name
        @rtype: Group"""
        return Group.create(self.pm_getUserManager().getGroup(self._unbox(name)), self._modelDataManager)
Пример #33
0
def newgroup():
    # Standard conditions to check if the user has proper right to acces the page ***
    if DEBUG:
        pdb.set_trace()
    user = User.query.filter(
        User.ext_id_hashed == session.get('profile_ext_id_hashed')).first()
    if user is None:
        session.clear()
        return redirect(url_for('index'))
    elif user.account_status == 0:
        return render_template(
            "message.html",
            message=
            "Please wait for admin approval. Contact an admin if needed.",
            avatar_url=user.avatar_url)
    elif user.account_type != 2:
        return render_template(
            "message.html",
            message="You do not have proper right to access this site. "
            "Please contact an admin if needed.",
            avatar_url=user.avatar_url)
    # End of conditions ******************************
    group_action = request.values.get('group_action', '')
    user_action = request.values.get('user_action', '')
    if group_action:
        new_name = request.values.get('new_name', '')
        group_id = request.values.get('group_id', '')
        if group_action == "add":
            try:
                group = Group(name=new_name)
                db.session.add(group)
                db.session.commit()
            except Exception:
                db.session.rollback()
        if group_action == "rename":
            try:
                group = Group.query.filter(Group.id == group_id).first()
                group.name = new_name
                db.session.commit()
            except Exception:
                db.session.rollback()
        elif group_action == "cancel":
            return redirect("/groups")
        elif group_action == "delete":
            try:
                group = Group.query.filter(Group.id == group_id).first()
                member_data = GroupMember.query.filter(
                    GroupMember.group_id == group_id).all()
                db.session.delete(group)
                for member in member_data:
                    db.session.delete(member)
                db.session.commit()
            except Exception:
                db.session.rollback()
        return redirect('/groups')
    if user_action:
        user_id = request.values.get('user_id', '')
        group_id = request.values.get('group_id', '')
        if user_action == "add":
            try:
                new_member = GroupMember(group_id=group_id, user_id=user_id)
                db.session.add(new_member)
                db.session.commit()
            except Exception:
                db.session.rollback()
        elif user_action == "remove":
            try:
                old_member = GroupMember.query.filter(
                    GroupMember.user_id == user_id,
                    GroupMember.group_id == group_id).first()
                db.session.delete(old_member)
                db.session.commit()
            except Exception:
                db.session.rollback()
        if len(str(group_id)) > 0:
            return redirect('/groups/' + str(group_id))
        else:
            return redirect('/groups')
    return render_template('newgroup.html',
                           user=user,
                           group=None,
                           member=[],
                           outer=User.query.all())
Пример #34
0
def save_group_id_to_group(group_data):
    # Функция сохранения group_id в таблице group
    session = Session()
    c1 = Group(group_id=group_data)
    session.add(c1)
    session.commit()
Пример #35
0
	def post(self):
		if not userIsLoggedIn(self):
			return
			
		rejectPath = UrlBuilder(self.request).buildUrl('/reject')
		
		user = users.get_current_user()
		lang = getLanguage(self, user)
		group = Group.get(self.request.get("group"))
		
		creatorMember = Membership.gql("WHERE group = :1 AND user = :2", group, user)[0]
		if not creatorMember:
			return
		
		command = self.request.get("command")
		members = group.memberships
		
		parser = OrderParser()
		parser.lang = lang
		transaction = parser.parse(members, command)
		
		if transaction.error:
			alertMessage(self, transaction.error)
			return
			
		payersBalanceBefore = transaction.payer.balance
		
		for debt in transaction.debts:
		    debtor = debt.member
		    payer = transaction.payer
		    debtorLang = getLanguage(self, debtor.user)
			
		    if debtor.user.email().lower() == payer.user.email().lower():
		        continue
			
		    debtorsBalanceBefore = debtor.balance
		    
		    # Adjust balance
		    debtor.balance -= debt.money
		    debtor.put()
		    
		    payer.balance += debt.money
		    
		    debtorsBalanceNow = debtor.balance
		    
		    # Create transaction
		    tr = Transaction(
		        group = group,
		        creatorMember = creatorMember, 
		        fromMember = debtor,
		        toMember = payer,
		        type = 'debt',
		        amount = debt.money, 
		        reason = debt.reason,
		        isRejected = False
		        )
		    tr.put()
			
		    # If the one that created this transaction is the one that owes,
		    # don't sent a mail to him/her
		    if creatorMember.user == debtor.user:
		    	continue
		    
		    # Build the reject url
		    rejectUrl = UrlBuilder(self.request).buildUrl('/reject')
		    rejectUrl += "?key=%s&h=%s" % (str(tr.key()), tr.hash)
		    
		    # Try send email to the debtor
		    if creatorMember.user == transaction.payer.user:
		    	message = createActionMail(payer, debtor, debt.money, debt.reason, debtorsBalanceBefore, debtorsBalanceNow, rejectUrl, youOwedSomeone(debtorLang), debtorLang) 
		    else:
		    	message = createThirdPartyActionMail(creatorMember, payer, debtor, debt.money, debt.reason, debtorsBalanceBefore, debtorsBalanceNow, rejectUrl, creatorSaysYouOwedSomeone(debtorLang), debtorLang)
		    
		    sendEmail(message)
				
		transaction.payer.put()
		
		payersBalanceNow = transaction.payer.balance
		
		# Now try send email to the payer with a summary
		if not creatorMember.user == transaction.payer.user:
			payerLang = getLanguage(self, transaction.payer.user)
			message = createBulkMail(transaction, creatorMember, payersBalanceBefore, payersBalanceNow, payerLang)
			sendEmail(message)
				
		location = '/group?group=%s&msg=%s' % (group.key(), _('Debts saved!', lang))
		redirectPage(self,location)
Пример #36
0
def process_classics_users():

    # just to get a sense of timing
    print_time()

    # get a list of groups related to our classics keyword
    groups = gc.find_groups(CLASSICS_GROUP_KEYWORD)

    # make sure we get all pages
    gpage = 1

    while groups:
    # while groups and gpage == 1: # for testing

        print '*' * 10, 'group page', gpage

        for group_dict in groups: 
        # for group_dict in groups[0:1]:  # for testing

            # skip this group if its already been processed
            if Group.query.get(group_dict['id']):
                print '\t\t\talready added group id', group_dict['id'], ', skipping...'
                continue

            # get actual group object
            group = gc.group(group_dict['id'])
            # group = gc.group(95455) # testing

            # note: some group names are unicode (greek!) and don't translate well to ascii
            group_name = group.title.encode('unicode-escape')
            print '***** processing group', group.gid, group_name

            # make sure we get all pages of members
            mpage = 1
            member_results = True

            # keep track of whether it was processed successfully
            process_success = True

            while member_results:

                print '\tmember page', mpage

                try:
                    member_results = group.get_members(page=mpage)
                except Exception as e:
                    try:
                        err_string = str(e)
                    except:
                        err_string = '<no error string>'

                    print '~~~~~~~~ ERROR: problem getting members:', err_string
                    print "~~~~~~~~ Moving on."

                    # record that it was not successfully processed
                    process_success=False
                    break

                for member in member_results:
                    user_id = member['id']['#text']

                    # skip this user if already processed
                    if User.query.get(user_id):
                        continue

                    # otherwise, add the reviews (and  add the user to the db)
                    success = add_reviews_by_user(user_id)

                mpage += 1

            # we're done with this group -- put it in the db so we can skip it 
            # if we re-process
            group_row = Group(group_id=group.gid, 
                              group_name=group_name, 
                              process_success=process_success)
            db.session.add(group_row)
            db.session.commit()

        # get the next page
        gpage += 1
        groups = gc.find_groups(CLASSICS_GROUP_KEYWORD, page=gpage)
Пример #37
0
    def post(self, identifier):
        if self.ObjectType is Object:
            raise MethodNotAllowed()

        schema = self.Schema()

        if request.is_json:
            obj = schema.loads(
                request.get_data(parse_form_data=True, as_text=True))
        elif 'json' in request.form:
            obj = schema.loads(request.form["json"])
        else:
            obj = None

        if obj and obj.errors:
            return {"errors": obj.errors}, 400

        if identifier == 'root':
            parent_object = None
        else:
            if not g.auth_user.has_rights(Capabilities.adding_parents):
                raise Forbidden("You are not permitted to link with parent")
            parent_object = authenticated_access(Object, identifier)

        metakeys = request.form.get('metakeys')
        upload_as = request.form.get("upload_as") or "*"

        if metakeys:
            metakeys = MetakeyShowSchema().loads(metakeys)
            if metakeys.errors:
                logger.warn('schema error', extra={'error': metakeys.errors})
                raise BadRequest()
            metakeys = metakeys.data['metakeys']

        item, is_new = self.create_object(obj)

        if item is None:
            raise Conflict("Conflicting object types")

        if is_new:
            db.session.add(item)

        if metakeys:
            for metakey in metakeys:
                if item.add_metakey(metakey['key'],
                                    metakey['value'],
                                    commit=False) is None:
                    raise NotFound("Metakey '{}' not defined or insufficient "
                                   "permissions to set that one".format(
                                       metakey["key"]))

        if parent_object:
            item.add_parent(parent_object, commit=False)
            logger.info('relation added',
                        extra={
                            'parent': parent_object.dhash,
                            'child': item.dhash
                        })

        if upload_as == "*":
            share_with = [
                group.id for group in g.auth_user.groups
                if group.name != "public"
            ]
        else:
            if not g.auth_user.has_rights(Capabilities.sharing_objects) and \
               upload_as not in [group.name for group in g.auth_user.groups]:
                raise NotFound("Group {} doesn't exist".format(upload_as))
            group = Group.get_by_name(upload_as)
            if group is None:
                raise NotFound("Group {} doesn't exist".format(upload_as))
            share_with = [group.id, Group.get_by_name(g.auth_user.login).id]
            if group.pending_group is True:
                raise NotFound("Group {} is pending".format(upload_as))

        for share_group_id in share_with:
            item.give_access(share_group_id,
                             AccessType.ADDED,
                             item,
                             g.auth_user,
                             commit=False)

        if is_new:
            for all_access_group in Group.all_access_groups():
                item.give_access(all_access_group.id,
                                 AccessType.ADDED,
                                 item,
                                 g.auth_user,
                                 commit=False)

        db.session.commit()

        if is_new:
            hooks.on_created_object(item)
            if self.on_created:
                self.on_created(item)
        else:
            hooks.on_reuploaded_object(item)
            if self.on_reuploaded:
                self.on_reuploaded(item)

        logger.info('{} added'.format(self.ObjectTypeStr),
                    extra={
                        'dhash': item.dhash,
                        'is_new': is_new
                    })

        return schema.dump(item)
Пример #38
0
 def save(cls, user, **kwargs):
     g.current_user = user if user else None
     admin_group = Group.select().where(Group.name == 'admin').get()
     g.is_admin = admin_group.is_member(g.current_user)
Пример #39
0
def setup_database():
    init_model(engine)
    teardownDatabase()
    elixir.setup_all(True)

    # Creating permissions

    see_site = Permission()
    see_site.permission_name = u'see-site'
    see_site.description = u'see-site permission description'
    DBSession.save(see_site)

    edit_site = Permission()
    edit_site.permission_name = u'edit-site'
    edit_site.description = u'edit-site permission description'
    DBSession.save(edit_site)

    commit = Permission()
    commit.permission_name = u'commit'
    commit.description = u'commit permission description'
    DBSession.save(commit)

    # Creating groups

    admins = Group()
    admins.group_name = u'admins'
    admins.display_name = u'Admins Group'
    admins.permissions.append(edit_site)
    DBSession.save(admins)

    developers = Group(group_name=u'developers',
                       display_name=u'Developers Group')
    developers.permissions = [commit, edit_site]
    DBSession.save(developers)

    trolls = Group(group_name=u'trolls', display_name=u'Trolls Group')
    trolls.permissions.append(see_site)
    DBSession.save(trolls)

    # Plus a couple of groups with no permissions
    php = Group(group_name=u'php', display_name=u'PHP Group')
    DBSession.save(php)

    python = Group(group_name=u'python', display_name=u'Python Group')
    DBSession.save(python)

    # Creating users

    user = User()
    user.user_name = u'rms'
    user.password = u'freedom'
    user.email_address = u'*****@*****.**'
    user.groups.append(admins)
    user.groups.append(developers)
    DBSession.save(user)

    user = User()
    user.user_name = u'linus'
    user.password = u'linux'
    user.email_address = u'*****@*****.**'
    user.groups.append(developers)
    DBSession.save(user)

    user = User()
    user.user_name = u'sballmer'
    user.password = u'developers'
    user.email_address = u'*****@*****.**'
    user.groups.append(trolls)
    DBSession.save(user)

    # Plus a couple of users without groups
    user = User()
    user.user_name = u'guido'
    user.password = u'phytonic'
    user.email_address = u'*****@*****.**'
    DBSession.save(user)

    user = User()
    user.user_name = u'rasmus'
    user.password = u'php'
    user.email_address = u'*****@*****.**'
    DBSession.save(user)

    DBSession.commit()
Пример #40
0
 def do_something(self):
     l = self.get_contacts_in_group(Group(id="123"))
     print(l)
     for item in l:
         print(item)
     print(len(l))
Пример #41
0
 def convert(group):
     return Group(id=str(group.id),
                  name=group.name,
                  footer=group.footer)
Пример #42
0
    def post(self):
        """
        ---
        description: Request new user account
        tags:
            - auth
        requestBody:
            description: User basic information
            content:
              application/json:
                schema: UserRegisterSchema
        responses:
            200:
                description: User login on successful registration
                content:
                  application/json:
                    schema: UserSuccessSchema
        """
        if not app_config.malwarecage.enable_registration:
            raise Forbidden("User registration is not enabled.")

        schema = UserRegisterSchema()
        obj = schema.loads(request.get_data(as_text=True))

        if obj.errors:
            return {"errors": obj.errors}, 400

        login = obj.data.get("login")

        if db.session.query(exists().where(User.login == login)).scalar():
            raise Conflict("Name already exists")

        if db.session.query(exists().where(Group.name == login)).scalar():
            raise Conflict("Name already exists")

        recaptcha_secret = app_config.malwarecage.recaptcha_secret

        if recaptcha_secret:
            try:
                recaptcha_token = obj.data.get("recaptcha")
                recaptcha_response = requests.post(
                    'https://www.google.com/recaptcha/api/siteverify',
                    data={
                        'secret': recaptcha_secret,
                        'response': recaptcha_token
                    })
                recaptcha_response.raise_for_status()
            except Exception as e:
                logger.exception("Temporary problem with ReCAPTCHA.")
                raise InternalServerError(
                    "Temporary problem with ReCAPTCHA.") from e

            if not recaptcha_response.json().get('success'):
                raise Forbidden("Wrong ReCAPTCHA, please try again.")

        user = User()
        user.login = login
        user.email = obj.data.get("email")
        user.additional_info = obj.data.get("additional_info")
        user.pending = True
        user.disabled = False
        user.requested_on = datetime.datetime.now()
        user.groups.append(Group.public_group())
        user.reset_sessions()
        db.session.add(user)

        group = Group()
        group.name = login
        group.private = True
        group.users.append(user)
        db.session.add(group)
        db.session.commit()

        try:
            send_email_notification("pending",
                                    "Pending registration in Malwarecage",
                                    user.email,
                                    base_url=app_config.malwarecage.base_url,
                                    login=user.login)
        except MailError:
            logger.exception("Can't send e-mail notification")

        logger.info('User registered', extra={'user': user.login})
        schema = UserSuccessSchema()
        return schema.dump({"login": user.login})
Пример #43
0
def upload():
    data = request.get_array(field_name="file")
    user_id = request.form["user_id"]
    ##First check; Does the first row contain just one column and if so is that group name
    ## taken in his account?
    print(data[0], file=sys.stderr)
    try:
        if first_row_excel_length(data[0])== 1:
            check_group = Group.query.filter_by(name=data[0][0], owner_id=user_id).count()
            if check_group == 0:
                new_group = Group(name=data[0][0], owner_id=int(user_id))
                db.session.add(new_group)
                db.session.flush()
            else:
                return jsonify({
                    "status":"FAILED",
                    "reason":"The Name given to the group already exists in your account"
                })
            ##Second Check: check that the length of the second row equals 5
            if first_row_excel_length(data[1])== 5:
                #We will now add the entries to the data base
                destination_group = Group.query.filter_by(name=data[0][0],
                                                          owner_id=user_id).one()
                emails_used = []
                email_info_objects = []
                for indx, value in enumerate(data):
                    if indx == 0 or indx == 1:
                        continue
                    else:
                        #Check if parent information exists
                        check_parent = Parents.query.filter_by(email=value[4]).count()
                        the_parent_id = None
                        if check_parent == 1 :
                            parent = Parents.query.filter_by(email = value[4]).one()
                            if value[2] == parent.name:
                                the_parent_id = parent.id
                                print(str(the_parent_id), file=sys.stderr)
                            else:
                                return jsonify({
                                    "status":"FAILED",
                                    "reason":"parent email in row "+ str(indx+1)+" is already in "
                                                                                 "use"
                                })
                        else:
                            new_parent = Parents(name=value[2], email=value[4], telephone=value[3])
                            db.session.add(new_parent)
                            db.session.flush()
                            the_parent_id = Parents.query.filter_by(email=value[4]).one().id
                        ## Now we must add the student
                        print(value[1] in emails_used, file=sys.stderr)
                        if value[1] not in emails_used:
                            new_student = Students(name=value[0], email=value[1], parent_id=the_parent_id, teacher_id=user_id, group_id=destination_group.id)
                            db.session.add(new_student)
                            db.session.flush()
                            emails_used.append(value[1])
                            email_info_objects.append({
                                "row":indx + 1,
                                "email":value[1]
                            })
                            print(emails_used, file=sys.stderr)
                        else:
                            the_index_email = emails_used.index(value[1])
                            print("Inside else", file=sys.stderr)
                            print(emails_used[the_index_email], file=sys.stderr)
                            return jsonify({
                                "status":"FAILED",
                                "reason":"the student email in row: "+str(indx + 1)+" "
                                                                                "already exists in row: "+ str(email_info_objects[the_index_email]["row"])
                            })
                db.session.commit()
                user = Users.query.filter_by(id=int(user_id)).one().restReturn
                user.update({
                    "status":"SUCCESS"
                })
                return jsonify(user)

            else:
                return jsonify({
                    "status":"FAILED",
                    "reason": "The header should be of length 5; found "
                            + str(first_row_excel_length(data[1]))
        })
        else:
            return jsonify({
                "status":"FAILED",
                "reason":"First Row in excel document should contain only one column, instead found "
                         +str(first_row_excel_length(data[0]))
            })
    except:
        e = sys.exc_info()
        traceback.print_exception(*e)
        return "Error Sending message"