Esempio n. 1
0
def debug_login():
    action = flask.request.args.get('action', None)

    if action == 'make':
        email = flask.request.args.get('email', '')
        try:
            user = models.User.objects(email=email).get()
        except:
            helpers.api_error(code=404, message='Invalid email')
        t = models.Ticket(user=user)
        t.save()
        dialog = open('./dialogs/utility-auth.txt', 'r').read()
        print(dialog.format(colorama, user, t))
        return helpers.api_success()

    elif action == 'confirm':
        token = flask.request.args.get('token', None)
        ticket = models.Ticket.objects(id=token).get()
        user = ticket.user
        flask_login.login_user(user, fresh=True)
        return helpers.api_success()

    elif action == 'release':
        flask_login.logout_user()
        return helpers.api_success()

    else:
        helpers.api_error(code=400, message='Invalid utility-auth action')
Esempio n. 2
0
def user_login():
    """Log a user in and return their information"""
    uname = flask.request.args['username'].lower()
    passw = flask.request.args['password']

    # Try and find the user
    user = None
    try:
        user = models.Provider.objects(username=uname).get()
    except DoesNotExist:
        return helpers.api_error(
            code=401,
            data='username',
            message='Username does not exist'
        )

    # Check the password
    if user.password != passw:
        return helpers.api_error(
            code=401,
            data='password',
            message='Password is incorrect'
        )

    # Log them in!
    flask_login.login_user(user)
    return helpers.api_success(data=user)
Esempio n. 3
0
def api_document_put(document_name, document_id):
    '''Make changes to an existing document and save it to the database'''
    user = helpers.user_required(1)
    model = models.model_get(document_name)

    # get the dictionary of arguments
    args = flask.request.get_json()

    # get the document
    document = None
    try:
        document = model.objects.get(id=document_id)
    except mongoengine.errors.ValidationError:
        return helpers.api_error(message='No document found', code=404)

    # iterate through the args and screen them
    if args:
        for arg_name in args:
            print('PROCESSING ARG_NAME', arg_name)
            print('VALUE', args[arg_name])

    # update the document and return a success
    document.update(**args)
    document.reload()
    if document._after_put(user):
        document.save()
    return helpers.api_success(message='Document updated.')
Esempio n. 4
0
def api_document_post(document_name):
    '''Create a new document and insert it into the database'''
    user = helpers.user_required(1)
    model = models.model_get(document_name)

    # get the dictionary of arguments
    args = flask.request.get_json()

    # filter out fields based on access level
    try:
        for field_name in model._blacklist_postput[user.access]:
            args.pop(field_name, None)
    except IndexError:
        pass

    # some types need extra processing (e.g., datetime fields)
    model_fields = model._fields
    for arg_name in args:
        value = args[arg_name]
        if isinstance(model_fields.get(arg_name, None), mongoengine.fields.DateTimeField):
            args[arg_name] = dateutil.parser.parse(value)

    # put together the new document
    new = model(**args)

    # some models need special handling, so make sure to call the 'after' func
    new._after_post(user)

    # now save it and return it
    new.save()
    return helpers.api_success(data=new)
Esempio n. 5
0
def api_image_upload():
    # Require a user be logged in
    user = helpers.user_required()

    # Get the uploaded file from flask
    upload_file = flask.request.files['file']

    # Determine the new S3 filename
    upload_id = uuid.uuid4().hex

    s3_path_full = upload_id + '.jpg'
    s3_path_thumb = upload_id + '_thumb.jpg'

    # Process the image into full and thumbnail variants
    image_full, image_thumb = image.process_image(upload_file)

    # Write both to buffer and upload them to S3
    buffer_full = io.BytesIO()
    image_full.save(buffer_full, format='JPEG')
    s3_connection.upload(s3_path_full, buffer_full, 'clarityapp')

    buffer_thumb = io.BytesIO()
    image_thumb.save(buffer_thumb, format='JPEG')
    s3_connection.upload(s3_path_thumb, buffer_thumb, 'clarityapp')

    # return the final wallpaper document
    return helpers.api_success(data=upload_id)
Esempio n. 6
0
def api_document_delete(document_name, document_id):
    """Delete an existing document from the database"""
    user = helpers.user_required(1)
    model = models.model_get(document_name)

    # get the document
    document = None
    try:
        document = model.objects.get(id=document_id)
    except mongoengine.errors.ValidationError:
        return helpers.api_error(message='No document found', code=404)

    # delete it!
    document.delete()
    return helpers.api_success(message='Document deleted.')
Esempio n. 7
0
def user_get():
    """Return the currently logged in user's information (or not)."""
    return helpers.api_success(data=helpers.user_required())
Esempio n. 8
0
def api_document_get_by_id(document_name, document_id):
    """Get one specific document instance from an ID"""
    user = helpers.user_get()
    model = models.model_get(document_name)
    return helpers.api_success(data=model.objects.get(id=document_id))
Esempio n. 9
0
def api_document_get(document_name):
    '''Query the database'''
    user = helpers.user_get()
    model = models.model_get(document_name)

    # filter the args
    args_listable = ['__order', '__field']
    args_query = {}
    args_other = {}
    args = flask.request.args
    for arg_name in args:
        if arg_name.startswith('__'):
            if arg_name in args_listable:
                args_other[arg_name] = args.getlist(arg_name)
            else:
                args_other[arg_name] = args[arg_name]
        else:
            args_query[arg_name] = args[arg_name]

    # convert booleans
    model_fields = model._fields
    for arg_name in args_query:
        value = args_query[arg_name]
        if isinstance(model_fields.get(arg_name, None), mongoengine.fields.BooleanField):
            if value == 'true':
                args_query[arg_name] = True
            elif value == 'false':
                args_query[arg_name] = False
            else:
                raise ValueError('you dun fuked up')
            # args_query[arg_name] = True if value == 'true' else False

    # get the ball rolling, so to speak
    query = model.objects(**args_query)

    # We have to establish the access level of the user
    access_level = None

    # Check for anonymity, because anons won't have access fields
    if user.is_anonymous:
        access_level = 0
    else:
        access_level = user.access

    # Exclude the blacklisted fields
    for field_name in model._blacklist_get.get(access_level, []):
        query = query.exclude(field_name)

    # sort the query if applicable
    if '__order' in args_other:
        query = query.order_by(*args_other['__order'])

    # limit the results
    offset = int(args_other.get('__offset', 0))
    if offset:
        query = query.skip(offset)
    length = int(args_other.get('__length', 32))
    query = query.limit(length)

    # perform a text search if necessary
    if '__search' in args_other:
        query = query.search_text(args_other['__search'])

    # filter out unwanted fields
    if '__field' in args_other:
        query = query.scalar(*args_other['__field'])

    # return the results
    # return helpers.api_success(list(query))
    return helpers.api_success(data={
        'list': list(query),
        'count': query.count()
    })
Esempio n. 10
0
def user_logout():
    """Log a user out. That's it."""
    helpers.user_required()
    flask_login.logout_user()
    return helpers.api_success()