def test_local_strategy_extract_crendentials():
    class Local(LocalStrategy):
        def get_or_create_user(self, user: Dict) -> Dict:
            return super().get_or_create_user(user)

        def validate_credentials(self, username: str, password: str) -> Dict:
            return super().validate_credentials(username, password)

    # Create customs
    app = Flask("TESTS")
    app.secret_key = "630738a8-3b13-4311-8018-87554d6f7e85"
    Customs(app)

    # Create the strategy
    strategy = Local()

    with app.test_request_context("/?test=123", json={"bla": "bla"}):
        credentials = strategy.extract_credentials(request)
        assert credentials == {}

    with app.test_request_context("/?username=test&password=test"):
        credentials = strategy.extract_credentials(request)
        assert "username" in credentials
        assert "password" in credentials

    # Cleanup of the Customs object used for testing
    Customs.remove_instance()
def test_local_strategy_authenticate():
    class Local(LocalStrategy):
        def get_or_create_user(self, user: Dict) -> Dict:
            return super().get_or_create_user(user)

        def validate_credentials(self, username: str, password: str) -> Dict:
            return {}

    # Create customs
    app = Flask("TESTS")
    app.secret_key = "630738a8-3b13-4311-8018-87554d6f7e85"
    Customs(app)

    # Create the strategy
    strategy = Local()

    with app.test_request_context("/?test=123", json={"bla": "bla"}):

        with pytest.raises(UnauthorizedException):
            user = strategy.authenticate(request)

    with app.test_request_context("/?username=test&password=test"):
        user = strategy.authenticate(request)
        assert user == {}

    # Cleanup of the Customs object used for testing
    Customs.remove_instance()
Beispiel #3
0
def test_jwt_strategy_authenticate():
    class JWT(JWTStrategy):
        def get_or_create_user(self, user: Dict) -> Dict:
            return super().get_or_create_user(user)

    # Create customs
    app = Flask("TESTS")
    app.secret_key = "630738a8-3b13-4311-8018-87554d6f7e85"
    Customs(app)

    # Create the strategy
    strategy = JWT()

    with app.test_request_context("/?test=123", json={"bla": "bla"}):

        with pytest.raises(UnauthorizedException):
            user = strategy.authenticate(request)

    test_user = {}
    token = strategy.sign(test_user)

    with app.test_request_context("/",
                                  headers={"Authorization":
                                           f"Bearer {token}"}):
        user = strategy.authenticate(request)
        assert user == {}

    # Cleanup of the Customs object used for testing
    Customs.remove_instance()
def test_basic_strategy_authenticate():
    class Basic(BasicStrategy):
        def get_or_create_user(self, user: Dict) -> Dict:
            return {}

        def validate_credentials(self, username: str, password: str) -> Dict:
            return {}

    # Create customs
    app = Flask("TESTS")
    app.secret_key = "630738a8-3b13-4311-8018-87554d6f7e85"
    Customs(app)

    # Create the strategy
    strategy = Basic()

    with app.test_request_context("/?test=123", json={"bla": "bla"}):

        with pytest.raises(UnauthorizedException):
            user = strategy.authenticate(request)

    with app.test_request_context(
            "/",
            headers={
                "Authorization":
                "Basic %s" % base64.b64encode("test:test".encode()).decode()
            },
    ):
        user = strategy.authenticate(request)
        assert user == {}

    # Cleanup of the Customs object used for testing
    Customs.remove_instance()
Beispiel #5
0
def test_jwt_strategy_initialization_with_customs():
    class JWT(JWTStrategy):
        def get_or_create_user(self, user: Dict) -> Dict:
            return super().get_or_create_user(user)

    # Create customs
    app = Flask("TESTS")
    app.secret_key = "630738a8-3b13-4311-8018-87554d6f7e85"
    Customs(app)

    # Create the strategy
    strategy = JWT()

    assert strategy.name == "jwt"

    # Cleanup of the Customs object used for testing
    Customs.remove_instance()
def test_local_strategy_initialization_with_customs():
    class Local(LocalStrategy):
        def get_or_create_user(self, user: Dict) -> Dict:
            return super().get_or_create_user(user)

        def validate_credentials(self, username: str, password: str) -> Dict:
            return super().validate_credentials(username, password)

    # Create customs
    app = Flask("TESTS")
    app.secret_key = "630738a8-3b13-4311-8018-87554d6f7e85"
    Customs(app)

    # Create the strategy
    strategy = Local()

    assert strategy.name == "local"

    # Cleanup of the Customs object used for testing
    Customs.remove_instance()
        for k, v in self._id_rules.items():
            for id in v:
                self.result[k].add(nodes[id])

        # Collect by predicate
        for n in nodes.values():
            for label, predicates in self._predicate_rules.items():
                for predicate in predicates:
                    if predicate(n):
                        self.result[label].add(n)

    def print(self):
        for k, v in self.result.items():
            print(f"{k}:")
            for name in sorted([x.name for x in v]):
                print(f"    {name}")


c = Customs('case_100', FileType.PICKLE)
c.read()
c.translate()

cl = Classifier()
cl.add_id("specific", 9775968)
cl.add_id("specific", [9775967, 9775965])
cl.add_rule("py-files", lambda x: x.extension == "py")
cl.add_rule("big-files", lambda x: x.size > 10000)

cl.classify(c.id_dict)
cl.print()
Beispiel #8
0
from typing import Dict
from flask import Flask
from flask.json import jsonify

from customs import Customs
from customs.strategies import BasicStrategy
from customs.exceptions import UnauthorizedException

# Create the Flask app, and a secret for encrypting sessions
app = Flask(__name__)
app.secret_key = "541e8467-2321-4df9-8246-25b55dca3466"

# Create customs to protect the app, use sessions to keep users logged in across requests
customs = Customs(app, use_sessions=True)

# Mock database
DATABASE = {"admin": {"name": "Administrator User", "password": "******"}}


class BasicAuthentication(BasicStrategy):
    def get_or_create_user(self, user: Dict) -> Dict:
        if user.get("username") in DATABASE:
            return DATABASE[user["username"]]
        else:
            raise UnauthorizedException()

    def validate_credentials(self, username: str, password: str) -> Dict:
        if username in DATABASE and DATABASE[username].get(
                "password") == password:
            return DATABASE[username]
        else:
Beispiel #9
0
import os
import sys

from typing import Dict
from flask import Flask
from flask.templating import render_template

from customs import Customs
from customs.helpers import set_redirect_url

# Create the Flask app
app = Flask(__name__)
app.secret_key = "d2cc6f0a-0d9e-414c-a3ca-6b75455d6332"

# Create customs to protect the app, no need for sessions as we're using JWT tokens
customs = Customs(app, unauthorized_redirect_url="/login")

# Mock in-memory database (NOTE: Will forget everything on restart!)
DATABASE: Dict[str, Dict] = {}

# Import strategies from other examples
sys.path.insert(0,
                os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from google.main import google  # noqa
from github.main import github  # noqa

# ----------------------- #
# Define some open routes #
# ----------------------- #
Beispiel #10
0
from typing import Dict
from flask import Flask, Blueprint
from flask.json import jsonify

from customs import Customs
from customs.strategies import BasicStrategy, JWTStrategy
from customs.exceptions import UnauthorizedException

# Create the Flask app
app = Flask(__name__)

# Create customs to protect the app, no need for sessions as we're using JWT tokens
customs = Customs(app, use_sessions=False)

# Mock database
DATABASE: Dict[str, Dict] = {
    "admin": {"name": "Administrator User", "password": "******"}
}


class BasicAuthentication(BasicStrategy):
    def get_or_create_user(self, user: Dict) -> Dict:
        if user.get("username") in DATABASE:
            return DATABASE[user["username"]]
        else:
            raise UnauthorizedException()

    def validate_credentials(self, username: str, password: str) -> Dict:
        if username in DATABASE and DATABASE[username].get("password") == password:
            return DATABASE[username]
        else: