Example #1
0
def connect_handler(cv, provider):
    """Shared method to handle the connection process

    :param connection_values: A dictionary containing the connection values
    :param provider_id: The provider ID the connection shoudl be made to
    """
    cv.setdefault('user_id', current_user.get_id())
    connection = _datastore.find_connection(**cv)

    if connection is None:
        after_this_request(_commit)
        connection = _datastore.create_connection(**cv)
        msg = ('Connection established to %s' % provider.name, 'success')
        connection_created.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                connection=connection)
    else:
        msg = ('A connection is already established with %s '
               'to your account' % provider.name, 'notice')
        connection_failed.send(current_app._get_current_object(),
                               user=current_user._get_current_object())

    redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'),
                               get_url(config_value('CONNECT_ALLOW_VIEW')))

    do_flash(*msg)
    return redirect(redirect_url)
Example #2
0
def connect_handler(cv, provider):
    """Shared method to handle the connection process

    :param connection_values: A dictionary containing the connection values
    :param provider_id: The provider ID the connection shoudl be made to
    """
    cv.setdefault('user_id', current_user.get_id())
    connection = _datastore.find_connection(**cv)

    if connection is None:
        after_this_request(_commit)
        connection = _datastore.create_connection(**cv)
        msg = ('Connection established to %s' % provider.name, 'success')
        connection_created.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                connection=connection)
    else:
        msg = ('A connection is already established with %s '
               'to your account' % provider.name, 'notice')
        connection_failed.send(current_app._get_current_object(),
                               user=current_user._get_current_object())

    redirect_url = session.pop(config_value('POST_OAUTH_CONNECT_SESSION_KEY'),
                               get_url(config_value('CONNECT_ALLOW_VIEW')))

    do_flash(*msg)
    return redirect(redirect_url)
Example #3
0
def write_activity_on_follow(follow, **kwargs):
    if current_user.is_authenticated:
        if isinstance(follow.following, Dataset):
            write_activity.delay(UserFollowedDataset, current_user._get_current_object(), follow.following)
        elif isinstance(follow.following, Reuse):
            write_activity.delay(UserFollowedReuse, current_user._get_current_object(), follow.following)
        elif isinstance(follow.following, Organization):
            write_activity.delay(UserFollowedOrganization, current_user._get_current_object(), follow.following)
        elif isinstance(follow.following, User):
            write_activity.delay(UserFollowedUser, current_user._get_current_object(), follow.following)
Example #4
0
def write_activity_on_discuss(discussion, **kwargs):
    if current_user.is_authenticated:
        if isinstance(discussion.subject, Dataset):
            write_activity.delay(UserDiscussedDataset,
                                 current_user._get_current_object(),
                                 discussion.subject)
        elif isinstance(discussion.subject, Reuse):
            write_activity.delay(UserDiscussedReuse,
                                 current_user._get_current_object(),
                                 discussion.subject)
Example #5
0
def write_activity_on_discuss(discussion, **kwargs):
    if current_user.is_authenticated():
        if isinstance(discussion.subject, Dataset):
            write_activity.delay(
                UserDiscussedDataset, current_user._get_current_object(),
                discussion.subject)
        elif isinstance(discussion.subject, Reuse):
            write_activity.delay(
                UserDiscussedReuse, current_user._get_current_object(),
                discussion.subject)
Example #6
0
 def post(self, dataset):
     '''Upload a new community resource'''
     args = upload_parser.parse_args()
     infos = self.extract_infos_from_args(args, dataset)
     infos['owner'] = current_user._get_current_object()
     community_resource = CommunityResource.objects.create(**infos)
     return community_resource, 201
Example #7
0
    def make_submission_version_update_handler(cls, channel):
        identity = None
        if channel == 'SMS':
            identity = g.get('phone', '')
        elif channel == 'WEB':
            user = current_user._get_current_object()
            identity = user.email if not user.is_anonymous() else 'unknown'

        def update_submission_version(sender, document, **kwargs):
            if sender != Submission:
                return

            data_fields = document.form.tags
            if document.form.form_type == 'INCIDENT':
                data_fields.extend(['status'])
            version_data = {
                k: document[k]
                for k in data_fields if k in document
            }

            cls().create(submission=document,
                         data=json.dumps(version_data),
                         timestamp=datetime.utcnow(),
                         channel=channel,
                         identity=identity)

        return update_submission_version
Example #8
0
def update_submission_version(sender, document, **kwargs):
    if sender != services.submissions.__model__:
        return

    # save actual version data
    data_fields = document.form.tags
    if document.form.form_type == 'INCIDENT':
        data_fields.extend(['status'])
    version_data = {k: document[k] for k in data_fields if k in document}

    # get previous version
    previous = services.submission_versions.find(
        submission=document).order_by('-timestamp').first()

    if previous:
        prev_data = json.loads(previous.data)
        diff = DictDiffer(version_data, prev_data)

        # don't do anything if the data wasn't changed
        if not diff.added() and not diff.removed() and not diff.changed():
            return

    # save user email as identity
    channel = 'WEB'
    user = current_user._get_current_object()
    identity = user.email if not user.is_anonymous() else 'unknown'

    services.submission_versions.create(
        submission=document,
        data=json.dumps(version_data),
        timestamp=datetime.utcnow(),
        channel=channel,
        identity=identity
    )
Example #9
0
    def make_submission_version_update_handler(cls, channel):
        identity = None
        if channel == 'SMS':
            identity = g.get('phone', '')
        elif channel == 'WEB':
            user = current_user._get_current_object()
            identity = user.email if not user.is_anonymous() else 'unknown'

        def update_submission_version(sender, document, **kwargs):
            if sender != Submission:
                return

            data_fields = document.form.tags
            if document.form.form_type == 'INCIDENT':
                data_fields.extend(['status'])
            version_data = {
                k: document[k] for k in data_fields if k in document
            }

            cls().create(
                submission=document,
                data=json.dumps(version_data),
                timestamp=datetime.utcnow(),
                channel=channel,
                identity=identity
            )

        return update_submission_version
Example #10
0
def get_game_sessions():
    sessions = []
    user_id = current_user._get_current_object().id
    q = GameSession.query.outerjoin(GameSessionPlayers).filter(or_(GameSessionPlayers.user_id == user_id,GameSession.host_id == user_id)).order_by(GameSession.created).all()
    for session in q:
        sessions.append(session.as_dict())
    return api_package(data=sessions)
Example #11
0
def location_headers(pk):
    user = current_user._get_current_object()

    # disallow processing other users' files
    upload = services.user_uploads.get_or_404(pk=pk, user=user)
    try:
        dataframe = load_source_file(upload.data)
    except Exception:
        # delete loaded file
        upload.data.delete()
        upload.delete()
        return abort(400)

    deployment = g.deployment
    headers = dataframe.columns
    template_name = 'frontend/location_headers.html'

    if request.method == 'GET':
        form = generate_location_update_mapping_form(deployment, headers)
        return render_template(template_name, form=form)
    else:
        form = generate_location_update_mapping_form(deployment, headers,
                                                     request.form)

        if not form.validate():
            return render_template(template_name, form=form)
        else:
            # get header mappings
            data = form.data.copy()

            # invoke task asynchronously
            kwargs = {'upload_id': unicode(upload.id), 'mappings': data}
            import_locations.apply_async(kwargs=kwargs)

            return redirect(url_for('locations.locations_list'))
Example #12
0
def on_user_updated_organization(organization):
    if current_user and current_user.is_authenticated:
        user = current_user._get_current_object()
        write_activity.delay(UserUpdatedOrganization,
                             user,
                             organization,
                             organization=organization)
Example #13
0
def friends():
    args = request.args
    user = current_user._get_current_object()
    if 'NoGroup' in args:
        #Lets get friends that are NOT in groups only        
        q = Friends.query.filter(and_(Friends.user_id == user.id,Friends.group_id == None)).all()  
    else:        
        #otherwise lets get ALL friends regardless if they are in a group or not
        q = Friends.query.filter(Friends.user_id == user.id).all()    
    friends = []
    for f in q:
        friends.append({'type':'friend','friend':f.as_dict()})

    if 'FriendRequests' in args:
        print "Get requests"
        q = FriendRequests.query.filter(FriendRequests.user_id == user.id).all()

        print q, user.id
        for fr in q:
            friends.append({
                'type':'friend_request',
                'friend_request':{
                    'id':fr.id,
                    'username':fr.friend.username
                    }
                })

    return api_package(data=friends)
Example #14
0
def confirm_friend():
    user = current_user._get_current_object()
    form = request.get_json()
    schema = {
        'id':{'type':'integer','empty':False}
    }
    v = Validator(schema)
    if v.validate(form) is False:
        return api_validation_error(v.errors)

    friend_request = FriendRequests.query.filter(FriendRequests.id == form['id']).first()
    if friend_request:

        #we are confirming this, so create friendships that last both ways.
        my_friend = Friends(user_id = user.id,friend_id = friend_request.friend_id)
        their_friend = Friends(user_id = friend_request.friend_id,friend_id = user.id)

        meeple.db.session.add(my_friend)
        meeple.db.session.add(their_friend)
        meeple.db.session.delete(friend_request) #remove this friend request
        meeple.db.session.commit()

        #now return who this friend is back to them.
        return api_package(data=my_friend.as_dict())
    else:
        return api_error("This request does not exist")
Example #15
0
def add_friend_to_group(id):
    user = current_user._get_current_object()  
    form = request.get_json()
    schema = {
                'id':{'type':'integer','empty':False},
            } 
    v = Validator(schema)   
    if v.validate(form) is False:
        return api_validation_error(v.errors)  
    #first see if this is a valid group
    group = FriendsGroup.query.filter(and_(FriendsGroup.user_id == user.id,FriendsGroup.id == id)).first()

    if group:
        #lets see if this is a confirmed friend of yours
        friend = Friends.query.filter(and_(Friends.user_id == user.id,Friends.friend_id == form['id'])).first()

        if friend:
            #lets see if this friend is not in this group
            if friend.group_id == group.id:
                return api_error("This friend is already in this group")
            else:
                friend.group_id = group.id
                meeple.db.session.commit()
                return api_package()
        else:
            return api_error("Friend does not exist")
    else:
        return api_error("This group does not exist.")
Example #16
0
def remove_connection(provider_id, provider_user_id):
    """Remove a specific connection for the authenticated user to the
    specified provider
    """
    provider = get_provider_or_404(provider_id)

    ctx = dict(provider=provider.name,
               user=current_user,
               provider_user_id=provider_user_id)

    deleted = _datastore.delete_connection(user_id=current_user.get_id(),
                                           provider_id=provider_id,
                                           provider_user_id=provider_user_id)

    if deleted:
        after_this_request(_commit)
        msg = ('Connection to %(provider)s removed' % ctx, 'info')
        connection_removed.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                provider_id=provider_id)
    else:
        msg = ('Unabled to remove connection to %(provider)s' % ctx, 'error')

    do_flash(*msg)
    return redirect(request.referrer or get_post_login_redirect())
Example #17
0
 def get(self):
     '''List all discussions related to my organizations.'''
     q = filter_parser.parse_args().get('q')
     discussions = discussions_for(current_user._get_current_object())
     discussions = discussions.order_by('-created')
     if q:
         discussions = discussions.filter(title__icontains=q.decode('utf-8'))
     return list(discussions)
Example #18
0
 def get(self):
     '''List all issues related to my organizations.'''
     q = filter_parser.parse_args().get('q')
     issues = issues_for(current_user._get_current_object())
     issues = issues.order_by('-created')
     if q:
         issues = issues.filter(title__icontains=q.decode('utf-8'))
     return list(issues)
Example #19
0
 def put(self, community):
     '''Update a given community resource'''
     form = api.validate(CommunityResourceForm, community)
     form.populate_obj(community)
     if not community.organization:
         community.owner = current_user._get_current_object()
     community.modified = datetime.now()
     community.save()
     return community
Example #20
0
 def get(self):
     '''List all discussions related to my organizations.'''
     q = filter_parser.parse_args().get('q')
     discussions = discussions_for(current_user._get_current_object())
     discussions = discussions.order_by('-created')
     if q:
         decoded = q.decode('utf-8')
         discussions = discussions.filter(title__icontains=decoded)
     return list(discussions)
Example #21
0
 def get(self):
     """List all discussions related to my organizations."""
     q = filter_parser.parse_args().get("q")
     discussions = Discussion.objects.from_organizations(
         current_user._get_current_object(), *current_user.organizations
     ).order_by("-created")
     if q:
         discussions = discussions.filter(title__icontains=q.decode("utf-8"))
     return list(discussions)
Example #22
0
def write_activity_on_follow(follow, **kwargs):
    if current_user.is_authenticated:
        if isinstance(follow.following, Dataset):
            write_activity.delay(UserFollowedDataset,
                                 current_user._get_current_object(),
                                 follow.following)
        elif isinstance(follow.following, Reuse):
            write_activity.delay(UserFollowedReuse,
                                 current_user._get_current_object(),
                                 follow.following)
        elif isinstance(follow.following, Organization):
            write_activity.delay(UserFollowedOrganization,
                                 current_user._get_current_object(),
                                 follow.following)
        elif isinstance(follow.following, User):
            write_activity.delay(UserFollowedUser,
                                 current_user._get_current_object(),
                                 follow.following)
Example #23
0
File: api.py Project: vinyll/udata
 def put(self, community):
     '''Update a given community resource'''
     form = api.validate(CommunityResourceForm, community)
     form.populate_obj(community)
     if not community.organization:
         community.owner = current_user._get_current_object()
     community.modified = datetime.now()
     community.save()
     return community
Example #24
0
def friend_groups():
    user = current_user._get_current_object()    
    
    q = FriendsGroup.query.filter(FriendsGroup.user_id == user.id).all()    
    groups = []
    for g in q:
        groups.append(g.as_dict())
    non_grouped = []

    return api_package(data=groups)
Example #25
0
def user_context_processor():
    if current_user.is_authenticated():
        user = current_user._get_current_object()
    else:
        user = None
    return {
        'user': user,
        'login_user_form': LoginForm(),
        'register_form': RegisterForm(),
    }
Example #26
0
    def get(self):
        '''List all current user pending notifications'''

        user = current_user._get_current_object()
        notifications = []

        orgs = [o for o in user.organizations if o.is_admin(user)]

        # Fetch user open issues
        datasets = Dataset.objects.owned_by(user, *orgs)
        reuses = Reuse.objects.owned_by(user, *orgs)
        for issue in Issue.objects(subject__in=list(datasets) + list(reuses)):
            notifications.append({
                'type': 'issue',
                'created_on': issue.created,
                'details': {
                    'subject': {
                        'type': issue.subject.__class__.__name__.lower(),
                        'id': str(issue.subject.id)
                    }
                }
            })

        # Fetch pending membership requests
        for org in orgs:
            for request in org.pending_requests:
                notifications.append({
                    'type': 'membership_request',
                    'created_on': request.created,
                    'details': {
                        'organization': org.id,
                        'user': {
                            'id': str(request.user.id),
                            'fullname': request.user.fullname,
                            'avatar': str(request.user.avatar)
                        }
                    }
                })

        # Fetch pending transfer requests
        for transfer in Transfer.objects(recipient__in=[user] + orgs,
                                         status='pending'):
            notifications.append({
                'type': 'transfer_request',
                'created_on': transfer.created,
                'details': {
                    'id': str(transfer.id),
                    'subject': {
                        'class': transfer.subject.__class__.__name__.lower(),
                        'id': str(transfer.subject.id)
                    }
                }
            })

        return notifications
Example #27
0
    def get(self):
        '''List all current user pending notifications'''

        user = current_user._get_current_object()
        notifications = []

        orgs = [o for o in user.organizations if o.is_admin(user)]

        # Fetch user open issues
        datasets = Dataset.objects.owned_by(user, *orgs)
        reuses = Reuse.objects.owned_by(user, *orgs)
        for issue in Issue.objects(subject__in=list(datasets)+list(reuses)):
            notifications.append({
                'type': 'issue',
                'created_on': issue.created,
                'details': {
                    'subject': {
                        'type': issue.subject.__class__.__name__.lower(),
                        'id': str(issue.subject.id)
                    }
                }
            })

        # Fetch pending membership requests
        for org in orgs:
            for request in org.pending_requests:
                notifications.append({
                    'type': 'membership_request',
                    'created_on': request.created,
                    'details': {
                        'organization': org.id,
                        'user': {
                            'id': str(request.user.id),
                            'fullname': request.user.fullname,
                            'avatar': str(request.user.avatar)
                        }
                    }
                })

        # Fetch pending transfer requests
        for transfer in Transfer.objects(recipient__in=[user]+orgs, status='pending'):
            notifications.append({
                'type': 'transfer_request',
                'created_on': transfer.created,
                'details': {
                    'id': str(transfer.id),
                    'subject': {
                        'class': transfer.subject.__class__.__name__.lower(),
                        'id': str(transfer.subject.id)
                    }
                }
            })

        return notifications
Example #28
0
def comment_create_view():
    submission = services.submissions.get_or_404(
        pk=request.form.get('submission'))
    comment = request.form.get('comment')
    saved_comment = services.submission_comments.create(
        submission=submission,
        user=current_user._get_current_object(),
        comment=comment,
        submit_date=datetime.utcnow())

    return jsonify(comment=saved_comment.comment,
                   date=mkunixtimestamp(saved_comment.submit_date),
                   user=saved_comment.user.email)
Example #29
0
 def post(self):
     '''Create a new community resource'''
     form = api.validate(CommunityResourceForm)
     resource = CommunityResource()
     form.populate_obj(resource)
     if not resource.dataset:
         api.abort(400,
                   errors={'dataset': 'A dataset identifier is required'})
     if not resource.organization:
         resource.owner = current_user._get_current_object()
     resource.modified = datetime.now()
     resource.save()
     return resource, 201
Example #30
0
def participant_list_import():
    form = file_upload_form(request.form)

    if not form.validate():
        return abort(400)
    else:
        # get the actual object from the proxy
        user = current_user._get_current_object()
        event = services.events.get_or_404(pk=form.event.data)
        upload = stash_file(request.files['spreadsheet'], user, event)
        upload.save()

        return redirect(
            url_for('participants.participant_headers', pk=unicode(upload.id)))
Example #31
0
 def post(self, id):
     '''Add comment and optionnaly close an issue given its ID'''
     issue = Issue.objects.get_or_404(id=id)
     form = api.validate(IssueCommentForm)
     issue.discussion.append(Message(
         content=form.comment.data,
         posted_by=current_user.id
     ))
     close = form.close.data
     if close:
         issue.closed_by = current_user._get_current_object()
         issue.closed = datetime.now()
     issue.save()
     if close:
         on_issue_closed.send(issue)
     return marshal(issue, issue_fields), 200
Example #32
0
def participant_list_import():
    form = file_upload_form(request.form)

    if not form.validate():
        return abort(400)
    else:
        # get the actual object from the proxy
        user = current_user._get_current_object()
        event = services.events.get_or_404(pk=form.event.data)
        upload = stash_file(request.files['spreadsheet'], user, event)
        upload.save()

        return redirect(url_for(
            'participants.participant_headers',
            pk=unicode(upload.id)
        ))
Example #33
0
def comment_create_view():
    submission = services.submissions.get_or_404(
        pk=request.form.get('submission'))
    comment = request.form.get('comment')
    saved_comment = services.submission_comments.create(
        submission=submission,
        user=current_user._get_current_object(),
        comment=comment,
        submit_date=datetime.utcnow()
    )

    return jsonify(
        comment=saved_comment.comment,
        date=mkunixtimestamp(saved_comment.submit_date),
        user=saved_comment.user.email
    )
Example #34
0
 def post(self, id):
     '''Add comment and optionnaly close an issue given its ID'''
     issue = Issue.objects.get_or_404(id=id)
     form = api.validate(IssueCommentForm)
     message = Message(content=form.comment.data, posted_by=current_user.id)
     issue.discussion.append(message)
     close = form.close.data
     if close:
         issue.closed_by = current_user._get_current_object()
         issue.closed = datetime.now()
     issue.save()
     if close:
         on_issue_closed.send(issue, message=message)
     else:
         on_new_issue_comment.send(issue, message=message)
     return marshal(issue, issue_fields), 200
Example #35
0
def participant_headers(pk):
    user = current_user._get_current_object()

    # disallow processing other users' files
    upload = services.user_uploads.get_or_404(pk=pk, user=user)
    try:
        dataframe = load_source_file(upload.data)
    except Exception:
        # delete loaded file
        upload.data.delete()
        upload.delete()
        return abort(400)

    deployment = g.deployment
    headers = dataframe.columns
    template_name = 'frontend/participant_headers.html'

    if request.method == 'GET':
        form = generate_participant_import_mapping_form(deployment, headers)
        return render_template(template_name, form=form)
    else:
        form = generate_participant_import_mapping_form(
            deployment, headers, request.form)

        if not form.validate():
            return render_template(
                template_name,
                form=form
            )
        else:
            # get header mappings
            data = form.data.copy()

            # phone_header = data.pop('phone')
            # group_header = data.pop('group')
            # mappings = {v: k for k, v in data.iteritems() if v}
            # mappings.update(phone=phone_header)
            # mappings.update(group=group_header)

            # invoke task asynchronously
            kwargs = {
                'upload_id': unicode(upload.id),
                'mappings': data
            }
            import_participants.apply_async(kwargs=kwargs)

            return redirect(url_for('participants.participant_list'))
Example #36
0
def participant_headers(pk):
    user = current_user._get_current_object()

    # disallow processing other users' files
    upload = services.user_uploads.get_or_404(pk=pk, user=user)
    try:
        dataframe = load_source_file(upload.data)
    except Exception:
        # delete loaded file
        upload.data.delete()
        upload.delete()
        return abort(400)

    deployment = g.deployment
    headers = dataframe.columns
    template_name = 'frontend/participant_headers.html'

    if request.method == 'GET':
        form = generate_participant_import_mapping_form(deployment, headers)
        return render_template(template_name, form=form)
    else:
        form = generate_participant_import_mapping_form(
            deployment, headers, request.form)

        if not form.validate():
            return render_template(
                template_name,
                form=form
            )
        else:
            # get header mappings
            data = form.data.copy()

            # phone_header = data.pop('phone')
            # group_header = data.pop('group')
            # mappings = {v: k for k, v in data.iteritems() if v}
            # mappings.update(phone=phone_header)
            # mappings.update(group=group_header)

            # invoke task asynchronously
            kwargs = {
                'upload_id': unicode(upload.id),
                'mappings': data
            }
            import_participants.apply_async(kwargs=kwargs)

            return redirect(url_for('participants.participant_list'))
Example #37
0
 def post(self, id):
     '''Add comment and optionnaly close a discussion given its ID'''
     discussion = Discussion.objects.get_or_404(id=id)
     form = api.validate(DiscussionCommentForm)
     message = Message(content=form.comment.data, posted_by=current_user.id)
     discussion.discussion.append(message)
     close = form.close.data
     if close:
         CloseDiscussionPermission(discussion).test()
         discussion.closed_by = current_user._get_current_object()
         discussion.closed = datetime.now()
     discussion.save()
     if close:
         on_discussion_closed.send(discussion, message=message)
     else:
         on_new_discussion_comment.send(discussion, message=message)
     return discussion
Example #38
0
def create_game_sessions():

    form = request.get_json()
    print form
    if form is None:
        return api_error("Invalid Request")

    schema = {
                'name':{'type':'string','empty':False},
                'game_id':{'type':'integer','required':True},
                'start_date':{'type':'string','empty':False},
                'host_is_playing':{'type':'boolean','required':True}
            }
    v = Validator(schema)
    if v.validate(form) is False:
        return api_validation_error(v.errors)    

    game = Game().query.filter_by(game_id=form['game_id']).first()
    if game is None:
        return api_error("There was an issue adding the game to this session.") #this probably shouldnt happen but, we should check anyways

    newgamesession = GameSession()
    user = current_user._get_current_object()

    if form['host_is_playing'] is True:
        newgamesession.players.append(user) #the user/host is also a player.
        addplayer_helper(newgamesession,user)

    newgamesession.host = user #attach this session to the user creating it, as they are the host.

    newgamesession.game = game #relate this gamesession to this board game

    #name is optional. If left empty, the board games name will be used instead.
    if 'name' in form:
        newgamesession.name = form['name']
    else:
        newgamesession.name = game.name

    #user can specify a future start date, otherwise utcnow() is used as default value in table.
    if 'start_date' in form:
        newgamesession.start_date = date_parse(form['start_date'])

    meeple.db.session.add(newgamesession)
    meeple.db.session.commit()
    return api_package(data=newgamesession.as_dict())
Example #39
0
def update_submission_version(sender, document, **kwargs):
    if sender != services.submissions.__model__:
        return

    # save actual version data
    data_fields = document.form.tags
    if document.form.form_type == 'INCIDENT':
        data_fields.extend(['status', 'witness'])
    version_data = {k: document[k] for k in data_fields if k in document}

    # save user email as identity
    channel = 'WEB'
    user = current_user._get_current_object()
    identity = user.email if not user.is_anonymous() else 'unknown'

    services.submission_versions.create(submission=document,
                                        data=json.dumps(version_data),
                                        timestamp=datetime.utcnow(),
                                        channel=channel,
                                        identity=identity)
Example #40
0
File: api.py Project: grouan/udata
 def post(self, id):
     '''Add comment and optionnaly close a discussion given its ID'''
     discussion = Discussion.objects.get_or_404(id=id)
     form = api.validate(DiscussionCommentForm)
     message = Message(
         content=form.comment.data,
         posted_by=current_user.id
     )
     discussion.discussion.append(message)
     close = form.close.data
     if close:
         CloseDiscussionPermission(discussion).test()
         discussion.closed_by = current_user._get_current_object()
         discussion.closed = datetime.now()
     discussion.save()
     if close:
         on_discussion_closed.send(discussion, message=message)
     else:
         on_new_discussion_comment.send(discussion, message=message)
     return discussion
Example #41
0
 def post(self, id):
     '''Add comment and optionnaly close an issue given its ID'''
     issue = Issue.objects.get_or_404(id=id)
     form = api.validate(IssueCommentForm)
     message = Message(
         content=form.comment.data,
         posted_by=current_user.id
     )
     issue.discussion.append(message)
     close = form.close.data
     if close:
         CloseIssuePermission(issue).test()
         issue.closed_by = current_user._get_current_object()
         issue.closed = datetime.now()
     issue.save()
     if close:
         on_issue_closed.send(issue, message=message)
     else:
         on_new_issue_comment.send(issue, message=message)
     return issue
Example #42
0
def location_headers(pk):
    user = current_user._get_current_object()

    # disallow processing other users' files
    upload = services.user_uploads.get_or_404(pk=pk, user=user)
    try:
        dataframe = load_source_file(upload.data)
    except Exception:
        # delete loaded file
        upload.data.delete()
        upload.delete()
        return abort(400)

    deployment = g.deployment
    headers = dataframe.columns
    template_name = 'frontend/location_headers.html'

    if request.method == 'GET':
        form = generate_location_update_mapping_form(deployment, headers)
        return render_template(template_name, form=form)
    else:
        form = generate_location_update_mapping_form(
            deployment, headers, request.form)

        if not form.validate():
            return render_template(
                template_name,
                form=form
            )
        else:
            # get header mappings
            data = form.data.copy()

            # invoke task asynchronously
            kwargs = {
                'upload_id': unicode(upload.id),
                'mappings': data
            }
            import_locations.apply_async(kwargs=kwargs)

            return redirect(url_for('locations.locations_list'))
Example #43
0
def remove_all_connections(provider_id):
    """Remove all connections for the authenticated user to the
    specified provider
    """
    provider = get_provider_or_404(provider_id)

    ctx = dict(provider=provider.name, user=current_user)

    deleted = _datastore.delete_connections(user_id=current_user.get_id(),
                                            provider_id=provider_id)
    if deleted:
        after_this_request(_commit)
        msg = ('All connections to %s removed' % provider.name, 'info')
        connection_removed.send(current_app._get_current_object(),
                                user=current_user._get_current_object(),
                                provider_id=provider_id)
    else:
        msg = ('Unable to remove connection to %(provider)s' % ctx, 'error')

    do_flash(*msg)
    return redirect(request.referrer)
Example #44
0
def create_friends_group():

    user = current_user._get_current_object()
    form = request.get_json()      
    schema = {
                'name':{'type':'string','empty':False},
            }
    v = Validator(schema)   
    if v.validate(form) is False:
        return api_validation_error(v.errors)  

    #first see if this name exists
    group = FriendsGroup.query.filter(and_(FriendsGroup.user_id == user.id,FriendsGroup.name == form['name'])).first()

    if group:
        return api_error("This group name already exists")

    group = FriendsGroup(user_id=user.id,name=form['name'])
    meeple.db.session.add(group)
    meeple.db.session.commit()

    return api_package(data=group.as_dict())
Example #45
0
def update_submission_version(sender, document, **kwargs):
    if sender != services.submissions.__model__:
        return

    # save actual version data
    data_fields = document.form.tags
    if document.form.form_type == 'INCIDENT':
        data_fields.extend(['status', 'witness'])
    version_data = {k: document[k] for k in data_fields if k in document}

    # save user email as identity
    channel = 'WEB'
    user = current_user._get_current_object()
    identity = user.email if not user.is_anonymous() else 'unknown'

    services.submission_versions.create(
        submission=document,
        data=json.dumps(version_data),
        timestamp=datetime.utcnow(),
        channel=channel,
        identity=identity
    )
Example #46
0
def add_player_to_session(id):    

    form = request.get_json()
    user = current_user._get_current_object()
    if form is None:
        return api_error("Invalid Request")
    try:
        id = int(id)
    except ValueError as e:
        return api_error("id values must be integers only.")

    schema = {
                'user_id':{'type':'integer','required':True}
            }
    v = Validator(schema)
    if v.validate(form) is False:
        return api_validation_error(v.errors)  

    gs = GameSession.query.filter_by(id=id).first()

    if gs is None:
        return api_error("Unable to find a game session by that id")

    new_player = Friends.query.filter(and_(Friends.user_id == user.id,Friends.friend_id == form['user_id'])).first()

    if new_player is None:
        return api_error("Unable to find player to add to this game session")  

    #check if this player is already in
    if new_player.friend in gs.players:
        return api_error("This player is already in this game session")

    gs.players.append(new_player.friend)

    player_props = addplayer_helper(gs,new_player.friend)
    meeple.db.session.commit()
    return api_package(data=player_props)    
Example #47
0
def request_friend():
    user = current_user._get_current_object()
    form = request.get_json()
    schema = {
        'username':{'type':'string','empty':False}
    }
    v = Validator(schema)
    if v.validate(form) is False:
        return api_validation_error(v.errors)
        #first check, is this you? You idiot...
    if user.username == form['username']:
        return api_error("You cannot friend yourself")

    friend = User.query.filter(User.username == form['username']).first()
    if friend:

        #second check, is he already your friend?
        am_i_friend = Friends.query.filter(and_(Friends.user_id == user.id,Friends.friend_id == friend.id)).first()
        if am_i_friend:
            return api_error("You are already friends")

        #is this already requested?
        ar = FriendRequests.query.filter(and_(FriendRequests.user_id == friend.id,FriendRequests.friend_id == user.id)).first()
        if ar:
            return api_package()

        #this is the inverse as to who this is for
        new_request = FriendRequests(user_id=friend.id,friend_id=user.id)
        """
            TODO insert notification event here as well. Notifcation table
            to show/email that so and so is requesting friendship
        """
        meeple.db.session.add(new_request)
        meeple.db.session.commit()
        return api_package()
    else:
        return api_error("User not found")
Example #48
0
 def get_or_404(self, **kwargs):
     if not current_user.is_authenticated():
         api.abort(404)
     return current_user._get_current_object()
Example #49
0
 def get(self):
     '''Fetch the current user (me) metrics'''
     return current_user._get_current_object()
Example #50
0
 def put(self, **kwargs):
     '''Update my profile'''
     user = current_user._get_current_object()
     form = api.validate(UserProfileForm, user)
     return form.save()
Example #51
0
 def get_query(self):
     '''Returns the queryset of the objects to list.'''
     user = current_user._get_current_object()
     return models.Event.objects(deployment=user.deployment)
Example #52
0
 def get_query(self):
     user = current_user._get_current_object()
     return models.User.objects(deployment=user.deployment)
Example #53
0
File: api.py Project: grouan/udata
 def put(self, **kwargs):
     '''Update my profile'''
     user = current_user._get_current_object()
     form = api.validate(UserProfileForm, user)
     return form.save()
Example #54
0
File: api.py Project: grouan/udata
 def get(self):
     '''Fetch the current user (me) identity'''
     return current_user._get_current_object()
Example #55
0
 def get_query(self):
     user = current_user._get_current_object()
     return models.Deployment.objects(pk=user.deployment.pk)
Example #56
0
def on_user_deleted_reuse(reuse):
    if not reuse.private and current_user and current_user.is_authenticated():
        user = current_user._get_current_object()
        organization = reuse.organization
        write_activity.delay(UserDeletedReuse, user, reuse, organization)