Esempio n. 1
0
def test_retrieve_refresh_token_ommitted():
    app = Sanic()
    app.config.SANIC_JWT_REFRESH_TOKEN_ENABLED = True

    with pytest.raises(exceptions.RefreshTokenNotImplemented):
        initialize(app,
                   authenticate=lambda: True,
                   store_refresh_token=lambda: True)
Esempio n. 2
0
def test_retrieve_refresh_token_ommitted():
    app = Sanic("sanic-jwt-test")

    with pytest.raises(exceptions.RefreshTokenNotImplemented):
        initialize(app,
                   authenticate=lambda: True,
                   refresh_token_enabled=True,
                   store_refresh_token=lambda: True)
Esempio n. 3
0
def test_configuration_initialize_method_default():
    try:
        app = Sanic()
        initialize(
            app,
            authenticate=lambda: True,
        )
    except Exception as e:
        pytest.fail('Raised exception: {}'.format(e))
Esempio n. 4
0
def test_invalid_classview():
    app = Sanic("sanic-jwt-test")

    class NotAView(object):
        pass

    with pytest.raises(exceptions.InvalidClassViewsFormat):
        initialize(app,
                   authenticate=lambda: True,
                   class_views=[(object, NotAView)])
Esempio n. 5
0
def start(port,
          site=None,
          username='******',
          password='******'):
    app.site = site
    users.append(User(2, username, password))
    initialize(app, authenticate=authenticate)
    return app.create_server(host="0.0.0.0",
                             port=port,
                             access_log=True)
Esempio n. 6
0
def test_store_refresh_token_and_retrieve_refresh_token_defined():
    app = Sanic("sanic-jwt-test")
    app.config.SANIC_JWT_REFRESH_TOKEN_ENABLED = True

    initialize(
        app,
        authenticate=lambda: True,
        store_refresh_token=lambda: True,
        retrieve_refresh_token=lambda: True,
    )

    assert True
Esempio n. 7
0
def create_app():

    app = Sanic(name='Normalizer')
    initialize(app, authenticate=authenticate)

    # Regex to search for "val", case insensitive
    r = re.compile(r'.*val.*', flags=re.IGNORECASE)

    @app.post('/normalize')
    @protected()
    def normalize(request: Request):
        return json(
            {d['name']: d[next(filter(r.match, d))]
             for d in request.json})

    return app
Esempio n. 8
0
def app():
    app = Sanic(__name__)
    app.config.SANIC_JWT_AUTHORIZATION_HEADER_PREFIX = "JWT"
    app.config.SANIC_JWT_EXPIRATION_DELTA = 360000
    app.config.SANIC_JWT_USER_ID = "username"

    sanicjwt = initialize(app, authentication_class=CustomAuth)
    app.blueprint(bp)

    return app, sanicjwt
Esempio n. 9
0
def initialize_authentication(app: Sanic) -> Sanic:
    """
    initialize authentication
    :param app: Sanic
    :return app: Sanic
    """
    # initialize(app, authenticate=authenticate)
    initialize(
        app,
        authentication_class=MyAuthentication,
        responses_class=MyResponses,
        add_scopes_to_payload=my_scope_extender,
        scopes_enabled=True,
        expiration_delta=EXPIRE_TIME,
        refresh_token_enabled=True,
        claim_nbf=True,
        claim_nbf_delta=1,  # 偏移量
        leeway=1  # 应用程序将用于解决系统时间配置中的细微变化的时间
    )
    return app
Esempio n. 10
0
def init_auth(sanic_app, secret="This is big secret, set me in app.yaml"):
    """
    Initiate sanic-jwt module

    Copyright (C) 2020 Mikhail Marenov - All Rights Reserved
    You MAY NOT CHANGE source code of Ax workflow without writen permission
    author. If you change source code in order to activate PRO features -
    YOU MAY BE SUBJECT TO HEAVY CIVIL PENALTIES. THESE INCLUDE MONETARY
    DAMAGES, COURT COSTS, AND ATTORNEYS FEES INCURRED
    Please read LICENSE.md for more information.
    """

    delta = 60  # seconds
    initialize(sanic_app,
               authenticate=authenticate,
               configuration_class=AxConfiguration,
               refresh_token_enabled=True,
               store_refresh_token=store_refresh_token,
               retrieve_refresh_token=retrieve_refresh_token,
               retrieve_user=retrieve_user,
               expiration_delta=delta,
               cookie_access_token_name='ax_auth',
               cookie_set=True,
               cookie_strict=False,
               login_redirect_url='/signin',
               secret=secret)

    with ax_model.scoped_session("init_auth - ERROR") as db_session:
        apply_lise(db_session)

        # Write cache form Everyone group
        asyncio.get_event_loop().run_until_complete(write_perm_cache(
            db_session=db_session, user_guid=None))

        # Write cache for dynamic roles
        asyncio.get_event_loop().run_until_complete(write_dynamic_roles_cache(
            db_session=db_session))
Esempio n. 11
0
    user = await User.find_one({"username": username})
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user


async def setup_movie_index(app, loop):
    data = json.load(open("scripts/imdb.json", "r"))
    await Movie.insert_many(data)
    await Movie.create_index([('name', pymongo.TEXT)], name='search_index')
    print(data)
    pass


async def scope_extender(user, *args, **kwargs):
    print(user)
    return [user.role,]


if __name__ == "__main__":
    # app.register_listener(setup_movie_index,
    #                       'before_server_start')
    initialize(app, authenticate=authenticate,add_scopes_to_payload=scope_extender)
    app.blueprint(users)
    app.blueprint(movies)
    app.run(host="0.0.0.0", port=8000, debug=True)
Esempio n. 12
0
initialize(
    app,
    authenticate=authenticate,
    # refresh_token_enabled=True,
    # store_refresh_token=store_refresh_token,
    # retrieve_refresh_token=retrieve_refresh_token,
    url_prefix='/v1/api/authentication',
    secret='fgkjhfkhgkfhkghfjdkgher5545458fjighui',
    # verify_exp = False,

    ## 标头令牌
    authorization_header='Authorization',
    authorization_header_prefix='Bearer',
    # Cookie令牌
    # cookie_domain - 更改与cooke关联的域(默认为'')
    # cookie_httponly - 是否在cookie上设置httponly标志(默认为True) 如果你是使用Cookie来传递JWTs,那么建议您不要不禁用cookie_httponly。这样做意味着客户端上运行的任何javascript都可以访问令牌。
    # cookie_access_token_name - 为访问令牌存储cookie的名称
    # cookie_refresh_token_name - 存储用于刷新令牌的cookie的名称
    cookie_set=True,
    # cookie_domain='mydomain.com',
    cookie_httponly=False,
    cookie_access_token_name='some-token',
    cookie_strict=False,


    # 设置过期时间, 默认30分钟
    # 访问令牌有效的时间长度。由于无法撤销访问令牌,因此建议将此时间段保持为短,并启用刷新令牌(可以撤销)以检索新的访问令牌。
    # 设置为一分钟
    expiration_delta=60,
)
Esempio n. 13
0
#
#
# class MyResponses(Responses):
#
#     @staticmethod
#     def exception_response(request, exception):
#         exception_message = str(exception)
#         return json({
#             'error': True,
#             'message': f'You encountered an exception: {exception_message}'
#         }, status=exception.status_code)

i = initialize(
    app,
    refresh_token_enabled=True,
    expiration_delta=EXPIRATION_DELTA,
    url_prefix="/api_user/v1/auth",
    class_views=(
        ('/register', Register),
        # ("/check_phone", CheckRegisteredParm),
        ("/login", MyAuthenticateEndpoint),
        ("/logout", LogoutEndpoint),
        ("/refresh_token", MyRefreshEndpoint),
        ("/captcha", Captcha)),
    authentication_class=MyAuthentication,
    # cookie_domain="sendMe.com",
)
if __name__ == "__main__":
    # app.run(host="0.0.0.0", port=9999)
    app.run(host="0.0.0.0", port=9999, debug=True)
Esempio n. 14
0
def test_initialize_compat():
    app = Sanic("sanic-jwt-test")

    initialize(app, lambda: True)

    assert True
Esempio n. 15
0
from sanic_jwt import initialize

from app import create_app
from app.users.auth import authenticate, retrieve_user, extend_payload, store_refresh_token, retrieve_refresh_token

app = create_app()
initialize(app,
           url_prefix='/token',
           authenticate=authenticate,
           retrieve_user=retrieve_user,
           extend_payload=extend_payload,
           refresh_token_enabled=True,
           store_refresh_token=store_refresh_token,
           retrieve_refresh_token=retrieve_refresh_token)

if __name__ == "__main__":
    HOST, PORT, DEBUG = app.config['HOST'], app.config['PORT'], app.config[
        'DEBUG']
    app.run(host=HOST, port=PORT, debug=DEBUG)
async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user


app = Sanic(__name__)
# initialize(app, authenticate=authenticate, cookie_set=True)
initialize(
    app,
    authenticate=authenticate,
    cookie_set=True,
    path_to_retrieve_user='******',
    path_to_verify='/my_verify',
    path_to_refresh='/my_refresh',
)

if __name__ == "__main__":
    app.run(port=8888)
Esempio n. 17
0
def test_configuration_initialize_method_default():
    try:
        app = Sanic("sanic-jwt-test")
        initialize(app, authenticate=lambda: True)
    except Exception as e:
        pytest.fail("Raised exception: {}".format(e))
Esempio n. 18
0
def test_initialize_compat():
    app = Sanic()

    initialize(app, lambda: True)

    assert True
Esempio n. 19
0

async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user


app = Sanic()
initialize(
    app,
    authenticate=authenticate,
    cookie_set=True,
    cookie_split=True,
)


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8888)
Esempio n. 20
0
from sanic import Sanic
from sanic.request import Request
from sanic.response import json
from sanic_jwt import initialize
from sanic_restful import Api

from src.auth import authenticate
from src.definitions import ApiError, BadRequestError
from src.resources import PolyDataResource, PolyDataResourceList

app = Sanic("Polyrize Interview Server")
api = Api(app)
initialize(app, authenticate=authenticate, url_prefix="/api/auth")


def build_error_response(message, status_code, error_code, **kwargs):
    return json({
        "error": error_code,
        "message": message,
        **kwargs
    },
                status=status_code)


# Handle exceptions
@app.exception(Exception)
def handle_error(request: Request, e):
    if isinstance(e, ApiError):
        return build_error_response(message=e.message,
                                    status_code=e.status_code,
                                    error_code=e.error_code)
Esempio n. 21
0
from sanic import Sanic
from sanic.response import json

from sanic_jwt import initialize
from sanic_jwt.decorators import scoped

app = Sanic("sanic-jwt-test")
initialize(app, authenticate=lambda: True)


@app.route("/scoped_empty")
@scoped("something")
async def scoped(request):
    return json({"scoped": True})


class TestEndpointsScoped(object):
    def test_scoped_empty(self):
        _, response = app.test_client.get("/scoped_empty")
        assert response.status == 401
        assert response.json.get("exception") == "Unauthorized"
        assert "Authorization header not present." in response.json.get(
            "reasons")
Esempio n. 22
0
from sanic import Sanic
from sanic.response import json
from sanic.views import HTTPMethodView
from sanic_jwt import exceptions
from sanic_jwt import initialize
from sanic_jwt import protected

from api import api

from auth import authenticate, retrieve_user

current_api_version = 1
app = Sanic(__file__)

app.blueprint(api, version=current_api_version)

initialize(app,
           authenticate=authenticate,
           retrieve_user=retrieve_user,
           url_prefix=f'/v{current_api_version}/api/auth')

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8888)
Esempio n. 23
0
    async def options(self, request):
        return response.text("", status=204)

    async def post(self, request):
        # create a magic login token and email it to the user

        response = {"magic-token": "123456789"}
        return json(response)


app = Sanic()
initialize(
    app,
    authenticate=lambda: True,
    class_views=[(
        "/magic-login",
        MagicLoginHandler,
    )  # The path will be relative to the url prefix
                 # (which defaults to /auth)
                 ],
)


class TestEndpointsExtra(object):
    def dispatch(self, path, method):
        method = getattr(app.test_client, method)
        request, response = method(path)
        return request, response

    def get(self, path):
        return self.dispatch(path, "get")
Esempio n. 24
0
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user


app = Sanic(name='bluefin')
sanic_jwt = initialize(app, authenticate=authenticate,
           expiration_delta=(60 * 60),
           secret=secret,
           retrieve_user=retrieve_user,
           )

# .......

@app.route("/hello")
async def test(request):
    return json({"hello": "world"})


@app.route("/protected")
@protected()
async def protected(request):
    return json({"protected": True})
Esempio n. 25
0
    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user


app = Sanic()
initialize(
    app,
    authenticate=authenticate,
    store_refresh_token=store_refresh_token,
    retrieve_refresh_token=retrieve_refresh_token,
    retrieve_user=retrieve_user,
)
app.config.SANIC_JWT_REFRESH_TOKEN_ENABLED = True
app.config.SANIC_JWT_CLAIM_ISS = 'foo:bar'
app.config.SANIC_JWT_CLAIM_IAT = True
app.config.SANIC_JWT_CLAIM_NBF = True
app.config.SANIC_JWT_CLAIM_AUD = 'bar:foo'


class User(object):
    def __init__(self, id, username, password):
        setattr(self, 'user_id', id)
        self.username = username
        self.password = password
Esempio n. 26
0
    result = await logic.auth_user(username, password)
    result = j.loads(result)['result']

    if result['status'] == "failed":
        raise exceptions.AuthenticationFailed("User not found.")
    elif result['status'] == "success":
        if result['auth'] == True:
            user = User(user_id=username, username=username, password=password)
            return user
        else:
            raise exceptions.AuthenticationFailed("Password is incorrect")


app = Sanic()
initialize(app,
           authenticate=authenticate,
           url_prefix="/api/auth",
           secret="secret")
CORS(app)


@app.route("/", methods=['GET', 'POST', 'OPTIONS'])
@protected()
async def test(request):
    # print(jwt_decode(request.headers['authorization'][7:], "secret"))
    print(request.json)
    return json({"Neko": "Gram!"})


@app.route("/api/register", methods=["GET"])
async def register(request):
    template = env.get_template('register.html')
Esempio n. 27
0

async def authenticate(request, *args, **kwargs):
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = username_table.get(username, None)
    if user is None:
        raise exceptions.AuthenticationFailed("User not found.")

    if password != user.password:
        raise exceptions.AuthenticationFailed("Password is incorrect.")

    return user


app = Sanic()
initialize(
    app,
    authenticate=authenticate,
    public_key=public_key,
    private_key=private_key,
    algorithm="RS256",
)  # or RS384 or RS512

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8888)
Esempio n. 28
0
    return json(response, 401)


@app.exception(UserDeleteException)
async def delete_user_exceptin_handle(request, exception):
    response = {
        "reasons": [str(exception)],
        "exception": StatusCode.DELETE_USER_FAILED.name
    }

    return json(response, 401)


initialize(app,
           authenticate=authenticate,
           retrieve_user=retrieve_user,
           url_prefix='/v1/api/auth')


def load_banner():
    """load the banner"""
    with open('banner.txt', 'r', encoding='utf-8') as f:
        banner = f.read()

    print(banner)


app.blueprint(user_route)
if __name__ == '__main__':
    load_banner()
    port = int(Config.get_instance().get('http.port', 80))
Esempio n. 29
0
    password = request.json.get("password", None)

    if not username or not password:
        raise exceptions.AuthenticationFailed("Missing username or password.")

    user = await User.find_one({
        "username": username,
        "password": hash_password(password)
    })
    if user is None:
        raise exceptions.AuthenticationFailed("Credentials aren't valid")

    return JWTUser(str(user["_id"]), user["username"], user["password"])


initialize(app, authenticate=authenticate)


class PostsView(HTTPMethodView):
    decorators = [protected()]

    async def post(self, request: Request):
        title = request.json.get("title")
        if title is None or not title:
            abort(400, "'title' is required")
        now = time.time()
        post = await Post.insert_one({"title": title, "createdAt": now})
        return json({
            "title": title,
            "createdAt": now,
            "id": str(post.inserted_id)
Esempio n. 30
0
async def retrieve_user(request, payload, *args, **kwargs):
    if payload:
        user_id = payload.get('user_id', None)
        if user_id is not None:
            return userid_table.get('user_id')
    else:
        return None


async def my_scope_extender(user, *args, **kwargs):
    return user.scopes


app = Sanic()
app.config.SANIC_JWT_HANDLER_PAYLOAD_SCOPES = my_scope_extender
initialize(app, authenticate=authenticate, retrieve_user=retrieve_user)
# initialize(app, authenticate=authenticate, retrieve_user=retrieve_user, add_scopes_to_payload=my_scope_extender)


@app.route("/")
async def test(request):
    return json({"hello": "world"})


@app.route("/protected")
@protected()
async def protected_route(request):
    return json({"protected": True, "scoped": False})


@app.route("/protected/scoped/1")