def verify_signature(self, signature: str) -> None: """Verify the signature associated with this instance. Raises `BadSignature` if message tampering occurred, or if the scope of the signed message does not match this feature, or if the signed ID does not match the ID of this instance. """ signed_obj = signing.loads(signature) if signed_obj.get('scope') != 'authorized_upload': raise signing.BadSignature('Invalid signed scope.') if signed_obj.get('id') != self.id: raise signing.BadSignature('Invalid signed ID.')
def get_user_from_password_reset_token(token: str) -> "User": """ Check that an activation token is valid and return the corresponding user record if it is. :param token: signed base64 encoded token :return: the User record :raises: BadSignature if the token is invalid or the User record is not found SignatureExpired if the signature is more than a day old """ max_age = settings.PASSWORD_RESET_TOKEN_MAX_AGE_DAYS * 24 * 3600 try: data = signing.loads( token, key=settings.PASSWORD_RESET_TOKEN_KEY, salt=PASSWORD_RESET_TOKEN_SALT, max_age=max_age, ) user_id, user_email, user_password = ( data["id"], data["email"], data["password"], ) return User.objects.get(id=user_id, email__iexact=user_email, password__iexact=user_password) except signing.SignatureExpired: raise except signing.BadSignature: raise except User.DoesNotExist: raise signing.BadSignature("Invalid Token")
def unsign(self, signature, url): """ Return a user object for a valid signature. """ User = get_user_model() data = signing.loads(signature, salt=self.get_salt(url), max_age=self.MAX_AGE) if not isinstance(data, dict): raise signing.BadSignature() try: return User.objects.get( **{ 'pk': data.get('user_id'), User.USERNAME_FIELD: data.get('username') }) except User.DoesNotExist: raise signing.BadSignature()
def get_user_from_activation_token(token: str, max_age: int = None) -> "User": """ Check that an activation token is valid, and if so, return corresponding user record. :param token: base64 encoded string generated by generate_activation_token :param max_age: max age of token in seconds :return: the User record :raises: BadSignature if token is invalid or User record is not found SignatureExpired if token is too old """ if max_age is None: max_age = settings.USER_ACTIVATION_TOKEN_MAX_AGE_DAYS * 24 * 3600 try: data = signing.loads(token, salt=USER_ACTIVATION_TOKEN_SALT, max_age=max_age) user_id, user_email = data["id"], data["email"] return User.objects.get(id=user_id, email__iexact=user_email) except signing.SignatureExpired: raise except signing.BadSignature: raise except User.DoesNotExist: raise signing.BadSignature("User record not found")