Exemplo n.º 1
0
def _ensure_auth_user(user_data: dict,
                      company_id: str,
                      log: Logger,
                      revoke: bool = False):
    ensure_credentials = {"key", "secret"}.issubset(user_data)
    if ensure_credentials:
        user = AuthUser.objects(credentials__match=Credentials(
            key=user_data["key"], secret=user_data["secret"])).first()
        if user:
            if revoke:
                user.credentials = []
                user.save()
            return user.id

    user_id = user_data.get("id", f"__{user_data['name']}__")

    log.info(f"Creating user: {user_data['name']}")
    user = AuthUser(
        id=user_id,
        name=user_data["name"],
        company=company_id,
        role=user_data["role"],
        email=user_data["email"],
        created=datetime.utcnow(),
        credentials=[
            Credentials(key=user_data["key"], secret=user_data["secret"])
        ] if not revoke else [] if ensure_credentials else None,
    )

    user.save()

    return user.id
Exemplo n.º 2
0
def _ensure_auth_user(user_data: dict, company_id: str, log: Logger, revoke: bool = False):
    key, secret = user_data.get("key"), user_data.get("secret")
    if not (key and secret):
        credentials = None
    else:
        creds = Credentials(key=key, secret=secret)

        user = AuthUser.objects(credentials__match=creds).first()
        if user:
            if revoke:
                user.credentials = []
                user.save()
            return user.id

        credentials = [] if revoke else [creds]

    user_id = user_data.get("id", f"__{user_data['name']}__")

    log.info(f"Creating user: {user_data['name']}")

    user = AuthUser(
        id=user_id,
        name=user_data["name"],
        company=company_id,
        role=user_data["role"],
        email=user_data["email"],
        created=datetime.utcnow(),
        credentials=credentials,
    )

    user.save()

    return user.id
Exemplo n.º 3
0
def authorize_credentials(auth_data, service, action, call_data_items):
    """ Validate credentials against service/action and request data (dicts).
        Returns a new basic object (auth payload)
    """
    try:
        access_key, _, secret_key = base64.b64decode(
            auth_data.encode()).decode('latin-1').partition(':')
    except Exception as e:
        log.exception('malformed credentials')
        raise errors.unauthorized.BadCredentials(str(e))

    query = Q(
        credentials__match=Credentials(key=access_key, secret=secret_key))

    fixed_user = None

    if FixedUser.enabled():
        fixed_user = FixedUser.get_by_username(access_key)
        if fixed_user:
            if secret_key != fixed_user.password:
                raise errors.unauthorized.InvalidCredentials(
                    'bad username or password')

            if fixed_user.is_guest and not FixedUser.is_guest_endpoint(
                    service, action):
                raise errors.unauthorized.InvalidCredentials(
                    'endpoint not allowed for guest')

            query = Q(id=fixed_user.user_id)

    with TimingContext(
            "mongo",
            "user_by_cred"), translate_errors_context('authorizing request'):
        user = User.objects(query).first()
        if not user:
            raise errors.unauthorized.InvalidCredentials(
                'failed to locate provided credentials')

        if not fixed_user:
            # In case these are proper credentials, update last used time
            User.objects(id=user.id, credentials__key=access_key).update(
                **{"set__credentials__$__last_used": datetime.utcnow()})

    with TimingContext("mongo", "company_by_id"):
        company = Company.objects(id=user.company).only('id', 'name').first()

    if not company:
        raise errors.unauthorized.InvalidCredentials('invalid user company')

    identity = Identity(user=user.id,
                        company=user.company,
                        role=user.role,
                        user_name=user.name,
                        company_name=company.name)

    basic = Basic(user_key=access_key, identity=identity)

    return basic
Exemplo n.º 4
0
def _ensure_user(user_data, company_id):
    user = User.objects(credentials__match=Credentials(
        key=user_data["key"], secret=user_data["secret"])).first()
    if user:
        return user.id

    log.info(f"Creating user: {user_data['name']}")
    user = User(
        id=f"__{user_data['name']}__",
        name=user_data["name"],
        company=company_id,
        role=user_data["role"],
        email=user_data["email"],
        created=datetime.utcnow(),
        credentials=[
            Credentials(key=user_data["key"], secret=user_data["secret"])
        ],
    )

    user.save()

    return user.id
Exemplo n.º 5
0
def _ensure_auth_user(user_data, company_id):
    ensure_credentials = {"key", "secret"}.issubset(user_data.keys())
    if ensure_credentials:
        user = AuthUser.objects(credentials__match=Credentials(
            key=user_data["key"], secret=user_data["secret"])).first()
        if user:
            return user.id

    log.info(f"Creating user: {user_data['name']}")
    user = AuthUser(
        id=user_data.get("id", f"__{user_data['name']}__"),
        name=user_data["name"],
        company=company_id,
        role=user_data["role"],
        email=user_data["email"],
        created=datetime.utcnow(),
        credentials=[
            Credentials(key=user_data["key"], secret=user_data["secret"])
        ] if ensure_credentials else None,
    )

    user.save()

    return user.id
Exemplo n.º 6
0
    def create_credentials(cls,
                           user_id: str,
                           company_id: str,
                           role: str = None) -> CredModel:

        with translate_errors_context():
            query = dict(id=user_id, company=company_id)
            user = User.objects(**query).first()
            if not user:
                raise errors.bad_request.InvalidUserId(**query)

            cred = CredModel(access_key=get_client_id(),
                             secret_key=get_secret_key())
            user.credentials.append(
                Credentials(key=cred.access_key, secret=cred.secret_key))
            user.save()

            return cred
Exemplo n.º 7
0
def authorize_credentials(auth_data, service, action, call_data_items):
    """ Validate credentials against service/action and request data (dicts).
        Returns a new basic object (auth payload)
    """
    try:
        access_key, _, secret_key = base64.b64decode(
            auth_data.encode()).decode('latin-1').partition(':')
    except Exception as e:
        log.exception('malformed credentials')
        raise errors.unauthorized.BadCredentials(str(e))

    with TimingContext(
            "mongo",
            "user_by_cred"), translate_errors_context('authorizing request'):
        user = User.objects(credentials__match=Credentials(
            key=access_key, secret=secret_key)).first()

    if not user:
        raise errors.unauthorized.InvalidCredentials(
            'failed to locate provided credentials')

    with TimingContext("mongo", "company_by_id"):
        company = Company.objects(id=user.company).only('id', 'name').first()

    if not company:
        raise errors.unauthorized.InvalidCredentials('invalid user company')

    identity = Identity(user=user.id,
                        company=user.company,
                        role=user.role,
                        user_name=user.name,
                        company_name=company.name)

    basic = Basic(user_key=access_key, identity=identity)

    return basic