Example #1
0
    def setUp(self):
        """ Create test database and set up test client """
        self.app = app.test_client()
        engine = create_engine(os.environ['TESTDB'])
        if not database_exists(engine.url):
            create_database(engine.url)
            # db.drop_all()
            db.create_all()
            db.session.commit()
            user1 = Users(username="******", password="******",
                          email="*****@*****.**", fname="joshua", sname="joshua", lname="joshua", category=1)
            user2 = Users(username="******", password="******",
                          email="*****@*****.**", fname="joshua2", sname="joshua2", lname="joshua2", category=2)
            user3 = Users(username="******", password="******",
                          email="*****@*****.**", fname="joshua2", sname="joshua2", lname="joshua2", category=3)
            subject1 = Subjects(name="Artificial Intelligence",
                                description="Computer Science AI, SC0AI",
                                created_by=1)
            subject2 = Subjects(name="Human Psychology",
                                description="Sociology, S0HP",
                                created_by=1)
            userrights1 = UserRights(name="Admin")
            userrights2 = UserRights(name="Teacher")
            userrights3 = UserRights(name="Student")

            usersubject1 = UserSubject(user=2, subject=1)
            usersubject2 = UserSubject(user=3, subject=1)
            usersubject3 = UserSubject(user=3, subject=2)

            db.session.add(user1)
            db.session.add(user2)
            db.session.add(user3)
            db.session.add(subject1)
            db.session.add(subject2)
            db.session.add(userrights1)
            db.session.add(userrights2)
            db.session.add(userrights3)
            db.session.add(usersubject1)
            db.session.add(usersubject2)
            db.session.add(usersubject3)

            db.session.commit()
Example #2
0
def init_db_data(root_user):
    if root_user == None:
        return None
    else:
        u = Users(username=root_user.get("username"),
                  email=root_user.get("email"),
                  privilege=PRIVILEGES.ROOT_USER)
        u._password = root_user.get("password")
        try:
            u.insert()
        except:
            print(traceback.format_exc())
            return False
        return True
    pass
Example #3
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = Users(email=form.email.data,
                     username=form.username.data, password=form.password.data)

        mail_message("Welcome to pitchperfect",
                     "email/welcome_user", user.email, user=user)

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

        return redirect(url_for('auth.login'))
        title = "New Account"
    return render_template('auth/register.html', registration_form=form)
Example #4
0
def migrate_superadmin():
    '''
    This function aims to migrate superadmin's account data (including username, email
    , password hash) from temporal SQLite database to main database.

    Why exists? At the beginning, database setting has not been configured yet. Thus it's
    impossible to store superadmin's account data to user's database directly.

    How it works? read superadmin's account data from GlobalConfig database (in which the data is stored
    when step 1 is done.) and run init_database() to ensure SQLAlchemy API is available. Next,
    just use the API to insert data and delete the original one since there's no reason to keep it then.

    :return:
    '''
    if app.config.get("SQLALCHEMY_DATABASE_URI") == None:
        # ensure main database is initialized and SQLAlchemy available.
        init_database()

    # read data from GlobalConfig database
    gc = GlobalConfig()
    _username = gc.get("temp_superadmin_username")
    _email = gc.get("temp_superadmin_email")
    _hash = gc.get("temp_superadmin_hash")

    #for superadmin, privilege = 1
    try:
        super_admin_user = Users(username=_username,
                                 privilege=PRIVILEGES.ROOT_USER,
                                 email=_email,
                                 hash=_hash)
        try:
            super_admin_user.insert_byhash()
        except:
            traceback.print_exc()
        # if everything works correctly <including the inserting operation above>,
        # it is time to delete account data
        gc.set("temp_superadmin_username", "")
        gc.set("temp_superadmin_email", "")
        gc.set("temp_superadmin_hash", "")

        # for empty value, just emit it
        return True
    except:
        g_logger.error(traceback.format_exc())
        return False
Example #5
0
 def on_post(self, req, res):
     session = req.context['session']
     request = req.context['data']
     if request:
         data = Users()
         data.fullname=request['fullname']
         data.username = request['username']
         data.email = request['email']
         data.password = hash_password(request['password']).decode('utf-8')
         data.token = encrypt_token(request['password']).decode('utf-8')
         data.phone_number=request['phone_number']
         data.address=request['address']
         data.account_number=request['account_number']
         data.birth_date=request['birth_date']
         data.role_id=request['role_id']
         data.birth_place_city_id=request['birth_place_city_id']
         session.add(data)
         self.on_success(res, None)
     else:
         raise InvalidParameterError(req.context['data'])
def create_users(db):
    print('[*] {0} - Adding users to datbase'.format(datetime.now()))
    # Create users
    from app.model import Users

    # Add AskJeeves user

    existing_user = Users.query.filter_by(
        username=app.config['ASKJEEVES_USERNAME']).first()
    if existing_user is None:
        user = Users(
            username=app.config['ASKJEEVES_USERNAME'],
            password=generate_password_hash(app.config['ASKJEEVES_PASSWORD'],
                                            method='sha256'),
        )
        db.session.add(user)

        # Commit user to database
        db.session.commit()

    # Query all users
    users = Users.query.all()
    print(users)
Example #7
0
def create_user():
    """ This is api for the user management registers user.

        Request Body:
            username: string, require
                The username of the user. Max length accepted is 50 and minimum length is 1.

            password: string, require
                The password of the user wanted to log in. Max length accepted is 50 and minimum length is 1.

        Returns:

            username: string
                username of newly registered user.

            group_id: string
                group id of this new user.

        Examples::

            curl --location --request POST 'http://<sv_address>:5013/api/v1/users' --header 'Authorization: Bearer <access_token>'
    """

    params = {
        'username': FieldString(requirement=True),
        'password': FieldString(requirement=True),
        'first_name': FieldString(requirement=True),
        'last_name': FieldString(requirement=True),
        'company': FieldString(),
        'address': FieldString(),
        'mobile': FieldString()
    }

    try:
        json_data = parse_req(params)
        # Check valid params
        validate(instance=json_data, schema=schema_user_create)

        username = json_data.get('username', None).lower().strip()
        password = json_data.get('password', None)
        first_name = json_data.get('first_name', None)
        last_name = json_data.get('last_name', None)
        company = json_data.get('company', None)
        address = json_data.get('address', None)
        mobile = json_data.get('mobile', None)
    except Exception as ex:
        logger.error('{} Parameters error: '.format(
            datetime.datetime.utcnow().strftime('%Y-%b-%d %H:%M:%S')) +
                     str(ex))
        return send_error(message="Registers user fail!")

    # log input fields
    # logger.debug(f"INPUT api create user: {json_data}")

    user = Users.find_by_user_name(user_name=username)
    if user:
        return send_error(message="User exist")

    if is_password_contain_space(password):
        return send_error(message='Password cannot contain spaces')

    create_date = datetime.datetime.utcnow().timestamp()
    _id = str(uuid.uuid1())
    user = Users(id=_id,
                 username=username,
                 password_hash=hash_password(password),
                 force_change_password=False,
                 create_date=create_date,
                 modified_date=create_date,
                 is_active=True,
                 firstname=first_name,
                 lastname=last_name,
                 company=company,
                 address=address,
                 mobile=mobile,
                 modified_date_password=create_date)
    user.save_to_db()
    data = {
        'id': _id,
        'username': username,
        'first_name': first_name,
        'last_name': last_name,
        'create_date': create_date
    }
    return send_result(data=data, message="Registers user successfully!")
Example #8
0
        items = request.json.get("items", None)

        return books.post_a_book(title=title,
                                 authors=authors,
                                 genre=genre,
                                 items=items)

    return jsonify({"books": books.get_all_books()})


@app.route('/books/<int:book_id>')
def get_book(book_id):
    return jsonify({"books": books.get_a_book(book_id=book_id)})


users = Users()


@app.route('/users', methods=["GET", "POST"])
def start():
    if request.method == "POST":
        name = request.json.get("name", None)
        types = request.json.get("types", None)
        age = request.json.get("age", None)

        return users.post_a_user(name=name, types=types, age=age)
    return jsonify({"users": users.get_users()})


@app.route('/users/<int:user_id>')
def get_a_user(user_id):
Example #9
0
 def setUp(self):
     self.new_user = Users(password = '******')