def post(self): """ """ roles_schema = RoleSchema() roles_data = request.get_json() validated_role_data, errors = roles_schema.load(roles_data) role_name = validated_role_data.get('name', None) if errors: return dict(status="fail", message=errors), 400 role_existant = Role.find_first(name=role_name) if role_existant: return dict( status="fail", message=f"Role {validated_role_data['name']} Already Exists." ), 400 role = Role(**validated_role_data) saved_role = role.save() if not saved_role: return dict(status='fail', message=f'Internal Server Error'), 500 new_role_data, errors = roles_schema.dumps(role) return dict( status='success', data=dict(role=json.loads(new_role_data)) ), 201
def role_store(): form = RoleCreateForm(request.form) if form.validate(): role = Role() role.create(data=form.data) return Success(message="操作成功!") return Fail(message=form.first_error)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context().push() db.create_all() Role.insert_roles() self.client = self.app.test_client()
def run(): roles = ('admin', 'attendee', 'booth', 'speaker', 'hackaton', 'ambassador', 'user', 'partner') for role in roles: new_role = Role() new_role.name = role db.session.add(new_role) db.session.commit()
def bulk_create(self, total: int, params: dict) -> bool: data = [] for item in range(total): data.append(self.make(params, to_dict=False, exclude=[])) RoleModel.bulk_create(data) return True
def add_role(self, role, app): try: RoleModel.insert({'name': role.name, 'state': role.state}) message = f'''Se agregó el role : {role.name} {role.state}''' print(message) return helper.handler_response(app, 201, message) except Exception as e: return helper.handler_response(app, 500, f'{str(e)}')
def new_role(self, name, help_=None, is_active=True, is_deleted=False): role = Role(name=name, help=help_, is_active=is_active, is_deleted=is_deleted) role.save() return role
def create_role(name='admin'): from app.models.role import Role admin = Role.query.filter_by(name=name).first() if not admin: with db.auto_commit(): admin = Role() admin.name = name db.session.add(admin) print("The '%s' role is created!" % name) return admin
def deploy(): from flask_migrate import upgrade from app.models.users import Role, User upgrade() # 创建表 Role.insert_roles() # 建立自连接 User.add_self_follows()
def run(): customer = Role(id=1, name='Customer', keyword='customer') ace = Role(id=2, name='AccountExecutive', keyword='account_executive') cashier = Role(id=3, name='Cashier', keyword='cashier') teller = Role(id=4, name='Teller', keyword='teller') db.session.add(customer) db.session.add(ace) db.session.add(cashier) db.session.add(teller) db.session.commit()
def init_role(resource: Resource): """ Create roles and associate it with a resource :param resource: Resource object :return: Edit Role for a resource """ role: Role = Role.create(f'Read {resource.name}') Setup.init_role_resource(role, resource, ActionType.READ) role: Role = Role.create(f'Edit {resource.name}') Setup.init_role_resource(role, resource, ActionType.WRITE) Setup.init_role_resource(role, resource, ActionType.DELETE) return role
def add(): form = RoleForm() if form.validate_on_submit(): data = form.data role = Role.query.filter_by(name=data['name']).count() if role == 1: flash("角色已经存在!", "err") return redirect(url_for("role.add")) role = Role(data) role.save() flash("角色添加成功!", "ok") redirect(url_for('role.add')) return render_template('admin/role/add.html', form=form)
def create_role(name, label): """ 设置角色 :param name: :param label: :return: """ with db.auto_commit(): role = Role() role.name = name role.label = label db.session.add(role) print("成功创建管理员角色: %s " % (name, ))
def create_roles(): """ For now creating roles in DB manually, Later on they can be created via API from AdminPanel as well. :return: """ role = Role.query.filter_by(name=ConstantsUtility.ADMIN).all() # Create role table only if it does not exist if not role: db.session.add(Role(name=ConstantsUtility.ADMIN)) db.session.add(Role(name=ConstantsUtility.CUSTOMER)) db.session.commit()
def reward(category, openid): gold = gamedataconfig.ALL_SHARE_CONFIG[_CATEGORY[category]]["reward"] now = datetime.now() try: share = Share.objects.get(openid=openid) except DoesNotExist: share = Share(openid=openid) t = getattr(share, category) if t is None or (now - t).days != 0: #不是同一天 Role.objects(openid=openid).update(inc__gold=gold) setattr(share, category, now) share.save() return "success"
def create_admin(username, email, password): from app.models.role import Role from app.models.user import User admin_role = Role() admin_role.name = "admin" admin_role.description = "the admin role duh." db.session.add(admin_role) new_user = User() new_user.username = username new_user.email = email new_user.set_password(password) new_user.roles.append(admin_role) db.session.add(new_user) # update the user roles db.session.commit()
def change_admin_role(self, is_admin): admin_role = Role.get_admin_role() if is_admin: self.roles.append(admin_role) else: if self.is_admin: self.roles.remove(admin_role)
def search_users_results(is_advanced, keyword, sorted_by, sorted_as, per_page, page, id_to_filter, name_to_filter, email_to_filter, phone_to_filter, confirmed_to_filter, deleted_to_filter, role_to_filter): if is_advanced == 1: query = User.advance_search(util.EMPTY, sorted_by, sorted_as, per_page, page, id_to_filter, name_to_filter, email_to_filter, phone_to_filter, confirmed_to_filter, deleted_to_filter, role_to_filter) else: query = User.search(util.EMPTY, sorted_by, sorted_as, per_page, page, name_to_filter, email_to_filter, phone_to_filter) users = query.items total = query.total if total % per_page == 0: last_page = int(total/per_page) elif total % per_page > 0: last_page = int(total/per_page) + 1 confirmeds = User.get_confirmeds() deleteds = User.get_deleteds() roles = Role.list() return render_template("backend/user/search.html", title="Search Result", users=users, empty_hash=util.EMPTY, per_page=per_page, page=page, total=total, last_page=last_page, confirmeds=confirmeds, deleteds=deleteds, roles=roles, sorted_by=sorted_by, sorted_as=sorted_as, id_to_filter=id_to_filter, name_to_filter=name_to_filter, keyword=keyword, email_to_filter=email_to_filter, phone_to_filter=phone_to_filter, confirmed_to_filter=confirmed_to_filter, deleted_to_filter=deleted_to_filter, role_to_filter=role_to_filter, is_advanced=is_advanced)
def patch(self, role_id): """ """ # To do check if user is admin role_schema = RoleSchema(partial=True) update_data = request.get_json() validated_update_data, errors = role_schema.load(update_data) if errors: return dict(status="fail", message=errors), 400 role = Role.get_by_id(role_id) if not role: return dict( status="fail", message=f"Role with id {role_id} not found" ), 404 if 'name' in validated_update_data: role.name = validated_update_data['name'] updated_role = role.save() if not updated_role: return dict(status='fail', message='Internal Server Error'), 500 return dict( status="success", message=f"Role {role.name} updated successfully" ), 200
def create(code, name, description=None): new_role_obj = Role(created_at=datetime_now(), code=code, name=name, description=description) return base_provider.create(obj=new_role_obj)
def setUp(self): self.BaseSetUp() self.mock_role = Role( id=1, created_at=datetime.now(), updated_at=datetime.now(), name="Mock role", help="Mock help", ) self.mock_user_role = UserRole( id=1, role_id=1, user_id=1, is_active=True, is_deleted=False, created_at=datetime.now(), updated_at=datetime.now(), ) self.mock_user = User( id=1, first_name="test", last_name="test", gender="male", password="******", is_active=True, is_deleted=False, created_at=datetime.now(), updated_at=datetime.now(), )
def change_user_manager_role(self, is_user_manager): user_manager_role = Role.get_user_manager_role() if is_user_manager: self.roles.append(user_manager_role) else: if self.is_user_manager: self.roles.remove(user_manager_role)
def role_add(): auth_list = request.values.getlist("auths") auth_list = list_to_str(auth_list) id_dict = MultiDict([('auths', auth_list)]) values = CombinedMultiDict([id_dict, request.form]) form = RoleAddForm(values) auths = Auth.query.all() if request.method == 'POST' and form.validate(): with db.auto_commit(): role = Role() role.set_attr(form.data) db.session.add(role) Oplog('添加角色:' + role.name) flash('添加角色成功~', 'ok') return redirect(url_for('admin.role_add')) return render_template('admin/role_add.html', auths=auths, form=form)
def post(self, *args, **kwargs): arg_dict = self.prepare_arg_dict() name = self.get_argument('name') pinyin_name = name_to_pinyin(name) arg_dict['pinyin_name'] = pinyin_name arg_dict['avatar'] = upload_image(self.request, 'avatar', prefix='role/avatar/', default='role/avatar/default.jpg') arg_dict['imagery'] = upload_image(self.request, 'imagery', prefix='role/imagery/', default='role/imagery/default.jpg') arg_dict['back_img'] = upload_image(self.request, 'back', prefix='role/back/', default='role/back/default.jpg') arg_dict['banner'] = upload_image(self.request, 'banner', prefix='role/banner/', default='role/banner/default.jpg') arg_dict['full_imagery'] = upload_image(self.request, 'full_imagery', prefix='role/full_imagery/') arg_dict['create_time'] = current_time_string() arg_dict['update_time'] = current_time_string() arg_dict['profession'] = '' try: yield Role.create(arg_dict) self.write({'status': 1}) except Exception, e: print e self.write({'status': 0})
def role_delete(ids): ids = ids.split('-') if '1' in ids: return Fail(message="不能删除超级管理员角色") roles = Role.get_all_in_ids(ids=ids) for role in roles: role.destroy() return Success(message="成功删除")
def create_role(): """ 创建角色 """ form1 = dict(name="普通管理员", auths="") form2 = dict(name="超级管理员", auths="") role1 = Role(form1) role2 = Role(form2) role1.save() role2.save()
def all_role(self, app): try: roles = RoleModel.get() result = {} if roles: result = roles.serialize() return helper.handler_response(app, 201, 'Lista de Roles', result) except Exception as e: return helper.handler_response(app, 500, f'{str(e)}')
def create(cls, **props): user = cls() user.password = cls.hash_password(props.pop('password')) user.update(**props) user_role = Role.get_user_role() user.roles.append(user_role) user.save() return user
def post(self): """ """ user_schema = UserSchema() user_data = request.get_json() validated_user_data, errors = user_schema.load(user_data) email = validated_user_data.get('email', None) client_base_url = os.getenv('CLIENT_BASE_URL', f'https://{request.host}/users') # To do change to a frontend url verification_url = f"{client_base_url}/verify/" secret_key = current_app.config["SECRET_KEY"] password_salt = current_app.config["VERIFICATION_SALT"] sender = current_app.config["MAIL_DEFAULT_SENDER"] template = "user/verify.html" subject = "Please confirm your email" if errors: return dict(status="fail", message=errors), 400 # get the customer role user_role = Role.find_first(name='customer') user_existant = User.query.filter_by(email=email).first() if user_existant: return dict( status="fail", message=f"Email {validated_user_data['email']} already in use." ), 400 user = User(**validated_user_data) if user_role: user.roles.append(user_role) saved_user = user.save() if not saved_user: return dict(status='fail', message=f'Internal Server Error'), 500 # send verification send_verification(email, user.name, verification_url, secret_key, password_salt, sender, current_app._get_current_object(), template, subject) new_user_data, errors = user_schema.dumps(user) return dict(status='success', data=dict(user=json.loads(new_user_data))), 201
def create_superuser(email, password, confirm_password): email_pattern = re.compile(r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?") # check passwords match if password != confirm_password: print("Passwords do not match") return # check email is of valid format if not re.match(email_pattern, email): print("Wrong email format") return # check administrator role exists admin_role = Role.find_first(**{'name': 'administrator'}) if not admin_role: try: admin_role = Role(name='administrator') admin_role.save() except Exception as e: print(str(e)) return # create admin user try: admin_user = User.find_first(**{'email': email}) if admin_user: print(f'email {email} already in use') return admin_user = User(email=email, name='admin', password=password) admin_user.verified = True admin_user.roles.append(admin_role) admin_user.save() print("Admin user created successfully") print('password: ', password) return except Exception as e: print(str(e)) return
def create_roles(): Role.create_roles() log('user roles created')
def f(*args, **kwargs): if Role.authorizedRoles(roles, stack.top.roles) is False: raise InsufficientRoles() return method(*args, **kwargs)