示例#1
0
def get_logger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.handlers = []
    logger.propagate = False
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    if console_logger['enabled']:
        s_handler = logging.StreamHandler()
        s_handler.setLevel(console_logger['level'])
        s_handler.setFormatter(formatter)
        logger.addHandler(s_handler)
    if file_logger['enabled']:
        f_handler = logging.FileHandler(file_logger['file_name'])
        f_handler.setLevel(file_logger['level'])
        f_handler.setFormatter(formatter)
        logger.addHandler(f_handler)
    if loggly_logger['enabled']:
        from loggly.handlers import HTTPSHandler
        l_handler = HTTPSHandler('https://logs-01.loggly.com/inputs/%s/tag/python' %
                                 loggly_logger['api_key'])
        l_handler.setLevel(loggly_logger['level'])
        l_formatter = logging.Formatter('{"loggerName":"%(name)s", "asciTime":"%(asctime)s", "fileName":"%(filename)s",'
                                        ' "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s",'
                                        ' "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d",'
                                        ' "levelName":"%(levelname)s", "message":"%(message)s"}')
        l_handler.setFormatter(l_formatter)
        logger.addHandler(l_handler)
    return logger
示例#2
0
    def __init__(self, logger, config):
        logger.setLevel(config['LOG_LEVEL'])
        formatter = jsonlogger.JsonFormatter(
            '%(asctime)s %(levelname)s %(module)s %(message)s',
            static_fields={'Environment': config['ENV']})

        if config['LOGGLY_TOKEN'] is not None:

            handler = HTTPSHandler(
                f'https://logs-01.loggly.com/inputs/{config["LOGGLY_TOKEN"]}/tag/todo-app'
            )
            handler.setFormatter(formatter)
            logger.addHandler(handler)
            getLogger('werkzeug').addHandler(
                HTTPSHandler(
                    f'https://logs-01.loggly.com/inputs/{config["LOGGLY_TOKEN"]}/tag/todoapp-requests'
                ))
        self._logger = logger
示例#3
0
def get_logger(name):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.handlers = []
    logger.propagate = False
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    if console_logger['enabled']:
        s_handler = logging.StreamHandler()
        s_handler.setLevel(console_logger['level'])
        s_handler.setFormatter(formatter)
        logger.addHandler(s_handler)
    if file_logger['enabled']:
        f_handler = logging.FileHandler(file_logger['file_name'])
        f_handler.setLevel(file_logger['level'])
        f_handler.setFormatter(formatter)
        logger.addHandler(f_handler)
    if loggly_logger['enabled']:
        from loggly.handlers import HTTPSHandler
        l_handler = HTTPSHandler(
            'https://logs-01.loggly.com/inputs/%s/tag/python' %
            loggly_logger['api_key'])
        l_handler.setLevel(loggly_logger['level'])
        l_formatter = logging.Formatter(
            '{"loggerName":"%(name)s", "asciTime":"%(asctime)s", "fileName":"%(filename)s",'
            ' "logRecordCreationTime":"%(created)f", "functionName":"%(funcName)s",'
            ' "levelNo":"%(levelno)s", "lineNo":"%(lineno)d", "time":"%(msecs)d",'
            ' "levelName":"%(levelname)s", "message":"%(message)s"}')
        l_handler.setFormatter(l_formatter)
        logger.addHandler(l_handler)
    return logger
示例#4
0
def create_app():
    # Defining logger
    logger = logging.getLogger(__name__)
    logger.warning('Hello, World!')
    logging.basicConfig(level=os.getenv('LOG_LEVEL', 'INFO'))
    # Launch app
    app = Flask(__name__)
    app.config.from_object(Config())

    # Loggly
    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app')
        handler.setFormatter(
            jsonlogger.JsonFormatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
        )
        app.logger.addHandler(handler)
        getLogger('werkzeug').addHandler(HTTPSHandler(f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todoapp-requests'))
        
    # Connect to mongo
    si.connect_mongo()

    # All the routes and setup code etc
    # Index
    @app.route('/')
    @reader_required
    def index():
        items = si.get_items()
        item_view_model = ViewModel(items)
        return render_template('index.html', view_model = item_view_model)

    # Add item 
    @app.route('/create_item', methods = ['POST'])
    @writer_required
    def create_item():
        title = request.form ['title']
        si.add_item(title)
        return redirect(url_for('index'))

    # Update item status
    @app.route('/item_status', methods = ['GET','POST'])
    @writer_required
    def item_status():
        item_title = request.form ['item_title']
        item_status = request.form ['item_status']
        item = si.get_item(item_title)
        if item != None:
            si.save_item(item,item_status)
        return redirect(url_for('index'))

    # Delete item
    @app.route('/del_item', methods = ['GET','POST'])
    @writer_required
    def del_item():
        del_title = request.form['del_title']
        delete_item(del_title)
        logger.info("Item deleted: %s", del_title)
        return redirect(url_for('index'))
    
    # Route for logout
    @app.route('/logout')
    @login_required
    def logout():
        logger.info("User logged out. User id: %s", current_user.id)
        logout_user()
        return redirect(url_for('index'))

    ### OAuth ###
    # Obtain GitHub OAuth Secrets:
    client_id = os.getenv('CLIENT_ID')
    client_secret = os.getenv('CLIENT_SECRET')

    # Initialize login_manager class
    login_manager = flask_login.LoginManager()

    # Create client
    client = WebApplicationClient(client_id)

    @login_manager.unauthorized_handler
    def unauthenticated():
        # Add logic to redirect to the Github OAuth flow when unauthenticated
        # Request identity
        # Redirect to site
        # Return -> redirect to github
        redirecturl = client.prepare_request_uri("https://github.com/login/oauth/authorize")
        return redirect(redirecturl)

    @login_manager.user_loader
    def load_user(user_id):
        return User(user_id)

    @app.route('/login', methods = ['GET'])
    def login():
        code = request.args.get('code')
        token_url, headers, body = client.prepare_token_request('https://github.com/login/oauth/access_token', code = code )
        headers['Accept']= 'application/json'
        response = requests.post(token_url, headers = headers, data = body, auth = (client_id,client_secret))
        response = response.json()
        access_token = response['access_token']
        usr_url = 'https://api.github.com/user'
        headers = {'Authorization': 'token ' + access_token}
        usr_response = requests.get(usr_url, headers = headers )
        usr_response = usr_response.json()
        user = User(usr_response['id'])
        login_user(user)
        logger.info("User logged in: %s", usr_response['id'])
        return redirect(url_for('index'))

    login_manager.init_app(app)

    ### MAIN ###
    if __name__ == '__main__':
        app.run()

    return app
示例#5
0
def create_app(database_name="Main"):
    app = Flask(__name__)
    app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")
    app.config["USER_UNAUTHORIZED_ENDPOINT"] = "/index"
    app.logger.setLevel(os.environ.get("LOG_LEVEL", default="INFO"))

    if os.environ.get('LOGGLY_TOKEN'):
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{os.environ.get("LOGGLY_TOKEN")}/tag/todo-app'
        )
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    mongo_database = MongoWrapper(os.environ.get('MONGO_URL'), database_name)
    login_manager = LoginManager()
    github_authenticator = GithubAuthentication()

    def roles_required(role_name):
        def wrapper(view_function):
            @wraps(view_function
                   )  # Tells debuggers that is is a function wrapper
            def decorator(*args, **kwargs):
                if not flask_login.current_user.check_role(role_name):
                    app.logger.warning(
                        "User attempted to access page without required permission"
                    )
                    # Redirect to unauthenticated page
                    return redirect(url_for('index'))
                return view_function(*args, **kwargs)

            return decorator

        return wrapper

    @login_manager.unauthorized_handler
    def unauthenticated():
        app.logger.info("Authenticating with github")
        authentication_url = github_authenticator.get_github_auth_url()
        return redirect(authentication_url)

    @login_manager.user_loader
    def load_user(user_id):
        if github_authenticator.authentication():
            return User(user_id)
        return None

    login_manager.init_app(app)

    @app.route('/', methods=['POST'])
    @login_required
    @roles_required(Roles.WRITER)
    def add_title():
        app.logger.info("Attempting to add new item with title %s",
                        request.form.get('title'))
        result = mongo_database.add_item(request.form.get('title'))
        app.logger.info("Inserted item with title: %s and id: %s",
                        request.form.get('title'), result.inserted_id)
        return redirect(url_for('index'))

    @app.route('/')
    @login_required
    def index():

        items = mongo_database.get_items()
        item_view_model = ViewModel(items)
        role_id = flask_login.current_user.role.value
        return render_template('index.html',
                               view_model=item_view_model,
                               role_id=role_id)

    @app.route('/complete_items/<id>')
    @login_required
    @roles_required(Roles.WRITER)
    def complete_items(id):
        app.logger.info("Completing item with id: %s", id)
        mongo_database.complete_item(id)
        return redirect(url_for('index'))

    @app.route('/move_todo/<id>')
    @login_required
    @roles_required(Roles.WRITER)
    def set_doing(id):
        app.logger.info("Move item to doing with id: %s", id)
        mongo_database.set_doing(id)
        return redirect(url_for('index'))

    @app.route('/undo_complete/<id>')
    @login_required
    @roles_required(Roles.WRITER)
    def undo_complete(id):
        app.logger.info("Undo completing item with id: %s", id)
        mongo_database.set_todo(id)
        return redirect(url_for('index'))

    @app.route('/create_board/<name>')
    @login_required
    @roles_required(Roles.WRITER)
    def create_board(name):
        mongo_database.create_board(name)
        return redirect(url_for('index'))

    @app.route('/login/callback', methods=["GET"])
    def github_authentication():
        user = github_authenticator.post_github_identity(request)
        flask_login.login_user(user)
        return redirect(url_for('index'))

    return app
示例#6
0
    converter = time.gmtime


class ContextFilter(logging.Filter):
    hostname = socket.gethostname()

    def filter(self, record):
        record.hostname = ContextFilter.hostname
        record.request_id = uuid.uuid1()


token = 'f2766e74-5933-4654-b141-86b737c1b389'
url = 'https://logs-01.loggly.com/inputs/' + token + '/tag/python'
print(url)

handler = HTTPSHandler(url)

log_format = ('{ "loggerName":"%(name)s", "asciTime":"%(asctime)s", '
              '"fileName":"%(filename)s", '
              '"logRecordCreationTime":"%(created)f", '
              '"functionName":"%(funcName)s", "levelNo":"%(levelno)s", '
              '"lineNo":"%(lineno)d", "time":"%(msecs)d", '
              '"levelName":"%(levelname)s", "message":"%(message)s"}, '
              '"hostname:"%(hostname)s, "requestId":"%(request_id)s')

# formatter = jsonlogger.JsonFormatter(log_format)
formatter = UTCFormatter(log_format)

handler.setFormatter(formatter)

# logger = logging.getLogger('myLogger')
示例#7
0
 def handler(cls, log_level):
     integration = Configuration.integration('loggly', required=True)
     token = integration['token']
     url = integration['url'] % dict(token=token)
     from loggly.handlers import HTTPSHandler
     return HTTPSHandler(url)
示例#8
0
def create_app():
    app = Flask(__name__)
    CLIENT_ID = os.environ.get("GITHUB_CLIENT_ID", None)
    CLIENT_SECRET = os.environ.get("GITHUB_CLIENT_SECRET", None)
    SECRET_KEY = os.environ.get("SECRET_KEY", None)
    WRITER_ROLE = os.environ.get("ROLEWRITER_USER", None)
    redirect_uri = os.environ.get("GITHUB_REDIRECT_URI", None)
    app.secret_key = SECRET_KEY
    logger = app.logger
    logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))

    if os.environ.get("LOGGLY_TOKEN", "") != "":
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{os.environ.get("LOGGLY_TOKEN")}/tag/todo-app'
        )
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)
    client = WebApplicationClient(CLIENT_ID)
    login_manager = LoginManager()
    login_manager.init_app(app)
    logger.debug("Created Application")

    @login_manager.unauthorized_handler
    def unauthenticated():
        identity_url = client.prepare_request_uri(
            'https://github.com/login/oauth/authorize', redirect_uri)
        app.logger.debug("Github authentication")
        return redirect(identity_url)

    @app.route("/login/callback")
    def callback():
        try:
            app.logger.debug("Github callback start")
            code = request.args.get("code")
            token_url, headers, body = client.prepare_token_request(
                "https://github.com/login/oauth/access_token",
                authorization_response=request.url,
                redirect_url=request.base_url,
                code=code,
            )
            token_response = requests.post(
                token_url,
                headers=headers,
                data=body,
                auth=(CLIENT_ID, CLIENT_SECRET),
            )

            # Parse the tokens!
            params = client.parse_request_body_response(token_response.text)
            uri, headers, body = client.add_token(
                "https://api.github.com/user")

            userinfo_response = requests.get(uri, headers=headers, data=body)
            app.logger.debug("Github callback succeess")

            users_name = userinfo_response.json()["login"]
            users_id = userinfo_response.json()["id"]
            email = userinfo_response.json()["email"]
            user = User(users_id, users_name, email, ROLES['reader'])
            appsession['users_id'] = users_id
            appsession['users_name'] = users_name
            appsession['email'] = email
            if users_name == WRITER_ROLE:
                user.access = ROLES['writer']
            else:
                user.access = ROLES['reader']
            app.logger.info("Logged in user %s", users_name)
            app.logger.info("Logged in user email %s", email)
            app.logger.info("Logged in user role %s", user.access)
            appsession['roles'] = user.access
            login_user(user)
            return redirect(url_for('index'))
        except Exception as e:
            app.logger.error(str(e))
            return "Could not authenticate user."

    @login_manager.user_loader
    def load_user(user_id):
        app.logger.debug("Creating user object")
        m_user_id = appsession.get('users_id')
        m_users_name = appsession.get('users_name')
        m_users_roles = appsession.get('roles')
        m_email = appsession.get('email')
        user = User(m_user_id, m_users_name, m_email, m_users_roles)
        return user

    @app.route('/')
    @login_required
    @requires_roles('reader', 'writer')
    def index():
        app.logger.debug("Index start")
        items = session.Boards().get_items()
        item_view_model = session.ViewModel(items)

        if app.config.get("LOGIN_DISABLED", False):
            mcurrent_user = ''
            misWriter = True  #for E2E testing
        else:
            mcurrent_user = current_user.username
            misWriter = (appsession.get('roles') == ROLES['writer'])
        app.logger.info("Is Writer %s", misWriter)
        app.logger.debug("Index end")
        return render_template('index.html',
                               view_model=item_view_model,
                               isWriter=misWriter,
                               currentuser=mcurrent_user)

    @app.route('/', methods=['POST'])
    @login_required
    @requires_roles('writer')
    def add_item():
        title = request.form.get('title')
        app.logger.info("Add Item %s", title)
        if title != '':
            session.Boards().add_item(title)
            app.logger.info("Item Successfully Added by %s", current_user.id)
        return redirect('/')

    @app.route('/<id>')
    @login_required
    @requires_roles('writer')
    def complete_item(id):
        if (id != "favicon.ico"):
            app.logger.info("Complete Item %s", id)
            todo_class = session.Boards()
            item = todo_class.get_item(id)
            item['status'] = "Completed"
            todo_class.save_item(item)
            app.logger.info("Item %s successfully Completed", id)
        return redirect('/')

    @app.route('/todo/<id>')
    @login_required
    @requires_roles('writer')
    def uncomplete_item(id):
        if (id != "favicon.ico"):
            app.logger.info("UnComplete Item %s", id)
            todo_class = session.Boards()
            item = todo_class.get_item(id)
            item['status'] = "Not Started"
            todo_class.save_item(item)
            app.logger.info("Item %s Set to unomplete.", id)
        return redirect('/')

    @app.route('/doing/<id>')
    @login_required
    @requires_roles('writer')
    def start_item(id):
        if (id != "favicon.ico"):
            app.logger.info("Start Item %s", id)
            todo_class = session.Boards()
            item = todo_class.get_item(id)
            item['status'] = "Doing"
            todo_class.save_item(item)
            app.logger.info("Item %s successfully Started.", id)
        return redirect('/')

    @app.route('/remove/<id>')
    @login_required
    @requires_roles('writer')
    def delete_item(id):
        app.logger.info("Remove Item %s", id)
        todo_class = session.Boards()
        todo_class.remove_item(id)
        app.logger.info("Item %s successfully Removed.", id)
        return redirect('/')

    return app
示例#9
0
def create_app():

    app = Flask(__name__)
    app.secret_key = os.getenv('APP_SECRET')
    app.config['LOG_LEVEL'] = os.getenv('LOG_LEVEL')
    app.config['LOGGLY_TOKEN'] = os.getenv('LOGGLY_TOKEN')
    login_manager.init_app(app)
    app.logger.setLevel(app.config['LOG_LEVEL'])

    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app'
        )
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    @app.route('/')
    @login_required
    def index():

        items = get_todo_cards()

        item_view_model = ViewModel(items)

        todays_date = datetime.datetime.strftime(datetime.date.today(),
                                                 '%d/%m/%Y')

        if request.values.get('sort') == '1':
            items.sort(key=lambda x: x.due_date, reverse=True)
        else:
            items.sort(key=lambda x: x.due_date)

        if 'LOGIN_DISABLED' not in app.config:
            if current_user.role == 'writer':
                return render_template('index.html',
                                       view_model=item_view_model,
                                       todays_date=todays_date)
            else:
                return render_template('index_ro.html',
                                       view_model=item_view_model,
                                       todays_date=todays_date)
        else:
            return render_template('index.html',
                                   view_model=item_view_model,
                                   todays_date=todays_date)

    @app.route('/new_item', methods=['POST'])
    @login_required
    def new_item():
        if 'LOGIN_DISABLED' in app.config or current_user.role == 'writer':
            new_item_title = request.form.get('new_item_title')
            trello_default_list = 'todo'
            if request.form.get('new_item_due'):
                due_date = datetime.datetime.strptime(
                    request.form.get('new_item_due'), '%Y-%m-%d')
            else:
                due_date = datetime.datetime.today() + datetime.timedelta(30)

            description = request.form.get('new_item_desc')

            new_card = ToDoCard(0, new_item_title,
                                trello_default_list, due_date, description,
                                datetime.datetime.today())
            create_todo_card(new_card)
            if 'LOGIN_DISABLED' not in app.config:
                app.logger.info(f"New card created by {current_user.id}")
            else:
                app.logger.info(f"New card created by TestUser")
        return redirect(request.headers.get('Referer'))

    @app.route('/toggle_status', methods=['POST'])
    @login_required
    def toggle_status():
        if 'LOGIN_DISABLED' in app.config or current_user.role == 'writer':
            card_id = request.form.get('toggle_item_id')
            new_list_id = request.form.get('new_list_id')

            move_todo_card(card_id, new_list_id)
            if 'LOGIN_DISABLED' not in app.config:
                app.logger.info(
                    F"Card modified by {current_user.id}, Card ID: {card_id}, New List ID: {new_list_id}"
                )
            else:
                app.logger.info(
                    F"Card modified by TestUser, Card ID: {card_id}, New List ID: {new_list_id}"
                )

        return redirect(request.headers.get('Referer'))

    @app.route('/login')
    def login():
        github_code = request.args.get('code')
        client = WebApplicationClient(os.environ.get('AUTH_CLIENTID'))
        token = client.prepare_token_request(os.environ.get('AUTH_TOKEN_URL'),
                                             code=github_code)
        access = requests.post(token[0],
                               headers=token[1],
                               data=token[2],
                               auth=(os.environ.get('AUTH_CLIENTID'),
                                     os.environ.get('AUTH_SECRET')))
        client.parse_request_body_response(access.text)
        github_user_request_param = client.add_token(
            os.environ.get('AUTH_API_URL'))
        user_id = requests.get(
            github_user_request_param[0],
            headers=github_user_request_param[1]).json()['login']
        print(user_id)

        login_user(User(user_id))
        app.logger.info(f"User {current_user.id} logged in")

        return redirect('/')

    if __name__ == '__main__':
        app.run()

    return app
示例#10
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('flask_config.Config')
    item_store = MongoWrapper(os.environ['DEFAULT_DATABASE'])

    login_manager = LoginManager()
    client_id = os.environ['CLIENT_ID']
    client_secret = os.environ['CLIENT_SECRET']
    authorization_url = 'https://github.com/login/oauth/authorize'
    access_token_url = 'https://github.com/login/oauth/access_token'
    oauth_client = WebApplicationClient(client_id)
    login_manager.init_app(app)

    app.logger.setLevel(os.environ.get('LOG_LEVEL', 'DEBUG'))

    loggly_token = os.environ.get('LOGGLY_TOKEN')

    if loggly_token:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{loggly_token}/tag/todo-app')
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    @login_manager.unauthorized_handler
    def unauthenticated():
        return redirect(oauth_client.prepare_request_uri(authorization_url))

    @login_manager.user_loader
    def load_user(user_id):
        if oauth_client.access_token is None:
            return None
        user = User(user_id)
        login_user(user)
        return user

    @app.route('/login/callback')
    def login():
        response = requests.post(
            oauth_client.prepare_request_uri(access_token_url,
                                             client_secret=client_secret,
                                             code=request.args.get('code')))
        oauth_client.parse_request_body_response(response.text)
        parsed_uri = oauth_client.add_token('https://api.github.com/user')
        user = requests.get(parsed_uri[0], headers=parsed_uri[1]).json()
        load_user(user['id'])
        return redirect('/')

    @app.route('/')
    @login_required
    def index():
        show_completed = request.args.get('show_completed') == 'True'
        items = item_store.get_items()
        view_model = IndexViewModel(items, show_completed,
                                    current_user.is_writer())
        return render_template('index.html', view_model=view_model)

    @app.route('/AddItem')
    @login_required
    @writer_only
    def add_item_page():
        return render_template('addItem.html')

    @app.route('/AddItem/Save', methods=['POST'])
    @login_required
    @writer_only
    def add_item_save():
        title = request.form.get('title')
        if not title:
            return redirect('/AddItem')
        description = request.form.get('description')
        due_date = request.form.get('due_date')
        item_store.create_new_item(title, description, due_date)
        app.logger.info('Queue created with title: %s', title)
        return redirect('/')

    @app.route('/StartItem', methods=['POST'])
    @login_required
    @writer_only
    def start_item():
        item_id = request.form.get('id')
        if not item_id:
            return redirect('/')
        item_store.move_item_to_doing(item_id)
        app.logger.info('Queue started with id: %s', item_id)
        return redirect('/')

    @app.route('/CompleteItem', methods=['POST'])
    @login_required
    @writer_only
    def complete_item():
        item_id = request.form.get('id')
        if not item_id:
            return redirect('/')
        item_store.move_item_to_done(item_id)
        app.logger.info('Queue completed with id: %s', item_id)
        return redirect('/')

    @app.route('/RemoveItem', methods=['POST'])
    @login_required
    @writer_only
    def remove_item():
        item_id = request.form.get('id')
        if not item_id:
            return redirect('/')
        item_store.archive_item(item_id)
        app.logger.info('Queue archived with id: %s', item_id)
        return redirect('/')

    @app.route('/ShowCompleted', methods=['POST'])
    @login_required
    def show_all_done_items():
        show_completed = request.form.get('show_completed') == 'False'
        return redirect('/?show_completed=' + str(show_completed))

    if __name__ == '__main__':
        app.run()

    return app
示例#11
0
def create_mongo_app(mongo_api):
    app = Flask(__name__)
    if loggly_token != "" and loggly_token != None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{loggly_token}/tag/todo-app')
        handler.setFormatter(
            Formatter(
                "[%(asctime)s].%(msecs)03d %(levelname)s in %(module)s: %(message)s"
            ))
        app.logger.addHandler(handler)

    if log_level == "" or log_level is None:
        app.logger.setLevel("ERROR")
    else:
        app.logger.setLevel(log_level)

    @app.route('/', methods=['GET'])
    @login_required
    def indexGet():
        current_user_role = check_user()
        item_view_model = ViewModel(mongo_api.load_todo_items(),
                                    current_user_role)
        return render_template('index.html', view_model=item_view_model)

    @app.route('/', methods=['POST'])
    @login_required
    def indexPost():
        current_user_role = check_user()
        if current_user_role == 'writer':
            item = request.form['item']
            post_id = mongo_api.add_todo_item(
                Item(status="Todo",
                     title=item,
                     last_modified=datetime.datetime.now().isoformat())
            ).inserted_id
            try:
                app.logger.info("user [%s] added post %s",
                                current_user.user_id, post_id)
            except:
                app.logger.info("anon user added post %s", post_id)
            return redirect(url_for('indexGet'))
        else:
            app.logger.warn("non-writer user [%s] trying to add a post",
                            current_user.user_id)
            return abort(403)

    @app.route('/complete_item', methods=['POST'])
    @login_required
    def indexPut():
        current_user_role = check_user()
        if current_user_role == 'writer':
            cardId = request.form['cardId']
            target_status = request.form['target']
            mongo_api.update_todo_item(cardId, target_status)
            app.logger.info("writer user [%s] updated post %s",
                            current_user.user_id, cardId)
            return redirect(url_for('indexGet'))
        else:
            app.logger.warn("non-writer user [%s] trying to update a post",
                            current_user.user_id)
            return abort(403)

    @app.route('/login/callback', methods=['GET'])
    def loginCallbackPost():
        token_response = r.post('https://github.com/login/oauth/access_token',
                                data={
                                    'client_id': oauth_client_id,
                                    'client_secret': oauth_client_secret,
                                    'code': request.args.get('code')
                                },
                                headers={'Accept': 'application/json'})

        oauth_client.parse_request_body_response(token_response.text)

        user_response = r.get(
            'https://api.github.com/user',
            headers={
                'Accept': 'application/json',
                'Authorization':
                f"token {token_response.json()['access_token']}"
            })

        login_user(User(user_response.json()['login']))

        return redirect(url_for('indexGet'))

    @app.route('/logout')
    def logout():
        logout_user()
        app.logger.info("user [%s] logging out", current_user.user_id)
        return redirect(url_for('indexGet'))

    @login_manager.unauthorized_handler
    def unauthenticated():
        if (current_app.config.get('LOGIN_DISABLED')
                or os.getenv("LOGIN_DISABLED") != ""):
            app.logger.info("login feature disabled")
            login_user(User('waormd'))
            return redirect(url_for('indexGet'))
        else:
            app.logger.info("login feature enabled")
            uri = oauth_client.prepare_request_uri(
                'https://github.com/login/oauth/authorize')
            return redirect(uri)

    @login_manager.user_loader
    def load_user(user_id):
        return User(user_id)

    def check_user():
        if (current_app.config.get('LOGIN_DISABLED')
                or current_user.user_id == 'waormd'):
            return 'writer'
        else:
            return 'reader'

    return app
示例#12
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config())
    app.config['LOGIN_DISABLED'] = os.environ.get('LOAD_DISABLED', 'False').lower() in ['true', '1']
    app.config['LOG_LEVEL'] = os.environ.get('LOG_LEVEL')
    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.config['LOGGLY_TOKEN'] = os.environ.get('LOGGLY_TOKEN')
    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app')
        handler.setFormatter(Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)
    login_manager.login_manager.init_app(app)

    @app.route('/', methods=['Get'])
    @login_required
    def index():
        items = mongo.fetch_all_items()
        items.sort(key=lambda k: k.status, reverse=True)
        item_view_model = view_model.ViewModel(items)
        if current_user.is_active == True:
            if current_user.role == 'writer':
                return render_template('index_writer.html', view_model=item_view_model)
            elif current_user.role == 'reader':
                return render_template('index_reader.html', view_model=item_view_model)
            else:
                return render_template('index_writer.html', view_model=item_view_model)
        else:
            return render_template('index_writer.html', view_model=item_view_model)
        

    @app.route('/add', methods=['Post'])
    @login_required
    def add_todo():
        if current_user.is_active == True:
            if current_user.role == 'writer' or current_user.role == 'admin':
                mongo.create_new_item(request.form.get('title'))
                app.logger.info("User %s added Todo item '%s'", current_user.name, request.form.get('title'))
                return redirect('/')
            else :
                flash('You do not have access. Please contact an admin')
                app.logger.info("User %s attempted to add Todo item, incorrect permissions", current_user.name)
                return redirect('/')
        else:
            mongo.create_new_item(request.form.get('title'))
            return redirect('/')

    @app.route('/doing_item/<todo_id>', methods=['Post'])
    @login_required
    def update_status_doing(todo_id):
        mongo.update_item_doing(todo_id)
        if current_user.is_active:
            app.logger.info("User %s set Todo item Id '%s' to 'Doing'", current_user.name, todo_id)
        return redirect('/')

    @app.route('/done_item/<todo_id>', methods=['Post'])
    @login_required
    def update_status_done(todo_id):
        mongo.update_item_done(todo_id)
        if current_user.is_active:
            app.logger.info("User %s set Todo item Id '%s' to 'Done'", current_user.name, todo_id)
        return redirect('/')

    @app.route('/delete/<todo_id>', methods=['Post'])
    @login_required
    def remove_item(todo_id):
        mongo.delete_item(todo_id)
        if current_user.is_active:
            app.logger.info("User %s deleted Todo item Id '%s'", current_user.name, todo_id)
        return redirect('/')

    @app.route('/login/callback')
    def login_callback():
        callback_code = request.args.get("code")
        github_client =  WebApplicationClient(os.environ.get('clientId'))
        github_token = github_client.prepare_token_request("https://github.com/login/oauth/access_token", code=callback_code) 
        github_access = requests.post(github_token[0], headers=github_token[1], data=github_token[2], auth=(os.environ.get('clientId'), os.environ.get('client_secret')))
        github_json = github_client.parse_request_body_response(github_access.text)
        github_user_request_param = github_client.add_token("https://api.github.com/user")
        github_user = requests.get(github_user_request_param[0], headers=github_user_request_param[1]).json()

        login_user(User(github_user))

        mongo.add_user_mongo(current_user)
        app.logger.info("User '%s' logged in successfully", current_user.name)

        return redirect('/') 

    @app.route('/users', methods=['Get'])
    @login_required
    def users():
        if current_user.role == 'admin':
            users = mongo.fetch_all_users()
            return render_template('index_users.html', users=users)
        else:
            flash('You do not have access. Please contact an admin')
            app.logger.info("User %s attempted to view Users page, incorrect permissions", current_user.name)
            return redirect('/')

    @app.route('/users/make_admin/<userid>', methods=['Post'])
    @login_required
    def make_admin(userid):
        mongo.make_admin(userid)
        app.logger.info("User %s changed permission level of User Id '%s' to Admin", current_user.name, userid)
        return  redirect('/users')

    @app.route('/users/make_reader/<userid>', methods=['Post'])
    @login_required
    def make_reader(userid):
        mongo.make_reader(userid)
        app.logger.info("User %s changed permission level of User Id '%s' to Reader", current_user.name, userid)
        return  redirect('/users')


    if __name__ == '__main__':
        app.run()  
    
    return app 
示例#13
0
def create_app():
    app = Flask(__name__)
    item_view_model = None
    app.logger.info("Starting the app logger")
    log_level = os.getenv('LOG_LEVEL')
    app.logger.setLevel(log_level)

    loggly_token = os.getenv('LOGGLY_TOKEN')
    if loggly_token is not None:
        app.logger.info("Setting up the loggly log")
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{loggly_token}/tag/todo-app')
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)
    else:
        app.logger.info("Loggly token was not found")

    logger.info("Starting the app")
    disable_login = os.getenv('FLASK_SKIP_LOGIN')
    if disable_login == "True":
        logger.info(
            "Switching off authentication in the app config for testing purposes"
        )
        app.config['LOGIN_DISABLED'] = True
    mongo_srv = os.getenv('MONGO_SRV')
    db_name = os.getenv('MONGO_DB')
    mongo_user = os.getenv('MONGO_USER')
    mongo_pwd = os.getenv('MONGO_PWD')
    mongo_connection = os.getenv('MONGO_CONNECTION')

    logger.info(
        "Setting up Mongo Client with user: %s, database: %s, mongo_connection: %s",
        mongo_user, db_name, mongo_connection)
    mongo_client = ToDoMongoClient(mongo_user, mongo_pwd, mongo_srv, db_name,
                                   mongo_connection)

    oauth_client_id = os.getenv('OAUTH_CLIENT_ID')
    oauth_secret_id = os.getenv('OAUTH_CLIENT_SECRET')

    logger.info("Setting up Login Manager")
    login_manager = LoginManager()
    login_manager.init_app(app)
    client = WebApplicationClient(oauth_client_id)

    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
    app.secret_key = os.getenv('SECRET_KEY')  # used for cookies
    writer_role = "Writer"
    reader_role = "Reader"
    admin_role = "Admin"

    #  All the routes and setup code etc
    @app.route('/')
    @login_required
    def index():
        app.logger.info("Opening index page")
        show_all = request.args.get('show_all')

        show_all_bool = show_all == "yes"
        app.logger.info("Getting all tasks")
        tasks = mongo_client.get_all_tasks()
        item_view_model = ViewModel(tasks)
        # We want to only show certain buttons and links to writers or admins UNLESS login is disabled (ie. we are running tests)
        writer_bool = (disable_login or current_user.role == writer_role)
        admin_bool = (disable_login or current_user.role == admin_role)
        return render_template('index.html',
                               title='To Do App',
                               view_model=item_view_model,
                               show_all=show_all_bool,
                               writer=writer_bool,
                               admin=admin_bool)

    @app.route('/items/add', methods=['POST'])
    @login_required
    def add_item():

        if (disable_login or current_user.role == writer_role):
            form_data = request.form
            task_title = form_data["title"]
            task_desc = form_data["description"]
            task_due_date = form_data["duedate"]
            app.logger.info("Adding a new task, details: %s | %s | %s",
                            task_title, task_desc, task_due_date)
            mongo_client.add_task(task_title, task_desc, task_due_date)
        else:
            logger.error(f"Reader Role is not allowed to add a task")
        return redirect('/')

    @app.route('/items/complete', methods=['POST', 'GET'])
    @login_required
    def complete_item():
        if (disable_login or current_user.role == writer_role):

            form_data = request.form
            task_id = form_data["id"]
            app.logger.info("Completing a task with ID: %s", task_id)
            mongo_client.complete_task(task_id)
        else:
            logger.error(f"Reader Role is not allowed to complete a task")
        return redirect('/')

    @app.route('/items/remove', methods=['POST'])
    @login_required
    def remove_item():
        if (disable_login or current_user.role == writer_role):
            form_data = request.form
            task_id = form_data["id"]
            app.logger.info("Deleting a task with ID: %s", task_id)
            mongo_client.delete_task(task_id)
        else:
            logger.error(f"Reader Role is not allowed to remove a task")
        return redirect('/')

    @app.route('/items/start', methods=['POST'])
    @login_required
    def start_item():
        if (disable_login or current_user.role == writer_role):
            form_data = request.form
            task_id = form_data["id"]
            app.logger.info("Starting a task with ID: %s", task_id)
            mongo_client.start_task(task_id)
        else:
            app.logger.error(f"Reader Role is not allowed to start a task")
        return redirect('/')

    @app.route('/users/', methods=['GET'])
    @login_required
    def get_users():
        if (disable_login or current_user.role == admin_role):

            users = mongo_client.get_all_users()

            return render_template('users.html',
                                   title='User Admin',
                                   users=users)
        else:
            app.logger.error(f"This page is only for administrators")

    @app.route('/users/update', methods=['POST'])
    @login_required
    def update_user():
        if (disable_login or current_user.role == admin_role):
            form_data = request.form
            user_id_to_update = form_data["id"]
            new_role = form_data["new_role"]
            app.logger.info("Updating a user with ID: %s to new role: %s",
                            user_id_to_update, new_role)
            mongo_client.update_user(user_id_to_update, new_role)
        else:
            app.logger.error(f"Reader Role is not allowed to update a task")
        return redirect('/users')

    @app.route('/items/restart', methods=['POST'])
    @login_required
    def restart_item():
        if (disable_login or current_user.role == writer_role):
            if request.method == 'POST':
                form_data = request.form
                task_id = form_data["id"]
                logger.info("Restarting a task with ID: %s", task_id)
                mongo_client.reopen_task(task_id)
        else:
            app.logger.error(f"Reader Role is not allowed to restart a task")
        return redirect('/')

    @app.route('/login/callback', methods=['GET'])
    def login():
        app.logger.info(f"Logging you in as a user")
        code = request.args.get("code")

        code = request.args.get("code")
        # Prepare and send a request to get tokens
        token_url, headers, body = client.prepare_token_request(
            "https://github.com/login/oauth/access_token",
            authorization_response=request.url,
            code=code)

        headers['Accept'] = 'application/json'

        token_response = requests.post(token_url,
                                       headers=headers,
                                       data=body,
                                       auth=(oauth_client_id, oauth_secret_id))

        client.parse_request_body_response(token_response.text)
        # access token is now stored in the client.access_token param

        userinfo_endpoint = "https://api.github.com/user"
        uri, headers, body = client.add_token(userinfo_endpoint)
        userinfo_response = requests.get(uri, headers=headers, data=body)

        login_id = userinfo_response.json()["login"]
        app.logger.debug(f"Looking for {login_id} in the database")
        # see if we can find the user in the database already
        user = mongo_client.get_user_by_username(login_id)
        if user is None:
            # new users get added with Reader rights
            app.logger.debug(
                f"Creating new user with {login_id} and reader role")
            user = mongo_client.add_user(login_id, reader_role)

        # Begin user session by logging the user in
        app.logger.info(f"Logging in to the session")
        session['username'] = user.username
        login_user(user)
        return redirect('/')

    if __name__ == '__main__':
        app.run(ssl_context="adhoc")

    @login_manager.unauthorized_handler
    def unauthenticated():
        authorize_endpoint = 'https://github.com/login/oauth/authorize'
        app.logger.info(
            f"User is unauthenticated, redirecting to authentication service")
        authorize_url = client.prepare_request_uri(
            authorize_endpoint,
            "https://test-alb-terx-todo-app-service.azurewebsites.net/login/callback"
        )
        return redirect(authorize_url)

    @login_manager.user_loader
    def load_user(user_id):
        # get the user from the database if it exists
        app.logger.info(f"Loading user")
        result_user = mongo_client.get_user_by_id(user_id)

        return result_user

    return app
示例#14
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('todo_app.flask_config.Config')
    login_manager = LoginManager()
    login_manager.init_app(app)
    if app.config['LOG_LEVEL'] is not None:
        app.logger.setLevel(app.config['LOG_LEVEL'])

    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app'
        )
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    # Values setup during registration
    clientId = os.getenv('CLIENTID')
    clientSecret = os.getenv('CLIENTSECRET')
    loginDisabled = app.config.get('LOGIN_DISABLED')
    githubClient = WebApplicationClient(clientId)

    @app.route('/login/callback')
    def call_back():
        callbackCode = request.args.get("code")
        tokenUrl, headers, body = githubClient.prepare_token_request(
            "https://github.com/login/oauth/access_token", code=callbackCode)
        headers["Accept"] = "application/json"
        r = requests.post(
            tokenUrl,
            headers=headers,
            data=body,
            auth=(clientId, clientSecret),
        )
        params = githubClient.parse_request_body_response(r.text)
        tokenUrl, headers, body = githubClient.add_token(
            "https://api.github.com/user")
        userInfo = requests.get(
            tokenUrl,
            headers=headers,
            data=body,
        )
        userInfo = userInfo.json()
        login_user(load_user(userInfo['login']))
        return redirect('/')

    @login_manager.unauthorized_handler
    def unauthenticated():
        githubRedirect = githubClient.prepare_request_uri(
            "https://github.com/login/oauth/authorize")
        app.logger.info(githubRedirect)
        # print(githubRedirect)
        return redirect(githubRedirect)

    @login_manager.user_loader
    def load_user(user_id):
        user = User(user_id)
        return user

    def validate_user_role(func):
        @wraps(func)
        def wrapTheFunction(*args, **kwargs):
            if (not loginDisabled and current_user.role == "reader"):
                app.logger.warn(f"Insufficient User Rights")
                return render_template("error.html",
                                       error="Insufficient User Rights")
            return func(*args, **kwargs)

        return wrapTheFunction

    @app.route('/')
    @login_required
    def get_items():
        app.logger.info(f"Get the card on a list and its status")
        return render_template("index.html",
                               model=ViewModel(MongoActions().get_cards()))

    @app.route('/add_item', methods=['POST'])
    @login_required
    @validate_user_role
    def add_new_item():
        app.logger.info(f"Adding a new card")
        title = request.form['title']
        MongoActions().add_new_card(title)
        return redirect('/')

    @app.route('/move_item/<id>', methods=['POST'])
    @login_required
    @validate_user_role
    def move_item(id):
        MongoActions().update_card_status(id)
        return redirect('/')

    @app.route('/delete_item/<id>', methods=['POST'])
    @login_required
    @validate_user_role
    def delete_item(id):
        MongoActions().delete_card(id)
        return redirect('/')

    return app
示例#15
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    app.logger.setLevel(os.environ.get("LOG_LEVEL"))

    if os.environ.get("LOGGLY_TOKEN") is not None:
        args = "https://logs-01.loggly.com/inputs/" + os.environ.get(
            "LOGGLY_TOKEN") + "/tag/todo-app"
        handler = HTTPSHandler(args)
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    @login_manager.unauthorized_handler
    def unauthenticated():
        uri = oauth_client.prepare_request_uri(
            'https://github.com/login/oauth/authorize')
        return redirect(uri)

    @login_manager.user_loader
    def load_user(user_id):
        return Authenticated_User(user_id)

    @app.route('/login/callback', methods=['GET'])
    def login_callback():
        token_url, headers, body = oauth_client.prepare_token_request(
            'https://github.com/login/oauth/access_token',
            authorization_response=request.url,
            code=request.args.get('code'))

        token_response = requests.post(token_url,
                                       headers=headers,
                                       data=body,
                                       auth=(oauth_client_id,
                                             oauth_client_secret))

        oauth_client.parse_request_body_response(token_response.text)

        userinfo_endpoint = 'https://api.github.com/user'
        uri, headers, body = oauth_client.add_token(userinfo_endpoint)
        user_response = requests.get(uri, headers=headers, data=body)
        authenticated_user = Authenticated_User(user_response.json()['login'])
        login_user(authenticated_user)

        return redirect('/')

    @app.route('/')
    @login_required
    def index():
        app.logger.info("Start rendering template for get call")
        app.logger.info(
            f'Env variables are {os.environ.get("MONGO_USER_NAME")}')
        cards = fetch_all_cards("To Do", "Doing", "Done")
        view_model_obj = ViewModel(cards)
        if app.config.get('LOGIN_DISABLED') or current_user.role == 'writer':
            user_role = 'writer'
        else:
            user_role = 'reader'
        app.logger.debug(f'Inside app.py - create_app() {view_model_obj}')
        app.logger.info("Rendering of the template follows...")
        return render_template(
            'index.html',
            todo_cards=view_model_obj.get_cards('To Do'),
            doing_cards=view_model_obj.get_cards('Doing'),
            done_cards=view_model_obj.return_all_done_cards(5),
            user_role=user_role)

    @app.route('/add-card', methods=["POST"])
    @login_required
    def add_item():
        if app.config.get('LOGIN_DISABLED') or current_user.role == 'writer':
            title = request.form['title_of_todo']
            status = request.form['status_of_todo']
            if (title != ""):
                TrelloCard.create_card(title, status)
            return redirect("/")
        else:
            return abort(403)

    @app.route('/complete/<id>', methods=["POST"])
    @login_required
    def complete_item(id):
        if app.config.get('LOGIN_DISABLED') or current_user.role == 'writer':
            todo_id = request.form['card_id_form']
            change_card_status(todo_id)
            return redirect("/")
        else:
            return abort(403)

    return app
def create_app():
    app = Flask(__name__)
    app.config.from_object('todo_app.flask_config.Config')
    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.wsgi_app = ReverseProxied(app.wsgi_app)

    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app')
        formatter = jsonlogger.JsonFormatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s %(requesterIpAddr)s")
        handler.setFormatter(formatter)
        app.logger.addHandler(handler)

    client_id = os.environ['GITHUB_CLIENT_ID']
    client_secret = os.environ['GITHUB_CLIENT_SECRET']
    base_url="https://api.github.com"
    authorization_url="https://github.com/login/oauth/authorize"
    token_endpoint = "https://github.com/login/oauth/access_token"

    client = WebApplicationClient(client_id)
    todo = mongodb_todo()
    usermanager = MongoDbUserService()

    login_manager = LoginManager()
    login_manager.init_app(app)


    @app.errorhandler(Exception)
    def handle_error(e):
        app.logger.error('exception', extra={
            "method": "{}".format(request.method),
            "requesterIpAddr": "{}".format(request.remote_addr),
            "url": "{}".format(request.url)
        }, exc_info=True)

        return render_template("error.html", error=str(e))
    
    @app.after_request
    def after_request(response):
        app.logger.info("after_request", extra={
            "method": "{}".format(request.method),
            "requesterIpAddr": "{}".format(request.remote_addr),
            "url": "{}".format(request.url),
            "status_code": "{}".format(response.status)
        })
        return response

    @login_manager.user_loader
    def load_user(user_id):        
        return UserToLogin(user_id)
    
    @login_manager.unauthorized_handler
    def unauthenticated():
        app.logger.info("Unauthorized attemp made.", extra={
            "method": "{}".format(request.method),
            "requesterIpAddr": "{}".format(request.remote_addr),
            "url": "{}".format(request.url)
        })
        return redirect(url_for('login'))
    
    @app.route('/logout')
    @login_required
    def logout():
        app.logger.info("User {} logged out of the system.".format(current_user.id), extra={
            "method": "{}".format(request.method),
            "requesterIpAddr": "{}".format(request.remote_addr),
            "url": "{}".format(request.url)
        })
        logout_user()
        session.clear()        
        return redirect("https://github.com/logout")
    
    @app.route("/login")
    def login():
        request_uri = client.prepare_request_uri(
            authorization_url,
            redirect_uri=request.base_url + "/callback",
            scope=None,
        )
        return redirect(request_uri)

    @app.route("/login/callback")
    def callback():
        code = request.args.get("code")
        app.logger.debug("{}".format(code), extra={
            "method": "{}".format(request.method),
            "requesterIpAddr": "{}".format(request.remote_addr),
            "url": "{}".format(request.url)
        })

        # Prepare and send request to get tokens! 
        token_url, headers, body = client.prepare_token_request(
            token_endpoint,
            authorization_response=request.url,
            redirect_url=request.base_url,
            code=code,
        )

        token_response = requests.post(
            token_url,
            headers=headers,
            data=body,
            auth=(client_id, client_secret),
        )

        if token_response.status_code != 200:
            return redirect(url_for('login'))

        json_data = token_response.content.decode('utf8').replace("'", '"')
        # Parse the tokens!
        client.parse_request_body_response(json_data)
        userinfo_endpoint = "{}/user".format(base_url)
        uri, headers, body = client.add_token(userinfo_endpoint)
        userinfo_response = requests.get(uri, headers=headers, data=body)
        if userinfo_response.ok:
            account_info_json = userinfo_response.json()
            currentUserName = str(account_info_json['login'])               
            login_user(UserToLogin(currentUserName))
            app.logger.info("User logged in {}".format(current_user.id), extra={
                "method": "{}".format(request.method),
                "requesterIpAddr": "{}".format(request.remote_addr),
                "url": "{}".format(request.url)
            })

            if usermanager.get_totalusercount() == 0:
                usermanager.create_user(username=currentUserName,role="admin")
                app.logger.info("User logged in {} has been give admin level access.".format(current_user.id), extra={
                    "method": "{}".format(request.method),
                    "requesterIpAddr": "{}".format(request.remote_addr),
                    "url": "{}".format(request.url)
                })
            
            if (usermanager.get_totalusercount() > 0) and (usermanager.get_findusercount(qry={"username": currentUserName}) == 0):
                usermanager.create_user(username=currentUserName,role="read")
                app.logger.info("User logged in {} has been give read level access.".format(current_user.id), extra={
                    "method": "{}".format(request.method),
                    "requesterIpAddr": "{}".format(request.remote_addr),
                    "url": "{}".format(request.url)
                })

        return redirect(url_for('get_index'))


    @app.route('/', methods=['GET'])
    @login_required
    def sendhome():
        return redirect(url_for('get_index'))


    ##### Core TODO_Tasks#####
    #error handling for 404
    # @app.errorhandler(404)
    # def not_found(e):
    #     return render_template("error.html", error='resource not found!')

    @app.route('/contact')
    def contact():
        return render_template('contact.html')
    
    @app.route('/home', methods=['GET'])
    @login_required
    def get_index():
        cardslist = []
        items = todo.get_AllItems()
        if (app.config['LOGIN_DISABLED']):
            userRole = False
        else:
            userRole = usermanager.IsDisable()

        for item in items:
            cardslist.append(Card(item))
        item_view_model = ViewModel(cardslist)
        return render_template('index.html', view_model=item_view_model, strRole=userRole)

  
    @app.route('/new', methods=['GET'])   # New Task
    @login_required
    @usermanager.hasWritePermission
    def getnew_post():
        return render_template('new_task.html')

    @app.route('/home', methods=['POST'])   # New Task
    @login_required
    @usermanager.hasWritePermission
    def post_index():
        response = todo.create_task(
            name = request.form['title'],
            due = request.form['duedate'],
            desc = request.form['descarea']
        )        
        if response is not None:
            if current_app.config["LOGIN_DISABLED"]==False:
                app.logger.info("{} create new task".format(current_user.id), extra={
                    "method": "{}".format(request.method),
                    "requesterIpAddr": "{}".format(request.remote_addr),
                    "url": "{}".format(request.url),
                    "data": "name: {} due: {} desc: {}".format(request.form['title'], str(request.form['duedate']), request.form['descarea'])
                })
            return redirect('/home')
        else:
            return render_template("error.html",error="failed to create task!")

    
    @app.route('/edit/<id>', methods=['GET']) #Edit task
    @login_required
    @usermanager.hasWritePermission
    def get_edit(id):
        item = todo.get_task(id=id)
        if item is not None:
            item_info = Card(item)
            return render_template('edit.html', task=item_info)
        else:
            return render_template("error.html", error="failed to obtain task info!")

    @app.route('/edit/<id>', methods=['POST']) #Edit task
    @login_required
    @usermanager.hasWritePermission
    def post_edit(id):
        response= todo.update_task(
            id = id,
            name = request.form['title'],
            desc = request.form['descarea'],
            due = request.form['duedate'],
            status = request.form['status']
        )
        if response is not None:
            if current_app.config["LOGIN_DISABLED"]==False:
                app.logger.info("{} update task".format(current_user.id), extra={
                    "method": "{}".format(request.method),
                    "requesterIpAddr": "{}".format(request.remote_addr),
                    "url": "{}".format(request.url),
                    "data": "id: {} name: {} due: {} desc: {} status: {}".format(id, request.form['title'], str(request.form['duedate']), request.form['descarea'], request.form['status'])
                })
            return redirect('/home')
        else:
            return render_template("error.html", error="failed to update task!")
    
    @app.route('/delete/<id>') # delete task
    @login_required
    @usermanager.hasWritePermission
    def delete(id):
        response = todo.delete_task(id=id)
        if response is not None: 
            if current_app.config["LOGIN_DISABLED"]==False:
                app.logger.info("{} deleted task".format(current_user.id), extra={
                    "method": "{}".format(request.method),
                    "requesterIpAddr": "{}".format(request.remote_addr),
                    "url": "{}".format(request.url),
                    "data": "id: {}".format(id)
                })
            return redirect('/home')
        else:
            return render_template("error.html",error="failed to delete task!") 
    
    ### Additional views ###
    @app.route('/getpreviousdonetasks', methods=['GET'])
    @login_required
    def get_previous_done_tasks():
        cardslist = []
        items = todo.get_older_done_task()
        for item in items:
            cardslist.append(Card(item))
        item_view_model = ViewModel(cardslist)
        userRole = usermanager.IsDisable()
        return render_template('previous_done_task.html', view_model=item_view_model, strRole=userRole)

    
    @app.route('/gettodaydonetasks', methods=['GET'])
    @login_required
    def get_today_done_tasks():
        cardslist = []
        items = todo.get_today_done_task()
        for item in items:
            cardslist.append(Card(item))
        item_view_model = ViewModel(cardslist)
        userRole = usermanager.IsDisable()
        return render_template('today_done_task.html', view_model=item_view_model, strRole=userRole)

############# UserManagement ##########################

    @app.route('/usermanager', methods=['GET'])  #portal
    @login_required
    @usermanager.hasRoleAdmin
    def get_usermanager():
        user_list = []
        items = usermanager.get_AllUsers()
        for item in items:
            user_list.append(User(item))
        item_view_model = ViewModel(user_list)
        return render_template('userManager.html', view_model=item_view_model)        
    
    @app.route('/edituser/<id>', methods=['GET']) #Edit user
    @login_required
    @usermanager.hasRoleAdmin
    def get_edituser(id):
        item = usermanager.get_user(id=id)
        if item is not None:
            item_info = User(item)
            return render_template('editUser.html', user=item_info)
        else:
            return render_template("error.html", error="failed to obtain user info!")

    
    @app.route('/edituser/<id>', methods=['POST']) #Edit user
    @login_required
    @usermanager.hasRoleAdmin
    def post_edituser(id):
        response = usermanager.update_user(
            id = id,
            username = request.form['username'],
            role = request.form['role']
        )
        if response is not None:
            app.logger.info("{} updated user permission".format(current_user.id), extra={
                "method": "{}".format(request.method),
                "requesterIpAddr": "{}".format(request.remote_addr),
                "url": "{}".format(request.url),
                "data": "id: {} username: {} role: {}".format(id, request.form['username'], request.form['role'])
            })
            return redirect('/usermanager')
        else:
            return render_template("error.html", error="failed to update user!")

    
    @app.route('/deleteuser/<id>') # delete user
    @login_required
    @usermanager.hasRoleAdmin
    def deleteuser(id):
        response = usermanager.delete_user(id=id)
        if response is not None:
            app.logger.info("{} deleted user".format(current_user.id), extra={
                "method": "{}".format(request.method),
                "requesterIpAddr": "{}".format(request.remote_addr),
                "url": "{}".format(request.url),
                "data": "id: {}".format(id)
            })
            return redirect('/usermanager')
        else:
            return render_template("error.html",error="failed to delete user!")

###############################################
      
    
    return app
示例#17
0
def index():

    mongosuperlist = [
    ]  # The name of the Mongo OVERALL list with all items in it

    mongo_view_model = [
    ]  # The name of the Mongo TO DO list (section of collection)
    mongo_view_model_doing = [
    ]  # The name of the Mongo DOING list (section of collection)
    mongo_view_model_done = [
    ]  # The name of the Mongo DONE list (section of collection)
    mongo_view_model_olddone = [
    ]  # Older 'done' items to be stored here (section of collection)
    mongosuperlist = list(db.newposts.find())

    if LOGGLY_TOKEN is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{LOGGLY_TOKEN}/tag/todo-app')
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

#  Create the various lists depending on status
    counter = 0
    for mongo_card in mongosuperlist:

        #A list of mongo rows from the collection called 'newposts'
        whatsthestatus = (mongosuperlist[counter]['status'])
        whatsthedate = (mongosuperlist[counter]['mongodate']
                        )  # Need the date to seperate older 'Done'
        counter = counter + 1  #Increment as need to get next list item
        if whatsthestatus == "todo":
            mongo_view_model.append(mongo_card)  # Append to the todo
        elif whatsthestatus == "doing":
            mongo_view_model_doing.append(mongo_card)  # Append to doing
        elif whatsthestatus == "done":
            if whatsthedate > olddate:
                mongo_view_model_done.append(
                    mongo_card)  # Append to display in done - recently
            else:
                mongo_view_model_olddone.append(
                    mongo_card)  # Append to display in older done record
                # note: Invalid or no status won't appear at all

# print("the current user is:  ")
    print(current_user.name)
    write_permission_user = (current_user.name)

    if (write_permission_user == "britboy4321"):
        current_user_role = "writer"
    else:
        current_user_role = "reader"

    print("CURRENT USER ROLE:")
    print(current_user_role)

    # If statement to go here:

    # allow_edit = (current_user.name)

    if (current_user_role == "writer"):  # Can now handle multiple users
        return render_template(
            'indexwrite.html',  # If user allowed to write: 
            passed_items_todo=mongo_view_model,  # Mongo To Do
            passed_items_doing=mongo_view_model_doing,  # Mongo Doing
            passed_items_done=mongo_view_model_done,  # Mongo Done
            passed_items_olddone=
            mongo_view_model_olddone  # Old items ready to be displayed elsewhere
        )
    else:
        return render_template(
            'indexread.html',  # If user NOT allowed to write: 
            passed_items_todo=mongo_view_model,  # Mongo To Do
            passed_items_doing=mongo_view_model_doing,  # Mongo Doing
            passed_items_done=mongo_view_model_done,  # Mongo Done
            passed_items_olddone=
            mongo_view_model_olddone  # Old items ready to be displayed elsewhere
        )
示例#18
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    sess = Session()
    app.secret_key = os.getenv("SECRET_KEY")
    app.logger.setLevel(app.config['LOG_LEVEL'])
    app.config['SESSION_TYPE'] = 'filesystem'
    sess.init_app(app)
    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app')
        handler.setFormatter(Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)
    collection=os.getenv("MONGO_COLLECTION")
    mongo_val = pymongo.MongoClient(os.getenv("MONGODB_CONNECTION_STRING"))
    try:
        db_name = mongo_val.get_database()
    except pymongo.errors.ConfigurationError:
        logging.warning('No default database. Using project_exercise database')
        db_name = mongo_val.get_database("project_exercise")
    app.logger.info('db name %s', db_name)
    collections = db_name.list_collection_names()
    if collection not in collections:
        todos = db_name[collection]
    todos = db_name[collection]
    _DEFAULT_ITEMS = []
    itemDict = []
    if os.getenv("disable_login")=='True':
        app.config["LOGIN_DISABLED"]=True

    def check_role(func):
        def wrapper_function(*args, **kwargs):
            if 'writer' in current_user.roles:
                return func(*args, **kwargs)
            else:
                app.logger.error('User does not have writer role enabled')
                raise Forbidden("Writer role required")
        wrapper_function.__name__ = func.__name__
        return wrapper_function

    @app.route('/items', methods=["GET", "PATCH"])
    @app.route('/', methods=["GET", "PATCH"])
    @login_required
    def index():
        if (os.getenv("disable_login")=='True'):
            login_user(User("Testing"))
        items = get_cards()
        item_view_model = ViewModel(items)
        return render_template('index.html',view_model=item_view_model)

    @app.route('/items/<id>', methods=["GET", "POST"])
    @login_required
    def get(id):
        item = get_card(id)
        return render_template('saveItem.html', item = item)

    @app.route('/items/<id>/edit', methods=["GET", "POST", "PUT"])
    @login_required
    @check_role
    def edit(id):
        item = get_card(id)
        if request.method=="POST":
            item["title"]=request.form.get('itemTitle')
            item["status"]=request.form.get('itemStatus')
            save_card(item)
            app.logger.info("%s has been edited", request.form.get('itemTitle'))
            return redirect(url_for('get', id = item["id"]))
        return render_template('edit.html', item = item)

    @app.route('/items/new', methods=["POST"])
    @login_required
    @check_role
    def add():
        title = request.form.get('itemTitle')
        add_card(title)
        app.logger.info("%s has been added", request.form.get('itemTitle'))
        return redirect(url_for('index'))

    def get_card(id):
        items = get_cards()
        return next((item for item in items if item['id'] == id), None)

    def save_card(item):
        date = datetime.datetime.now()
        existing_items = get_cards()
        updated_items = [item if item['id'] == existing_item['id'] else existing_item for existing_item in existing_items]
        todos.update_one({"_id":item['id']},{"$set":{"title":item['title'],"status":item['status'],'DateUpdated':date}})
        return item

    def add_card(title):
        date = datetime.datetime.now()
        print (date)
        id_val = ObjectId()
        id_val = str(id_val)
        item = Item(id_val, title, 'To Do', date.date())
        itemDict.append(item)
        todos.insert_one({'_id': id_val, 'title': title,'status':'To Do','DateUpdated':date})
        return item

    def get_cards():
        data = list(todos.find())
        updated_data = loads(dumps(data))
        _DEFAULT_ITEMS = selectFields(updated_data)
        return _DEFAULT_ITEMS

    def selectFields(updated_data):
        for x in updated_data:
            id = x['_id']
            vals = [li['id'] for li in _DEFAULT_ITEMS]
            for value in vals:
                if value == id:
                    break
            else:
                title = x['title']
                status= x['status']
                date = x['DateUpdated']
                itemDict.append(Item(id, title, status, date))
                item = { 'id': id, 'title': title, 'status': status, 'DateUpdated': date }
                _DEFAULT_ITEMS.append(item)
        return _DEFAULT_ITEMS
    
    
    @app.route('/login/', methods=["GET", "POST"])
    def login():
        code = request.args.get('code')
        request_body = {
            "code":code,
            "client_id":client_id,
            "client_secret":client_secret
        }
        response = requests.post("https://github.com/login/oauth/access_token",request_body,headers={"Accept": "application/json"})
        parsed = client.parse_request_body_response(response.content)
        access_token = parsed["access_token"]
        github_user = requests.get("https://api.github.com/user",headers={"Authorization": "token {0}".format(access_token)}).json()
        user = load_user(github_user["login"])
        if login_user(user):
            app.logger.info("User successfully logged in")
            return redirect("/")
        else:
            return app.logger.error("Error logging in")

    login_manager = LoginManager()

    @login_manager.unauthorized_handler
    def unauthenticated():
        login_manager.login_view='auth.login'
        url = client.prepare_request_uri('https://github.com/login/oauth/authorize', redirect_uri=redirect_uri_value)
        return redirect(url) 

    @login_manager.user_loader
    def load_user(user_id):
        return User(user_id)

    login_manager.init_app(app)
    return app
示例#19
0
def create_app():
    app = Flask(__name__)
    app.secret_key = os.urandom(24)

    login_disabled = os.getenv('LOGIN_DISABLED').upper() == 'TRUE'
    app.config['LOGIN_DISABLED'] = login_disabled

    handler = logging.StreamHandler(sys.stdout)
    app.logger.addHandler(handler)
    app.logger.setLevel(os.getenv('LOG_LEVEL'))
    loggly_token = os.getenv('LOGGLY_TOKEN')
    loggly_tag = os.getenv('LOGGLY_TAG')

    if loggly_token is not None and loggly_tag is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{loggly_token}/tag/{loggly_tag}'
        )
        handler.setFormatter(
            logging.Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    log = logging.getLogger('app')

    collection = get_db_collection()

    login_manager = LoginManager()

    client_id = os.getenv('CLIENT_ID')
    client_secret = os.getenv('CLIENT_SECRET')
    state = generate_random_string(6)

    oauth_client = WebApplicationClient(client_id)

    log.info('App has initiliased')

    @login_manager.unauthorized_handler
    def unauthenticated():
        log.debug('Redirecting user to authenticator')

        request_uri = oauth_client.prepare_request_uri(
            "https://github.com/login/oauth/authorize", state=state)
        return redirect(request_uri)

    @login_manager.user_loader
    def load_user(user_id):
        return User(user_id)

    login_manager.init_app(app)

    @app.route("/login/callback", methods=["GET"])
    def callback():
        log.debug('User has hit login callback')

        token_request_url, token_request_headers, token_request_body = oauth_client.prepare_token_request(
            token_url="https://github.com/login/oauth/access_token",
            authorization_response=request.url,
            state=state,
            client_secret=client_secret)
        token_response = requests.post(token_request_url,
                                       headers=token_request_headers,
                                       data=token_request_body)
        oauth_client.parse_request_body_response(
            token_response.content.decode(), state=state)

        user_info_request_url, user_info_request_headers, user_info_request_body = oauth_client.add_token(
            uri='https://api.github.com/user', )
        user_info_response = requests.get(user_info_request_url,
                                          data=user_info_request_body,
                                          headers=user_info_request_headers)

        github_username = user_info_response.json()['login']

        log.debug(f'Logging in user with username "{escape(github_username)}"')

        user = User(github_username)
        login_success = login_user(user)

        if login_success:
            log.debug(f'User login for "{escape(github_username)}" successful')
            return redirect(url_for('index'))
        else:
            log.error(
                f'User login for "{escape(github_username)}" unsuccessful')
            return "Unauthorised", 403

    @app.route('/')
    @login_required
    def index():
        user: User = current_user
        readonly = (not login_disabled) and user.get_role() == UserRole.Reader

        items = get_all_items(collection)

        return render_template('index.html',
                               view_model=ViewModel(items, readonly))

    @app.route('/items/<id>/complete')
    @require_write_privilege
    @login_required
    def complete_item(id):
        log.debug(
            f'Recieved request to mark item with ID "{escape(id)}" as complete'
        )

        mark_item_as_complete(collection, id)

        log.debug(f'Item with ID "{escape(id)}" marked as complete')
        return redirect(url_for('index'))

    @app.route('/items/new', methods=[HttpMethod.Post.value])
    @require_write_privilege
    @login_required
    def add_item():
        name = request.form['title']
        log.debug(f'Recieved add item request for item "{escape(name)}"')

        add_new_item(collection, name)

        log.debug(f'Item with name "{escape(name)}" added')
        return redirect(url_for('index'))

    if __name__ == '__main__':
        app.run(debug=True)

    return app
示例#20
0
def create_app():
    app = Flask(__name__)
    app.secret_key = os.environ.get("SECRET_KEY") or os.urandom(24)

    login_disabled = os.getenv('LOGIN_DISABLED') == 'True'
    app.config['LOGIN_DISABLED'] = login_disabled

    handler = logging.StreamHandler(sys.stdout)
    app.logger.addHandler(handler)
    app.logger.setLevel(os.getenv('LOG_LEVEL', 'INFO'))

    loggly_token = os.getenv('LOGGLY_TOKEN')
    loggly_tag = os.getenv('LOGGLY_TAG')

    if loggly_token is not None and loggly_tag is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{loggly_token}/tag/{loggly_tag}'
        )
        handler.setFormatter(
            logging.Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    log = logging.getLogger('app')

    collection = get_db_collection()

    # User session management setup
    login_manager = LoginManager()

    # This information is obtained upon registration of a new GitHub account
    client_id = os.getenv('CLIENT_ID')
    client_secret = os.getenv('CLIENT_SECRET')
    authorization_url = 'https://github.com/login/oauth/authorize'
    access_token_url = 'https://github.com/login/oauth/access_token'

    # OAuth 2.0 Client setup
    oauth_client = WebApplicationClient(client_id)

    log.info('Web Application has initialised')

    # Logic to redirect to Github OAuth flow when unauthenticated
    @login_manager.unauthorized_handler
    def unauthenticated():
        log.debug('Redirecting user to be authenticated via GitHub OAuth')
        request_uri = oauth_client.prepare_request_uri(authorization_url)
        return redirect(request_uri)

    # This callback is used to reload the user object from the user ID stored in the session.
    @login_manager.user_loader
    def load_user(user_id):
        return User(user_id)

    # Once the actual application object has been created, you can configure it for login with:
    login_manager.init_app(app)

    # Implement the callback route
    @app.route("/login/callback", methods=["GET"])
    def callback():
        log.debug(
            'Callback URL has been invoked after the user has been authenticated'
        )
        token_url, token_headers, token_body = oauth_client.prepare_token_request(
            token_url="https://github.com/login/oauth/access_token",
            authorization_response=request.url,
            client_secret=client_secret)
        token_response = requests.post(token_url,
                                       headers=token_headers,
                                       data=token_body)
        oauth_client.parse_request_body_response(
            token_response.content.decode())

        # Add token to the request uri, body or authorization header.
        user_info_request_url, user_info_request_headers, user_info_request_body = oauth_client.add_token(
            uri='https://api.github.com/user', )
        user_info_response = requests.get(user_info_request_url,
                                          data=user_info_request_body,
                                          headers=user_info_request_headers)

        github_username = user_info_response.json()['login']
        user = User(github_username)
        login_success = login_user(user)

        if login_success:
            log.debug(f'Successful logon for {github_username}')
            return redirect(url_for('index'))
        else:
            log.warning(f'Failed logon for {github_username}')
            return "Unauthorised", 403

    @app.route('/')
    @login_required
    def index():
        user = User(current_user.get_id())
        reader = (not login_disabled) and user.get_role() == Role.Reader
        items = get_all_items(collection)
        return render_template('index.html',
                               view_model=ViewModel(items, reader))

    @app.route('/', methods=['POST'])
    @login_required
    @restricted
    def add_item():
        title = request.form['item_title']
        description = request.form['item_description']
        log.debug(
            f'Request to add a new item with title: {title} and description: {description}'
        )
        add_new_item(collection, title, description)
        log.debug(
            f'New item added with title: {title} and description: {description}'
        )
        return redirect(url_for('index'))

    @app.route('/items/<id>/complete', methods=['POST'])
    @login_required
    @restricted
    def complete_item(id):
        log.debug(f'Request to mark item with id: {id} as complete')
        mark_item_as_complete(collection, id)
        log.debug(f'Item with id: {id} marked as complete')
        return redirect(url_for('index'))

    @app.route('/items/<id>/inprogress', methods=['POST'])
    @login_required
    @restricted
    def in_progress_item(id):
        log.debug(f'Request to mark item with id: {id} as in progress')
        mark_item_as_in_progress(collection, id)
        log.debug(f'Item with id: {id} marked as in progress')
        return redirect(url_for('index'))

    @app.route('/items/<id>/uncomplete', methods=['POST'])
    @login_required
    @restricted
    def uncomplete_item(id):
        log.debug(f'Request to mark item with id: {id} as uncompleted')
        mark_item_as_uncomplete(collection, id)
        log.debug(f'Item with id: {id} marked as uncompleted')
        return redirect(url_for('index'))

    @app.route('/items/delete/<id>', methods=['POST'])
    @login_required
    @restricted
    def delete_item(id):
        log.debug(f'Request to delete item with id: {id}')
        remove_item(collection, id)
        log.debug(f'Item with id: {id} has been deleted')
        return redirect(url_for('index'))

    if __name__ == '__main__':
        app.run(debug=True)

    return app
def create_app():
    app = Flask(__name__)
    app.config.from_object('flask_config.Config')
    app.logger.setLevel(app.config['LOG_LEVEL'])
    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app'
        )
        formatter = jsonlogger.JsonFormatter(
            "[%(asctime)s] %(levelname)s in %(module)s: %(message)s")
        handler.setFormatter(formatter)
        app.logger.addHandler(handler)
        getLogger('werkzeug').addHandler(
            HTTPSHandler(
                f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todoapp-requests'
            ))
    login_manager = LoginManager()

    @login_manager.unauthorized_handler
    def unauthenticated():
        client = WebApplicationClient(os.getenv("CLIENT_ID"))
        client.state = client.state_generator()
        authredirect = client.prepare_request_uri(
            "https://github.com/login/oauth/authorize", state=client.state)
        return redirect(authredirect)

    @login_manager.user_loader
    def load_user(user_id):
        user = User(user_id)
        app.logger.info("user id %s is loaded with role %s",
                        user.id,
                        user.role,
                        extra={
                            "user_id": user.id,
                            "role": user.role
                        })
        return user

    login_manager.init_app(app)

    class User(UserMixin):
        def __init__(self, userid):
            self.id = userid
            if self.id == "69510597":
                self.role = 'writer'
            else:
                self.role = 'reader'

    def writer_required(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if get_user_role() == 'reader':
                app.logger.warning(
                    "user tried to access an unauthorised page",
                    extra={"user_id": flask_login.current_user.get_id()})
                abort(403)
            else:
                return f(*args, **kwargs)

        return decorated_function

    def get_user_role():
        if app.config['LOGIN_DISABLED']:
            app.logger.warning("logins are disabled, all users are writers")
            return "writer"
        else:
            return flask_login.current_user.role

    @app.route('/')
    @login_required
    def index():
        items = mongo.get_items_mongo()
        items = sorted(items, key=lambda k: k.status, reverse=True)
        item_view_model = vm.ViewModel(items)
        role = get_user_role()
        return render_template('index.html',
                               view_model=item_view_model,
                               role=role)

    @app.route('/login/callback')
    def callback():
        client = WebApplicationClient(os.getenv("CLIENT_ID"))
        client.state = request.args.get('state')
        code = request.args.get('code')
        tokenurl, headers, body = client.prepare_token_request(
            'https://github.com/login/oauth/access_token',
            state=client.state,
            code=code)
        secret = os.getenv('OAUTH_SECRET')
        clientid = os.getenv("CLIENT_ID")
        tokenresponse = requests.post(tokenurl,
                                      data=body,
                                      auth=(clientid, secret))
        client.parse_request_body_response(tokenresponse.text)
        userinfo_endpoint = "https://api.github.com/user"
        uri, headers, body = client.add_token(userinfo_endpoint)
        userinfo_response = requests.get(uri, headers=headers, data=body)
        userinfo_json = userinfo_response.json()
        id = userinfo_json['id']
        flask_login.login_user(load_user(id))
        app.logger.info("user logged in Succesfully",
                        extra={"user_id": flask_login.current_user.get_id()})
        return redirect("/")

    @app.route('/<id>/doingcompleted', methods=['POST'])
    @login_required
    @writer_required
    def doingcompleteditem(id):
        mongo.mark_doing_item_done_mongo(id)
        app.logger.debug("doing item changed from doing to done",
                         extra={
                             "action": "complete_item",
                             "previous_state": 'doing',
                             'item_id': id,
                             "user_id": flask_login.current_user.get_id()
                         })
        app.logger.info("doing item changed from doing to done",
                        extra={
                            "action": "complete_item",
                            'item_id': id
                        })
        return redirect('/')

    @app.route('/<id>/todocompleted', methods=['POST'])
    @login_required
    @writer_required
    def todocompleteditem(id):
        mongo.mark_todo_item_done_mongo(id)
        app.logger.debug("doing item changed from todo to done",
                         extra={
                             "action": "complete_item",
                             "previous_state": 'todo',
                             'item_id': id,
                             "user_id": flask_login.current_user.get_id()
                         })
        app.logger.info("doing item changed from todo to done",
                        extra={
                            "action": "complete_item",
                            'item_id': id
                        })
        return redirect('/')

    @app.route('/<id>/doingtodo', methods=['POST'])
    @login_required
    @writer_required
    def doingtodoitem(id):
        mongo.mark_doing_item_todo_mongo(id)
        app.logger.debug("doing item changed from done to todo",
                         extra={
                             "action": "todo_item",
                             "previous_state": 'done',
                             'item_id': id,
                             "user_id": flask_login.current_user.get_id()
                         })
        app.logger.info("doing item changed from done to todo",
                        extra={
                            "action": "todo_item",
                            'item_id': id
                        })
        return redirect('/')

    @app.route('/<id>/donetodo', methods=['POST'])
    @login_required
    @writer_required
    def donetodoitem(id):
        mongo.mark_done_item_todo_mongo(id)
        app.logger.debug("todo item changed from done to todo",
                         extra={
                             "action": "todo_item",
                             "previous_state": 'done',
                             'item_id': id,
                             "user_id": flask_login.current_user.get_id()
                         })
        app.logger.info("todo item changed from done to todo",
                        extra={
                            "action": "todo_item",
                            'item_id': id
                        })

        return redirect('/')

    @app.route('/<id>/tododoing', methods=['POST'])
    @login_required
    @writer_required
    def tododoingitem(id):
        mongo.mark_todo_item_doing_mongo(id)
        app.logger.debug("todo item changed from todo to doing",
                         extra={
                             "action": "doing_item",
                             "previous_state": 'todo',
                             'item_id': id,
                             "user_id": flask_login.current_user.get_id()
                         })
        app.logger.info("todo item changed from todo to doing",
                        extra={
                            "action": "doing_item",
                            'item_id': id
                        })
        return redirect('/')

    @app.route('/<id>/donedoing', methods=['POST'])
    @login_required
    @writer_required
    def donedoingitem(id):
        mongo.mark_done_item_doing_mongo(id)
        app.logger.debug("todo item changed from done to doing",
                         extra={
                             "action": "doing_item",
                             "previous_state": 'done',
                             'item_id': id,
                             "user_id": flask_login.current_user.get_id()
                         })
        app.logger.info("todo item changed from done to doing",
                        extra={
                            "action": "doing_item",
                            'item_id': id
                        })
        return redirect('/')

    @app.route('/newitems', methods=['POST'])
    @login_required
    @writer_required
    def newitems():
        itemname = request.form.get('Title')
        id = mongo.add_item_mongo(itemname)
        app.logger.debug("todo item created",
                         extra={
                             "action": "create",
                             "item_name": itemname,
                             "user_id": flask_login.current_user.get_id(),
                             "item_id": id
                         })
        app.logger.info("todo item created",
                        extra={
                            "action": "create_item",
                            "item_name": itemname
                        })
        return redirect('/')

    if __name__ == '__main__':
        app.run()
    return app
示例#22
0
def create_app(item_store=ItemStore(), user_store=UserStore()):
    app = Flask(__name__)
    app.logger.setLevel(LogConfig.LOG_LEVEL)

    if LogConfig.LOGGLY_TOKEN is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{LogConfig.LOGGLY_TOKEN}/tag/todo-app'
        )
        handler.setFormatter(
            jsonlogger.JsonFormatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)
        getLogger('werkzeug').addHandler(
            HTTPSHandler(
                f'https://logs-01.loggly.com/inputs/{LogConfig.LOGGLY_TOKEN}/tag/todo-app-requests'
            ))

    oauth_provider = GithubOauthProvider()

    login_manager = LoginManager()
    login_manager.init_app(app)

    app.secret_key = oauth_provider.get_client_secret()

    @login_manager.unauthorized_handler
    def unauthenticated():
        # Authenticate with GitHub
        return redirect(oauth_provider.get_authenticate_uri())

    @login_manager.user_loader
    def load_user(user_id):
        user = user_store.get_user(user_id)
        return user

    @app.route('/login/callback')
    def login_callback():  # pylint: disable=unused-variable
        # Get authorization code from github
        code = request.args.get("code")

        # Use the authorization code to get user info
        userinfo = oauth_provider.get_user_info(
            authorization_response=request.url,
            redirect_url=request.base_url,
            code=code)

        user = User.from_json(userinfo)
        user_store.add_user_if_missing(user)

        # Begin user session
        login_user(user)

        return redirect("/")

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        app.logger.info('User has logged out')  # pylint: disable=no-member
        return redirect("/")

    @app.route("/admin")
    @login_required
    @user_admin_access
    def admin():
        users = user_store.get_users()
        app.logger.info('Entering admin page')  # pylint: disable=no-member
        return render_template('admin.html',
                               users=users,
                               current_user=current_user)

    @app.route('/user/<operation>/<id>', methods=['POST'])
    @login_required
    @user_write_access
    def update_user(operation, id):  # pylint: disable=unused-variable
        app.logger.info(f"Updateing user to {operation}")  # pylint: disable=no-member
        if operation == "reader":
            user_store.update_user(id, UserRole.READER)
        elif operation == "writer":
            user_store.update_user(id, UserRole.WRITER)
        elif operation == "admin":
            user_store.update_user(id, UserRole.ADMIN)
        elif operation == "delete":
            user_store.remove_user(id)
        return redirect("/admin")

    @app.route('/')
    @login_required
    def index():  # pylint: disable=unused-variable
        items = item_store.get_items()
        return render_template('index.html',
                               items_view_model=ItemsViewModel(items),
                               login_disabled=is_login_disabled(),
                               current_user=current_user)

    @app.route('/update/<id>/<new_status>', methods=['POST'])
    @login_required
    @user_write_access
    def update(id, new_status):  # pylint: disable=unused-variable
        app.logger.info(f'Updateing item id={id} new_status={new_status}')  # pylint: disable=no-member
        item_store.update_item(id, new_status)
        return redirect("/")

    @app.route('/add', methods=['GET', 'POST'])
    @login_required
    @user_write_access
    def add():  # pylint: disable=unused-variable
        if request.method == 'POST':
            if 'add' in request.form:
                app.logger.info(
                    f'Processing add name={request.form.get("new_todo_title")}'
                )  # pylint: disable=no-member
                id = item_store.add_item(
                    request.form.get('new_todo_title'),
                    request.form.get('new_todo_description'),
                    request.form.get('new_todo_due'))
                app.logger.info(f'Add new item id={id}')  # pylint: disable=no-member
            return redirect("/")

        return render_template('add.html')

    @app.route('/editdetails/<id>', methods=['GET', 'POST'])
    @login_required
    @user_write_access
    def editdetails(id):  # pylint: disable=unused-variable
        if request.method == 'POST':
            if 'edit' in request.form:
                app.logger.info(f'Editing item id={id}')  # pylint: disable=no-member
                item_store.edit_item(id, request.form.get('todo_title'),
                                     request.form.get('todo_description'),
                                     request.form.get('todo_due'))
            return redirect("/")

        return render_template('editdetails.html',
                               item=item_store.get_item(id))

    @app.route('/delete/<id>', methods=['GET', 'POST'])
    @login_required
    @user_write_access
    def delete(id):  # pylint: disable=unused-variable
        app.logger.info(f"Delete called")
        if request.method == 'POST':
            if 'delete' in request.form:
                app.logger.info(f'Deleting item id={id}')  # pylint: disable=no-member
                item_store.remove_item(id)
            return redirect("/")

        return render_template('delete.html', item=item_store.get_item(id))

    def is_login_disabled():  # pylint: disable=unused-variable
        if ('LOGIN_DISABLED' in app.config):
            return app.config['LOGIN_DISABLED']
        return False

    return app
示例#23
0
def create_app():
    app = Flask(__name__)
    app.secret_key = os.environ.get('SECRET_KEY')
    app.config['LOGIN_DISABLED'] = os.environ.get(
        'LOGIN_DISABLED', 'False').lower() in ['true', '1']
    app.config['LOG_LEVEL'] = os.environ.get('LOG_LEVEL', 'INFO')
    app.config['LOGGLY_TOKEN'] = os.environ.get('LOGGLY_TOKEN')
    app.logger.setLevel(app.config['LOG_LEVEL'])
    login_manager.init_app(app)

    if app.config['LOGGLY_TOKEN'] is not None:
        handler = HTTPSHandler(
            f'https://logs-01.loggly.com/inputs/{app.config["LOGGLY_TOKEN"]}/tag/todo-app'
        )
        handler.setFormatter(
            Formatter(
                "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"))
        app.logger.addHandler(handler)

    @app.route('/')
    @login_required
    def index():
        alllistids = {'ToDo': 'ToDo', 'Doing': 'Doing', 'Done': 'Done'}
        items = get_todo_cards()
        item_view_model = ViewModel(items, alllistids)

        if not app.config['LOGIN_DISABLED']:
            if current_user.role == 'writer':
                app.logger.info("User with role Writer logged in")
                return render_template('index.html',
                                       view_model=item_view_model)
            elif current_user.role == 'reader':
                app.logger.info("User with role Reader logged in")
                return render_template('indexreadonly.html',
                                       view_model=item_view_model)
            else:
                app.logger.warning(
                    "User role not determined, defaulting to Read Only")
                return render_template('indexreadonly.html',
                                       view_model=item_view_model)
        else:
            return render_template('index.html', view_model=item_view_model)

    @app.route('/add_new', methods=['POST'])
    @login_required
    def addtolist():
        if 'LOGIN_DISABLED' in app.config or current_user.role == 'writer':
            newitemtitle = request.form.get('title')
            newitemdescription = request.form.get('desc')
            create_todo_card(newitemtitle, newitemdescription)
        return redirect(request.headers.get('Referer'))

    @app.route('/update', methods=['POST'])
    @login_required
    def movetolist():
        if 'LOGIN_DISABLED' in app.config or current_user.role == 'writer':
            allcards = get_todo_cards()
            lists = {'ToDo': 'ToDo', 'Doing': 'Doing', 'Done': 'Done'}
            for card in allcards:
                if request.form.get("inprogcheck_" + str(card.id)) == str(
                        card.id):
                    for l in lists:
                        if l == "Doing":
                            desired_list_id = l
                            move_todo_card(card.id, desired_list_id)
                            app.logger.info("Card %s moved to list %s",
                                            card.id, desired_list_id)
                if request.form.get("donecheck_" + str(card.id)) == str(
                        card.id):
                    for l in lists:
                        if l == "Done":
                            desired_list_id = l
                            move_todo_card(card.id, desired_list_id)
                            app.logger.info("Card %s moved to list %s",
                                            card.id, desired_list_id)
                if request.form.get("deletecheck_" + str(card.id)) == str(
                        card.id):
                    delete_todo_card(card.id)
                    app.logger.info("Card %s has been deleted", card.id)
        return redirect(request.headers.get('Referer'))

    @app.route('/show_older_done_items', methods=['POST'])
    @login_required
    def show_older_completed_items():
        if 'LOGIN_DISABLED' in app.config or current_user.role == 'writer':
            alllistids = {'ToDo': 'ToDo', 'Doing': 'Doing', 'Done': 'Done'}
            items = get_todo_cards()
            item_view_model = ViewModel(items, alllistids)
        return render_template('showolderitems.html',
                               view_model=item_view_model)

    @app.route('/login/callback')
    def login_callback():
        callback_code = request.args.get("code")
        github_client = WebApplicationClient(os.environ.get('GHOAUTHCLIENTID'))
        github_token = github_client.prepare_token_request(
            "https://github.com/login/oauth/access_token", code=callback_code)
        github_access = requests.post(
            github_token[0],
            headers=github_token[1],
            data=github_token[2],
            auth=(os.environ.get('GHOAUTHCLIENTID'),
                  os.environ.get('GHOAUTHCLIENTSECRET')))
        github_json = github_client.parse_request_body_response(
            github_access.text)
        github_user_request_param = github_client.add_token(
            "https://api.github.com/user")
        github_user = requests.get(
            github_user_request_param[0],
            headers=github_user_request_param[1]).json()

        login_user(User(github_user['login']))
        app.logger.info("Github User %s successfully logged in",
                        github_user['login'])
        return redirect('/')

    if __name__ == '__main__':
        app.run()

    return app