Exemplo n.º 1
0
async def run(token_data, payload):
    # Payload : {
    #   'new_password': '******',
    # }
    container = get_current_container()
    user_folders = await container.async_get("users")

    data = {}

    valid_data = ["username", "email", "name", "password", "properties"]

    for key in valid_data:
        if key in token_data:
            data[key] = token_data[key]

    user = await create_content_in_container(
        user_folders,
        "User",
        token_data.get("username", token_data.get("id")),
        creators=(token_data.get("username", token_data.get("id")),),
        check_security=False,
        **data,
    )
    user.user_roles = ["guillotina.Member"]
    await notify(ObjectAddedEvent(user))

    jwt_token, data = authenticate_user(user.id, timeout=app_settings["jwt"]["token_expiration"])
    await notify(UserLogin(user, jwt_token))

    return {"exp": data["exp"], "token": jwt_token}
Exemplo n.º 2
0
    async def __call__(self):
        data = await self.request.json()
        creds = {
            'type': 'basic',
            'token': data['password'],
            'id': data.get('username', data.get('login'))
        }

        for validator in app_settings['auth_token_validators']:
            if (validator.for_validators is not None and
                    'basic' not in validator.for_validators):
                continue
            user = await validator(self.request).validate(creds)
            if user is not None:
                break

        if user is None:
            raise HTTPUnauthorized(content={
                'text': 'login failed'
            })

        jwt_token, data = authenticate_user(user.id)
        await notify(UserLogin(user, jwt_token))

        return {
            'exp': data['exp'],
            'token': jwt_token
        }
Exemplo n.º 3
0
    async def __call__(self):
        data = await self.request.json()
        creds = {"type": "basic", "token": data["password"], "id": data.get("username", data.get("login"))}

        for validator in app_settings["auth_token_validators"]:
            if validator.for_validators is not None and "basic" not in validator.for_validators:
                continue
            user = await validator().validate(creds)
            if user is not None:
                break

        if user is None:
            raise HTTPUnauthorized(content={"text": "login failed"})

        session_manager = query_utility(ISessionManagerUtility)
        if session_manager is not None:
            data = json.dumps(dict(self.request.headers))
            session = await session_manager.new_session(user.id, data=data)
            data = {"session": session}
        else:
            data = {}

        jwt_token, data = authenticate_user(
            user.id, timeout=app_settings["jwt"]["token_expiration"], data=data
        )
        await notify(UserLogin(user, jwt_token))

        return {"exp": data["exp"], "token": jwt_token}
Exemplo n.º 4
0
async def run(token_data, payload):
    user_to_change_password = token_data["v_user"]
    user = await find_user({"id": user_to_change_password})

    await user.set_password(payload.get("password", None))

    jwt_token, data = authenticate_user(
        user.id, timeout=app_settings["jwt"]["token_expiration"])
    await notify(UserLogin(user, jwt_token))

    return {"exp": data["exp"], "token": jwt_token}
Exemplo n.º 5
0
    async def __call__(self):
        data = await self.request.json()
        creds = {"type": "basic", "token": data["password"], "id": data.get("username", data.get("login"))}

        for validator in app_settings["auth_token_validators"]:
            if validator.for_validators is not None and "basic" not in validator.for_validators:
                continue
            user = await validator().validate(creds)
            if user is not None:
                break

        if user is None:
            raise HTTPUnauthorized(content={"text": "login failed"})

        jwt_token, data = authenticate_user(user.id)
        await notify(UserLogin(user, jwt_token))

        return {"exp": data["exp"], "token": jwt_token}
async def run(token_data, payload):
    util = get_utility(ILDAPUsers)

    try:
        await util.add_user(token_data["id"], token_data.get("fullname", ""))
    except bonsai.AlreadyExists:
        pass

    if "password" in token_data:
        await util.set_password(token_data["id"], token_data['password'])
    elif "password" in payload:
        await util.set_password(token_data["id"], payload['password'])

    user = util.create_g_user(token_data['id'], token_data.get("fullname", ""))

    jwt_token, data = authenticate_user(
        user.id, timeout=app_settings["jwt"]["token_expiration"])
    await notify(UserLogin(user, jwt_token))

    return {"exp": data["exp"], "token": jwt_token}
async def auth_callback(context, request):
    provider = request.matchdict['provider']

    if provider in utils.oauth1_providers:
        oauth_verifier = request.url.query.get('oauth_verifier')
        oauth_token = request.url.query.get('oauth_token')
        client = utils.get_client(provider, oauth_token=oauth_token)
        cache_utility = get_utility(ICacheUtility)
        request_token = await cache_utility.get(CACHE_PREFIX + oauth_token)
        if request_token is None:
            raise web.HTTPBadRequest(
                reason='Failed to obtain proper request token.')
        oauth_token, oauth_token_secret, otoken_data = await client.get_access_token(  # noqa
            oauth_verifier, oauth_token)

        client_args = dict(oauth_token=oauth_token,
                           oauth_token_secret=oauth_token_secret)
    else:
        client = utils.get_client(provider)
        if 'error' in request.url.query:
            raise HTTPBadRequest(content=dict(request.url.query))

        if 'code' not in request.url.query:
            raise HTTPBadRequest(content=dict(request.url.query))

        code = request.url.query['code']

        if 'callback' not in request.url.query:
            callback = str(request.url.with_path('@callback/' + provider))
        else:
            callback = request.url.query['callback']

        forwarded_proto = request.headers.get('X-Forwarded-Proto', None)
        if forwarded_proto and forwarded_proto != request.scheme:
            callback = callback.replace(request.scheme + '://',
                                        forwarded_proto + '://')

        otoken, otoken_data = await client.get_access_token(
            code, redirect_uri=callback)

        client_args = dict(access_token=otoken,
                           refresh_token=otoken_data['refresh_token'])

    if 'expires_in' in otoken_data:
        timeout = otoken_data['expires_in']
    else:
        timeout = 60 * 60 * 1

    client = utils.get_client(provider, **client_args)
    user, user_data = await client.user_info()

    jwt_token, data = authenticate_user(
        user.id, {
            'first_name': user.first_name,
            'last_name': user.last_name,
            'email': user.email,
            'username': user.username,
            'client': provider,
            'client_args': client_args,
            'allowed_scopes': user_data.get('allowed_scopes'),
            'scope': request.url.query.get('scope').split(' '),
            'identifier': 'oauth'
        },
        timeout=timeout)

    await notify(UserLogin(user, jwt_token))

    result = {'exp': data['exp'], 'token': jwt_token}
    if app_settings.get('auth_callback_url'):
        url = yarl.URL(app_settings['auth_callback_url']).with_query(result)
        return HTTPFound(str(url))
    return result
Exemplo n.º 8
0
async def _login_user(request, accept_data, user):
    # log user in directly now
    async with aiohttp.ClientSession() as session:
        csrf = await utils.get_csrf_cookie_str(request)
        async with session.get(
                accept_data['redirect_to'], headers={
                    'Cookie': csrf
                }, allow_redirects=False) as resp:
            assert resp.status == 302
            url = URL(resp.headers['Location'])
            challenge = url.query['consent_challenge']
            consent = await _get_consent(challenge)

            accept_request = await hydra_admin_request(
                'put', os.path.join('consent', challenge, 'accept'),
                json={
                    'grant_scope': consent['requested_scope'],
                    # The session allows us to set session data for id
                    # and access tokens
                    'session': {
                        'access_token': {
                            'username': user['username'],
                        },
                        'id_token': {
                            'username': user['username'],
                            'email': user['email'],
                            'phone': user['phone'],
                            'data': user['data'],
                            'allowed_scopes': user['allowed_scopes'],
                        }
                    },
                    'remember': False,
                    'remember_for': 3600
                }
            )

            auth_url = URL(accept_request['redirect_to'])
            async with session.get(
                    auth_url, headers={
                        'Cookie': csrf
                    }, allow_redirects=False) as resp:
                url = URL(resp.headers['Location'])
                assert 'code' in url.query
                code = url.query['code']
                client = auth_utils.get_client('hydra')
                callback = auth_url.query['redirect_uri']

                otoken, _ = await client.get_access_token(
                    code, redirect_uri=callback)

                client_args = dict(access_token=otoken)
                user, user_data = await client.user_info()

                jwt_token, data = authenticate_user(user.id, {
                    'first_name': user.first_name,
                    'last_name': user.last_name,
                    'email': user.email,
                    'username': user.username,
                    'client': 'hydra',
                    'client_args': client_args,
                    'allowed_scopes': user_data.get('allowed_scopes'),
                    'scope': consent['requested_scope'],
                })

                await notify(UserLogin(user, jwt_token))

                return {
                    'exp': data['exp'],
                    'token': jwt_token
                }