Exemplo n.º 1
0
def auth(provider):
    """Auth redirect URL"""
    if not connexion.request.args.get("code"):
        return "Bad request", 400
    code = connexion.request.args["code"]
    frontend_url = build_url(
        current_app.config.get("FRONTEND_URL", "http://localhost:3000"),
        "login")
    provider_config = _get_provider_config(provider)
    user = _get_user_from_provider(provider, provider_config, code)
    if not user:
        return "Unauthorized", 401
    jwt_token = generate_token(user.id)
    token = _find_or_create_token("login-token", user)
    token.token = jwt_token
    session.add(token)
    session.commit()
    if provider == "keycloak":
        query_params = urlencode({
            "email": user.email,
            "name": user.name,
            "token": jwt_token
        })
        return redirect(f"{frontend_url}?{query_params}")
    elif provider == "google":
        return {"email": user.email, "name": user.name, "token": jwt_token}
    else:
        return make_response(
            AUTH_WINDOW.format(data=json.dumps({
                "email": user.email,
                "name": user.name,
                "token": jwt_token
            })))
Exemplo n.º 2
0
def get_keycloak_config(is_private=False):
    """Return the configuration for a keycloak provider"""
    if not current_app.config.get(
            "KEYCLOAK_CLIENT_ID") or not current_app.config.get(
                "KEYCLOAK_BASE_URL"):
        return {}
    backend_url = current_app.config.get("BACKEND_URL",
                                         "http://localhost:8080/api")
    if not backend_url.endswith("/api"):
        backend_url += "/api"
    server_url = current_app.config.get("KEYCLOAK_BASE_URL")
    if not server_url.endswith("auth"):
        server_url = build_url(server_url, "auth")
    realm = current_app.config.get("KEYCLOAK_REALM")
    realm_base_url = build_url(server_url, "realms", realm)
    config = {
        "server_url":
        server_url,
        "authorization_url":
        build_url(realm_base_url, "protocol/openid-connect/auth"),
        "realm":
        realm,
        "client_id":
        current_app.config.get("KEYCLOAK_CLIENT_ID"),
        "redirect_uri":
        backend_url + "/login/auth/keycloak",
    }
    if current_app.config.get("KEYCLOAK_ICON"):
        config["icon"] = current_app.config["KEYCLOAK_ICON"]
    if current_app.config.get("KEYCLOAK_NAME"):
        config["display_name"] = current_app.config["KEYCLOAK_NAME"]
    if is_private:
        config["user_url"] = build_url(realm_base_url,
                                       "protocol/openid-connect/userinfo")
        config["token_url"] = build_url(realm_base_url,
                                        "protocol/openid-connect/token")
    return config
Exemplo n.º 3
0
def register(email=None, password=None):
    """Register a user

    :param email: The e-mail address of the user
    :type email: str
    :param password: The password for the user
    :type password: str
    """
    if not connexion.request.is_json:
        return "Bad request, JSON is required", 400
    details = connexion.request.get_json()
    if not details.get("email") or not details.get("password"):
        return {
            "code": "EMPTY",
            "message": "Username and/or password are empty"
        }, 401

    # Create a random activation code. Base64 just for funsies
    activation_code = urlsafe_b64encode(str(
        uuid4()).encode("utf8")).strip(b"=").decode()
    # Create a user
    user = User(email=details["email"],
                password=details["password"],
                activation_code=activation_code)
    session.add(user)
    session.commit()

    # Send an activation e-mail
    activation_url = build_url(
        current_app.config.get("BACKEND_URL", "http://localhost:8080/"),
        "api",
        "login",
        "activate",
        activation_code,
    )
    mail = current_app.extensions.get("mail")
    if mail and hasattr(mail, "state") and mail.state is not None:
        mail.send_message(
            "[Ibutsu] Registration Confirmation",
            recipients=[email],
            body=ACTIVATION_EMAIL.format(activation_url=activation_url),
        )
    else:
        print(
            f"No e-mail configuration. Email: {email} - activation URL: {activation_url}"
        )
    return {}, 201
Exemplo n.º 4
0
def activate(activation_code=None):
    """Activate a user's account

    :param activation_code: The activation code
    """
    if not activation_code:
        return "Not Found", 404
    user = User.query.filter(User.activation_code == activation_code).first()
    login_url = build_url(
        current_app.config.get("FRONTEND_URL", "http://localhost:3000"),
        "login")
    if user:
        user.is_active = True
        user.activation_code = None
        session.add(user)
        session.commit()
        return redirect(
            f"{login_url}?st=success&msg=Account+activated,+please+log+in.")
    else:
        return redirect(
            f"{login_url}?st=error&msg=Invalid+activation+code,+please+check+the+link"
            "+in+your+email.")
Exemplo n.º 5
0
def get_provider_config(provider, is_private=False):
    """Return the customised config for a provider"""
    backend_url = current_app.config.get("BACKEND_URL",
                                         "http://localhost:8080/api")
    provider_upper = provider.upper()
    server_url = current_app.config.get(f"{provider_upper}_BASE_URL")
    provider_config = OAUTH_CONFIG.get(provider, {})
    config = {
        "redirect_uri":
        backend_url + f"/login/auth/{provider}",
        "scope":
        provider_config.get("sep", " ").join(provider_config.get("scope", [])),
    }
    if provider == "facebook":
        config["app_id"] = current_app.config.get("FACEBOOK_APP_ID")
    else:
        config["client_id"] = current_app.config.get(
            f"{provider_upper}_CLIENT_ID")
    if current_app.config.get(f"{provider_upper}_AUTH_URL"):
        config["authorization_url"] = build_url(
            server_url, current_app.config.get(f"{provider_upper}_AUTH_URL"))
    elif provider_config.get("auth_url"):
        config["authorization_url"] = build_url(server_url,
                                                provider_config["auth_url"])
    if is_private:
        config["client_secret"] = current_app.config.get(
            f"{provider_upper}_CLIENT_SECRET")
        config["user_url"] = build_url(server_url,
                                       provider_config.get("user_url"))
        if current_app.config.get(f"{provider_upper}_TOKEN_URL"):
            config["token_url"] = build_url(
                server_url,
                current_app.config.get(f"{provider_upper}_TOKEN_URL"))
        elif provider_config.get("token_url"):
            config["token_url"] = build_url(server_url,
                                            provider_config["token_url"])
        if provider_config.get("email_url"):
            config["email_url"] = build_url(server_url,
                                            provider_config["email_url"])
    return config