Ejemplo n.º 1
0
    def _authenticate(self, validate, user_id, tenant_id=None):
        if tenant_id:
            duser = api.USER.get_by_tenant(user_id, tenant_id)
            if duser == None:
                raise fault.UnauthorizedFault("Unauthorized on this tenant")
        else:
            duser = api.USER.get(user_id)
            if duser == None:
                raise fault.UnauthorizedFault("Unauthorized")

        if not duser.enabled:
            raise fault.UserDisabledFault("Your account has been disabled")

        if not validate(duser):
            raise fault.UnauthorizedFault("Unauthorized")

        # use user's default tenant_id if one is not specified
        tenant_id = tenant_id or duser.tenant_id

        # check for an existing token
        dtoken = api.TOKEN.get_for_user_by_tenant(duser.id, tenant_id)

        if not dtoken or dtoken.expires < datetime.now():
            # Create new token
            dtoken = models.Token()
            dtoken.id = str(uuid.uuid4())
            dtoken.user_id = duser.id
            dtoken.tenant_id = tenant_id
            dtoken.expires = datetime.now() + timedelta(days=1)
            api.TOKEN.create(dtoken)

        return self.__get_auth_data(dtoken)
Ejemplo n.º 2
0
    def __validate_token(self, token_id, belongs_to=None, is_check_token=None):
        """
        Method to validate a token.
        token_id -- value of actual token that need to be validated.
        belngs_to -- optional tenant_id to check whether the token is
        mapped to a specific tenant.
        is_check_token -- optional argument that tells whether
        we check the existence of a Token using another Token
        to authenticate.This value decides the faults that are to be thrown.
        """
        if not token_id:
            raise fault.UnauthorizedFault("Missing token")

        (token, user) = self.__get_dauth_data(token_id)

        if not token:
            if is_check_token:
                raise fault.ItemNotFoundFault("Token does not exist.")
            else:
                raise fault.UnauthorizedFault(
                    "Bad token, please reauthenticate")

        if token.expires < datetime.now():
            if is_check_token:
                raise fault.ItemNotFoundFault("Token expired, please renew.")
            else:
                raise fault.ForbiddenFault("Token expired, please renew.")

        if not user.enabled:
            raise fault.UserDisabledFault("User %s has been disabled!" %
                                          user.id)

        if user.tenant_id:
            self.__validate_tenant_by_id(user.tenant_id)

        if token.tenant_id:
            self.__validate_tenant_by_id(token.tenant_id)

        if belongs_to and unicode(token.tenant_id) != unicode(belongs_to):
            raise fault.UnauthorizedFault("Unauthorized on this tenant")

        return (token, user)