Ejemplo n.º 1
0
 def test_activate_user(self):
     test_user = User(username='******', password='******')
     self.assertFalse(test_user.is_active, "Test_user is active after .deactivate().")
     test_user.activate()
     self.assertTrue(test_user.is_active, "Test_user is inactive after .activate().")
     test_user.deactivate()
     self.assertFalse(test_user.is_active, "Test_user is active after .deactivate().")
Ejemplo n.º 2
0
    def post(self):

        form = CreateUserForm(self)

        if form.validate():

            user = self.db.query(User).filter_by(
                username=form.username.data ).first()

            if user:
                form.username.errors.append(
                    _('This username is occupied') )
            else:
                enc_password = enc_login_passwd(form.password.data)

                new = User( username = form.username.data,
                            password = enc_password )
                self.db.add( new )
                self.db.commit()

                new.init_account(self.db)

                profile = UserProfile( new )
                self.db.add(profile)
                self.db.commit()

                url = self.reverse_url('admin:user:view')
                url += '?id=%s' % new.id
                return self.redirect( url )

        self.render( form = form )
Ejemplo n.º 3
0
 def test_user_password(self):
     test_user = User(username='******', password='******')
     self.assertTrue(test_user.check_password('test_pass'), "Wrong password hash generated after creting user.")
     self.assertIn('pbkdf2:sha256:1000$', test_user.password)
     self.assertEqual(len(test_user.password), 92, "Wrong hash length.")
     test_user.set_password('another_password')
     self.assertIn('pbkdf2:sha256:1000$', test_user.password)
     self.assertEqual(len(test_user.password), 92, "Wrong hash length.")
     self.assertTrue(test_user.check_password('another_password'), "Wrong password hash generated after setting password.")
def create_dummy_user(
        email='*****@*****.**',
        name='AzureDiamond',
        password='******'):
    user = User()
    user.name = name
    user.set_password(password)
    user.email = email
    return user
Ejemplo n.º 5
0
 def test_confirm_new_email_works_with_generated_token(self, app):
     """confirm_new_mail should return True & set email w/ valid token."""
     user = User()
     user.id = 42
     user.email = '*****@*****.**'
     new_email = '*****@*****.**'
     token = user.generate_new_email_token(new_email)
     assert user.confirm_new_email(token)
     assert new_email == user.email
def make_dummy_user():
    """Create a basic dummy for testing.

    Returns:
        User: A basic user with no confirmed account or privileges.
    """
    user = User()
    user.name = 'AzureDiamond'
    user.set_password('hunter2')
    user.email = '*****@*****.**'
    return user
Ejemplo n.º 7
0
def set_admin(login, password):
    """
    Creates new user (login=<email>) or updates its password
    """

    form = ConsoleRegisterForm(login=login, password=password)
    if form.validate():
        try:
            User.set_admin(login, password)
            print 'Admin-user created (%s)' % login
        except Exception, e:
            print e
Ejemplo n.º 8
0
    def test_revoke_permission(self, app):
        """revoke_permission should remove perm if set.

        It should not change anything if the permission given isn't set.
        """
        user = User()
        user.permissions = 0b111
        user.revoke_permission(0b10)
        assert user.permissions == 0b101
        user.revoke_permission(0b1)
        assert user.permissions == 0b100
        # Revoking unset permissions shouldn't change anything.
        user.revoke_permission(0b10)
        assert user.permissions == 0b100
        user.revoke_permission(0b1)
        assert user.permissions == 0b100
Ejemplo n.º 9
0
    def test_can(self, app):
        """can should return True if user has permission, False if not.

        Note:
            Permissions are in the form of set bits in an integer. Since the
            actual Permission attributes may change in the future, we can
            more easily test can() with dummy permissions here, it works the
            same way as using Permission attributes insted.
        """
        user = User()
        perm1 = 0b1
        perm2 = 0b10
        perm3 = 0b100
        user.permissions = perm1 | perm3    # 0b101
        assert user.can(perm1)
        assert user.can(perm3)
        assert not user.can(perm2)
Ejemplo n.º 10
0
 def test_password_reset(self, app):
     """Password should be reset if given a valid token and a new pass."""
     user = User()
     user.id = 42
     user.set_password('hunter2')
     token = user.generate_password_reset_token()
     newpass = '******'
     assert user.reset_password(token, newpass)
     assert user.verify_password(newpass)
Ejemplo n.º 11
0
 def test_confirm_new_email_bad_token_or_wrong_user(self, app):
     """confirm_new_email returns false if token is bad or wrong user."""
     user1 = User()
     user1.id = 42
     user2 = User()
     user2.id = 33
     token = user1.generate_new_email_token('*****@*****.**')
     assert not user2.confirm_new_email(token)
     assert not user1.confirm_account('badtoken')
Ejemplo n.º 12
0
 def test_confirm_account_bad_token_or_wrong_user(self, app):
     """confirm_account returns false if token is bad or for wrong user."""
     user1 = User()
     user1.id = 42
     user2 = User()
     user2.id = 33
     token = user1.generate_account_confirmation_token()
     assert not user2.confirm_account(token)
     assert not user1.confirm_account('badtoken')
Ejemplo n.º 13
0
 def test_reset_password_bad_token_or_wrong_user(self, app):
     """reset_password returns false with a bad token or wrong user."""
     user1 = User()
     user1.id = 42
     user2 = User()
     user2.id = 33
     token = user1.generate_password_reset_token()
     assert not user2.reset_password(token, 'foo')
     assert not user1.reset_password('badtoken', 'foo')
Ejemplo n.º 14
0
class TestAuthModels(unittest.TestCase):

    def setUp(self):
        self.app = app.test_client()
        self.user = User('admin')

    def tearDown(self):
        pass

    def test_is_authenticated(self):
        self.assertEquals(True, self.user.is_authenticated())

    def test_is_active(self):
        self.assertEquals(True, self.user.is_active())

    def test_is_anonyous(self):
        self.assertEquals(False, self.user.is_anonymous())

    def test_get_id(self):
        self.assertEquals('admin', self.user.get_id())
Ejemplo n.º 15
0
    def populate(self):
        """Populate the model with test data"""

        # Create the default user
        user = User(email=self.user.get('email'), password=self.user.get('password'))
        user.details = UserDetails(name=self.user.get('name'), user=user)
        db.session.add(user)

        # Create administrator
        admin = User(email=self.admin.get('email'), password=self.admin.get('password'), is_admin=True)
        admin.details = UserDetails(name=self.admin.get('name'), user=admin)
        db.session.add(admin)

        # Create application owner
        owner = User(email=self.owner.get('email'), password=self.owner.get('password'))
        owner.details = UserDetails(name=self.owner.get('name'), user=owner)
        db.session.add(owner)

        app = Application(owner=owner, name=self.application.get('name'))
        db.session.add(app)

        # Create a client
        client = Client(app=app, name=self.client.get('name'),
                        allowed_grant_types=[GrantTypes.PASSWORD, GrantTypes.REFRESH_TOKEN],
                        _default_scopes='user other',
                        _redirect_uris='http://localhost')
        db.session.add(client)
        db.session.commit()

        # Remember the values
        self.user['id'] = user.username
        self.admin['id'] = admin.username
        self.owner['id'] = owner.username
        self.application['id'] = app.id
        self.client['id'] = client.client_id
Ejemplo n.º 16
0
    def post(self):

        form = self.form
        openid = self.openid

        if form.validate():

            encpass = enc_login_passwd(form.password.data)
            U = User( username = form.username.data,
                      password = encpass,
                      language = self.language )

            user_info = self.get_user_info
            U.nickname = user_info.get('nickname', U.username)

            U.email = form.email.data

            self.db.add( U )
            self.db.commit()

            U.init_account(self.db)
            U.last_login = datetime.datetime.now()
            openid.user_id = U.id
            self.db.commit()

            self.save_session(U.id)
            self.db.delete(self.K)
            self.db.commit()

            return self.redirect_next('/account')

        self.render()
Ejemplo n.º 17
0
def admin(email):
    """Create an administrator account"""

    # Check if the user already exists
    user = User.query.filter(User.email == email).first()
    if not user:
        user = User(email=email)
        user.password = query_password()
        db.session.add(user)
        sys.stdout.write("Creating '%s'" % email)
    else:
        sys.stdout.write("User '%s' already exists " % email)

    if not Grant.check_grant(user, Roles.ADMIN):
        if query_yes_no(", are you sure you want to grant admin rights?", default="no"):
            db.session.add(Grant(user=user, role=Roles.ADMIN))
            db.session.commit()
            return "User with email '%s' is now an administrator" % email
        else:
            return "Command cancelled"

    print("and is an administrator.")
Ejemplo n.º 18
0
    def authenticate(self, username, password, app):
        mongo_service = services.Mongo()
        print(username, password, app)
        u = mongo_service.authenticate_user(username, app)

        if u:
            user = User(u["email"], u["password"], u["name"], u["app"], u["admin"])
            if password == user.password:
                user.set_authenticated(True, "User successfully authenticated")
            else:
                user.set_authenticated(False, "Invalid Password")
        else:
            user = User(username, password, None, app, None)
            user.set_authenticated(False, "Username not found")
        return user
Ejemplo n.º 19
0
    def setUp(self):
        from app import app
        app.config.update(
            SERVER_NAME='localhost:%s' % app.config.get('PORT')
        )
        self.app = app.test_client()
        from app import db
        self.db = db

        user = User('%s' % str(uuid.uuid4())[:8],
                    '*****@*****.**' % str(uuid.uuid4())[:8],
                    '%s' % str(uuid.uuid4())[:8])
        user.role_admin = True
        self.db.session.add(user)
        self.user_admin = user

        user = User('%s' % str(uuid.uuid4())[:8],
                    '*****@*****.**' % str(uuid.uuid4())[:8],
                    '%s' % str(uuid.uuid4())[:8])
        self.db.session.add(user)
        self.user_user = user

        self.baseUrl = 'http://localhost:%s' % app.config.get('PORT')
Ejemplo n.º 20
0
def login():
    if "user_id" in session:
        return redirect("/posts/")

    form = LoginForm(request.form)
    # Verify the sign in form
    if form.validate_on_submit():
        user = User.query(User.email == form.email.data).get()
        if user and check_password_hash(user.password, form.password.data):
            session["user_id"] = user.key.id()
            flash("Welcome %s" % user.name)
            return redirect("/posts/")

        flash("Invalid email or password", "error")

    return render_template("auth/signin.html", form=form)
Ejemplo n.º 21
0
def reset_password(token):
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    user = User.validate_reset_password_token(token)
    if not user:
        return redirect(url_for('auth.forgot_password'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        user.set_password(form.password.data)
        db.session.commit()
        flash(
            'Your password has been changed successfully. Try signing in with it here.'
        )
        return redirect(url_for('auth.login'))
    return render_template('reset_password.html',
                           title='Reset password',
                           form=form)
Ejemplo n.º 22
0
    def test_new_user_fail(self, test_client) -> None:
        """
        GIVEN a wrong User model
        WHEN a new User is created
        THEN check the name, email and password
        :return: None
        """
        from app.auth.models import User

        new_user = User(name="TestUser",
                        email="*****@*****.**",
                        password="******")

        assert new_user.id != 1
        assert new_user.name == "TestUser"
        assert new_user.email == "*****@*****.**"
        assert new_user.password == "TestPassword"
Ejemplo n.º 23
0
 def test_change_password(self):
     user = User.get_by(username='******')
     self.login(username_or_email=user.email)
     headers = self.set_api_headers(token=self.auth_token)
     data = {'new_password': '******'}
     url = url_for('auth.change_password', _external=True)
     response = self.client.post(
         url,
         content_type=self.JSON,
         headers=headers,
         data=json.dumps(data),
     )
     response.json = self.get_json_response(response)
     self.assertEqual(response.status_code, 200)
     self.assertIsNotNone(response.json['data']['message'])
     user.password = '******'
     db.session.commit()
Ejemplo n.º 24
0
 def test_change_email_request(self):
     user = User.get_by(id=1)
     token = user.generate_auth_token(3600)
     url = url_for('auth.change_email_request', _external=True)
     data = {'new_email': '*****@*****.**'}
     response = self.client.post(url,
                                 content_type=self.JSON,
                                 headers=self.set_api_headers(token=token),
                                 data=json.dumps(data))
     response.json = self.get_json_response(response)
     self.assertEqual(response.status_code, 201)
     self.assertIsNotNone(response.json['data']['token'])
     self.assertIsNotNone(response.json['data']['confirm_email_url'])
     self.assertIsNotNone(response.json['data']['expiration'])
     user.set_confirmed(commit=False)
     user.email = '*****@*****.**'
     db.session.commit()
Ejemplo n.º 25
0
def reset_password(token):
    if current_user.is_authenticated:
        return redirect(url_for('posts.home'))

    user = User.verify_reset_token(token)
    if not user:
        flash('The Link has been expired, make a new request', 'warning')
        return redirect(url_for('auth.reset_request'))

    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')

        user.password = hashed_password
        db.session.commit()
        flash("The password has been changed.", "success")
    return render_template('reset_password.html', form=form)
Ejemplo n.º 26
0
def signup():
    """User signup page."""

    form = RegistrationForm()

    if form.validate_on_submit():
        new_user = User.create(
            form.name.data,
            form.username.data,
            form.email.data,
            form.password.data,
        )
        do_login(new_user)

        return redirect(url_for('twitter.dashboard'))

    return render_template('auth/signup.html', form=form)
Ejemplo n.º 27
0
 def test_customer_sign_up_correctly(self):
     with self.app.app_context():
         res = self.client.post("/api/auth/signup-customer",
                                json={
                                    "username": "******",
                                    "password": "******",
                                    "passwordconfirmation": "12341234",
                                    "name": "Juan",
                                    "surname": "Garrido",
                                    "nif": "12345678A",
                                    "email": "*****@*****.**"
                                })
         user = User.get_by_username("test1")
         customer = Customer.get_by_nif("12345678A")
         self.assertEqual(200, res.status_code)
         self.assertEqual("test1", user.username)
         self.assertEqual("12345678A", customer.nif)
Ejemplo n.º 28
0
def delete_invoice(invoice_number):
    invoice = Invoice.get_by_invoice_number(invoice_number)
    invoice.delete()
    contract = Contract.get_by_contract_number(invoice.contract_number)
    invoices = __get_invoices(contract.contract_number)
    if len(invoices) == 0:
        logged_user = User.get_by_username(get_jwt_identity())
        logged_customer = Customer.get_by_user_id(logged_user.id)
        nif = logged_customer.nif
        cus_dwe_con = Customer_Dwelling_Contract \
         .get_by_nif_and_contract_number(
          nif,
          invoice.contract_number
         )
        cus_dwe_con.delete()
        contract.delete()
    return "", 200
Ejemplo n.º 29
0
def admin():
    logged_user = google_users.get_current_user()
    form = AdminForm(request.form)
    if form.validate_on_submit():
        user = User()
        user.email = form.email.data
        user.name = form.name.data
        user.password = generate_password_hash(form.password.data)
        user.put()
        return redirect(url_for("auth.admin"))

    users = User.query().order(-User.created_at)
    return render_template(
        "auth/admin.html", form=form, users=users, logged_user=logged_user, google_users=google_users
    )
Ejemplo n.º 30
0
    def test_new_user_fail(self, test_client) -> None:
        """
        GIVEN a wrong User model
        WHEN a new User is created
        THEN check the name, email and password
        :return: None
        """
        from app.auth.models import User

        new_user = User(name=TestConstants.TEST_USER_NAME,
                        email=TestConstants.TEST_USER_EMAIL_3,
                        password=TestConstants.TEST_USER_PASSWORD)

        assert new_user.id != 1
        assert new_user.name == TestConstants.TEST_USER_NAME
        assert new_user.email == TestConstants.TEST_USER_EMAIL_3
        assert new_user.password == TestConstants.TEST_USER_PASSWORD
Ejemplo n.º 31
0
def register():
    try:
        if current_user.is_authenticated:
            return redirect(url_for('main.homepage'))
        form = RegisterForm()
        if form.validate_on_submit():
            nUser = User.register(form)
            flash('Registrazione confermata per utente {}'.format(nUser.email))

            login_user(nUser)
            return redirect(url_for('main.homepage'))

        return redirect(url_for("auth.login"))
        #return render_template('auth/user/register.html', title="Register", form=form)
    except Exception as e:
        flash("Errore: " + str(e))
        return redirect(url_for("auth.login"))
Ejemplo n.º 32
0
def make_guinea_pig():
    """Create an additional dummy user when more than one user is needed.

    Returns:
        User: A basic user with a confirmed account but no privileges.
    """
    cavy = User()   # Cavy is another name for guinea pig.
    cavy.email = '*****@*****.**'
    cavy.name = 'Mister Squeals'
    cavy.set_password('food')
    cavy.confirmed = True
    return cavy
Ejemplo n.º 33
0
def signup():
    if current_user.is_active:
        flash('Already logged in', 'info')
        return redirect(url_for('index.home'))
    # If sign in form is submitted
    form = SignUpForm(request.form)
    # Verify the sign in form
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if not user and form.password.data == form.password_confirm.data:
            # SQL_I Safe Code
            new_user = User(email=form.email.data,
                            password=PasswordLib().get_hashed_password(
                                form.password.data),
                            name=form.name.data,
                            company=form.company.data)
            # Original SQL Alchemy function
            # db.session.add(new_user)

            # SQL_I Vulnerable Code
            db.engine.execute(
                "INSERT INTO auth_user (id, date_created, date_modified, name, email, password, status, company)\
                 VALUES ('%s', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '%s', '%s', '%s', %d, '%s')"
                % (new_user.id, new_user.name, new_user.email,
                   new_user.password, 1, new_user.company))

            # SQL_I Protected Using Parameters
            # db.engine.execute(
            #     "INSERT INTO auth_user (id, date_created, date_modified, name, email, password, status, company)\
            #     VALUES (?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?, ?, 1, ?)",
            #     new_user.id, new_user.name, new_user.email, new_user.password, new_user.company
            # )

            password_history = History(userid=new_user.id,
                                       password=new_user.password)
            db.session.add(password_history)
            db.session.commit()
            flash(f'Welcome {form.name.data}! user created successfully',
                  'info')
            return redirect(url_for('index.home'))
        if form.password.data != form.password_confirm.data:
            flash('Password don\'t match!', 'error')
        else:
            flash('User already exists!', 'error')
    return render_template("auth/signup.html", form=form)
Ejemplo n.º 34
0
    def get_notices():
        notices = Notice.query.order_by(desc(Notice.modified))

        # check if signed in
        if hasattr(g, 'user'):
            user = g.user
        else:
            auth_header = request.headers.get('Authorization', 'Null')
            token = auth_header
            user = User.verify_auth_token(token)
        if not user:
            notices = notices.filter_by(is_public=True)

        # check if the user is admin
        if not user or not user.has_permission('admin'):
            notices = notices.filter_by(is_shown=True)

        return notices
Ejemplo n.º 35
0
    def test_confirm_email(self, db):
        unverified_user = User(email='*****@*****.**',
                               first_name='hi',
                               last_name='there',
                               hashed_password='******')
        db.add(unverified_user)
        db.commit()

        assert not unverified_user.email_verified

        confirm_link = get_email_confirmation_link(
            app.url_path_for('confirm_email'), unverified_user.email)

        response = client.get(confirm_link)
        assert response.status_code == status.HTTP_200_OK
        assert response.json()['detail'] == 'ok'
        db.refresh(unverified_user)
        assert unverified_user.email_verified
Ejemplo n.º 36
0
def login():
    """User login page."""
    # If the user has an active session, redirect home
    if 'uid' in session:
        g.user = User.query.get(session['uid'])
        if g.user is not None:
            return redirect(url_for('twitter.dashboard'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.authenticate(form.username.data, form.password.data)
        if user is not None:
            do_login(user)
            return redirect(url_for('twitter.dashboard'))
        else:
            form.username.errors.append(
                'The username and password you entered did not match our records. Please double-check and try again.')

    return render_template('auth/login.html', form=form)
Ejemplo n.º 37
0
    def decorated(*args, **kwargs):
        token = None

        if 'Authorization' in request.headers:
            token = request.headers['Authorization'][7:]
        if not token:
            return jsonify({'message': 'Token is missing.'}), 401
        try:
            public_id = User.decode_auth_token(token)
        except jwt.ExpiredSignatureError:
            return jsonify(
                {'message':
                 'Token signature expired. Please log in again.'}), 401
        except jwt.InvalidTokenError:
            return jsonify({'message':
                            'Invalid token. Please log in again.'}), 401
        current_user = User.query.filter_by(public_id=public_id).first()
        return f(current_user, *args, **kwargs)
Ejemplo n.º 38
0
def set_post(post,form):
    post.title=form.title.data
    if(post.url==None or post.url==''):
        post.url=post.slugify(post.title)
    else:
        post.url=post.slugify(post.url)
    post.description=form.description.data
    post.content=form.content.data
    post.post_type=form.post_type.data
    post.post_status=form.post_status.data
    post.author=User.get_by_id(session['user_id'])
    post.category=Category(name=form.category.data)
    my_tags = []
    for tag in form.tags.data.lower().split(','):
        my_tags.append(Tag(name=tag))
    post.tags=my_tags

    return post
Ejemplo n.º 39
0
    def test_model_write(self, app):
        """Can our model be used to write data to the DB?"""

        with app.app_context():
            new_user = User(
                username='******',
                email='*****@*****.**',
                password='',
            )

            db.session.add(new_user)
            db.session.commit()

            extracted_user = User.query.first()

            assert extracted_user is not None
            assert extracted_user.username == 'Test'
            assert extracted_user.email == '*****@*****.**'
Ejemplo n.º 40
0
def createsuperuser(username="******", email="root@localhost"):
    """
    Create a superuser
    """
    import getpass
    password = getpass.getpass()
    admin_role = Role.query.filter_by(name='Administrator').first()
    if admin_role is None:
        raise ValueError(
            'Admin role not found. Did you initialize the database with manage.py initdb'
        )
    # FIXME: check if the account exists first
    u = User(username=username,
             email=email,
             role=admin_role,
             password=password)
    db.session.add(u)
    db.session.commit()
Ejemplo n.º 41
0
    def test_follow(self):
        # users creation
        u1 = User(username='******', email='*****@*****.**')
        u2 = User(username='******', email='*****@*****.**')
        db.session.add(u1)
        db.session.add(u2)
        db.session.commit()

        self.assertEqual(u1.followed.all(), [])
        self.assertEqual(u2.followed.all(), [])

        u1.follow(u2)
        db.session.commit()
        self.assertTrue(u1.is_following(u2))
        self.assertEqual(u1.followed.count(), 1)
        self.assertEqual(u1.followed.first().username, 'susan')
        self.assertEqual(u2.followers.count(), 1)
        self.assertEqual(u2.followers.first().username, 'john')

        u1.unfollow(u2)
        db.session.commit()
        self.assertFalse(u1.is_following(u2))
        self.assertEqual(u1.followed.count(), 0)
        self.assertEqual(u2.followers.count(), 0)
Ejemplo n.º 42
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for("home.home"))
    form = RegistrationForm()

    if form.validate_on_submit():

        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode("utf-8")
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=hashed_password)
        db.session.add(user)
        db.session.commit()
        flash("Account created", "primary")

        return redirect(url_for("auth.login"))

    return render_template("auth/register.html", title="Register", form=form)
Ejemplo n.º 43
0
    def test_known_user(self):
        user = User(username=USERNAME,
                    password_hash=generate_password_hash(PASSWORD),
                    role_id=1)

        db.session.add(user)
        db.session.commit()

        response = self.client.post('/auth/login',
                                    data={
                                        'username': USERNAME,
                                        'password': PASSWORD
                                    })

        self.assertEqual(response.status_code, 302)
        self.assertTrue('/index' in response.get_data(as_text=True))
        with self.client.session_transaction() as session:
            self.assertTrue(('message',
                             'Successfully signed in.') in session['_flashes'])
Ejemplo n.º 44
0
def create_user(name: str, email: str, password: str) -> Tuple:
    """
    This method creates the new user
    or throws ValueError if email
    already exists.
    :param name: Name of user in form of string
    :param email: Email of user in form of string
    :param password: Password of user in form of string
    :return: Tuple of None and ( ValueError or User Details )
    """
    user = User.query.filter_by(email=email).first()
    password = generate_password_hash(password)
    if not user:
        user = User(name=name, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        return None, user_schema.dump(user)
    else:
        return ValueError(ErrorMessage.EMAIL_ALREADY_EXISTS), None
Ejemplo n.º 45
0
def is_authorized():
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_header = auth_header
        auth_token = auth_header.split(" ")
        if len(auth_token) > 1:
            auth_token = auth_token[1] if len(auth_token) > 1 else ''
        else:
            return False, _('Bad authentication. Please try again')
    else:
        return False, _('Bad authentication. Please try again')

    if auth_token:
        try:
            resp = User.decode_auth_token(auth_token)
        except Exception as e:
            return False, str(e)

        return True, resp
Ejemplo n.º 46
0
def login():
    if current_user.is_authenticated:
        return redirect(page_not_found("e"))

    form = LoginForm()

    if form.validate_on_submit():
        user = User.get_by_username(form.username.data)
        if user is None or not user.check_password(form.password.data):
            flash("Invalid username or password", 'danger')
            return redirect(url_for("auth.login"))

        login_user(user, remember=form.remember_me.data)
        flash(f'You are logged in!', 'success')
        return redirect(request.args.get('next') or url_for('main.home'))

    random_image = f"shop_{randint(1, 5)}.webp"

    return render_template('login.html', form=form, random=random_image)
Ejemplo n.º 47
0
def reset_token(token):
    if current_user.is_authenticated:
        return redirect(url_for('main_bp.home'))
    user = User.verify_reset_token(token)
    if user is None:
        flash('That is an invalid or expired token', 'warning')
        return redirect(url_for('auth_bp.reset_request'))
    form = ResetPasswordForm()
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(
            form.password.data).decode('utf-8')
        user.password = hashed_password
        db.session.commit()
        flash('Your password has been updated! You are now able to log in',
              'success')
        return redirect(url_for('auth_bp.login'))
    return render_template('auth/reset_token.html',
                           title='Reset Password',
                           form=form)
Ejemplo n.º 48
0
 def test_title_slug_duplicated(self):
     with self.app.app_context():
         admin = User.get_by_email('*****@*****.**')
         post = Post(user_id=admin.id,
                     title='Prueba',
                     content='Lorem Ipsum')
         post.save()
         post_2 = Post(user_id=admin.id,
                       title='Prueba',
                       content='Lorem Ipsum Lorem Ipsum')
         post_2.save()
         self.assertEqual('prueba-1', post_2.title_slug)
         post_3 = Post(user_id=admin.id,
                       title='Prueba',
                       content='Lorem Ipsum Lorem Ipsum')
         post_3.save()
         self.assertEqual('prueba-2', post_3.title_slug)
         posts = Post.get_all()
         self.assertEqual(3, len(posts))
Ejemplo n.º 49
0
    def test_update_permission(self, app):
        """update_permission returns True if updated, false if not.

        It should also change the user's permission if updated.
        """
        user = User()
        user.permissions = 0
        perm1 = 0b1
        perm2 = 0b10
        assert update_permission(user, perm1, True, 'perm1')
        assert user.can(perm1)
        assert not update_permission(user, perm1, True, 'perm1')
        assert user.can(perm1)
        assert update_permission(user, perm2, True, 'perm2')
        assert user.can(perm2)
        assert update_permission(user, perm1, False, 'perm1')
        assert not user.can(perm1)
        assert user.can(perm2)
Ejemplo n.º 50
0
    def _on_user_info2(self, data):

        data = json.loads(data)

        ret = data.get('ret', None)
        if ret != 0:
            self.write(_('QQ auth failed: %s') % data.get('msg', ''))
            return self.finish()

        # create new user
        O = OpenID(openid=self.openid, _type=1)  # TODO: QQ now
        O.config = json.dumps({'get_user_info': data})
        self.db.add(O)
        self.db.commit()

        while True:
            username = '******' % random.randint(1, 10000000)
            U = self.db.query(User).filter_by(username=username).first()
            if not U: break

        U = User(username=username,
                 password='******',
                 language=self.language)

        U.nickname = data.get('nickname', None)
        U.email_valid = True
        self.db.add(U)
        self.db.commit()

        U.init_account(self.db)

        self.save_session(U.id)
        U.last_login = datetime.datetime.now()

        O.user_id = U.id

        self.db.commit()

        # TODO: drop account relationships
        profile = UserProfile(U)
        self.db.add(profile)
        self.db.commit()

        self.redirect('/account')
Ejemplo n.º 51
0
 def _log_in_as(self, user):
     roles = user.get('roles') or []
     email, password = user['email'], user['password']
     user = User.query.filter_by(email=email).first()
     if user is None:
         user = User.create_user(username=email,
                                 email=email,
                                 password=hash_password(password))
     for role in roles:
         self._add_role_name_to_user(user, role)
     resp = self.client.post(
         url_for('auth.login'),
         data={
             'email': email,
             'password': password,
             'remember': 'y'  # Not sure why it's required, but some
             # test cases having follow_redirects=True
             # fails without it.
         })
     self.assertEqual(resp.status_code, 302)
Ejemplo n.º 52
0
def register():
    if current_user.is_authenticated:
        flash("You are already logged in", 'warning')
        return redirect(url_for("posts.home"))

    form = RegistrationForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        email = form.email.data
        hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')

        new_user = User(username= username, email=email, password=hashed_password)

        db.session.add(new_user)
        db.session.commit()

        flash("Cool, you're done. {}" .format(username), 'success')
        return redirect(url_for('auth.login'))
    return render_template("register.html", reg_form=form)
Ejemplo n.º 53
0
def reset_password_set(token):
	if current_user.is_authenticated:
		return redirect(url_for('catalogue.home'))
	user = User.verify_reset_token(token)
	if not(user):
		flash("Token is invalid or expired","error")
		return redirect(url_for("authentication.reset_password_request"))
	form = ResetPasswordForm()
	if form.validate_on_submit():
		user = User.query.filter_by(user_email=form.email.data).first()
		if not user:
			flash("User does not exists","error")
			return redirect(url_for("authenticatoion.update_password"))
		
		user.update_password(form.new_password.data)
		
		flash("Password Updated Sucessfully","green")
		return redirect(url_for('catalogue.home'))
	form.email.data = user.user_email
	return render_template("authentication/update_forgot_password.html",form=form)
Ejemplo n.º 54
0
 def test_load_users(self, db):
     """load_users loads all users in database into select_user.choices."""
     user1 = User()
     user1.name = 'Bob'
     user1.email = '*****@*****.**'
     user2 = User()
     user2.name = 'Eris'
     user2.email = '*****@*****.**'
     db.session.add(user1)
     db.session.add(user2)
     form = SelectUserForm()
     form.load_users()
     print(form.select_user.choices)
     assert (user1.id, user1.name) in form.select_user.choices
     assert (user2.id, user2.name) in form.select_user.choices
Ejemplo n.º 55
0
    def _on_user_info2(self, data):

        data = json.loads( data )

        ret = data.get('ret', None)
        if ret != 0:
            self.write(_('QQ auth failed: %s') % data.get('msg',''))
            return self.finish()

        # create new user
        O = OpenID( openid = self.openid, _type = 1 ) # TODO: QQ now
        O.config = json.dumps( { 'get_user_info': data } )
        self.db.add(O)
        self.db.commit()

        while True:
            username = '******' % random.randint(1, 10000000)
            U = self.db.query(User).filter_by(username=username).first()
            if not U: break
            
        U = User( username = username,
                  password = '******',
                  language = self.language )

        U.nickname = data.get('nickname', None)
        U.email_valid = True
        self.db.add( U )
        self.db.commit()

        U.init_account(self.db)

        self.save_session(U.id)
        U.last_login = datetime.datetime.now()

        O.user_id = U.id

        self.db.commit()

        # TODO: drop account relationships
        profile = UserProfile( U )
        self.db.add(profile)
        self.db.commit()

        self.redirect('/account')
Ejemplo n.º 56
0
 def test_reset_password_wrong_email(self, app, db):
     """reset_password flashes and error if wrong user's email provided."""
     user = make_dummy_user()
     user.confirmed = True
     db.session.add(user)
     db.session.commit()
     token = user.generate_password_reset_token()
     user2 = User()
     user2.name = 'Ford Prefect'
     user2.set_password('knowwhereyourtowelis')
     user2.email = '*****@*****.**'
     user2.confirmed = True
     db.session.add(user2)
     db.session.commit()
     data = dict(
         email=user2.email,
         password1='heartofgold',
         password2='heartofgold')
     with app.test_client() as tc:
         rv = tc.post(url_for('auth.reset_password', token=token),
                      data=data,
                      follow_redirects=True)
     assert 'Error: Given token is invalid' in str(rv.data)
Ejemplo n.º 57
0
 def setUp(self):
     self.app = app.test_client()
     self.user = User('admin')
Ejemplo n.º 58
0
 def test_password_hashing(self, app):
     """verify_password() should return true if given correct password."""
     dummy = User()
     password = '******'
     dummy.set_password(password)
     assert dummy.verify_password(password)
Ejemplo n.º 59
0
 def test_password_attribute_raises_exception(self, app):
     """Trying to read User.password should raise an attribute error."""
     dummy = User()
     dummy.password = '******'
     with pytest.raises(AttributeError):
         dummy.password