Example #1
1
def test_override_token_post():
    responses.add(responses.POST, "https://slack.com/api/chat.postMessage")

    app = Flask(__name__)
    slack_bp = make_slack_blueprint(
        client_id="foo", client_secret="bar",
        backend=MemoryBackend({"access_token": "abcde"}),
    )
    app.register_blueprint(slack_bp, url_prefix="/login")

    with app.test_request_context("/"):
        app.preprocess_request()
        resp = slack.post("chat.postMessage", data={
            "token": "xyz",
            "channel": "#general",
            "text": "ping",
            "icon_emoji": ":robot_face:",
        })
    request_data = url_decode(resp.request.body)
    assert request_data["token"] == "xyz"
    assert request_data["channel"] == "#general"
    assert request_data["text"] == "ping"
    assert request_data["icon_emoji"] == ":robot_face:"
    # should not be present
    url = URLObject(resp.request.url)
    assert "token" not in url.query_dict
Example #2
1
def test_auto_token_get():
    responses.add(responses.GET, "https://slack.com/api/chat.postMessage")

    app = Flask(__name__)
    slack_bp = make_slack_blueprint(
        client_id="foo", client_secret="bar",
        backend=MemoryBackend({"access_token": "abcde"}),
    )
    app.register_blueprint(slack_bp, url_prefix="/login")

    with app.test_request_context("/"):
        app.preprocess_request()
        resp = slack.get("chat.postMessage", data={
            "channel": "#general",
            "text": "ping",
            "icon_emoji": ":robot_face:",
        })
    request_data = url_decode(resp.request.body)
    assert request_data["channel"] == "#general"
    assert request_data["text"] == "ping"
    assert request_data["icon_emoji"] == ":robot_face:"
    # the `token` parameter should have been automatically added
    assert request_data["token"] == "abcde"
Example #3
0
def create_app(test_config=None):
    app = Flask(__name__, instance_relative_config=True)
    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/auth')
    app.secret_key = FLASK_SECRET_KEY

    login_blueprint = make_slack_blueprint(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        scope=['identity.basic,identity.team'],
        redirect_url='/auth')
    app.register_blueprint(login_blueprint, url_prefix='/login')
    app.register_blueprint(routes)
    return app

    @app.before_request
    def before_request():
        print('here')
        db.connect()

    @app.after_request
    def after_request(response):
        db.close()
        return response
Example #4
0
def test_override_token_post():
    responses.add(responses.POST, "https://slack.com/api/chat.postMessage")

    app = Flask(__name__)
    slack_bp = make_slack_blueprint(
        client_id="foo",
        client_secret="bar",
        backend=MemoryBackend({"access_token": "abcde"}),
    )
    app.register_blueprint(slack_bp, url_prefix="/login")

    with app.test_request_context("/"):
        app.preprocess_request()
        resp = slack.post("chat.postMessage",
                          data={
                              "token": "xyz",
                              "channel": "#general",
                              "text": "ping",
                              "icon_emoji": ":robot_face:",
                          })
    request_data = url_decode(resp.request.body)
    assert request_data["token"] == "xyz"
    assert request_data["channel"] == "#general"
    assert request_data["text"] == "ping"
    assert request_data["icon_emoji"] == ":robot_face:"
    # should not be present
    url = URLObject(resp.request.url)
    assert "token" not in url.query_dict
Example #5
0
def register_oauthhandlers(app):
    blueprint = None
    if not app.config["OAUTH_TYPE"]: return
    if app.config["OAUTH_TYPE"] == 'slack':
        blueprint = slack.make_slack_blueprint(
            client_id=app.config["OAUTH_ID"],
            client_secret=app.config["OAUTH_SECRET"],
            scope="identity.basic,identity.email",
            redirect_to="auth.slack_login",
            login_url="/login",
            # authorized_url=None,
            # session_class=None,
            # storage=None,
            subdomain=app.config["OAUTH_DOMAIN"],
        )
    elif app.config["OAUTH_TYPE"] == 'azure':
        blueprint = azure.make_azure_blueprint(
            client_id=app.config["OAUTH_ID"],
            client_secret=app.config["OAUTH_SECRET"],
            tenant=app.config["OAUTH_DOMAIN"],
            scope="profile email User.ReadBasic.All openid",
            redirect_to="auth.azure_login",
            login_url="/login",
        )
    elif app.config["OAUTH_TYPE"] == 'github':
        blueprint = github.make_github_blueprint(
            client_id=app.config["OAUTH_ID"],
            client_secret=app.config["OAUTH_SECRET"],
            # scope="user,read:user",
            redirect_to="auth.github_login",
            login_url="/login",
        )
    if blueprint is not None:
        app.register_blueprint(blueprint, url_prefix="/oauth")
Example #6
0
def test_auto_token_get():
    responses.add(responses.GET, "https://slack.com/api/chat.postMessage")

    app = Flask(__name__)
    slack_bp = make_slack_blueprint(
        client_id="foo",
        client_secret="bar",
        backend=MemoryBackend({"access_token": "abcde"}),
    )
    app.register_blueprint(slack_bp, url_prefix="/login")

    with app.test_request_context("/"):
        app.preprocess_request()
        resp = slack.get("chat.postMessage",
                         data={
                             "channel": "#general",
                             "text": "ping",
                             "icon_emoji": ":robot_face:",
                         })
    request_data = url_decode(resp.request.body)
    assert request_data["channel"] == "#general"
    assert request_data["text"] == "ping"
    assert request_data["icon_emoji"] == ":robot_face:"
    # the `token` parameter should have been automatically added
    assert request_data["token"] == "abcde"
Example #7
0
def configure_slack_auth(app):
    config = get_app_config()
    app.secret_key = config['secret_key']
    blueprint = make_slack_blueprint(
        client_id=config['client_id'],
        client_secret=config['client_secret'],
        scope=["identify", "chat:write:bot"],
    )
    app.register_blueprint(blueprint, url_prefix="/login")
Example #8
0
def test_blueprint_factory_with_subdomain():
    slack_bp = make_slack_blueprint(
        client_id="foo",
        client_secret="bar",
        scope=["identity", "im:write"],
        redirect_to="index",
        subdomain="my-team",
    )
    assert slack_bp.authorization_url == "https://my-team.slack.com/oauth/authorize"
    assert slack_bp.token_url == "https://slack.com/api/oauth.access"
Example #9
0
def test_load_from_config():
    app = Flask(__name__)
    app.secret_key = "anything"
    app.config["SLACK_OAUTH_CLIENT_ID"] = "foo"
    app.config["SLACK_OAUTH_CLIENT_SECRET"] = "bar"
    slack_bp = make_slack_blueprint(redirect_to="index")
    app.register_blueprint(slack_bp)

    resp = app.test_client().get("/slack")
    url = resp.headers["Location"]
    client_id = URLObject(url).query.dict.get("client_id")
    assert client_id == "foo"
Example #10
0
def test_load_from_config():
    app = Flask(__name__)
    app.secret_key = "anything"
    app.config["SLACK_OAUTH_CLIENT_ID"] = "foo"
    app.config["SLACK_OAUTH_CLIENT_SECRET"] = "bar"
    slack_bp = make_slack_blueprint(redirect_to="index")
    app.register_blueprint(slack_bp)

    resp = app.test_client().get("/slack")
    url = resp.headers["Location"]
    client_id = URLObject(url).query.dict.get("client_id")
    assert client_id == "foo"
Example #11
0
def test_context_local():
    responses.add(responses.GET, "https://slack.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    sbp1 = make_slack_blueprint(
        "foo1",
        "bar1",
        redirect_to="url1",
        backend=MemoryBackend({"access_token": "app1"}),
    )
    app1.register_blueprint(sbp1)

    app2 = Flask(__name__)
    sbp2 = make_slack_blueprint(
        "foo2",
        "bar2",
        redirect_to="url2",
        backend=MemoryBackend({"access_token": "app2"}),
    )
    app2.register_blueprint(sbp2)

    # outside of a request context, referencing functions on the `slack` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        slack.get("https://slack.com")

    # inside of a request context, `slack` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        slack.get("https://slack.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        slack.get("https://slack.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Example #12
0
def test_blueprint_factory():
    slack_bp = make_slack_blueprint(
        client_id="foo",
        client_secret="bar",
        scope=["identity", "im:write"],
        redirect_to="index",
    )
    assert isinstance(slack_bp, OAuth2ConsumerBlueprint)
    assert slack_bp.session.scope == ["identity", "im:write"]
    assert slack_bp.session.base_url == "https://slack.com/api/"
    assert slack_bp.session.client_id == "foo"
    assert slack_bp.client_secret == "bar"
    assert slack_bp.authorization_url == "https://slack.com/oauth/authorize"
    assert slack_bp.token_url == "https://slack.com/api/oauth.access"
Example #13
0
def test_blueprint_factory():
    slack_bp = make_slack_blueprint(
        client_id="foo",
        client_secret="bar",
        scope=["identity", "im:write"],
        redirect_to="index",
    )
    assert isinstance(slack_bp, OAuth2ConsumerBlueprint)
    assert slack_bp.session.scope == ["identity", "im:write"]
    assert slack_bp.session.base_url == "https://slack.com/api/"
    assert slack_bp.session.client_id == "foo"
    assert slack_bp.client_secret == "bar"
    assert slack_bp.authorization_url == "https://slack.com/oauth/authorize"
    assert slack_bp.token_url == "https://slack.com/api/oauth.access"
Example #14
0
def register_oauthhandlers(app):
    if app.config["OAUTH_TYPE"]:
        if app.config["OAUTH_TYPE"] == 'slack':
            blueprint = make_slack_blueprint(
                client_id=app.config["OAUTH_ID"],
                client_secret=app.config["OAUTH_SECRET"],
                subdomain=app.config["OAUTH_DOMAIN"],
                scope="identity.basic,identity.email",
                redirect_to="auth.slack_login",
                login_url="/login",
                # authorized_url=None,
                # session_class=None,
                # storage=None,
            )
            app.register_blueprint(blueprint, url_prefix="/oauth")
Example #15
0
def test_context_local():
    responses.add(responses.GET, "https://slack.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    sbp1 = make_slack_blueprint(
        "foo1", "bar1", redirect_to="url1",
        backend=MemoryBackend({"access_token": "app1"}),
    )
    app1.register_blueprint(sbp1)

    app2 = Flask(__name__)
    sbp2 = make_slack_blueprint(
        "foo2", "bar2", redirect_to="url2",
        backend=MemoryBackend({"access_token": "app2"}),
    )
    app2.register_blueprint(sbp2)

    # outside of a request context, referencing functions on the `slack` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        slack.get("https://slack.com")

    # inside of a request context, `slack` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        slack.get("https://slack.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        slack.get("https://slack.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Example #16
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    app.wsgi_app = ProxyFix(app.wsgi_app)
    app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/abc')
    app.secret_key = FLASK_SECRET_KEY

    app.register_blueprint(api)
    app.register_blueprint(make_slack_blueprint())
    app.register_blueprint(slack)
    app.register_blueprint(remote_controller)
    return app
from flask import Flask, render_template, request, redirect, url_for
from flask_pymongo import PyMongo
from flask_dance.contrib.slack import make_slack_blueprint, slack

app = Flask(__name__)
app.config['SECRET_KEY'] = 'linuxdegilgnulinux'
app.config[
    'MONGO_URI'] = "mongodb://*****:*****@myflask-shard-00-00-raeh0.mongodb.net:27017,myflask-shard-00-01-raeh0.mongodb.net:27017,myflask-shard-00-02-raeh0.mongodb.net:27017/test?ssl=true&replicaSet=myFlask-shard-0&authSource=admin&retryWrites=true&w=majority"

app.config["SLACK_OAUTH_CLIENT_ID"] = ''
app.config["SLACK_OAUTH_CLIENT_SECRET"] = ''
slack_bp = make_slack_blueprint(scope=["admin,identify,bot,incoming-webhook,channels:read,chat:write:bot,links:read"])
app.register_blueprint(slack_bp, url_prefix="/login")

mongo = PyMongo(app)


@app.route('/')
def home():
    return render_template("index.html")


@app.route('/create', methods=['POST'])
def create():
    if not slack.authorized:
        return redirect(url_for("slack.login"))
    resp = slack.post("chat.postMessage", data={
        "text": 'HeyBooster!',
        "channel": "#general",
        "icon_emoji": ":male-technologist:",
    })
Example #18
0
 def _make_app(*args, **kwargs):
     app = Flask(__name__)
     app.secret_key = "whatever"
     blueprint = make_slack_blueprint(*args, **kwargs)
     app.register_blueprint(blueprint)
     return app
Example #19
0
def get_app_config():
    path_to_yaml = join(HERE, '..', 'config.yaml')
    with open(path_to_yaml, 'r') as ymlfile:
        web = yaml.load(ymlfile).get('web')

    default = {'client_id': '', 'client_secret': '', 'secret_key': ''}
    return web or default


config = get_app_config()
app = Flask(__name__)
app.secret_key = config['secret_key']
blueprint = make_slack_blueprint(
    client_id=config['client_id'],
    client_secret=config['client_secret'],
    scope=["identify", "chat:write:bot"],
)
app.register_blueprint(blueprint, url_prefix="/login")


#### Routes ####

@app.route("/")
def index():
    if not slack.authorized:
        return redirect(url_for("slack.login"))
    context = {}
    return render_template('index.html', **context)

import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.slack import make_slack_blueprint, slack
from flask_sslify import SSLify
from raven.contrib.flask import Sentry

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
sslify = SSLify(app)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")
app.config["SLACK_OAUTH_CLIENT_ID"] = os.environ.get("SLACK_OAUTH_CLIENT_ID")
app.config["SLACK_OAUTH_CLIENT_SECRET"] = os.environ.get("SLACK_OAUTH_CLIENT_SECRET")
slack_bp = make_slack_blueprint(scope=["identify", "chat:write:bot"])
app.register_blueprint(slack_bp, url_prefix="/login")

@app.route("/")
def index():
    if not slack.authorized:
        return redirect(url_for("slack.login"))
    resp = slack.post("chat.postMessage", data={
        "channel": "#general",
        "text": "ping",
        "icon_emoji": ":robot_face:",
    })
    assert resp.ok, resp.text
    return resp.text

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