示例#1
0
    def test_roles(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User.create(username, password)
        self.assertTrue(user.has_roles())
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User(username=username, password=password)
        role_names = map(lambda i: uuid.uuid4().hex, range(3))
        roles = []
        for role_name in role_names:
            role = Role.create(role_name)
            user.roles.append(role)
            roles.append(role)

        db.session.add(user)
        db.session.commit()
        self.assertTrue(
            user.has_roles(allowed=[roles[0].name, roles[1].name]))
        self.assertTrue(
            user.has_roles(allowed=[roles[0].name, "foo"]))
        self.assertTrue(
            user.has_roles(allowed=["foo", roles[0].name]))
        self.assertFalse(
            user.has_roles(allowed=["foo"]))
        self.assertTrue(
            user.has_roles(required=[roles[0].name, roles[1].name]))
        self.assertFalse(
            user.has_roles(required=[roles[0].name, roles[1].name, "foo"]))
    def test_get(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User.create(username, password)
        user_by_id = User.get(user.id)
        self.assertEqual(user_by_id.id, user.id)
        user_by_name = User.get(user.username)
        self.assertEqual(user_by_name.id, user.id)

        with self.assertRaises(TypeError):
            User.get(None)
    def test_get(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User.create(username, password)
        user_by_id = User.get(user.id)
        self.assertEqual(user_by_id.id, user.id)
        user_by_name = User.get(user.username)
        self.assertEqual(user_by_name.id, user.id)

        with self.assertRaises(TypeError):
            User.get(None)
    def test_roles(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User.create(username, password)
        self.assertTrue(user.has_roles())
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User(username=username, password=password)
        role_names = map(lambda i: uuid.uuid4().hex, range(3))
        roles = []
        for role_name in role_names:
            role = Role.create(role_name)
            user.roles.append(role)
            roles.append(role)

        db.session.add(user)
        db.session.commit()
        self.assertTrue(
            user.has_roles(allowed=[roles[0].name, roles[1].name]))
        self.assertTrue(
            user.has_roles(allowed=[roles[0].name, "foo"]))
        self.assertTrue(
            user.has_roles(allowed=["foo", roles[0].name]))
        self.assertFalse(
            user.has_roles(allowed=["foo"]))
        self.assertTrue(
            user.has_roles(required=[roles[0].name, roles[1].name]))
        self.assertFalse(
            user.has_roles(required=[roles[0].name, roles[1].name, "foo"]))
示例#5
0
 def test_user_auth_token(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertEqual(
         user.get_auth_token(),
         login_serializer.dumps([str(user.id), user.password]))
 def test_user_auth_token(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertEqual(
         user.get_auth_token(),
         login_serializer.dumps([str(user.id), user.password]))
 def test_create_user(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user_id = User.create(username, password).id
     db.session.remove()
     user = User.query.filter_by(id=user_id).first()
     self.assertIsNotNone(user)
     self.assertEqual(user.username, username)
示例#8
0
def load_user(user):
    """
    callback for :func:`flask_login.LoginManager.user_loader`

    When the user id is is not present in the session this function
    is used to load the user from the database directly.
    """
    return User.get(user)
示例#9
0
    def validate_password(self, field):
        if self.dbuser is False:
            self.dbuser = User.get(request.form["username"])

        if self.dbuser:
            password = str(field.data)
            if self.dbuser.hash_password(password) != self.dbuser.password:
                raise ValidationError("invalid password")
示例#10
0
    def validate_password(self, field):
        if self.dbuser is False:
            self.dbuser = User.get(request.form["username"])

        if self.dbuser:
            password = str(field.data)
            if self.dbuser.hash_password(password) != self.dbuser.password:
                raise ValidationError("invalid password")
 def test_create_user(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user_id = User.create(username, password).id
     db.session.remove()
     user = User.query.filter_by(id=user_id).first()
     self.assertIsNotNone(user)
     self.assertEqual(user.username, username)
示例#12
0
def load_user(user):
    """
    callback for :func:`flask_login.LoginManager.user_loader`

    When the user id is is not present in the session this function
    is used to load the user from the database directly.
    """
    return User.get(user)
    def setUp(self):
        super(TestLogin, self).setUp()

        # create a normal user
        self.normal_username = uuid.uuid4().hex
        self.normal_password = uuid.uuid4().hex
        self.normal_user = User.create(self.normal_username,
                                       self.normal_password)

        # create an admin
        self.admin_username = uuid.uuid4().hex
        self.admin_password = uuid.uuid4().hex
        self.admin_user = User.create(self.admin_username, self.admin_password)
        self.admin_user.roles.append(Role.create("admin"))

        # commit the changes to the database
        db.session.commit()
示例#14
0
    def setUp(self):
        super(TestLogin, self).setUp()

        # create a normal user
        self.normal_username = uuid.uuid4().hex
        self.normal_password = uuid.uuid4().hex
        self.normal_user = User.create(
            self.normal_username, self.normal_password)

        # create an admin
        self.admin_username = uuid.uuid4().hex
        self.admin_password = uuid.uuid4().hex
        self.admin_user = User.create(
            self.admin_username, self.admin_password)
        self.admin_user.roles.append(Role.create("admin"))

        # commit the changes to the database
        db.session.commit()
    def test_check_password(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User.create(username, password)
        self.assertTrue(user.check_password(password))
        self.assertFalse(user.check_password(""))

        with self.assertRaises(AssertionError):
            user.check_password(None)
    def test_check_password(self):
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        user = User.create(username, password)
        self.assertTrue(user.check_password(password))
        self.assertFalse(user.check_password(""))

        with self.assertRaises(AssertionError):
            user.check_password(None)
 def test_is_active(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertTrue(user.is_active())
     user.active = False
     self.assertFalse(user.is_active())
     user.active = True
     self.assertTrue(user.is_active())
     user.expiration = datetime.now() + timedelta(seconds=.5)
     time.sleep(1.5)
     self.assertFalse(user.is_active())
     user.expiration = datetime.now() + timedelta(days=1)
     self.assertTrue(user.is_active())
 def test_is_active(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertTrue(user.is_active())
     user.active = False
     self.assertFalse(user.is_active())
     user.active = True
     self.assertTrue(user.is_active())
     user.expiration = datetime.now() + timedelta(seconds=.5)
     time.sleep(1.5)
     self.assertFalse(user.is_active())
     user.expiration = datetime.now() + timedelta(days=1)
     self.assertTrue(user.is_active())
示例#19
0
def load_token(token):
    """
    callback for :func:`flask_login.LoginManager.token_loader`

    When a user is already loaded check the token provided to be sure
    the password matches and that the token has not expired.
    """
    # The token was encrypted using itsdangerous.URLSafeTimedSerializer which
    # allows us to have a max_age on the token itself.  When the cookie is
    # stored on the users computer it also has a expiry date, but could be
    # changed by the user, so this feature allows us to enforce the exipry
    # date of the token server side and not rely on the users cookie to expire.
    try:
        userid, password = login_serializer.loads(
            token,
            max_age=app.config["REMEMBER_COOKIE_DURATION"].total_seconds())
        user = User.get(userid)
        return user if user and user.password == password else None

    except BadTimeSignature:
        return None
示例#20
0
def login_page():
    """display and process the login for or action"""
    if request.method == "POST" and request.content_type == "application/json":
        user = User.get(request.json["username"])

        if user and user.check_password(request.json["password"]):
            login_user(user, remember=True)
            return jsonify(None)

        return jsonify(None), UNAUTHORIZED

    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        login_user(form.dbuser, remember=True)
        return redirect(request.args.get("next") or "/")

    if request.content_type == "application/json":
        abort(BAD_REQUEST)

    return render_template("pyfarm/login.html", form=form,
                           next=request.args.get("next") or "/")
示例#21
0
def load_token(token):
    """
    callback for :func:`flask_login.LoginManager.token_loader`

    When a user is already loaded check the token provided to be sure
    the password matches and that the token has not expired.
    """
    # The token was encrypted using itsdangerous.URLSafeTimedSerializer which
    # allows us to have a max_age on the token itself.  When the cookie is
    # stored on the users computer it also has a expiry date, but could be
    # changed by the user, so this feature allows us to enforce the exipry
    # date of the token server side and not rely on the users cookie to expire.
    try:
        userid, password = login_serializer.loads(
            token,
            max_age=app.config["REMEMBER_COOKIE_DURATION"].total_seconds())
        user = User.get(userid)
        return user if user and user.password == password else None

    except BadTimeSignature:
        return None
示例#22
0
def setup_page():
    form = NewUserForm(request.form)

    if request.method == "GET":
        # create the admin role if it does not exist and
        # find any existing administrators
        admin_role = Role.query.filter_by(name="admin").first()
        if admin_role is None:
            admin_role = Role.create("admin")
            admin_users = []
        else:
            admin_users = admin_role.users

        return render_template("pyfarm/setup.html",
                               form=form,
                               admin_role=admin_role,
                               admin_users=admin_users)

    elif request.method == "POST":
        if form.validate():
            # make sure we're still the only admin
            admin_role = Role.query.filter_by(name="admin").first()

            if admin_role and admin_role.users.first():
                return render_template(
                    "pyfarm/setup.html",
                    error="someone else created an administrator")

            user = User.create(request.form["username"],
                               request.form["password"],
                               email=request.form["email"])
            user.roles.append(Role.create("admin"))
            db.session.add(user)
            db.session.commit()

            return render_template("pyfarm/setup.html",
                                   finished=True,
                                   redirect_seconds=5)

        return render_template("pyfarm/setup.html", form=form)
示例#23
0
def setup_page():
    form = NewUserForm(request.form)

    if request.method == "GET":
        # create the admin role if it does not exist and
        # find any existing administrators
        admin_role = Role.query.filter_by(name="admin").first()
        if admin_role is None:
            admin_role = Role.create("admin")
            admin_users = []
        else:
            admin_users = admin_role.users

        return render_template(
            "pyfarm/setup.html", form=form,
            admin_role=admin_role, admin_users=admin_users)

    elif request.method == "POST":
        if form.validate():
            # make sure we're still the only admin
            admin_role = Role.query.filter_by(name="admin").first()

            if admin_role and admin_role.users.first():
                return render_template(
                    "pyfarm/setup.html",
                    error="someone else created an administrator")

            user = User.create(
                request.form["username"],
                request.form["password"],
                email=request.form["email"])
            user.roles.append(Role.create("admin"))
            db.session.add(user)
            db.session.commit()

            return render_template(
                "pyfarm/setup.html", finished=True, redirect_seconds=5)

        return render_template("pyfarm/setup.html", form=form)
示例#24
0
def login_page():
    """display and process the login for or action"""
    if request.method == "POST" and request.content_type == "application/json":
        user = User.get(request.json["username"])

        if user and user.check_password(request.json["password"]):
            login_user(user, remember=True)
            return jsonify(None)

        return jsonify(None), UNAUTHORIZED

    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        login_user(form.dbuser, remember=True)
        return redirect(request.args.get("next") or "/")

    if request.content_type == "application/json":
        abort(BAD_REQUEST)

    return render_template("pyfarm/login.html",
                           form=form,
                           next=request.args.get("next") or "/")
示例#25
0
    def validate_username(self, field):
        if self.dbuser is False:
            self.dbuser = User.get(request.form["username"])

        if self.dbuser is None:
            raise ValidationError("invalid username")
 def test_hash_password(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertEqual(user.password, User.hash_password(password))
 def test_get_id(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertEqual(user.get_id(), user.id)
示例#28
0
    def validate_username(self, field):
        if self.dbuser is False:
            self.dbuser = User.get(request.form["username"])

        if self.dbuser is None:
            raise ValidationError("invalid username")
    def post(self):
        """
        A ``POST`` to this endpoint will create a new job group.

        .. http:post:: /api/v1/jobgroups/ HTTP/1.1

            **Request**

            .. sourcecode:: http

                POST /api/v1/jobgroups/ HTTP/1.1
                Accept: application/json

                {
                    "title": "Test Group",
                    "user": "******",
                    "main_jobtype": "Test JobType"
                }


            **Response**

            .. sourcecode:: http

                HTTP/1.1 201 CREATED
                Content-Type: application/json

                {
                    "id": 2,
                    "jobs": [],
                    "user": "******",
                    "main_jobtype": "Test JobType",
                    "title": "Test Group"
                }

        :statuscode 201: a new job group was created
        :statuscode 400: there was something wrong with the request (such as
                         invalid columns being included)
        """
        username = g.json.pop("user")
        user = User.query.filter_by(username=username).first()
        if not user and AUTOCREATE_USERS:
            user = User(username=username)
            if AUTO_USER_EMAIL:
                user.email = AUTO_USER_EMAIL.format(username=username)
            db.session.add(user)
            logger.warning("User %s was autocreated on job group create",
                           username)
        elif not user:
            return (jsonify(
                error="User %s not found" % username), NOT_FOUND)

        jobtype_name = g.json.pop("main_jobtype")
        jobtype = JobType.query.filter_by(name=jobtype_name).first()
        if not jobtype:
            return (jsonify(
                error="Jobtype %s not found" % jobtype_name), NOT_FOUND)

        jobgroup = JobGroup(user=user, main_jobtype=jobtype, **g.json)
        db.session.add(jobgroup)
        db.session.commit()

        jobgroup_data = jobgroup.to_dict()
        jobgroup_data.pop("user_id", None)
        jobgroup_data.pop("main_jobtype_id", None)
        logger.info("Created job group %s: %r", jobgroup.title, jobgroup_data)

        return jsonify(jobgroup_data), CREATED
 def test_hash_password(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertEqual(user.password, User.hash_password(password))
示例#31
0
    def post(self):
        """
        A ``POST`` to this endpoint will create a new job group.

        .. http:post:: /api/v1/jobgroups/ HTTP/1.1

            **Request**

            .. sourcecode:: http

                POST /api/v1/jobgroups/ HTTP/1.1
                Accept: application/json

                {
                    "title": "Test Group",
                    "user": "******",
                    "main_jobtype": "Test JobType"
                }


            **Response**

            .. sourcecode:: http

                HTTP/1.1 201 CREATED
                Content-Type: application/json

                {
                    "id": 2,
                    "jobs": [],
                    "user": "******",
                    "main_jobtype": "Test JobType",
                    "title": "Test Group"
                }

        :statuscode 201: a new job group was created
        :statuscode 400: there was something wrong with the request (such as
                         invalid columns being included)
        """
        username = g.json.pop("user")
        user = User.query.filter_by(username=username).first()
        if not user and AUTOCREATE_USERS:
            user = User(username=username)
            if AUTO_USER_EMAIL:
                user.email = AUTO_USER_EMAIL.format(username=username)
            db.session.add(user)
            logger.warning("User %s was autocreated on job group create", username)
        elif not user:
            return (jsonify(error="User %s not found" % username), NOT_FOUND)

        jobtype_name = g.json.pop("main_jobtype")
        jobtype = JobType.query.filter_by(name=jobtype_name).first()
        if not jobtype:
            return (jsonify(error="Jobtype %s not found" % jobtype_name), NOT_FOUND)

        jobgroup = JobGroup(user=user, main_jobtype=jobtype, **g.json)
        db.session.add(jobgroup)
        db.session.commit()

        jobgroup_data = jobgroup.to_dict()
        jobgroup_data.pop("user_id", None)
        jobgroup_data.pop("main_jobtype_id", None)
        logger.info("Created job group %s: %r", jobgroup.title, jobgroup_data)

        return jsonify(jobgroup_data), CREATED
示例#32
0
 def validate_username(self, field):
     user = User.get(request.form["username"])
     if user is not None:
         raise ValidationError("%s already exists" %
                               request.form["username"])
示例#33
0
 def validate_username(self, field):
     user = User.get(request.form["username"])
     if user is not None:
         raise ValidationError(
             "%s already exists" % request.form["username"])
 def test_get_id(self):
     username = uuid.uuid4().hex
     password = uuid.uuid4().hex
     user = User.create(username, password)
     self.assertEqual(user.get_id(), user.id)