def on_delete(self, req, res ,id): session = req.context['session'] try: Users.find_delete(session,id) self.on_success(res,None) except NoResultFound: raise DataNotFound()
def on_put(self, req, res): session = req.context['session'] request = req.context['data'] if request: if request['id'] != None: Users.find_update(session,request['id'],request) self.on_success(res, None) else: raise InvalidParameterError(req.context['data'])
def set_password(uid, priv): F = request.json ori_password = F.get("ori_password") new_password = F.get("new_password") try: result, _ = Users.compare_password(None, ori_password, uid=uid) if result == True: Users.set_password(new_password, uid=uid) return rtn.success(True) else: return rtn.error(503) except: logger.error(traceback.format_exc()) return rtn.error(500)
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
def on_get(self, req, res,id): session = req.context['session'] try: data = Users.find_one(session, id) self.on_success(res, data.to_dict()) except NoResultFound: raise DataNotFound()
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
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()
def process_login(self, req, res): data = req.context['data'] email = data['email'] password = data['password'] session = req.context['session'] try: data = Users.find_by_email(session, email) if verify_password(password, data.password.encode('utf-8')): self.on_success(res, data.to_dict()) else: raise PasswordNotMatch() except NoResultFound: raise UserNotExistsError('User email: %s' % email)
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)
class UserTest(unittest.TestCase): def setUp(self): self.new_user = Users(password = '******') def test_password(self): self.assertTrue(self.new_user.pass_secure is not None) def test_read_password(self): with self.assertRaises(AttributeError): self.new_user.password def test_verify_password(self): self.assertTrue(self.new_user.verify_password('MERCY'))
def login(): def make_token(digits): return ''.join( random.choice(string.ascii_lowercase + string.digits) for _ in range(digits)) try: F = request.json username = F.get("username") password = F.get("password") remember_me = F.get("remember_me") if db.session.query(Users).filter( Users.username == username).first() == None: return rtn.error(502) # username not found result, _user = Users.compare_password(username, password) if result: _token_str = make_token(32) tk = UserToken(token=_token_str) tk.insert(username) # redirect different page as account types differ if _user.privilege == PRIVILEGES.ROOT_USER: # make response with cookie #resp = make_response(redirect("/super_admin/")) resp = make_response(rtn.success(200)) elif _user.privilege == PRIVILEGES.INST_OWNER: resp = make_response(rtn.error(503)) # not super admin else: resp = make_response(rtn.error(500)) # fatal error (unknown) # `remember me` checkbox ticked if remember_me: resp.set_cookie('session_token', _token_str, max_age=24 * 10 * 3600) else: # session resp.set_cookie("session_token", _token_str, expires=None) return resp else: return rtn.error(504) # password error except: traceback.print_exc() return rtn.error(500)
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)
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!")
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):
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 setUp(self): self.new_user = Users(password = '******')