Beispiel #1
0
 def token(self):
     if self._token is not None and self._cached_token is None:
         self._cached_token = self._token.copy()
         self._cached_token['token'] = if_unicode_to_bytes(self._token_sig) \
             + b'!!!!' + \
             if_unicode_to_bytes(base64.b64encode(
                 if_unicode_to_bytes(js.dumps(self._token))))
     return self._cached_token
Beispiel #2
0
    def new_token(self,
                  user_id,
                  username,
                  domain=None,
                  tenant_id=None,
                  expire=None):
        """Create Token.

        This part of step 1 during the authentication after validation.

        Args:
            user_id (str): User ID
            username (str): Username.
            email (str): User email address.
            token (str): Unique token for specific user.
            domain_id (str): Current domain id.
            tenant_id (str): Current tenant id.
        """
        self._token = {}
        if user_id is None:
            raise ValueError('Require user_id for new_token')
        if username is None:
            raise ValueError('Require username for new_token')

        # These are only set during valid login.
        # Unique user id.
        self._token['user_id'] = user_id

        # Unique username.
        self._token['username'] = username

        # Token creation datetime, format YYYY/MM/DD HH:MM:SS.
        self._token['creation'] = now()

        # Token expire datetime, format YYYY/MM/DD HH:MM:SS.
        if expire is None:
            expire = (now() + timedelta(seconds=self._token_expire))
            self._token['expire'] = expire.strftime("%Y/%m/%d %H:%M:%S")
        else:
            self._token['expire'] = expire

        # Scope domain.
        self._token['domain'] = domain
        self._token['domain_id'] = domain_id(domain)

        # Scope tenant.
        self._token['tenant_id'] = tenant_id

        # Scope roles.
        self._token['roles'] = user_roles(user_id, domain, tenant_id)

        # Token Signature
        private_key = g.app.app_root.rstrip('/') + '/token.key'
        bytes_token = if_unicode_to_bytes(js.dumps(self._token))
        self._token_sig = pki.sign(private_key, base64.b64encode(bytes_token))
        return self._token_sig
Beispiel #3
0
    def json(self):
        # Return json token.
        if not self.authenticated:
            raise AccessDeniedError("Credentials token missing")

        utc_expire = utc(self._credentials['expire'])
        if now() > utc_expire:
            raise AccessDeniedError('Auth Token Expired')

        credentials = {}
        credentials['token'] = self.token
        credentials.update(self._credentials)
        return js.dumps(credentials)
Beispiel #4
0
    def save(self):
        req = g.current_request
        content = if_unicode_to_bytes(js.dumps(self._session))
        content = base64.b64encode(content)
        content = if_bytes_to_unicode(content)
        if len(content) > 1920:
            raise ValueError('SessionCookie size exceeded 15KB')

        cookie = self._session_id
        path = '/' + req.app.lstrip('/')
        req.response.set_cookie(cookie,
                                content,
                                path=path,
                                domain=req.host,
                                max_age=self._expire)
Beispiel #5
0
    def token(self):
        # Return serialized token.
        if not self.authenticated:
            raise AccessDeniedError("Credentials token missing")

        utc_expire = utc(self._credentials['expire'])
        if now() > utc_expire:
            raise AccessDeniedError('Auth Token Expired')

        bytes_token = if_unicode_to_bytes(
            js.dumps(self._credentials, indent=None))
        b64_token = base64.b64encode(bytes_token)
        token_sig = if_unicode_to_bytes(self._rsakey.sign(b64_token))
        token = if_bytes_to_unicode(token_sig + b'!!!!' + b64_token)
        if len(token) > 1280:
            raise ValueError("Auth Token exceeded 10KB" +
                             " - Revise Assignments for credentials")

        return token
Beispiel #6
0
    def body(self, obj):
        """Set Response Body.

        Accepts following objects:
            'str', and 'bytes', if str will be encoded to bytes.
            file, iter like objects must return bytes.
            OrderedDict, dict and list will be translated json
            and encoded to 'UTF-8'

        Args:
            obj (object): Any valid object for response body.
        """
        if isinstance(obj, (
                str,
                bytes,
        )):
            # If Body is string, bytes.
            obj = if_unicode_to_bytes(obj)
            if self.content_type is None:
                self.content_type = self._DEFAULT_CONTENT_TYPE
            self._stream = obj
        elif isinstance(obj, (
                OrderedDict,
                dict,
                list,
                tuple,
        )):
            # If JSON serializeable object.
            self.content_type = const.APPLICATION_JSON
            self._stream = if_unicode_to_bytes(js.dumps(obj))
        elif hasattr(obj, 'json'):
            # If JSON serializeable object.
            self.content_type = const.APPLICATION_JSON
            self._stream = if_unicode_to_bytes(obj.json)
        elif hasattr(obj, 'read') or hasattr(obj, '__iter__'):
            # If body content behaves like file.
            if self.content_type is None:
                self.content_type = const.APPLICATION_OCTET_STREAM
            self._stream = obj
        else:
            raise ValueError('resource not returning acceptable object %s' %
                             type(obj))
Beispiel #7
0
    def form_json(self):
        form = self.form

        json_safe_object = {}

        for prop in form:
            field = form[prop]
            if isinstance(field, list):
                for item in field:
                    if prop not in json_safe_object:
                        json_safe_object[prop] = []
                    if item.filename:
                        data = base64.encodestring(item.file.read())
                        file_obj = {
                            'name': item.filename,
                            'type': item.type,
                            'base64': data
                        }
                        json_safe_object[prop].append(file_obj)
                    else:
                        if ((isinstance(item.value, str) and item.value != '')
                                or (isinstance(item, bytes) and item != b'')):
                            json_safe_object[prop].append(item.value)
            else:
                if field.filename:
                    data = base64.encodestring(field.file.read())
                    file_obj = {
                        'name': field.filename,
                        'type': field.type,
                        'base64': data
                    }
                    json_safe_object[prop] = file_obj
                else:
                    if ((isinstance(field.value, str) and field.value != '')
                            or (isinstance(field.value, bytes)
                                and field.value != b'')):
                        json_safe_object[prop] = field.value

        return js.dumps(json_safe_object)
Beispiel #8
0
 def form_json(self):
     return js.dumps(self.form_dict)
Beispiel #9
0
 def json(self):
     """Return JSON Object of container"""
     return js.dumps(self())
Beispiel #10
0
 def __str__(self):
     if self.token is None:
         return '{}'
     else:
         return js.dumps(self.token)