Ejemplo n.º 1
0
 def setUp(self):
     db.create_all(app=self.app)
     self.bootstrap_user = user_manipulator.create(
         email=self.app.config['BOOTSTRAP_USER_EMAIL'],
         password='******',
         active=True)
     self.real_user = user_manipulator.create(
         email='real_user@unittests',
         password='******',
         active=True,
     )
     self.passwords = {
         self.bootstrap_user: '******',
         self.real_user: '******',
     }
Ejemplo n.º 2
0
 def setUp(self):
     db.create_all(app=self.app)
     self.bootstrap_user = user_manipulator.create(
         email=self.app.config['BOOTSTRAP_USER_EMAIL'],
         password='******',
         active=True
     )
     self.real_user = user_manipulator.create(
         email='real_user@unittests',
         password='******',
         active=True,
     )
     self.passwords = {
         self.bootstrap_user:'******',
         self.real_user: '******',
     }
Ejemplo n.º 3
0
    def setUp(self):
        super(self.__class__, self).setUp()

        # Create a test user that will be queried for
        u = user_manipulator.create(email="test@unittest")
        self.user_email = u.email
        self.user_id = u.id
Ejemplo n.º 4
0
    def setUp(self):
        super(self.__class__, self).setUp()

        # Create a test user that will be queried for
        u = user_manipulator.create(email="test@unittest")
        self.user_email = u.email
        self.user_id = u.id
Ejemplo n.º 5
0
    def post(self):
        """
        POST desired email and password to change the current user's email.
        Checks that the desired new email isn't already registerd

        This will create the new user. The encoded email payload will have
        a second argument `id` which is the id of the user making this
        request. We assume that the view responsible for verifying emails
        knows what to do with this extra argument. This should be deprecated
        by using signals in the future.
        """
        try:
            data = get_post_data(request)
            email = data['email']
            password = data['password']
            verify_url = data['verify_url']
        except (AttributeError, KeyError):
            return {'error': 'malformed request'}, 400

        u = user_manipulator.first(email=current_user.email)
        if not u.validate_password(password):
            abort(401)

        if user_manipulator.first(email=email) is not None:
            return {
                "error": "{0} has already been registered".format(email)
            }, 403
        send_email(
            email_addr=email,
            base_url=verify_url,
            email_template=VerificationEmail,
            payload=[email, u.id]
        )
        send_email(
            email_addr=current_user.email,
            email_template=EmailChangedNotification
        )
        user_manipulator.create(
            email=email,
            password=password,
            active=True,
            registered_at=datetime.datetime.now(),
            login_count=0,
        )
        return {"message": "success"}, 200
Ejemplo n.º 6
0
    def post(self):
        """
        POST desired email and password to change the current user's email.
        Checks that the desired new email isn't already registerd

        This will create the new user. The encoded email payload will have
        a second argument `id` which is the id of the user making this
        request. We assume that the view responsible for verifying emails
        knows what to do with this extra argument. This should be deprecated
        by using signals in the future.
        """
        try:
            data = get_post_data(request)
            email = data['email']
            password = data['password']
            verify_url = data['verify_url']
        except (AttributeError, KeyError):
            return {'error': 'malformed request'}, 400

        u = user_manipulator.first(email=current_user.email)
        if not u.validate_password(password):
            abort(401)

        if user_manipulator.first(email=email) is not None:
            return {
                "error": "{0} has already been registered".format(email)
            }, 403
        send_email(
            email_addr=email,
            base_url=verify_url,
            email_template=VerificationEmail,
            payload=[email, u.id]
        )
        send_email(
            email_addr=current_user.email,
            email_template=EmailChangedNotification
        )
        user_manipulator.create(
            email=email,
            password=password,
            active=True,
            registered_at=datetime.datetime.now(),
            login_count=0,
        )
        return {"message": "success"}, 200
Ejemplo n.º 7
0
    def validate(self):
        r = super(AdsClassicFallBackLoginForm, self).validate()
        if r is True:
            return r

        cu = None
        try:
            cu = ClassicUserInfo(self.email.data, self.password.data)
        except HTTPError:
            return False  # if we can't contact ADS Classic, make it non-fatal

        if cu.is_authenticated():  # Classic did let them in....

            if not hasattr(
                    self,
                    'user') or self.user is None:  # User does not exist yet
                user_manipulator.create(email=self.email.data,
                                        password=self.password.data,
                                        name=cu.get_name(),
                                        active=True)
            else:
                if not self.user.password:  # password not set
                    return False
                if not self.user.validate_password(
                        self.password.data):  # Invalid passwd
                    self.user.password = self.password.data
                    user_manipulator.save(self.user)
                if requires_confirmation(self.user):
                    return False
                if not self.user.is_active() and cu.is_real_user(
                ):  # Disabled account
                    self.user.active = True
                    user_manipulator.save(self.user)

            # revalidate
            return super(AdsClassicFallBackLoginForm, self).validate()

        elif cu.is_real_user(
        ):  # they didn't get it, but the account at least exists...
            if self.user is None:
                user_manipulator.create(email=self.email.data,
                                        password=gen_salt(12),
                                        name=cu.get_name(),
                                        active=False)
        return False
Ejemplo n.º 8
0
    def validate(self):
        r = super(AdsClassicFallBackLoginForm, self).validate()
        if r is True:
            return r
        
        cu = None
        try:
            cu = ClassicUserInfo(self.email.data, self.password.data)
        except HTTPError:
            return False  # if we can't contact ADS Classic, make it non-fatal

        if cu.is_authenticated(): # Classic did let them in....
            
            if not hasattr(self, 'user') or self.user is None:  # User does not exist yet
                user_manipulator.create(email=self.email.data, 
                                     password=self.password.data,
                                     name=cu.get_name(),
                                     active=True)
            else:
                if not self.user.password: # password not set
                    return False
                if not self.user.validate_password(self.password.data): # Invalid passwd 
                    self.user.password = self.password.data
                    user_manipulator.save(self.user)
                if requires_confirmation(self.user):
                    return False
                if not self.user.is_active() and cu.is_real_user(): # Disabled account
                    self.user.active = True
                    user_manipulator.save(self.user)
                
            # revalidate
            return super(AdsClassicFallBackLoginForm, self).validate()
        
        elif cu.is_real_user(): # they didn't get it, but the account at least exists...
            if self.user is None:
                user_manipulator.create(email=self.email.data, 
                                     password=gen_salt(12),
                                     name=cu.get_name(),
                                     active=False)
        return False
Ejemplo n.º 9
0
class UserRegistrationView(Resource):
    """
    Implements new user registration
    """

    decorators = [
        ratelimit.shared_limit_and_check("50/600 second", scope=scope_func)
    ]

    def post(self):
        """
        Standard user registration workflow;
        verifies that the email is available, creates a de-activated accounts,
        and sends verification email that serves to activate said account
        """
        try:
            data = get_post_data(request)
            email = data['email']
            password = data['password1']
            repeated = data['password2']
            verify_url = data['verify_url']
        except (AttributeError, KeyError):
            return {'error': 'malformed request'}, 400

        if not verify_recaptcha(request):
            return {'error': 'captcha was not verified'}, 403
        if password != repeated:
            return {'error': 'passwords do not match'}, 400
        try:
            validate_email(email)
            validate_password(password)
        except ValidationError, e:
            return {'error': 'validation error'}, 400

        if user_manipulator.first(email=email) is not None:
            return {
                'error':
                'an account is already'
                ' registered for {0}'.format(email)
            }, 409
        send_email(email_addr=email,
                   base_url=verify_url,
                   email_template=WelcomeVerificationEmail,
                   payload=email)
        u = user_manipulator.create(
            email=email,
            password=password,
            active=True,
            registered_at=datetime.datetime.now(),
            login_count=0,
        )
        return {"message": "success"}, 200
Ejemplo n.º 10
0
    def setUp(self):
        @self.app.route('/postlogin')
        def username():
            if current_user.is_authenticated():
                return current_user.email
            return u'Anonymous'

        @self.app.errorhandler(404)
        def handle_404(e):
            raise e
        db.create_all(app=self.app)

        FlaskAppTestCase.setUp(self)

        user = user_manipulator.create(email='montysolr', password='******', active=True)
        self.user = user

        from adsws.modules.oauth2server.models import OAuthClient, Scope, OAuthToken
        from adsws.modules.oauth2server.registry import scopes as scopes_registry

        # Register a test scope
        scopes_registry.register(Scope('adsws:internal'))
        self.base_url = self.app.config.get('SITE_SECURE_URL')

        # create a client in the database
        c1 = OAuthClient(
            client_id='bumblebee',
            client_secret='client secret',
            name='bumblebee',
            description='',
            is_confidential=False,
            user_id=user.id,
            _redirect_uris='%s/client/authorized' % self.base_url,
            _default_scopes="adsws:internal",
            ratelimit=1.0
        )
        db.session.add(c1)
        db.session.commit()

        self.oauth = OAuth(self.app)

        # have the remote app ready
        self.authenticate()
Ejemplo n.º 11
0
    def test_users_crud_operations(self):
        """
        perform and test create, read, update, and delete patterns on user
        models using the `user_manipulator` service
        """

        # .new() should not save the User to the database
        joe = user_manipulator.new(email='joe')
        self.assertIsNone(user_manipulator.first(email='joe'))

        # .save() should save the User to the database
        user_manipulator.save(joe)
        u = user_manipulator.first(email='joe')
        self.assertIsNotNone(u)
        self.assertEqual(u.email, 'joe')

        # .create() should create immediately
        elias = user_manipulator.create(email='elias')
        u = user_manipulator.first(email='elias')
        self.assertIsNotNone(u)
        self.assertEqual(elias, u)

        # .update() should update immediately
        user_manipulator.update(elias, confirmed_at=datetime(2000, 1, 1))
        u = user_manipulator.first(email='elias')
        self.assertEqual(u.confirmed_at, datetime(2000, 1, 1))
        self.assertEqual(elias, u)

        # .delete() should delete immediately
        user_manipulator.delete(elias)
        u = user_manipulator.first(email='elias')
        self.assertIsNone(u)

        # even though this object was deleted in the db, we still should
        # have a reference to the python object
        self.assertIsNotNone(elias)
        self.assertEqual(elias.confirmed_at, datetime(2000, 1, 1))
Ejemplo n.º 12
0
    def test_users_crud_operations(self):
        """
        perform and test create, read, update, and delete patterns on user
        models using the `user_manipulator` service
        """

        # .new() should not save the User to the database
        joe = user_manipulator.new(email='joe')
        self.assertIsNone(user_manipulator.first(email='joe'))

        # .save() should save the User to the database
        user_manipulator.save(joe)
        u = user_manipulator.first(email='joe')
        self.assertIsNotNone(u)
        self.assertEqual(u.email, 'joe')

        # .create() should create immediately
        elias = user_manipulator.create(email='elias')
        u = user_manipulator.first(email='elias')
        self.assertIsNotNone(u)
        self.assertEqual(elias, u)

        # .update() should update immediately
        user_manipulator.update(elias, confirmed_at=datetime(2000, 1, 1))
        u = user_manipulator.first(email='elias')
        self.assertEqual(u.confirmed_at, datetime(2000, 1, 1))
        self.assertEqual(elias, u)

        # .delete() should delete immediately
        user_manipulator.delete(elias)
        u = user_manipulator.first(email='elias')
        self.assertIsNone(u)

        # even though this object was deleted in the db, we still should
        # have a reference to the python object
        self.assertIsNotNone(elias)
        self.assertEqual(elias.confirmed_at, datetime(2000, 1, 1))
Ejemplo n.º 13
0
    def setUp(self):
        """
        Sets up all of the users, clients, and tokens that management commands
        will run against.
        """

        db.create_all(app=self.app)

        now = datetime.datetime.now()
        delta = datetime.timedelta
        times = [
            now,
            now-delta(seconds=3),
            now+delta(seconds=3),
            now+delta(hours=1),
        ]
        self.times = times  # Save for comparisons in the tests

        # This is a user that has registered but not confirmed their account
        u = user_manipulator.create(
            email="unconfirmed@unittest",
            registered_at=now+delta(seconds=1),
        )
        db.session.add(u)

        # This is a user that has registered but not confirmed their account,
        # and furthermore will not have a registered_at attribute set
        u = user_manipulator.create(
            email="blankuser@unittest",
        )
        db.session.add(u)

        # This is a user that has registered and confirmed their account
        u = user_manipulator.create(
            email="user@unittest",
            registered_at=now,
            confirmed_at=now,
        )
        db.session.add(u)

        for _time in times:

            client = OAuthClient(
                user_id=u.id,
                client_id=gen_salt(20),
                client_secret=gen_salt(20),
                is_confidential=False,
                is_internal=True,
                _default_scopes="",
                last_activity=_time,
            )
            db.session.add(client)

            token = OAuthToken(
                client_id=client.client_id,
                user_id=u.id,
                access_token=gen_salt(20),
                refresh_token=gen_salt(20),
                expires=_time,
                _scopes="",
                is_personal=False,
                is_internal=True,
            )
            db.session.add(token)

        # Add a client without a last_activity to verify that the cleanup
        # scripts do not break under this condition
        client = OAuthClient(
            user_id=u.id,
            client_id=gen_salt(20),
            client_secret=gen_salt(20),
            is_confidential=False,
            is_internal=True,
            _default_scopes="",
        )
        db.session.add(client)

        # Add a token without an expiry to verify that the cleanup scripts
        # do not break under this condition
        token = OAuthToken(
            client_id=client.client_id,
            user_id=u.id,
            access_token=gen_salt(20),
            refresh_token=gen_salt(20),
            _scopes="",
            is_personal=False,
            is_internal=True,
        )
        db.session.add(token)
        db.session.commit()