Example #1
0
    def invalidate_all_tokens(self, user=None):
        if user is None:
            user = self.get_user()

        user.uuid = getUUID()
        user.save()
        return True
Example #2
0
    def fill_payload(self, userobj, expiration=None, token_type=None):
        """ Informations to store inside the JWT token,
        starting from the user obtained from the current service

        Claim attributes listed here:
        http://blog.apcelent.com/json-web-token-tutorial-example-python.html

        TTL is measured in seconds
        """

        if expiration is None:
            expiration = timedelta(seconds=self.longTTL)

        payload = {'user_id': userobj.uuid, 'jti': getUUID()}

        short_jwt = (Detector.get_global_var('AUTH_FULL_JWT_PAYLOAD',
                                             '').lower() == 'false')

        if token_type is not None:
            if token_type in (self.PWD_RESET, self.ACTIVATE_ACCOUNT):
                short_jwt = True
                payload["t"] = token_type

        if not short_jwt:
            now = datetime.now(pytz.utc)
            nbf = now  # you can add a timedelta
            exp = now + expiration
            payload['iat'] = now
            payload['nbf'] = nbf
            payload['exp'] = exp

        return payload
Example #3
0
    def manage_missing_parameter(
        self,
        func: Any,
        param: str,
        definition: fields.Field,
        update: Update,
        context: CallbackContext[UD, CD, BD],
        error: List[str],
    ) -> None:

        if not update.message:  # pragma
            log.critical(
                "Debug code: missing message in manage_missing_parameter")
            return None

        # Parameters without description should raise some kind of errors/warnings?
        if "description" in definition.metadata:
            description = definition.metadata["description"]
        else:  # pragma: no cover
            description = "???"

        # Enum -> InlineKeyboardButton
        if definition.validate and isinstance(definition.validate,
                                              validate.OneOf):

            choices = definition.validate.choices
            labels = definition.validate.labels
            if len(tuple(labels)) != len(tuple(choices)):
                labels = choices

            keyboard = []
            for k, val in dict(zip(choices, labels)).items():
                data_key = getUUID()
                # Because func, update and context are not (easily) serializable they
                # are saved in a data_cache and the callback will access them
                # by using the assigned unique data_key
                data_cache[data_key] = {
                    "func": func,
                    "update": update,
                    "context": context,
                    "parameter": k,
                }

                # All InlineKeyboardButton are registered with one single callback
                # function (SIGH and SOB!!). The data_key passed as callback_data will
                # be used to access the specific data and call again the command func
                # by augmenting the parameters list with the choice from the button
                keyboard.append(
                    [InlineKeyboardButton(val, callback_data=data_key)])
            reply_markup = InlineKeyboardMarkup(keyboard)

            update.message.reply_text(description, reply_markup=reply_markup)
        # Other errors
        # Never raised during tests
        else:  # pragma: no cover
            update.message.reply_text(f"{description}\n{param}: {error[0]}")
Example #4
0
    def create_group(self, groupdata: Dict[str, Any]) -> Group:

        groupdata.setdefault("uuid", getUUID())

        group = self.db.Group(**groupdata)

        self.db.session.add(group)
        self.db.session.commit()

        return group
Example #5
0
    def create_group(self, groupdata: Dict[str, Any]) -> Group:

        groupdata.setdefault("uuid", getUUID())
        groupdata.setdefault("id", groupdata["uuid"])

        group = self.db.Group(**groupdata)

        group.save()

        return group
Example #6
0
 def invalidate_all_tokens(self, user=None):
     """
         To invalidate all tokens the user uuid is changed
     """
     if user is None:
         user = self._user
     user.uuid = getUUID()
     user.save()
     log.warning("User uuid changed to: {}", user.uuid)
     return True
Example #7
0
    def fill_payload(
        self,
        user: User,
        expiration: Optional[datetime] = None,
        token_type: Optional[str] = None,
    ) -> Tuple[Payload, Payload]:
        """Informations to store inside the JWT token,
        starting from the user obtained from the current service

        Claim attributes listed here:
        http://blog.apcelent.com/json-web-token-tutorial-example-python.html

        TTL is measured in seconds
        """

        payload: Payload = {"user_id": user.uuid, "jti": getUUID()}
        full_payload: Payload = payload.copy()

        if not token_type:
            token_type = self.FULL_TOKEN

        short_token = False
        if token_type in (
                self.PWD_RESET,
                self.ACTIVATE_ACCOUNT,
                self.UNLOCK_CREDENTIALS,
        ):
            short_token = True
            payload["t"] = token_type

        full_payload["t"] = token_type

        now = datetime.now(pytz.utc)

        if expiration is None:
            expiration = now + timedelta(seconds=self.DEFAULT_TOKEN_TTL)

        full_payload["iat"] = now
        full_payload["nbf"] = now  # you may add a timedelta
        full_payload["exp"] = expiration

        if not short_token:
            payload["iat"] = full_payload["iat"]
            payload["nbf"] = full_payload["nbf"]
            payload["exp"] = full_payload["exp"]

        # first used for encoding
        # second used to store information on backend DB
        return payload, full_payload
Example #8
0
 def invalidate_all_tokens(self, user=None):
     """
         To invalidate all tokens the user uuid is changed
     """
     if user is None:
         user = self._user
     user.uuid = getUUID()
     try:
         self.db.session.add(user)
         self.db.session.commit()
         log.warning("User uuid changed to: {}", user.uuid)
     except BaseException as e:
         log.error("DB error ({}), rolling back", e)
         self.db.session.rollback()
     return True
Example #9
0
    def create_user(self, userdata: Dict[str, Any], roles: List[str]) -> User:

        userdata.setdefault("authmethod", "credentials")
        userdata.setdefault("uuid", getUUID())

        if "password" in userdata:
            userdata["password"] = self.get_password_hash(userdata["password"])

        userdata, extra_userdata = self.custom_user_properties_pre(userdata)

        user = self.db.User(**userdata)
        self.link_roles(user, roles)

        self.custom_user_properties_post(user, userdata, extra_userdata,
                                         self.db)

        self.db.session.add(user)

        return user
Example #10
0
    def create_user(self, userdata, roles):

        if "authmethod" not in userdata:
            userdata["authmethod"] = "credentials"

        if "password" in userdata:
            userdata["password"] = self.get_password_hash(userdata["password"])

        if "uuid" not in userdata:
            userdata["uuid"] = getUUID()

        userdata = self.custom_user_properties(userdata)

        user = self.db.User(**userdata)
        self.link_roles(user, roles)

        self.db.session.add(user)

        return user
Example #11
0
        def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
            out = None

            try:
                out = func(self, *args, **kwargs)
            # Catch the exception requested by the user
            except RestApiException as e:

                if e.is_warning:
                    log.warning(e)
                else:
                    log.exception(e)
                    log.error(e)

                return self.response(
                    e.args[0],
                    code=e.status_code,
                    force_json=True,
                )

            except werkzeug.exceptions.BadRequest:  # pragma: no cover
                # do not stop werkzeug BadRequest
                raise

            except werkzeug.exceptions.UnprocessableEntity:
                # do not stop werkzeug UnprocessableEntity, it will be
                # catched by handle_marshmallow_errors
                raise

            # raised in case of malformed Range header
            except werkzeug.exceptions.RequestedRangeNotSatisfiable:
                raise
            # Catch any other exception

            # errors with RabbitMQ credentials raised when sending Celery tasks
            except AccessRefused as e:  # pragma: no cover
                log.error(e)
                return self.response("Unexpected Server Error",
                                     code=500,
                                     force_json=True)
            except Exception as e:

                if SENTRY_URL is not None:  # pragma: no cover
                    capture_exception(e)

                excname = e.__class__.__name__
                message = str(e)
                if not message:  # pragma: no cover
                    message = "Unknown error"

                error_id = getUUID()

                log.error("Catched {} exception with ID {}: {}", excname,
                          error_id, message)
                log.exception(message)

                if excname in ["SystemError"]:  # pragma: no cover
                    return self.response("Unexpected Server Error",
                                         code=500,
                                         force_json=True)

                return self.response(
                    {
                        excname:
                        f"There was an unexpected error. ErrorID: {error_id}"
                    },
                    code=400,
                )

            return out
Example #12
0
 def custom_user_properties(self, userdata):
     new_userdata = super(Authentication,
                          self).custom_user_properties(userdata)
     if not new_userdata.get('uuid'):
         new_userdata['uuid'] = getUUID()
     return new_userdata