Esempio n. 1
0
File: users.py Progetto: ifczt/py-oa
def creat(token):
    res_dir = request.get_json()
    res_dir['superior'] = token['u_id']
    res_dir['u_id'] = str(uuid.uuid1())
    # noinspection PyBroadException
    try:
        _user = Users(**res_dir)
        db.session.add(_user)
        db.session.flush()
        db.session.commit()
    except Exception:
        return Error409.to_dict()
    if res_dir['power'] not in POWER_INTRODUCTION:  # 判断是否存在该权限
        return Error4014.to_dict()
    res_dir.update({
        'id': _user.id,
        'yeah_sales_volume': 0,
        'signing_rate': '暂未出单',
        'sales_volume': 0,
        'login_time': '暂未使用',
        'active': 1,
        'power': POWER_INTRODUCTION[res_dir['power']],
        'u_id': _user.u_id
    })
    Succ200.data = res_dir
    return Succ200.to_dict()
def admin_register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = Users(username=form.username.data,
                     email=form.email.data,
                     first_name=form.first_name.data,
                     last_name=form.last_name.data,
                     phone_number=form.phone_num.data,
                     usertype='Admin')
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        flash('You have been registered in this webpage')
        return redirect(url_for('login'))
    return render_template('register.html',
                           title='Admin Register',
                           form=form,
                           usertype='Admin')
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = Users(username=form.username.data,
                     email=form.email.data,
                     first_name=form.first_name.data,
                     last_name=form.last_name.data,
                     phone_number=form.phone_num.data,
                     usertype='Customer')
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        customer = Customers(user_id=user.id)
        db.session.add(customer)
        db.session.commit()
        trans_customer = Trans_users(username=user.username,
                                     first_name=user.first_name,
                                     last_name=user.last_name,
                                     email=user.email,
                                     phone_number=user.phone_number,
                                     user_id=user.id)
        db.session.add(trans_customer)
        db.session.commit()
        cart_customer = Cart_customers(user_id=user.id)
        db.session.add(cart_customer)
        db.session.commit()
        library_customer = Library_customers(user_id=user.id)
        db.session.add(library_customer)
        db.session.commit()
        flash('You have been registered in this webpage')
        return redirect(url_for('login'))
    return render_template('register.html',
                           title='Register',
                           form=form,
                           usertype='Customer')
def register():
    if request.method == "GET":
        return render_template('register.html')
    else:
        username = request.form.get("username")
        password = request.form.get("password")
        password_confirmation = request.form.get("password_confirmation")
        email = request.form.get("email")

        email_rex = "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"

        try:
            if username is None or not username:
                raise ValueError("Имя пользователя должно быть задано")
            if password is None or not password:
                raise ValueError("Пароль должен быть задан")
            if password != password_confirmation:
                raise ValueError("Пароли не совпадают")
            username_confirmation = Users.query.filter_by(
                username=username).first()
            if username_confirmation is not None:
                raise ValueError("Такое имя пользователя уже есть")

            regexp = re.compile(email_rex)

            if not regexp.match(email):
                raise ValueError("Email имеет неправильный вид")

        except Exception as e:
            return render_template("register.html", errors=e)

        try:
            user = Users(username, password, email)
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            return render_template("register.html", errors=e)

        login_user(user, remember=True)
        return redirect(url_for("index"))
Esempio n. 5
0
 def setUp(self):
     """Initializes test for user Class"""
     self.usr = Users()
Esempio n. 6
0
class TestForUserClass(unittest.TestCase):
    """Test for user class"""
    def setUp(self):
        """Initializes test for user Class"""
        self.usr = Users()

    # tests for register
    def test_for_empty_fields(self):
        """Test for empty fields"""
        result = self.usr.register_user('', '', '', '')
        self.assertEqual(
            {
                'status': 'error',
                'message': {
                    'type': '',
                    'msg': 'Please fill in all fields'
                }
            },
            result,
        )

    def test_for_empty_username_field(self):
        """Test for empty username field"""
        result = self.usr.register_user('', '*****@*****.**', 'pass', 'pass')
        self.assertEqual(
            {
                "status": "error",
                'message': {
                    'type': '',
                    'msg': 'Please fill in all fields'
                }
            }, result)

    def test_for_invalid_name_characters(self):
        """Test for invalid characters in name"""
        result = self.usr.register_user('user%&#', '*****@*****.**',
                                        'password', 'password')
        self.assertEqual(
            {
                "status": "error",
                "message": {
                    "type": "username_error",
                    "msg": "Username contains invalid characters"
                }
            }, result)

    def test_for_invalid_email_address(self):
        """Test for invalid email address"""
        result = self.usr.register_user('user', '*****@*****.**',
                                        'password', 'password')
        self.assertEqual(
            {
                "status": "error",
                "message": {
                    'type': 'email_error',
                    'msg': "Invalid Email address"
                }
            }, result)

    def test_for_empty_email_field(self):
        """Test for empty email field"""
        result = self.usr.register_user('user', '', 'pass', 'pass')
        self.assertEqual(
            {
                "status": "error",
                'message': {
                    'type': '',
                    'msg': 'Please fill in all fields'
                }
            }, result)

    def test_for_non_matching_passwords(self):
        """Test for non-matching passwords"""
        result = self.usr.register_user('user', '*****@*****.**', 'password',
                                        'pass')
        self.assertEqual(
            {
                "status": "error",
                'message': {
                    'type': 'password_error',
                    'msg': 'Passwords do not match'
                }
            }, result)

    def test_for_reg_password_less_than_6_characters(self):
        """Test for reg password less than 6 characters"""
        self.usr.register_user('user', '*****@*****.**', 'pass', 'pass')
        result = self.usr.login_user('*****@*****.**', 'mypas')
        self.assertEqual(
            {
                "status": "error",
                "message": {
                    'type': "password_error",
                    'msg': "Password must be more than 6 characters"
                }
            }, result)

    def test_for_existing_user(self):
        """Test for existing user"""
        self.usr.register_user('user', '*****@*****.**', 'password',
                               'password')
        result = self.usr.register_user('user', '*****@*****.**', 'password',
                                        'password')
        self.assertEqual(
            {
                "message": {
                    'type': '',
                    'msg': "User already exists. Please login"
                },
                'status': 'error'
            }, result)

    # tests for login
    def test_for_empty_login_fields(self):
        """Test for empty fields"""
        result = self.usr.login_user('', '')
        self.assertEqual(
            {
                "status": "error",
                'message': {
                    'type': '',
                    'msg': 'Please fill in all fields'
                }
            },
            result,
        )

    def test_for_empty_login_mail_field(self):
        """Test for empty email field"""
        result = self.usr.login_user('', 'pass')
        self.assertEqual(
            {
                "status": "error",
                'message': {
                    'type': '',
                    'msg': 'Please fill in all fields'
                }
            }, result)

    def test_for_empty_password_field(self):
        """Test for empty password field"""
        result = self.usr.login_user('*****@*****.**', '')
        self.assertEqual(
            {
                "status": "error",
                'message': {
                    'type': '',
                    'msg': 'Please fill in all fields'
                }
            }, result)

    def test_for_password_less_than_6_field(self):
        """Test for password les than 6 characters"""
        self.usr.login_user('*****@*****.**', 'pass')
        result = self.usr.login_user('*****@*****.**', 'mypas')
        self.assertEqual(
            {
                "status": "error",
                "message": {
                    'type': "password_error",
                    'msg': "Password must be more than 6 characters"
                }
            }, result)

    def test_for_wrong_password_(self):
        """Test for wrong password"""
        self.usr.login_user('*****@*****.**', 'password')
        result = self.usr.login_user('*****@*****.**', 'mypassword')
        self.assertEqual(
            {
                'status': 'error',
                "message": {
                    'type': '',
                    'msg': "Invalid password or email address"
                }
            }, result)

    # test for update user
    def test_for_update_non_existing_user(self):
        """Test for updating non-existing user"""
        self.usr.update_user(1, 'user', '*****@*****.**', 'pass', 'pass')
        result = self.usr.update_user('', 'user', '*****@*****.**', 'pass',
                                      'pass')
        self.assertEqual(
            {
                'status': 'error',
                'message': 'Sorry, could not update user'
            }, result)

    # test for delete account
    def test_for_delete_non_existing_user(self):
        """Test for deleting non-existing user"""
        self.usr.delete_account(1)
        result = self.usr.delete_account('')
        self.assertEqual(
            {
                'status': 'error',
                'message': 'Sorry, could not delete User'
            }, result)