Exemplo n.º 1
0
    def put(self, request):
        """
        Peforms the password reset for the user with user.email=email if the
        token is a valid token attached to that user.
        """
        uuid = request.data['uuid']

        # Get the user from the email
        try:
            user = User.objects.get(uuid=uuid)
        except User.DoesNotExist:
            log.debug("User does not exist: uuid={}".format(uuid))
            return ResponseMessage.INVALID_CREDENTIALS

        email = user.email.lower()
        password = request.data['password']

        # Check password
        user = authenticate(username=email, password=password)
        if user is None:
            return ResponseMessage.INVALID_CREDENTIALS

        # Check tokens
        l0 = request.data['token_level_0']
        l1 = request.data['token_level_1']

        claims0 = TokenManager.validate(user, l0, TokenType.LEVEL_ZERO)
        if not claims0:
            log.debug("LEVEL_ZERO is invalid.")
            return ResponseMessage.INVALID_CREDENTIALS

        claims1 = TokenManager.validate(user, l1, TokenType.LEVEL_ONE)
        if not claims1:
            log.debug("LEVEL_ONE is invalid.")
            return ResponseMessage.INVALID_CREDENTIALS

        TokenManager.delete(user, claims1)

        l1 = TokenManager.generate(user, TokenType.LEVEL_ONE)

        log.info("User uuid={} has changed their password".format(user.uuid))
        user.set_password(request.data['new_password'])
        user.save()

        return JsonResponse({
            'token_level_1': l1.decode('ascii'),
        },
                            status=201)
Exemplo n.º 2
0
def request_must_have(expected, required):
    if not isinstance(expected, set):
        expected = set(expected)

    if expected == required:
        return True

    messages = []

    extra = expected - required
    if extra:
        messages.append("Extra fields were found: {}".format(extra))

    missing = required - expected
    if missing:
        messages.append("Fields were missing: {}".format(missing))

    log.info("Errors in request: {}".format(messages))
    return False
Exemplo n.º 3
0
    def put(self, request):
        """Register a new user into the system."""

        request.data['email'] = request.data['email'].lower()
        serializer = UserSerializer(data=request.data)

        if not serializer.is_valid():
            log.warning("{} => {}{}".format(
                "User data was deemed invalid by UserSerializer",
                str(serializer.errors), request.data))
            return ResponseMessage.INVALID_MESSAGE(str(serializer.errors))

        user = User.objects.create_user(username=None,
                                        email=serializer.data['email'].lower(),
                                        password=serializer.data['password'])
        log.info("User has been registered: {}".format(user))
        return JsonResponse({
            'email': user.email,
            'uuid': user.uuid
        },
                            status=201)
Exemplo n.º 4
0
    def put(self, request):
        """Register a new user into the system."""

        request.data['email'] = request.data['email'].lower()
        serializer = UserSerializer(data=request.data)
        errorMessages = ErrorMessages()
        if not serializer.is_valid():
            log.warning("{} => {}{}".format(
                "User data was deemed invalid by UserSerializer",
                str(serializer.errors), request.data))
            return errorMessages.sendError(request.data['role'])
        user = User.objects.create_user(username=None,
                                        email=serializer.data['email'].lower(),
                                        password=serializer.data['password'])
        # is_superuser = True,
        # is_staff = True)
        log.info("User has been registered: {}".format(user))
        return JsonResponse({
            'email': user.email,
            'uuid': user.uuid
        },
                            status=201)
Exemplo n.º 5
0
    def generate(user, kind):
        """
        Generate a session token for the user, providing the level and exp.

        :param user: The user to generate the token for.
        :type user: models.User
        :param kind: The type of token to generate
        :type kind: models.TokenType
        :return: JWT encoded claims
        :rtype: str
        :Example:

        >>> user = User.objects.create(...)
        >>> token = TokenManager.generate(user, TokenType.LEVEL_ZERO)
        """
        assert(isinstance(kind, TokenType))
        assert(kind in list(TokenType))

        now = timezone.now()

        claims = {
            'iat': now,
            'exp': now + kind.ttl(),
            'sub': user.uuid,
            'jti': user.nonce(),
            'typ': int(kind.value),
        }

        jwt = PyJWT(options={
            'require_exp': True,
            'require_iat': True,
        })

        ValidTokens.objects.create(
            jti=claims['jti'], exp=claims['exp'], user=user)

        log.info("Generated a {} for {}".format(kind, user.uuid))
        return jwt.encode(claims, user.private_key(), algorithm='HS256')
Exemplo n.º 6
0
    def post(self, request):
        """
        Peforms the password reset for the user with user.email=email if the
        token is a valid token attached to that user.
        """
        # Get the user from the email
        try:
            user = User.objects.get(email=request.data['email'].lower())
        except User.DoesNotExist:
            return ResponseMessage.INVALID_CREDENTIALS

        token = request.data['token']

        # Validate the token matches the user token
        claims = TokenManager.validate(user, token, TokenType.RESET_PASSWORD)
        if not claims:
            return ResponseMessage.INVALID_CREDENTIALS

        TokenManager.delete(user, claims)
        log.info("User uuid={} has changed their password".format(user.uuid))
        user.set_password(request.data['password'])
        user.save()
        return JsonResponse({}, status=201)