コード例 #1
0
def test_get_meeting_join_info(client: FlaskClient) -> None:
    user1 = User(uuid=example_uuid1)
    user2 = User(uuid=example_uuid2)
    user3 = User(uuid=example_uuid3)
    meeting = Meeting(uuid=example_uuid4,
                      owner=user1,
                      name='Lorem ipsum',
                      description='Lorem ipsum sit dolor amet.',
                      datetime=datetime(2020, 1, 2, 3, 4, 5))
    membership1 = Membership(meeting=meeting, user=user1, nickname='Alice')
    membership2 = Membership(meeting=meeting, user=user2, nickname='Bob')
    membership3 = Membership(meeting=meeting, user=user3, nickname='Charlie')
    db.session.add(membership1)
    db.session.add(membership2)
    db.session.add(membership3)
    db.session.commit()

    response = client.get(f'/api/v1/meetings/{meeting.uuid}')
    assert response.status_code == 200
    assert response.json == {
        'name': 'Lorem ipsum',
        'datetime': '2020-01-02T03:04:05',
        'members_count': 3,
        'owner_nickname': 'Alice',
    }
コード例 #2
0
ファイル: views.py プロジェクト: oerb/share-tech
def new_location(request):
    """
    New Location
    """
    data = {}
    template = 'itembase/simpleform.djhtml'
    data['message'] = None
    data['headstring'] = 'New Location'
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            location = Location(
                lc_name=form.cleaned_data['lc_name'],
                lc_geo=form.cleaned_data['lc_geo'],
                lc_adr=form.cleaned_data['lc_adr'],
                lc_city=form.cleaned_data['lc_city'],
                lc_www=form.cleaned_data['lc_www'],
                lc_mail=form.cleaned_data['lc_mail'],
                lc_info=form.cleaned_data['lc_info'],
            )
            location.save()
            print(location)
            membership = Membership(
                me_user=request.user,
                me_location=location,
                me_trust1=request.user,
                me_trust2=request.user,
            )
            membership.save()
            print membership
            return redirect('itembase/home')
        return redirect('itembase/home')
    else:
        data['form'] = LocationForm()
    return render(request, template, data)
コード例 #3
0
def unsubscribe(team_name, member):
    if len(member.teams()) == 0:
        return 'Du er ikke medlem av noen team'

    if len(member.teams()) > 1 and not team_name:
        return 'Du må spesifisere team, `meld av <team>`'

    team = None
    if team_name:
        team_name = _clean_team_name(team_name)
        team = Team.get_or_none(Team.name == team_name)

        if team is None:
            return 'Finner ikke team `{}`'.format(team_name)

        if not team.has_member(member):
            return 'Du er ikke medlem av `{}`'.format(team.name)
    else:
        team = member.teams()[0]

    Membership.delete().where(Membership.member == member.id).where(
        Membership.team == team.id).execute()

    if member.team_id == team.id:
        member.team_id = None
        member.save()

    return 'Du er nå avmeldt'
コード例 #4
0
ファイル: views.py プロジェクト: caylan/Bulletin
def create(request):
    '''
    Sets up a group creation form wherein the user may choose the necessary
    criteria for the group they wish to create.

    The user may select the name of the group.
    '''
    if request.method == 'POST':
        form = GroupCreationForm(request.POST)
        if form.is_valid():
            group = form.save()

            # Create the default user membership
            m = Membership(user=request.user, group=group, is_admin=True)
            m.save()

            # Send emails to invited members.
            _send_email_invites(request, group)
            ''' Redirect to the new group '''
            return HttpResponse(group.json(), mimetype='application/json')
    else:
        raise Http404
    return render(request, 'group_create_modal.html', {
        'form': form,
    })
コード例 #5
0
ファイル: views.py プロジェクト: oerb/share-tech
def new_location(request):
    """
    New Location
    """
    data = {}
    template = 'itembase/simpleform.djhtml'
    data['message'] = None
    data['headstring'] = 'New Location'
    if request.method == "POST":
        form = LocationForm(request.POST)
        if form.is_valid():
            location = Location(lc_name=form.cleaned_data['lc_name'],
                                lc_geo=form.cleaned_data['lc_geo'],
                                lc_adr=form.cleaned_data['lc_adr'],
                                lc_city=form.cleaned_data['lc_city'],
                                lc_www=form.cleaned_data['lc_www'],
                                lc_mail=form.cleaned_data['lc_mail'],
                                lc_info=form.cleaned_data['lc_info'],
                                )
            location.save()
            print(location)
            membership = Membership(me_user = request.user,
                                    me_location = location,
                                    me_trust1 = request.user,
                                    me_trust2 = request.user,
            )
            membership.save()
            print membership
            return redirect('itembase/home')
        return redirect('itembase/home')
    else:
        data['form'] = LocationForm()
    return render(request, template, data)
コード例 #6
0
def addMembership(membership_dict):
    newMembership = Membership(
        #id = id,
        user_id=membership_dict.get('user_id'),
        start_date=membership_dict.get('start_date'),
        last_renew_date=membership_dict.get('last_renew_date'),
        is_active=membership_dict.get('is_active'))
    newMembership.save()
    return newMembership
コード例 #7
0
ファイル: views.py プロジェクト: siarheipashkevich/PythonLabs
 def form_valid(self, form):
     self.object = form.save(commit=False)
     Membership.objects.filter(project=self.object).delete()
     for member_id in form.data.getlist("members[]"):
         membership = Membership()
         membership.project = self.object
         membership.employee = Employee.objects.get(pk=member_id)
         membership.save()
     return super(ModelFormMixin, self).form_valid(form)
コード例 #8
0
def test_get_membership_details(client: FlaskClient) -> None:
    user1 = User(uuid=example_uuid1)
    user2 = User(uuid=example_uuid2)
    meeting = Meeting(uuid=example_uuid3,
                      owner=user1,
                      name='Lorem ipsum',
                      description='Lorem ipsum sit dolor amet.',
                      datetime=datetime(2020, 1, 2, 3, 4, 5),
                      stop_name='Czarnowiejska')
    membership1 = Membership(meeting=meeting,
                             user=user1,
                             nickname='Alice',
                             stop_name='Kawiory')
    membership2 = Membership(meeting=meeting,
                             user=user2,
                             nickname='Bob',
                             stop_name='Muzeum Narodowe')
    db.session.add(membership1)
    db.session.add(membership2)
    db.session.commit()

    response = client.get(f'/api/v1/memberships/{meeting.uuid}/{user2.uuid}')
    assert response.status_code == 200
    assert response.json == {
        'uuid':
        meeting.uuid,
        'name':
        'Lorem ipsum',
        'description':
        'Lorem ipsum sit dolor amet.',
        'datetime':
        '2020-01-02T03:04:05',
        'stop_name':
        'Czarnowiejska',
        'members': [
            {
                'nickname': 'Alice',
                'is_owner': True,
                'is_you': False,
                'stop_name': 'Kawiory',
            },
            {
                'nickname': 'Bob',
                'is_owner': False,
                'is_you': True,
                'stop_name': 'Muzeum Narodowe',
            },
        ],
        'membership': {
            'is_owner': False,
            'stop_name': 'Muzeum Narodowe',
        }
    }
コード例 #9
0
ファイル: views.py プロジェクト: oerb/share-tech
def join_location(request, location_id):
    """
    Join a Location
    """
    data = {}
    location = get_object_or_404(Location, pk=location_id)
    membership = Membership(me_user = request.user,
                            me_location = location,
    )
    membership.save()
    print membership
    return redirect('itembase/home')
コード例 #10
0
ファイル: forms.py プロジェクト: boundis/boundisbackend
 def save(self,group_obj):
         try:
                 persons = User.objects.get(username=self.cleaned_data['member'])
         except User.DoesNotExist:
                 return "User does not exist."
         personss = User.objects.get(username=persons)
         try:
                 check = Membership.objects.get(group=group_obj,person=personss)
                 return "User already in group"
         except Membership.DoesNotExist:
                 new_membership = Membership(person=personss,membership_type=self.cleaned_data['membership_type'],group=group_obj)
                 new_membership.save()
                 return new_membership
コード例 #11
0
ファイル: utils.py プロジェクト: AASHE/iss
def upsert_memberships(since, get_all=True):
    """Upserts Memberships for MemberSuite objects.
    """
    if not get_all:
        memberships = ms_session.mem_service.get_all_memberships(
            since_when=since)
    else:
        memberships = ms_session.mem_service.get_all_memberships()
    if memberships:
        for membership in memberships:
            logger.debug(
                'upserting membership {mem}'.format(mem=membership.id))
            Membership.upsert_membership(membership=membership)
コード例 #12
0
ファイル: views.py プロジェクト: oerb/share-tech
def join_location(request, location_id):
    """
    Join a Location
    """
    data = {}
    location = get_object_or_404(Location, pk=location_id)
    membership = Membership(
        me_user=request.user,
        me_location=location,
    )
    membership.save()
    print membership
    return redirect('itembase/home')
コード例 #13
0
ファイル: member.py プロジェクト: cardmaster/makeclub
 def getMember(self, user=''):
     if (not user):
         user = self.targetUser
     if (self.member):
         member = self.member
     else:
         member = Membership.between(user, self.club)
         if (not member):
             member = Membership(name=user.nickname(),
                                 email=user.email(),
                                 club=self.club,
                                 user=user)
     return member
コード例 #14
0
ファイル: views.py プロジェクト: A-malagon/2015-sat-pfinal
def GuardarActividad(request,recurso):
    if request.user.is_authenticated():
        hoy = date.today()
        fechaHoy = str(hoy)
        iden = int(recurso) - 1 
        (mensaje, admin, logger, request.user.username) = autenticacionUsuario(request)
        nombreUsuario = request.user.username
        contenidos = Contenidos.objects.all()
        userName = Usuario.objects.get(nombre=nombreUsuario)
        m1 = Membership(contenido=contenidos[iden], usuario=userName,
                      fechaEleccion= fechaHoy)
        m1.save()
        todas = "/todas"
    return HttpResponseRedirect(todas)
コード例 #15
0
ファイル: test_scripts.py プロジェクト: wietlabs/krk_meetings
def test_delete_outdated_meetings(session: Session, dt: Optional[datetime], should_be_deleted: bool):
    owner = User(uuid=example_uuid1)
    user = User(uuid=example_uuid2)
    meeting = Meeting(uuid=example_uuid3, owner=owner, datetime=dt)
    membership1 = Membership(meeting=meeting, user=owner, nickname='Alice')
    membership2 = Membership(meeting=meeting, user=user, nickname='Bob')
    db.session.add(membership1)
    db.session.add(membership2)
    db.session.commit()

    delete_outdated_meetings(session)

    assert (Meeting.query.get(example_uuid3) is None) is should_be_deleted
    assert (Membership.query.get((example_uuid3, example_uuid1)) is None) is should_be_deleted
    assert (Membership.query.get((example_uuid3, example_uuid2)) is None) is should_be_deleted
コード例 #16
0
ファイル: views.py プロジェクト: adamfeuer/surveytool
def save_memberships_from_form(user, form):
   delete_memberships_for_user(user)
   for project in form.cleaned_data['surveys']:
      membership = Membership(user = user, project = project)
      membership.save()
   user_details_list = UserDetail.objects.filter(user = user.id)
   if (len(user_details_list) > 0):
      user_details = user_details_list[0]
   else:
      user_details = UserDetail()
   user_details.phone_number = form.cleaned_data['phone_number']
   user_details.smartphone = form.cleaned_data['smartphone']
   user_details.no_messages = form.cleaned_data['no_messages']
   user_details.save()
   return
コード例 #17
0
def test_leave_meeting(client: FlaskClient) -> None:
    owner = User(uuid=example_uuid1)
    user = User(uuid=example_uuid2)
    meeting = Meeting(uuid=example_uuid3, owner=owner)
    membership1 = Membership(meeting=meeting, user=owner)
    membership2 = Membership(meeting=meeting, user=user)
    db.session.add(membership1)
    db.session.add(membership2)
    db.session.commit()

    response = client.delete(f'/api/v1/memberships/{meeting.uuid}/{user.uuid}')
    assert response.status_code == 204
    assert response.data == b''

    assert Membership.query.get((meeting.uuid, user.uuid)) is None
コード例 #18
0
ファイル: test.py プロジェクト: cardmaster/makeclub
	def get(self, *args):
		respo = self.response.out.write
		output = self.dbg
		
		respo ("<html><head><title>Test</title></head><body>")
		if (self.request.path.endswith('/clean')):
			output ("Begin Clean Up")
			self.cleanUp()
			output ("Cleaning up done")
			return
		output("Now let's go")
		billList = [('Cort', '75.5'), ('Balls', '15')]
		output ("BillList: ", billList)
		
		allacts = Activity.all()
		for act in allacts:
			bill = act.bill
			for entry in bill:
				output ("Entry:", entry, ",", lb = False)
			output()
			output ("acts:", act.key().id(), "Total Expense:", act.expense, "Expanse Bill: ", bill)
		
		mem = Membership.all().get()
		output ("New activity")
		act = Activity(name = "test act", duration=2.0, organizer = mem.user, club = mem.club, bill = billList, expense = '100' )
		output ("Expense:", act.expense)
		output ("Bill:", act.bill)
		output ("Now, put")
		key = act.put()
		output ("Act Saved: ", act.is_saved(), "Key is ", key, " Id is", key.id())
		respo("</body></html>")
コード例 #19
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
	def put(self):
		oldms = Membership.between(self.member, self.activity)
		entry = self
		if (oldms):
			oldms.copy(self)
			entry = oldms
		return db.Model.put (entry)
コード例 #20
0
ファイル: clubprivilige.py プロジェクト: cardmaster/makeclub
 def initRequest(self):
     urlconf = urldict[type(self).__name__]
     slug, useremail = urlconf.analyze(self.request.path)
     club = Club.getClubBySlug(slug)
     if (not club):
         return errorPage(self.response, "No Such Club: '%s'" % slug,
                          urldict['ClubList'].path(), 404)
     user = users.get_current_user()
     pathuser = user
     if (useremail):
         getuser = users.User(useremail)
         if (getuser):
             pathuser = getuser
     if (hasClubPrivilige(user, club, "privGrant", pathuser)):
         self.user = user
         self.target = Membership.between(pathuser, club)
         if (self.target):
             return True
         else:
             return errorPage(
                 self.response,
                 "User %s is not a member of club %s" % (pathuser, slug),
                 urldict['ClubView'].path(slug), 403)
     else:
         return errorPage(
             self.response,
             "Access Deny For Privilige Grant Operation on Club %s, to user %s"
             % (slug, pathuser), urldict['ClubView'].path(slug), 403)
コード例 #21
0
ファイル: access.py プロジェクト: cardmaster/makeclub
	def __init__(self, user, club):
		super(ClubUser, self).__init__(user)
		self.club = club
		if (club.is_saved()):
			self.member = Membership.between(user, club)
		else:
			self.member = None
コード例 #22
0
ファイル: member.py プロジェクト: cardmaster/makeclub
    def visit(self):
        if (self.club and self.user):
            return True
        #Analyze req path first
        slug, pathuser = urlconf.analyze(self.request.path)
        #Get club
        club = Club.getClubBySlug(slug)
        if (not club):
            return errorPage(self.response, "No such club " + slug, '/clubs',
                             404)

        #Check user status
        user = users.get_current_user()
        if (not user):
            return errorPage(self.response, "User not login",
                             users.create_login_url(self.request.uri),
                             self.response, 403)

        #That the one we modify is the path user. if omitted, user current user as target
        if (pathuser):
            pathuser = users.User(pathuser)
        else:
            pathuser = user
        #@warning: I don't know is it correct to add access control code here
        if (not hasClubPrivilige(user, club, 'membership', pathuser.email())):
            return errorPage(self.response, "Can not access", '/', 403)
        self.user = user
        self.club = club
        self.member = Membership.between(pathuser, club)
        self.targetUser = pathuser
        return True
コード例 #23
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
 def put(self):
     oldms = Membership.between(self.member, self.activity)
     entry = self
     if (oldms):
         oldms.copy(self)
         entry = oldms
     return db.Model.put(entry)
コード例 #24
0
ファイル: member.py プロジェクト: cardmaster/makeclub
    def visit(self):
        if self.club and self.user:
            return True
            # Analyze req path first
        slug, pathuser = urlconf.analyze(self.request.path)
        # Get club
        club = Club.getClubBySlug(slug)
        if not club:
            return errorPage(self.response, "No such club " + slug, "/clubs", 404)

            # Check user status
        user = users.get_current_user()
        if not user:
            return errorPage(
                self.response, "User not login", users.create_login_url(self.request.uri), self.response, 403
            )

            # That the one we modify is the path user. if omitted, user current user as target
        if pathuser:
            pathuser = users.User(pathuser)
        else:
            pathuser = user
            # @warning: I don't know is it correct to add access control code here
        if not hasClubPrivilige(user, club, "membership", pathuser.email()):
            return errorPage(self.response, "Can not access", "/", 403)
        self.user = user
        self.club = club
        self.member = Membership.between(pathuser, club)
        self.targetUser = pathuser
        return True
コード例 #25
0
	def post(self, *args): 
		stat, user = self.accessControl()
		pathslug=self.analyzePath()
		clubmd = self.parsePostdata (self.request, pathslug)
		if (clubmd): #Put valid, then redirect
			if ( self.editOrCreateRight(user, clubmd) ):
				self.clubmodel = clubmd
				isNewClub = not clubmd.is_saved()
				clubmd.put()
				if (isNewClub): #Create New Membership For Owner when create the club
					mem = Membership(user=user, club = clubmd)
					mem.put()
				infoPage (self.response, "Successfullyt Saved Club", "Club Saved", urldict['ClubView'].path(clubmd.slug))
			else:
				return
		else:
			self.get()
コード例 #26
0
def test_delete_meeting(client: FlaskClient) -> None:
    owner = User(uuid=example_uuid1)
    user = User(uuid=example_uuid2)
    meeting = Meeting(uuid=example_uuid3, owner=owner)
    membership1 = Membership(meeting=meeting, user=owner, nickname='Alice')
    membership2 = Membership(meeting=meeting, user=user, nickname='Bob')
    db.session.add(membership1)
    db.session.add(membership2)
    db.session.commit()

    response = client.delete(f'/api/v1/meetings/{meeting.uuid}',
                             json={'owner_uuid': owner.uuid})
    assert response.status_code == 204
    assert response.data == b''

    assert Meeting.query.get(meeting.uuid) is None
    assert Membership.query.get((meeting.uuid, owner.uuid)) is None
    assert Membership.query.get((meeting.uuid, user.uuid)) is None
コード例 #27
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
	def between(mem, act):
		if (not isinstance(mem, Membership)): #Will be use as user
			user = mem
			mem = Membership.between(user, act.club)
		if (not mem):
			return None
		q = ActivityParticipator.all()
		q.filter('member = ', mem).filter('activity = ', act)
		return q.get()
コード例 #28
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
 def between(mem, act):
     if (not isinstance(mem, Membership)):  #Will be use as user
         user = mem
         mem = Membership.between(user, act.club)
     if (not mem):
         return None
     q = ActivityParticipator.all()
     q.filter('member = ', mem).filter('activity = ', act)
     return q.get()
コード例 #29
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
	def post(self, *args):
		urlcfg = urldict['ActivityParticipate']
		id, oper = urlcfg.analyze(self.request.path)
		id = int(id)
		actobj = self.getActModel(id)
		if (not actobj):
			return errorPage (self.response,  urldict['ClubList'].path(),  "No such activity",  404 )
		user = get_current_user();
		if (not user):
			return errorPage ( self.response,  "Not login",   create_login_url(self.request.url),   403)
		target = self.request.get ('target')
		cluburl = urldict['ClubView'].path(actobj.club.slug)
		if (not hasActPrivilige(user, actobj, oper,target) ):
			return errorPage ( self.response,  "Can not access",   cluburl,   403)
		if (target):
			targetUser = User(target)
			if(not targetUser):
				return errorPage ( self.response,  "Illegal access",   cluburl,   403)
		else: #if target omitted, use current user as target
			targetUser = user
			
		mem = Membership.between (targetUser, actobj.club)
		if (not mem):
			return errorPage ( self.response,  "Not a member",   cluburl,   403)
		
		acturl = urldict['ActivityView'].path(id)
		if (oper == 'join'):
			actp = ActivityParticipator.between (mem, actobj)
			if (not actp):
				actp = ActivityParticipator(member = mem, activity = actobj)
				actp.put()
			return infoPage (self.response, "Successfully Joined", "%s has join activity %s" % (mem.name, actobj.name), acturl)
		elif (oper == 'quit'):
			actp = ActivityParticipator.between(mem, actobj)
			if (actp):
				if (actp.confirmed):
					return errorPage ( self.response,  "Cannot delete confirmed participator",   acturl,   403)
				else:
					actp.delete()
			return infoPage (self.response, "Successfully Quited", "%s success quit activity %s" % (mem.name, actobj.name), acturl)
		elif (oper == 'confirm'):
			actp = ActivityParticipator.between(mem, actobj)
			if (actp):
				actp.confirmed = not actp.confirmed 
				actp.put()
				return infoPage (self.response, "Successfully Confirmed", "success confirmed %s join activity %s" % (mem.name, actobj.name), acturl)
			else:
				return errorPage ( self.response,  "No Such a Member",   acturl,   404)
		elif (oper == 'bill' or oper == "rebill"):
			billobj = ActivityBill.generateBill(actobj, oper == "rebill")#If in rebill operation, we could enable rebill
			if (billobj):
				billobj.put()
				billDict = dict(billobj = billobj)
				return infoPage (self.response, "Successfully Billded", str(billobj.memberBill), acturl)
			else:
				return errorPage (self.response, "Error Will Generate Bill", acturl, 501)
コード例 #30
0
ファイル: member.py プロジェクト: cardmaster/makeclub
 def getMember(self, user=""):
     if not user:
         user = self.targetUser
     if self.member:
         member = self.member
     else:
         member = Membership.between(user, self.club)
         if not member:
             member = Membership(name=user.nickname(), email=user.email(), club=self.club, user=user)
     return member
コード例 #31
0
ファイル: views.py プロジェクト: nmasur/creationdex
def profile(request):
	basic = get_basic(request)
	try:
		profile = Profile.objects.get(user=request.GET['id'])
		edit = None
		invitables = None
		if request.method == 'POST' and request.POST['invite']:
			try:
				obj = Membership.objects.filter(
						project_id=request.POST['invite']
					).get(
						user_id=request.GET['id']
					)
			except Membership.DoesNotExist:
				obj = Membership(project_id=request.POST['invite'],
					user_id=request.GET['id'])
			obj.approved_by_proj=True
			note = Notification(
				user=obj.user, subject=obj.project.user, 
				project=obj.project)
			if obj.approved_by_user:
				note.content = "accepted your request to join the project"
			else:
				note.content = "invited you to join the project"
			obj.save()
			send_note(note)
		if request.user.id == profile.id:
			edit = 'edit'
		elif basic:
			committed = Membership.objects.filter(
				user=profile.user.id).filter(
				approved_by_proj=True).select_related('project')
			invitables = Project.objects.filter(
				user=request.user.id).exclude(
				id__in=committed.values_list('project', flat=True))
		memberships = get_memberships(profile.user)
		ac = are_colleagues(request.user, profile.user)
		return render(request, 'profile.html', {'profile': profile, 'basic': basic,
			'edit': edit, 'memberships': memberships, 'invitables': invitables,
			'are_colleagues': ac})
	except Profile.DoesNotExist:
		return HttpResponseRedirect("/profiles")
コード例 #32
0
def test_leave_meeting_owner(client: FlaskClient) -> None:
    owner = User(uuid=example_uuid1)
    meeting = Meeting(uuid=example_uuid2, owner=owner)
    membership = Membership(meeting=meeting, user=owner)
    db.session.add(membership)
    db.session.commit()

    response = client.delete(
        f'/api/v1/memberships/{meeting.uuid}/{owner.uuid}')
    assert response.status_code == 403
    assert response.json == {'error': 'Meeting owner cannot leave meeting'}
コード例 #33
0
ファイル: club.py プロジェクト: cardmaster/makeclub
	def get(self, *args):
		path = self.request.path
		slug = lastWordOfUrl(path)
		if (slug):
			club = Club.getClubBySlug(slug)
		if (club):
			templatevars = dict(club = club )
			user = users.get_current_user()
			membership = Membership.between (user, club)
			if (membership):
				templatevars['membership'] = membership
			elif (user and hasClubPrivilige(user, club, 'join')): #Could Join
				templatevars['action'] = memberurlconf.path(club.slug, user.email())
				templatevars['userName'] = user.nickname()
				templatevars['userEmail'] = user.email()
			else:
				templatevars['loginUrl'] = users.create_login_url(self.request.uri)
			if (membership and hasClubPrivilige(user, club, 'newAct')):
				templatevars['newAct'] = urldict['ActivityNew'].path(slug)
			if (hasClubPrivilige(user, club, "edit")):
				templatevars['editurl'] = urldict['ClubEdit'].path(club.slug)
			mq = Membership.all()
			mq.filter ('club = ', club)
			memset = []
			for mem in mq:
				if (hasClubPrivilige(user, club, "privGrant")):
					mem.privEdit = urldict['ClubPrivilige'].path(slug, mem.user.email())
				memset.append(mem)
			templatevars['members'] = memset
			aq = Activity.all()
			aq.filter ('club = ', club)
			avpath = urldict['ActivityView'].path
			actlist = []
			for act in aq:
				act.linkpath = avpath (act.key().id())
				actlist.append (act)
			templatevars['acts'] = actlist
			self.response.out.write (render(self.template, templatevars, self.request.url) )
		else:
			self.response.set_status(404)
			errorPage( self.response,  "Club Not Found",   listurlconf.path())
コード例 #34
0
def test_join_meeting_already_a_member(client: FlaskClient) -> None:
    owner = User(uuid=example_uuid1)
    user = User(uuid=example_uuid2)
    meeting = Meeting(uuid=example_uuid3, owner=owner)
    membership = Membership(meeting=meeting, user=user, nickname='Bob')
    db.session.add(membership)
    db.session.commit()

    response = client.put(f'/api/v1/memberships/{meeting.uuid}/{user.uuid}',
                          json={'nickname': 'Bobby'})
    assert response.status_code == 400
    assert response.json == {'error': 'Already a member'}
コード例 #35
0
def test_get_user_meetings(client: FlaskClient) -> None:
    user1 = User(uuid=example_uuid1)
    user2 = User(uuid=example_uuid2)
    user3 = User(uuid=example_uuid3)
    meeting1 = Meeting(uuid=example_uuid4, owner=user1, name='Lorem ipsum')
    meeting2 = Meeting(uuid=example_uuid5,
                       owner=user2,
                       datetime=datetime(2020, 1, 2, 3, 4, 5))
    membership1 = Membership(meeting=meeting1, user=user1, nickname='Alice')
    membership2 = Membership(meeting=meeting1, user=user3, nickname='Charlie')
    membership3 = Membership(meeting=meeting2, user=user1, nickname='Ala')
    membership4 = Membership(meeting=meeting2, user=user2, nickname='Bob')
    membership5 = Membership(meeting=meeting2, user=user3, nickname='Charlie')
    db.session.add(membership1)
    db.session.add(membership2)
    db.session.add(membership3)
    db.session.add(membership4)
    db.session.add(membership5)
    db.session.commit()

    response = client.get(f'/api/v1/users/{user1.uuid}/meetings')
    assert response.status_code == 200
    assert response.json == {
        'meetings': [
            {
                'uuid': meeting1.uuid,
                'name': 'Lorem ipsum',
                'nickname': 'Alice',
                'datetime': None,
                'members_count': 2,
            },
            {
                'uuid': meeting2.uuid,
                'name': None,
                'nickname': 'Ala',
                'datetime': '2020-01-02T03:04:05',
                'members_count': 3,
            },
        ]
    }
コード例 #36
0
def test_edit_membership_details(client: FlaskClient) -> None:
    user = User(uuid=example_uuid1)
    meeting = Meeting(uuid=example_uuid2, owner=user)
    membership = Membership(meeting=meeting, user=user)
    db.session.add(membership)
    db.session.commit()

    response = client.patch(f'/api/v1/memberships/{meeting.uuid}/{user.uuid}',
                            json={'stop_name': 'Chopina'})
    assert response.status_code == 204
    assert response.data == b''

    membership = Membership.query.get((meeting.uuid, user.uuid))
    assert membership.stop_name == 'Chopina'
コード例 #37
0
ファイル: views.py プロジェクト: caylan/Bulletin
def create(request):
    """
    Sets up a group creation form wherein the user may choose the necessary
    criteria for the group they wish to create.

    The user may select the name of the group.
    """
    if request.method == "POST":
        form = GroupCreationForm(request.POST)
        if form.is_valid():
            group = form.save()

            # Create the default user membership
            m = Membership(user=request.user, group=group, is_admin=True)
            m.save()

            # Send emails to invited members.
            _send_email_invites(request, group)

            """ Redirect to the new group """
            return HttpResponse(group.json(), mimetype="application/json")
    else:
        raise Http404
    return render(request, "group_create_modal.html", {"form": form})
コード例 #38
0
def join_meeting(meeting_uuid: str, user_uuid: str):
    validate_meeting_uuid(meeting_uuid)
    validate_user_uuid(user_uuid)

    check_json_data()
    nickname = get_nickname()

    meeting = find_meeting(meeting_uuid)
    user = find_user(user_uuid)

    membership = Membership(user=user, meeting=meeting, nickname=nickname)
    db.session.add(membership)
    try:
        db.session.commit()
    except (IntegrityError, FlushError):
        raise ApiException('Already a member', 400)

    return '', 204
コード例 #39
0
ファイル: clubprivilige.py プロジェクト: cardmaster/makeclub
	def initRequest(self):
		urlconf = urldict[type(self).__name__]
		slug, useremail = urlconf.analyze(self.request.path)
		club = Club.getClubBySlug(slug)
		if (not club):
			return errorPage(self.response, "No Such Club: '%s'" % slug, urldict['ClubList'].path(), 404)
		user = users.get_current_user()
		pathuser = user
		if (useremail):
			getuser = users.User(useremail)
			if (getuser):
				pathuser = getuser
		if (hasClubPrivilige(user, club, "privGrant", pathuser)):
			self.user = user
			self.target = Membership.between(pathuser, club)
			if (self.target):
				return True
			else:
				return errorPage(self.response, "User %s is not a member of club %s" % (pathuser, slug), urldict['ClubView'].path(slug), 403 )
		else:
			return errorPage(self.response, "Access Deny For Privilige Grant Operation on Club %s, to user %s" % (slug, pathuser), urldict['ClubView'].path(slug), 403 )
コード例 #40
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
	def cancel(self):
		if (self.isCancelled):
			return True
		self.activity.isBilled=False
		self.activity.put()
		self.cancelTime = datetime.now()
		self.isCancelled = True
		for tup in self.memberBill:
			user = users.User(tup[0])
			money = Decimal(tup[1])
			mem = Membership.between(user, self.activity.club)
			if (mem):
				mem.balance = mem.balance + money
				mem.put()
				actp = ActivityParticipator.between(mem, self.activity)
				actp.expense = 0
				actp.put()
		club = self.activity.club
		club.fund -= self.sum #When cancel, not effect
		club.put()	
		self.put()
コード例 #41
0
def create_meeting():
    check_json_data()
    owner_uuid = get_owner_uuid()
    name = get_meeting_name()
    description = get_meeting_description()
    dt = get_datetime()
    nickname = get_nickname()

    owner = find_user(owner_uuid)

    meeting = Meeting(name=name,
                      description=description,
                      datetime=dt,
                      owner=owner)
    membership = Membership(meeting=meeting, user=owner, nickname=nickname)
    db.session.add(membership)
    db.session.commit()

    return make_response({
        'uuid': meeting.uuid,
    }, 201, {'Location': f'/api/v1/meetings/{meeting.uuid}'})
コード例 #42
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
 def cancel(self):
     if (self.isCancelled):
         return True
     self.activity.isBilled = False
     self.activity.put()
     self.cancelTime = datetime.now()
     self.isCancelled = True
     for tup in self.memberBill:
         user = users.User(tup[0])
         money = Decimal(tup[1])
         mem = Membership.between(user, self.activity.club)
         if (mem):
             mem.balance = mem.balance + money
             mem.put()
             actp = ActivityParticipator.between(mem, self.activity)
             actp.expense = 0
             actp.put()
     club = self.activity.club
     club.fund -= self.sum  #When cancel, not effect
     club.put()
     self.put()
コード例 #43
0
def add_users_to_new_groups(users):
    groups = [
        Group(name='Python'),
        Group(name='GraphQL'),
        Group(name='SQLAlchemy'),
        Group(name='PostgreSQL'),
    ]
    db_session.bulk_save_objects(groups, return_defaults=True)
    db_session.flush()

    memberships = [
        Membership(
            user_id=user.id,
            group_id=group.id,
            is_moderator=user.id == group.id,
            creator_username=choice(users).username,
        )
        for user in users
        for group in groups
    ]
    db_session.bulk_save_objects(memberships, return_defaults=True)
    db_session.flush()
    return groups
コード例 #44
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
 def execute(self):
     if (self.isExecuted):
         return
     self.isExecuted = True
     self.activity.isBilled = True
     self.activity.put()
     for tup in self.memberBill:
         email = tup[0]
         cost = tup[1]
         user = users.User(email)
         mem = Membership.between(user, self.activity.club)
         bal = mem.balance
         mem.balance = bal - cost
         mem.put()
         actp = ActivityParticipator.between(mem, self.activity)
         actp.expense = cost
         actp.put()
     club = self.activity.club
     if (self.oldfund):
         oldfund = self.oldfund
     else:
         oldfund = club.fund
     club.fund = oldfund + self.sum  #When do bill, member's money will go to club's fund
     club.put()
コード例 #45
0
ファイル: activity.py プロジェクト: cardmaster/makeclub
	def execute(self):
		if (self.isExecuted):
			return
		self.isExecuted = True
		self.activity.isBilled=True
		self.activity.put()
		for tup in self.memberBill:
			email = tup[0]
			cost = tup[1]
			user = users.User(email)
			mem = Membership.between(user, self.activity.club)
			bal = mem.balance
			mem.balance = bal - cost
			mem.put()
			actp = ActivityParticipator.between(mem, self.activity)
			actp.expense = cost
			actp.put()
		club = self.activity.club
		if (self.oldfund):
			oldfund = self.oldfund
		else:
			oldfund = club.fund
		club.fund = oldfund + self.sum #When do bill, member's money will go to club's fund
		club.put()			
コード例 #46
0
ファイル: access.py プロジェクト: cardmaster/makeclub
	def isUserClubMember(self):
		return Membership.between(self.user, self.act.club)
コード例 #47
0
ファイル: forms.py プロジェクト: boundis/boundisbackend
 def save(self,person_obj):
         new_group = Group(group_name=self.cleaned_data['group_name'],group_type=self.cleaned_data['group_type'])
         new_group.save()
         new_membership = Membership(person=person_obj,membership_type='owner',group=new_group)
         new_membership.save()
         return new_group
コード例 #48
0
ファイル: views.py プロジェクト: nmasur/creationdex
def project(request):
	basic = get_basic(request)
	try:
		project = Project.objects.get(id=request.GET['id'])
		member_status = None
		if basic:
			try:
				memberships = Membership.objects.filter(user_id=request.user.id)
				membership = memberships.get(project_id=project.id)
			except Membership.DoesNotExist:
				membership = Membership(user=request.user, project=project)
			if request.user.id == project.user.id:
				member_status = 'admin'
			elif membership.is_staff:
				member_status = 'staff'
			elif membership.approved_by_user and not membership.approved_by_proj:
				member_status = 'requested'
			elif membership.approved_by_proj and not membership.approved_by_user:
				member_status = 'invited'
			elif membership.approved_by_user and membership.approved_by_proj:
				member_status = 'member'
			if request.method == 'POST':
				note = Notification(user=project.user, subject=membership.user,
					project=project)
				if request.POST.get('makepost'):
					return HttpResponseRedirect(
						"/makepost?id=" + str(project.id))
				elif request.POST.get('manageproject'):
					return HttpResponseRedirect(
						"/manageproject?id=" + str(project.id))
				elif request.POST.get('join'):
					membership.approved_by_user = True
					if membership.approved_by_proj == True:
						note.content = "accepted your invitation to join"
						member_status = 'member'
					else:
						note.content = "requested to join your project"
						note.request = True
						member_status = 'requested'
				elif request.POST.get('withdraw'):
					membership.approved_by_user = False
					note.deleted = True
					member_status = None
				elif request.POST.get('leave'):
					membership.approved_by_user = False
					membership.approved_by_proj = False
					membership.is_staff = False
					note.content = "left your project"
					member_status = None
				elif request.POST.get('quit'):
					membership.is_staff = False
					note.content = "is no longer a staff member of"
					if membership.approved_by_proj and membership.approved_by_user:
						member_status = 'member'
					else:
						member_status = None
				membership.save()
				send_note(note)
		memberships = Membership.objects.filter(project_id=project.id)
		members = memberships.filter(approved_by_user=True).filter(approved_by_proj=True)
		staff = members.filter(is_staff=True)
		participants = members.filter(is_staff=False)
		posts = Post.objects.filter(
				project_id=project.id
			).filter(
				deleted=False
			).order_by(
				'-posted'
			)
		if not basic:
			posts = posts.filter(public=True)
		posts = posts[:7]
		return render(request, 'project.html', {'project': project, 'basic': basic, 
			'member_status': member_status, 'staff': staff, 'participants': participants,
			'posts': posts, 'is_member': is_member(request.user, project)})
	except ObjectDoesNotExist:
		return HttpResponseRedirect("/projects")
コード例 #49
0
ファイル: views.py プロジェクト: adamfeuer/surveytool
def save_memberships_for_projects(user, projects):
   for project in projects:
      membership = Membership(user = user, project = project)
      membership.save()
コード例 #50
0
def updateMembership(_, info, **kwargs):
    updatedMembership = Membership.objects(id=kwargs["id"]).first()
    updatedMembership.update(**kwargs)
    updatedMembership.reload()
    return updatedMembership
コード例 #51
0
def delMembership(_, info, id):
    deletedMembership = Membership.objects(id=id).first()
    deletedMembership.delete()
    return deletedMembership