예제 #1
0
def process_single_event(event_id):
    if not ObjectId.is_valid(event_id):
        return json_abort({
            'message': 'Invalid event id'
        }, 400)
    try:
        with no_auto_dereference(Event):
            event = Event.objects.get({'_id': ObjectId(event_id), 'user': current_identity.id})
        if 'GET' in request.method:
            result = get_event_dict(event)
            return Response(json.dumps(result), mimetype=JSON_MIME)
        elif 'PUT' in request.method:
            data = request.get_json(force=True)
            if isinstance(data, str):
                data = json.loads(data)
            schema = EventSchema(data)
            schema.save(current_identity, event)
            return Response("Success")
        else:
            event.delete()
            return Response("Success")
    except Event.DoesNotExist:
        return json_abort({
            'message': 'User has not such event'
        }, 400)
    except InvalidDataException as ex:
        return json_abort({
            'message': ex.message,
            'fields': ex.fields
        }, 400)
예제 #2
0
    def dispatch_request(self, slug):
        deleted_count = NewsletterSubscription.query.filter_by(
            slug=slug).delete()
        db.session.commit()

        if deleted_count == 0:
            json_abort(
                'Subscription does not exist or has been already deleted', 403)

        return {'message': 'Newsletter subscription deleted'}
예제 #3
0
 def delete(self, id):
     session = Session()
     username = oidc.user_getfield('username')
     grant = session.query(RoleGrant).get(id)
     if not grant:
         json_abort(404)
     if not grant.topic.user == username:
         json_abort(403)
     session.delete(grant)
     session.commit()
     logger.debug(grant)
     return jsonify(grant)
예제 #4
0
    def dispatch_request(self, slug):
        updated_count = NewsletterSubscription.query.filter_by(
            slug=slug).filter(NewsletterSubscription.confirmed != True).update(
                {'confirmed': True})

        db.session.commit()

        if updated_count == 0:
            json_abort(
                'Subscription does not exist or has been already confirmed',
                403)

        return {'message': 'Newsletter subscription confirmed'}
예제 #5
0
 def post(self, topic_id):
     session = Session()
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     if not kargs.get('desc'):
         json_abort(400, "desc missing")
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404)
     now = datetime.datetime.now()
     if topic.start_time <= now:
         json_abort(403, "Voting already started. No changes allowed")
     grant = session.query(RoleGrant).filter(
         RoleGrant.topic_id == topic_id).filter(
             RoleGrant.role.in_(roles)).all()
     logger.debug("{}, {}, {}".format(topic.user, username,
                                      topic.user != username))
     if topic.user != username and 'admin' not in roles and not grant:
         json_abort(403)
     option = TopicOption(**kargs)
     option.topic_id = topic_id
     session.add(option)
     session.commit()
     logger.debug(option.to_dict())
     session = Session()
     if not oidc.is_api_request():
         url = url_for('api_topic', id=topic_id)
         data = {"url": url, "message": "Success. Redirecting to %s" % url}
         return jsonify(data)
     return jsonify(option)
예제 #6
0
def create_task(list_id):
    ''' creates a new task for a list '''

    # 1. Check whether the specified list exists
    if (len([l for l in myLists if l.id == list_id]) < 1):
        json_abort(404, 'List not found')

    # 2. Check whether the required parameters have been sent
    try:
        data = request.get_json()
    except:
        json_abort(400, 'No JSON provided')

    if data == None:
        json_abort(400, 'Invalid Content-Type')

    title = data.get('title', None)
    if title == None:
        json_abort(400, 'Invalid request parameters')

    # 3. calculate the next id
    id = max([int(t.id) for t in myTasks] + [-1]) + 1
    newTask = Task(title, list_id, id=str(id), status=Task.NORMAL)

    # 4. append task to array
    myTasks.append(newTask)

    # 5. return new task
    return jsonify(newTask.__dict__)
예제 #7
0
 def put(self, id):
   session = Session()
   username = oidc.user_getfield('username')
   topic = session.query(Topic).get(id)
   if topic:
     now = datetime.datetime.now()
     if topic.start_time <= now and now <= topic.end_time:
       json_abort(403)
     if topic.user != username:
       json_abort(403)
     kargs = request.get_json(silent=True)
     logger.debug(kargs)
     fields = Topic.get_form_fields()
     for field in fields:
        if kargs.get(field):
           setattr(topic, field, kargs[field])
     now = datetime.datetime.now()
     minimum = datetime.timedelta(minutes=5) 
     if kargs.get('start_time') and (parse(kargs.get('start_time'), yearfirst=True) - now) < minimum:
       json_abort(400, "You can't edit a topic 5 minutes before start.")
     if topic.start_time >= topic.end_time:
       json_abort(400, "End time can not be less than Start time.")
     session.commit()
     if not oidc.is_api_request():
       url = url_for('api_topic', id=int(id))
       data = { "url": url, "message": "Success. Redirecting to %s" % url }
       return jsonify(data) 
   return jsonify(topic)
예제 #8
0
 def put(self, topic_id, id):
     session = Session()
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     if not kargs.get('role'):
         json_abort(400, "role missing")
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404, "Topic doesn't exist")
     now = datetime.datetime.now()
     if topic.start_time <= now:
         json_abort(403, "Voting already started. No changes allowed")
     grant = session.query(RoleGrant).filter(
         RoleGrant.topic_id == topic_id).filter(
             RoleGrant.role.in_(roles)).all()
     if 'admin' not in roles and not grant:
         json_abort(403)
     invite = session.query(Invite).get(id)
     if kargs.get('role'):
         invite.role = kargs.get('role')
     session.add(invite)
     session.commit()
     logger.debug(invite.to_dict())
     session = Session()
     if not oidc.is_api_request():
         url = url_for('api_topic', id=topic_id)
         data = {"url": url, "message": "Success. Redirecting to %s" % url}
         return jsonify(data)
     return jsonify(invite)
def remove_task(list_id, task_id):
    # 1. Check whether the specified list exists
    if (len([l for l in myLists if l.id == list_id]) < 1):
        json_abort(404, 'List not found')

    # 2. Check whether the specified task exists
    tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]
    if (len(tasks) < 1):
        json_abort(404, 'Task not found')

    # 3. finally remove the task
    myTasks.remove(tasks[0])

    return jsonify({'result': True})
예제 #10
0
 def put(self, id):
     session = Session()
     username = oidc.user_getfield('username')
     grant = session.query(RoleGrant).get(id)
     kargs = request.get_json(silent=True)
     if kargs.get('id'):
         topic = session.query(Topic).get(kargs['topic_id'])
         if not topic.user == username:
             json_abort(403)
         grant.topic = topic
     if kargs.get('role'):
         grant.role = kargs.get('role')
     session.commit()
     logger.debug(grant)
     return jsonify(grant)
def delete_task(list_id, task_id):
    # 1. list does not exist
    match = [l for l in myLists if l.id == list_id]
    if len(match) == 0:
        json_abort(404, 'List not found')

    # 2. Check whether the specified task exists
    tasks = [t for t in tasklist if t.list == list_id and t.list == task_id]
    if len(tasks) == 0:
        json_abort(404, 'Task not found')

    # 3. Delete the task
    #tasklist.remove(tasklist[tasks])
    tasklist.remove(tasks[0])

    return jsonify({'result': True})
예제 #12
0
def get_category_by_name(name):
    try:
        category = EventCategory.objects.get({'name': name, 'user': current_identity.id})
        result = CategorySchema().dump(category).data
        return Response(json.dumps(result), mimetype=JSON_MIME)
    except EventCategory.DoesNotExist:
        return json_abort({
            'message': 'User has not category with this name'
        }, 400)
예제 #13
0
 def delete(self, id):
   session = Session()
   roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield('cognito:groups') else []
   topic = session.query(Topic).get(id)
   if topic:
     now = datetime.datetime.now()
     if now > topic.start_time:
       json_abort(403, "Voting started. Can't delete")
     if 'admin' not in roles:
       json_abort(403)
   topic = session.query(Topic).get(id)
   session.delete(topic)
   session.commit()
   logger.debug(topic.to_dict())
   if not oidc.is_api_request():
     url = url_for('api_topic', id=int(id))
     data = { "url": url, "message": "Success. Redirecting to %s" % url }
   return jsonify(topic)
예제 #14
0
def get_sentiment_of_text():
    text = request.args.get('text')
    if not text:
        return json_abort({'message': 'No input parameter text'}, 400)
    tokens = text.split(' ')
    result = []
    for token in tokens:
        if not token.isalpha():
            continue
        result.append({'token': token, 'sentiment': random.random()})
    return jsonify(result)
예제 #15
0
def update_task(list_id, task_id):
    # 1. Check wheter the specidic list exists
    if (len([l for l in myLists if l.id == list_id]) < 1):
        json_abort(404, 'List not found')

    # 2. Check whether the specified task exists
    tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]
    if (len(tasks) < 1):
        json_abort(404, 'Task not found')

    # 3. Check whether the required parameters have been sent
    try:
        data = request.get_json()
    except:
        json_abort(400, 'No JSON provided')

    if data == None:
        json_abort(400, 'Invalid Content-Type')

    title = data.get('title', None)
    if title == None:
        json_abort(400, 'Invalid request parameters')

    # 4. Finally update the task
    myTask = [t for t in myTasks if t.id == task_id and t.list == list_id][0]
    myTask.title = data.get('title', None)
    try:
        myTask.status = data.get('status', None)
    except:
        pass
    try:
        myTask.description = data.get('description', None)
    except:
        pass
    try:
        myTask.due = data.get('description', None)
    except:
        pass
    myTask.revision += 1

    return jsonify(myTask.__dict__)
예제 #16
0
def add_new_category():
    data = request.get_json(force=True)
    if isinstance(data, str):
        data = json.loads(data)
    try:
        category = save_category(data, current_identity)
        return Response(json.dumps({'id': str(category.id)}))
    except InvalidDataException as ex:
        print(ex.message, ex.fields)
        return json_abort({
            'message': ex.message,
            'fields': ex.fields
        }, 400)
예제 #17
0
def add_new_event():
    data = request.get_json(force=True)
    if isinstance(data, str):
        data = json.loads(data)
    schema = EventSchema(data)
    try:
        user = current_identity
        schema.save(user)
    except InvalidDataException as ex:
        return json_abort({
            'message': ex.message,
            'fields': ex.fields
        }, 400)
    return Response("Success")
def createtask(list_id):
    #list does not exist
    match = [l for l in myLists if l.id == list_id]
    if len(match) == 0:
        json_abort(404, 'List not found')

    #title does not exist
    data = request.get_json()
    title = data.get('title')
    if title == None:
        json_abort(400, 'No title')

    #increment task id
    task_id = max([int(i.id) for i in tasklist] + [-1])
    task_id += 1

    #define new task
    newTask = Task(title, list_id, task_id, status=Task.NORMAL)

    #append new task to tasklist
    tasklist.append(newTask)

    return jsonify(newTask.__dict__)
예제 #19
0
def registry():
    data = request.get_json(force=True)
    if isinstance(data, str):
        data = json.loads(data)
    schema = UserSchema(data)
    try:
        user = schema.save()
        jwt = utils.get_jwt()
        access_token = jwt.jwt_encode_callback(user)
        return jwt.auth_response_callback(access_token, user)
    except InvalidDataException as ex:
        return utils.json_abort({
            'message': ex.message,
            'fields': ex.fields
        }, 400)
예제 #20
0
 def post(self):
   session = Session()
   username = oidc.user_getfield('username')
   kargs = request.get_json(silent=True)
   logger.debug(kargs)
   topic = Topic(
     **kargs 
   )
   now = datetime.datetime.now()
   minimum = datetime.timedelta(minutes=5)
   if (parse(topic.start_time, yearfirst=True) - now) < minimum:
     json_abort(400, "You can only create a topic with minimum 5 minute in advance.")
   if topic.start_time >= topic.end_time:
     json_abort(400, "End time can not be less than Start time.")
   topic.user = username
   session.add(topic)
   session.commit()
   logger.debug(topic.to_dict())
   session = Session()
   if not oidc.is_api_request():
     url = url_for('api_topic', id=int(topic.id))
     data = { "url": url, "message": "Success. Redirecting to %s" % url }         
     return jsonify(data) 
   return jsonify(topic)
예제 #21
0
def process_specific_category(category_id):
    if not ObjectId.is_valid(category_id):
        return json_abort({
            'message': 'Invalid category id'
        }, 400)
    user = current_identity
    filter_query = {'_id': ObjectId(category_id)}
    not_found_message = 'No such category'
    if 'GET' not in request.method:
        filter_query.update({
            'user': user.id
        })
        not_found_message = 'This user did not create this category to update/delete'

    try:
        category = EventCategory.objects.get(filter_query)
        if 'GET' in request.method:
            result = CategorySchema().dump(category).data
            return Response(json.dumps(result), mimetype=JSON_MIME)
        elif 'PUT' in request.method:
            data = request.get_json(force=True)
            if isinstance(data, str):
                data = json.loads(data)
            save_category(data, user, category)
        else:
            category.delete()
        return Response("Success")
    except EventCategory.DoesNotExist:
        return json_abort({
            'message': not_found_message
        }, 400)
    except InvalidDataException as ex:
        return json_abort({
            'message': ex.message,
            'fields': ex.fields
        }, 400)
예제 #22
0
    def _get_validated_data(self, data):
        if 'email' not in data:
            json_abort('Field email is missing in your request', 400)

        if not is_email_valid(data['email']):
            json_abort('Provided email has incorrect format', 400)

        if db.session.query(
                NewsletterSubscription.query.filter_by(
                    email=data['email']).exists()).scalar():
            json_abort('Provided email has been already subscribed', 403)

        return data
예제 #23
0
def process_my_info():
    user = current_identity
    if 'GET' in request.method:
        schema = UserOutputSchema()
        result = schema.dump(user).data
        return Response(json.dumps(result), mimetype=JSON_MIME)
    else:
        data = request.get_json(force=True)
        if isinstance(data, str):
            data = json.loads(data)
        schema = UserSchema(data)
        try:
            schema.save(user)
            return Response("Success")
        except InvalidDataException as ex:
            return json_abort({
                'message': ex.message,
                'fields': ex.fields
            }, 400)
예제 #24
0
def login():
    if current_identity:
        return utils.json_abort({'message': 'User has already logged in'}, 400)
    data = request.get_json(force=True)
    if isinstance(data, str):
        data = json.loads(data)
    username = data.get('username', None)
    password = data.get('password', None)

    if not username or not password:
        raise JWTError('Bad Request', 'Invalid credentials')

    identity = authenticate(username, password)

    jwt = utils.get_jwt()
    if identity:
        access_token = jwt.jwt_encode_callback(identity)
        return jwt.auth_response_callback(access_token, identity)
    else:
        raise JWTError('Bad Request', 'Invalid credentials')
예제 #25
0
def update_task(list_id, task_id):
     # 1. Check that list exist
    if (len([l for l in myLists if l.id == list_id]) < 1):
        json_abort(404, 'List not found')

    # 2. Check that task exists
        tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]
    if (len(tasks) < 1):
        json_abort(404, 'Task not found')

     tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]

    #4 Check title is a string
     if (isinstance ( data.get('title')) , str ) !=1
         json_abort(404, 'title is not a string')
예제 #26
0
 def post(self):
     session = Session()
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     logger.debug(kargs)
     if not kargs.get('topic_id'):
         json_abort(400)
     topic = session.query(Topic).get(kargs['topic_id'])
     if not topic:
         json_abort(400)
     if not topic.user == username:
         json_abort(403)
     grant = RoleGrant(**kargs)
     session.add(grant)
     session.commit()
     logger.debug(grant)
     return jsonify(grant)
예제 #27
0
 def delete(self, topic_id, id):
     session = Session()
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     username = oidc.user_getfield('username')
     kargs = request.get_json(silent=True)
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404, "Topic doesn't exist")
     now = datetime.datetime.now()
     if topic.start_time <= now and now <= topic.end_time:
         json_abort(403, "Voting already started. No changes allowed")
     grant = session.query(RoleGrant).filter(
         RoleGrant.topic_id == topic_id).filter(
             RoleGrant.role.in_(roles)).all()
     if 'admin' not in roles and not grant and topic.user != username:
         json_abort(403)
     option = session.query(TopicOption).get(id)
     session.delete(option)
     session.commit()
     logger.debug(option)
     return jsonify(option)
def update_task(list_id, task_id):
    if (len([l for l in myLists if l.id == list_id]) < 1):
        json_abort(404, 'List not found')

    tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]
    if (len(tasks) < 1):
        json_abort(404, 'Task not found')

    try:
        data = request.get_json()
    except:
        json_abort(400, 'No JSON provided')

    if data == None:
        json_abort(400, 'Invalid Content-Type')

    title = data.get('title', None)
    status = data.get('status', None)
    description = data.get('description', None)
    due = data.get('due', None)
    revision = data.get('revision', None)

    if title == None or status == None or description == None or revision == None:
        json_abort(400, 'Invalid request parameters')

    tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]
    if tasks[0].revision > revision:
        json_abort(400, 'No update, oder revision')
    else:
        tasks[0].title = title
        tasks[0].status = status
        tasks[0].description = description
        tasks[0].due = due
        tasks[0].revision = revision

    return jsonify(tasks[0].__dict__)
예제 #29
0
 def post(self):
     session = Session()
     username = oidc.user_getfield('username')
     roles = oidc.user_getfield('cognito:groups') if oidc.user_getfield(
         'cognito:groups') else []
     kargs = request.get_json(silent=True)
     logger.debug(kargs)
     vote_jwt = kargs.get('vote')
     if not vote_jwt:
         json_abort(400, "Vote missing")
     if not oidc.is_api_request():
         json_abort(403)
     secret = oidc.get_access_token().split('.')[-1]
     payload = jwt.decode(vote_jwt, secret, algorithms=['HS256'])
     fields = ['token', 'topic_id', 'option_id']
     for field in fields:
         if not payload.get(field):
             json_abort(400, "%s missing in token" % field)
     topic_id = payload.get('topic_id')
     topic = session.query(Topic).get(topic_id)
     if not topic:
         json_abort(404, description="Topic not found")
     now = datetime.datetime.now()
     if topic.start_time > now and topic.end_time < now:
         json_abort(400, description="Voting not begun yet")
     mapper = session.query(Mapper).filter(
         Mapper.topic_id == topic_id).filter(Mapper.user == username).all()
     if mapper:
         json_abort(409)
     invite = session.query(Invite).filter(
         Invite.topic_id == topic_id).filter(Invite.role.in_(roles)).all()
     if not invite and topic.user != username:
         json_abort(403)
     vote = Vote(topic_id=payload['topic_id'],
                 option_id=payload['option_id'],
                 token=payload['token'])
     mapper = Mapper(user=username, topic_id=topic_id)
     session.add(vote)
     session.add(mapper)
     session.commit()
     logger.debug(vote)
     return jsonify(vote)
예제 #30
0
    # 2. Check that task exists
        tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]
    if (len(tasks) < 1):
        json_abort(404, 'Task not found')

     tasks = [t for t in myTasks if t.id == task_id and t.list == list_id]

    #4 Check title is a string
     if (isinstance ( data.get('title')) , str ) !=1
         json_abort(404, 'title is not a string')
    elif
     tasks[0].title = data.get('title')

    #5 Check status is a string
    if (isinstance(data.get('status'), str)) != 1
        json_abort(404, 'title is not a string')
    elif
        tasks[0].title = data.get('title')
    #6 Check description is a string
    #7 Check due is a string
    #8 Check revision is true
    #9 Update the task



    updateTask = Task(title, list_id, id=str(id), status = Task.NORMAL)
    return jsonify({'result': True})

if __name__ == '__main__':
    app.run(host='localhost', port=20005, debug=True)