Ejemplo n.º 1
0
import hug
import falcon
import hug.development_runner
from middleware.multipart import MultipartMiddleware

api = hug.API(__name__)
api.http.add_middleware(MultipartMiddleware())
route = hug.http(api=api)


@route.post("/upload")
def upload(**kwargs):
    file = kwargs.get("upload_file")
    if file:
        print(file.name)

    return file.name


if __name__ == "__main__":
    hug.development_runner.hug("app2.py", port=9090)
Ejemplo n.º 2
0
import os
import hug
# Settings file

# Path of the project folder
_CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))

# Path of the documents folder
_DOCUMENT_PATH = os.path.join(_CURRENT_PATH, 'documents')

# Credentials
USERNAME = '******'
PASSWORD = '******'

authenticated_area= hug.http(requires=hug.authentication.basic(hug.authentication.verify(USERNAME, PASSWORD)))
Ejemplo n.º 3
0
                request.context['logger'].error(
                    'Potential security concern. Valid key provided but the user was incorrect. User provided was {} when database lists user as {}'
                    .format(apiUser, matchedEntry.name))
                request.context['payload']['errors'].append('Access denied.')
                authenticated = False
        else:
            request.context['logger'].info(
                'User not authenticated: {}'.format(apiUser))
            request.context['payload']['errors'].append('Access denied.')
            authenticated = False

        ## Authenticate user/client key
        if not authenticated:
            raise HTTPUnauthorized('Invalid Authentication',
                                   'Provided security context was invalid')

    except:
        exceptionOnly = traceback.format_exception_only(
            sys.exc_info()[0],
            sys.exc_info()[1])
        request.context['logger'].error(
            'Failure in validSecurityContext: {}'.format(exceptionOnly))
        request.context['payload']['errors'].append(exceptionOnly)
        raise

    return authenticated


## Wrapper context for api functions to use
hugWrapper = hug.http(requires=validSecurityContext)
Ejemplo n.º 4
0
user = redis.from_url(REDIS_URL, db=user_db_id)
pet = redis.from_url(REDIS_URL, db=pet_db_id)

super_secret_key = 'abcd1234'
"""
HELPER FUNCTIONS
"""


def get_uuid():
    return str(uuid.uuid4())


#login authentication
authentication = hug.http(requires=hug.authentication.basic(
    hug.authentication.verify('shelter', '1234')))


@authentication.get('/login')
@authentication.post('/login')
def login(user: hug.directives.user, key=super_secret_key):
    return {
        "message": "Successfully authenticated with user: {0}".format(user),
        "key": key
    }


def cors_support(response, *args, **kwargs):
    response.set_header('Access-Control-Allow-Origin', '*')
    response.set_header('Access-Control-Allow-Method', 'POST, GET, OPTIONS')
    response.set_header('Access-Control-Allow-Headers', 'Content-Type')
Ejemplo n.º 5
0
# -*- coding: utf-8 -*-
from contextlib import contextmanager
from falcon import HTTP_404, HTTP_204

import hug
import psycopg2
import psycopg2.pool

api = hug.http(prefixes='/api')

db = psycopg2.pool.SimpleConnectionPool(1,10,
    dbname='putting-challenge',
    user='******',
    password='******',
    host='localhost',
    port=5432
)

@contextmanager
def get_cursor():
    """A ContextManager for getting a cursor"""
    try:
        conn = db.getconn()
        with conn: # ensure commit or rollback
            with conn.cursor() as cur:
               yield cur
    except:
        raise
    finally:
        db.putconn(conn)
Ejemplo n.º 6
0
import hug
from pony import orm
import json
import falcon

from .models import db, Experiment, Trial, User, State
from . import crypto

basic_auth = hug.http(requires=hug.authentication.basic(crypto.verify_user))
token_auth = hug.http(requires=hug.authentication.token(crypto.verify_token))
admin_auth = hug.http(requires=hug.authentication.token(crypto.verify_admin))


@hug.exception()
def handle_exceptions(exception):
    if isinstance(exception, orm.ObjectNotFound):
        raise falcon.HTTPNotFound()
    elif isinstance(exception, orm.TransactionIntegrityError):
        raise falcon.HTTPConflict()
    elif isinstance(exception, orm.CacheIndexError):
        raise falcon.HTTPConflict()
    elif isinstance(exception, KeyError):
        raise falcon.HTTPBadRequest()
    else:
        raise exception


@hug.response_middleware()
def CORS(request, response, resource):
    response.set_header('Access-Control-Allow-Origin', '*')
    response.set_header('Access-Control-Allow-Methods',
Ejemplo n.º 7
0
#!/usr/local/bin/python3
# coding: utf-8

import hug
import time
import threading
from core.database import database
from core.templates import get_template

user, passwd = open('etc/leakManager.conf').read().split(':')
admin_area = hug.http(requires=hug.authentication.basic(
    hug.authentication.verify(user.strip(), passwd.strip())))


@admin_area.post('/massInsert', output=hug.output_format.html)
def massInsert(body, request, response):
    leaks = str(body['leakmass']).replace("'b", "").split('\\n')
    count = len(leaks)
    db = database()
    thread = threading.Thread(target=db.saveMassLeaks, args=(leaks, ))
    thread.start()
    message = 'You have loaded %d new leaks the process to register will happen in bakground!' % count
    return "<script>alert('%s');document.location = '/'</script>" % message


@admin_area.post('/updatePassword')
def updatePassword(body):
    db = database()
    totalupdates = db.updatePassword(body['password-old'],
                                     body['password-new'])
    message = '%d passwords were updated!' % totalupdates
Ejemplo n.º 8
0
import hug
from hug_explainable import middleware, explain

api = hug.API(__name__)
CODE_URLS = {
    '/hug_explainable/':
    'https://github.com/timothycrosley/hug_explainable/blob/develop/hug_explainable/',
    'examples/':
    'https://github.com/timothycrosley/hug_explainable/blob/develop/examples/'
}
middleware.init(api, code_urls=CODE_URLS)
route = hug.http().suffixes('.explain.json', '.explain.html')


@route.get()
def my_code(explain: explain):
    with explain("Doing maths", 10):
        answer = 10 + 10
    with explain("Doing maths", 10):
        answer = 10 + 10
    with explain("Doing maths", {
            'numbers': [1, 2, 3, 4],
            'booleans': {
                'true': True,
                'false': False
            }
    }):
        answer = 10 + 10
    with explain("Doing maths", 10):
        answer = 10 + 10
        return {'answer': answer, 'explanation': explain}
Ejemplo n.º 9
0
import hug
import jwt

secret_key = 'tacotacotacotac0'


def token_verify(token):
    try:
        return jwt.decode(token, secret_key, algorithms='HS256')
    except jwt.DecodeError:
        return False


auth_hug = hug.http(requires=hug.authentication.token(token_verify))