示例#1
0
    def test_validate_token_ok_02(self) -> None:
        """ Test the function that validates a token, with a success case for an REFRESH token. """

        # The expected result
        expected_result = True, 123

        # Prepare the mocks
        configuration.REFRESH_TOKEN_VALIDITY_DAYS = 5

        token = authentication.generate_token(123,
                                              authentication.TokenType.REFRESH,
                                              unittest.mock.MagicMock())

        db_calls_mock.get_token.return_value = models.Token(
            token,
            datetime.date.today() +
            datetime.timedelta(days=configuration.REFRESH_TOKEN_VALIDITY_DAYS))

        # Call the function
        actual_result = authentication.validate_token(
            token.encode(), authentication.TokenType.REFRESH,
            unittest.mock.MagicMock())

        # Verify the result
        self.assertEqual(expected_result, actual_result)
        db_calls_mock.get_token.assert_called()
示例#2
0
def add_client():

	data = request.json
	if not data:
		abort(400)

	firstname = data.get('firstname')
	lastname = data.get('lastname')
	email = data.get('email')
	password = data.get('password')

	# todo validate email/password

	if not email or not password or not firstname or not lastname:
		abort(400)

	client = app.db['clients'].find_one({'email': email})
	if client:
		abort(400, 'account already exists')

	payload = {'firstname': firstname,
			   'lastname': lastname,
			   'email': email,
			   'password': encrypt_password(password)}

	payload['_created'] = payload['_updated'] = datetime.utcnow().replace(microsecond=0).replace(tzinfo=pytz.utc)

	clientId = app.db['clients'].insert(payload)

	token_resp = generate_token(str(clientId))
	return jsonify(token_resp)
示例#3
0
    def test_generate_token_ok_01(self) -> None:
        """ Test the function that generates a token, with a success case for REFRESH. """

        # The expected result
        expected_expiration_date = datetime.datetime.today().replace(
            microsecond=0) + datetime.timedelta(days=5)

        expected_type = 'REFRESH'

        # Prepare the mocks
        token_payload = {'key': 'value'}
        token = jwt.encode(token_payload, 'secret key', algorithm='HS256')

        configuration.REFRESH_TOKEN_VALIDITY_DAYS = 5
        db_calls_mock.register_token.return_value = models.Token(
            token, expected_expiration_date.date())

        # Call the function
        actual_result = authentication.generate_token(
            1, authentication.TokenType.REFRESH, unittest.mock.MagicMock())

        # Verify the result
        self.assertIsNotNone(actual_result)
        db_calls_mock.register_token.assert_called()

        # Verify the date
        actual_expiration_date = datetime.datetime.fromtimestamp(
            authentication.get_token_field(actual_result, 'exp'))
        self.assertEqual(expected_expiration_date, actual_expiration_date)

        # Verify the other fields exist
        self.assertEqual(expected_type,
                         authentication.get_token_field(actual_result, 'type'))
        self.assertEqual(1,
                         authentication.get_token_field(actual_result, 'user'))
示例#4
0
def get_token():
    token = authentication.generate_token('user')
    response.status = 200
    return {
        "status": 200,
        "token": token,
    }
示例#5
0
    def test_generate_token_error_02(self) -> None:
        """ Test the function that generates a token, with an error due to invalid token type. """

        # Call the function
        actual_result = authentication.generate_token(
            1, unittest.mock.MagicMock())

        # Verify the result
        self.assertIsNone(actual_result)
        db_calls_mock.register_token.assert_not_called()
示例#6
0
def send_verification_email(user: models.User):
    """
    Send a verification email.

    :param user: the user.
    """

    verification_token = authentication.generate_token(
        user.id, authentication.TokenType.VERIFICATION)

    process_emails.set_language(user.language)
    return process_emails.send_verification_email(user.email,
                                                  verification_token)
示例#7
0
    def post(self, args):
        """Login with an external token."""

        external_token = args['external_token']
        source = args['source']

        language = None

        for k, v in args.items():
            if v is None:
                continue

            if k == 'language':
                language = v

        with session_scope() as session:
            # Get the email from the token
            email = external_authentication.external_authentication(
                external_token, source)

            # If we can't get the email
            if email is None:
                return flask.make_response('', 400)

            # Check if there's a user
            user = processing.get_user_by_email(session, email)

            # Register the user
            if user is None:
                user = processing.register_external_user(session,
                                                         email,
                                                         source,
                                                         language=language)

                # If the registration failed
                if user is None:
                    return flask.make_response('', 400)

            # Generate the refresh token
            refresh_token = authentication.generate_token(
                user.id, authentication.TokenType.REFRESH, session=session)

            username = user.email[:user.email.index('@')]

            return flask.make_response(
                flask.jsonify({
                    'token': str(refresh_token),
                    'username': username,
                    **processing.get_settings(session, user.id)
                }), 200)
示例#8
0
    def test_generate_token_error_03(self) -> None:
        """ Test the function that generates a token, with an error due to invalid secret key. """

        # Prepare the mocks
        configuration.CHANGE_EMAIL_TOKEN_VALIDITY_DAYS = 5
        configuration.secret_key = None

        # Call the function
        actual_result = authentication.generate_token(
            1, authentication.TokenType.CHANGE_EMAIL_NEW)

        # Verify the result
        self.assertIsNone(actual_result)
        db_calls_mock.register_token.assert_not_called()
示例#9
0
    def test_generate_token_error_01(self) -> None:
        """ Test the function that generates a token, with an error case for REFRESH due to a fail in the insertion of
        the token in the DB. """

        # Prepare the mocks
        configuration.REFRESH_TOKEN_VALIDITY_DAYS = 5
        db_calls_mock.register_token.return_value = None

        # Call the function
        actual_result = authentication.generate_token(
            1, authentication.TokenType.REFRESH, unittest.mock.MagicMock())

        # Verify the result
        self.assertIsNone(actual_result)
        db_calls_mock.register_token.assert_called()
示例#10
0
    def test_generate_access_token_error_01(self) -> None:
        """ Test the function that generates an access token, with an error due to an invalid REFRESH token. """

        # Prepare the mocks
        configuration.DELETION_TOKEN_VALIDITY_DAYS = 5

        # Call the function
        refresh_token = authentication.generate_token(
            123, authentication.TokenType.DELETION)

        actual_result, actual_token = authentication.generate_access_token(
            unittest.mock.MagicMock(), refresh_token)

        # Verify the result
        self.assertFalse(actual_result)
        self.assertIsNone(actual_token)
示例#11
0
def authenticate():

	data = request.json
	if not data:
		abort(400)

	email = data.get('email')
	password = data.get('password')

	if not email or not password:
		abort(400)

	client = app.db['clients'].find_one({'email': email})
	if not client or not verify_password(password, client.get('password')):
		abort(403, 'invalid credentials')

	token_resp = generate_token(str(client['_id']))
	return jsonify(token_resp)
示例#12
0
    def test_validate_token_error_03(self) -> None:
        """ Test the function that validates a token, with an error due to different type in payload. """

        # The expected result
        expected_result = False, None

        # Prepare the mocks
        configuration.ACCESS_TOKEN_VALIDITY_HOURS = 5

        # Call the function
        token = authentication.generate_token(123,
                                              authentication.TokenType.ACCESS)

        actual_result = authentication.validate_token(
            token, authentication.TokenType.DELETION)

        # Verify the result
        self.assertEqual(expected_result, actual_result)
示例#13
0
def send_deletion_email(session, user_id: str) -> bool:
    """
    Send a verification email.

    :param session: the db session.
    :param user_id: the user id.
    """

    # Get user
    user = session.query(models.User).filter(models.User.id == user_id).first()

    if user is None:
        return False

    deletion_token = authentication.generate_token(
        user.id, authentication.TokenType.DELETION, session)

    process_emails.set_language(user.language)
    return process_emails.send_deletion_email(user.email, deletion_token)
示例#14
0
    def test_validate_token_ok_01(self) -> None:
        """ Test the function that validates a token, with a success case for an ACCESS token. """

        # The expected result
        expected_result = True, 123

        # Prepare the mocks
        configuration.ACCESS_TOKEN_VALIDITY_HOURS = 5

        # Call the function
        token = authentication.generate_token(123,
                                              authentication.TokenType.ACCESS)

        actual_result = authentication.validate_token(
            token.encode(), authentication.TokenType.ACCESS)

        # Verify the result
        self.assertEqual(expected_result, actual_result)
        db_calls_mock.get_token.assert_not_called()
示例#15
0
def send_password_recovery_email(session, user_id: str) -> bool:
    """
    Send a recover password email.

    :param session: the db session.
    :param user_id: the user id.
    """

    # Get user
    user = session.query(models.User).filter(models.User.id == user_id).first()

    if user is None:
        return False

    password_recovery_token = authentication.generate_token(
        user.id, authentication.TokenType.PASSWORD_RECOVERY, session)

    process_emails.set_language(user.language)
    return process_emails.send_password_recovery_email(
        user.email, password_recovery_token)
示例#16
0
def send_change_email_old(session, user_id: str) -> bool:
    """
    Send a change email email to the old email.

    :param session: the db session.
    :param user_id: the user id.
    """

    # Get user
    user = session.query(models.User).filter(models.User.id == user_id).first()

    if user is None:
        return False

    change_email_old_token = authentication.generate_token(
        user.id, authentication.TokenType.CHANGE_EMAIL_OLD, session)

    process_emails.set_language(user.language)
    return process_emails.send_change_email_old(user.email,
                                                change_email_old_token)
示例#17
0
    def test_validate_token_error_04(self) -> None:
        """ Test the function that validates a token, with an error due to db not finding the REFRESH token. """

        # The expected result
        expected_result = False, None

        # Prepare the mocks
        configuration.REFRESH_TOKEN_VALIDITY_DAYS = 5
        db_calls_mock.get_token.return_value = None

        # Call the function
        token = authentication.generate_token(123,
                                              authentication.TokenType.REFRESH)

        actual_result = authentication.validate_token(
            token.encode(), authentication.TokenType.REFRESH,
            unittest.mock.MagicMock())

        # Verify the result
        self.assertEqual(expected_result, actual_result)
        db_calls_mock.get_token.assert_called()
示例#18
0
    def test_generate_token_ok_02(self) -> None:
        """ Test the function that generates a token, with a success case for VERIFICATION.
         And also include some extra fields in the payload."""

        # The expected result
        expected_expiration_date = datetime.datetime.today().replace(
            microsecond=0) + datetime.timedelta(days=5)

        expected_type = 'VERIFICATION'

        # Prepare the mocks
        configuration.VERIFICATION_TOKEN_VALIDITY_DAYS = 5

        # Call the function
        actual_result = authentication.generate_token(
            1234,
            authentication.TokenType.VERIFICATION,
            payload_extra={'extra_key': 'extra_value'})

        # Verify the result
        self.assertIsNotNone(actual_result)
        db_calls_mock.register_token.assert_not_called()

        # Verify the date
        actual_expiration_date = datetime.datetime.fromtimestamp(
            authentication.get_token_field(actual_result, 'exp'))
        self.assertEqual(expected_expiration_date, actual_expiration_date)

        # Verify the other fields exist
        self.assertEqual(expected_type,
                         authentication.get_token_field(actual_result, 'type'))
        self.assertEqual(1234,
                         authentication.get_token_field(actual_result, 'user'))
        self.assertEqual(
            'extra_value',
            authentication.get_token_field(actual_result, 'extra_key'))
示例#19
0
    def test_generate_access_token_ok(self) -> None:
        """ Test the function that generates an access token, with a success case. """

        # The expected result
        expected_expiration_date = datetime.datetime.today().replace(
            microsecond=0) + datetime.timedelta(hours=10)

        expected_type = 'ACCESS'

        # Prepare the mocks
        configuration.REFRESH_TOKEN_VALIDITY_DAYS = 5
        configuration.ACCESS_TOKEN_VALIDITY_HOURS = 10

        refresh_token = authentication.generate_token(
            123, authentication.TokenType.REFRESH, unittest.mock.MagicMock())
        db_calls_mock.register_token.return_value = models.Token(
            refresh_token, expected_expiration_date.date())

        # Call the function
        actual_result, actual_token = authentication.generate_access_token(
            unittest.mock.MagicMock(), refresh_token)

        # Verify the result
        self.assertTrue(actual_result)
        self.assertIsNotNone(actual_token)

        # Verify the date
        actual_expiration_date = datetime.datetime.fromtimestamp(
            authentication.get_token_field(actual_token, 'exp'))
        self.assertEqual(expected_expiration_date, actual_expiration_date)

        # Verify the other fields exist
        self.assertEqual(expected_type,
                         authentication.get_token_field(actual_token, 'type'))
        self.assertEqual(123,
                         authentication.get_token_field(actual_token, 'user'))
示例#20
0
    def post(self):
        """Login made by the user, generating an authentication token."""

        with session_scope() as session:
            auth = flask.request.authorization
            user = processing.get_user_by_email(session, auth['username'])

            if user is not None:
                if user.verified:
                    refresh_token = authentication.generate_token(
                        user.id,
                        authentication.TokenType.REFRESH,
                        session=session)

                    if auth['username'].find('@') != -1:
                        username = auth['username'][:auth['username'].index('@'
                                                                            )]
                    else:
                        username = auth['username']

                    return flask.make_response(
                        flask.jsonify({
                            'token':
                            str(refresh_token),
                            'username':
                            username,
                            **processing.get_settings(session, user.id)
                        }), 200)
                else:
                    return flask.make_response('Unverified Account', 400)

            # This should never happen
            else:
                print('ERROR: The user passed the decorator verification!')
                return flask.make_response('Unauthorized Access',
                                           403)  # Should be 503
示例#21
0
					page_id
				) VALUES (
					'{user_id}',
					'{page_id}')
			""".format(user_id=user_id, page_id=demo_page_id))

    except Exception, error:
        print 'ERROR: ', error
        return bad_request(error)
    finally:
        conn.commit()
        cursor.close()

    data = {
        'id': user_id,
        'authToken': generate_token(user_id),
        'profileType': profile_type
    }

    response = make_response(jsonify(data))
    response.status_code = 201
    return response


@api.route('/user/<user_id>', methods=['GET'])
@auth.login_required
def get_user(user_id):

    conn = g.mysql.connection
    cursor = conn.cursor()