def init_role(license): project_directory = os.path.abspath(".") data_directory = os.path.join(project_directory, "users", "data") role_data_file = os.path.join(data_directory, "roles.json") Role.load_from_json(role_data_file, license) print("roles worked!!")
async def create_role(request: Request) -> Dict: """ 创建角色 """ request_body = request.json name = request_body["name"] description = request_body["description"] role = Role(name=name, description=description) role.save() return {"message": "创建成功"}
def create_tables(): database.connect() Category.drop_table(fail_silently=True) Thread.drop_table(fail_silently=True) Post.drop_table(fail_silently=True) Role.drop_table(fail_silently=True) Profile.drop_table(fail_silently=True) database.create_tables([Category, Thread, Post, Profile, Role]) database.close() if settings.DEBUG: setup_temp_data()
def delete_role(role_id, raise_exception=False) -> None: role: Role = Role.get(role_id) if not role: if raise_exception: raise ObjNotFound() else: role.delete()
def register(): """ Registers a new user --- tags: - Users parameters: - in: body name: User responses: 201: description: User created """ email = request.json['email'] user_exists = User.query.filter_by(email=email).first() if user_exists: return jsonify(message='That email already exists.'), 409 else: name = request.json['name'] password = request.json['password'] role = request.json['role'] if role not in set(item.value for item in Role): return jsonify(message='The role provided does not exist'), 422 role_obj = Role(role) if role_obj == Role.admin: logged_user = current_user if not logged_user or logged_user.role != Role.admin: return jsonify(message='Only admin users can create other admin users'), 403 user = User(name=name, email=email, password=generate_password_hash(password), role=role_obj) db.session.add(user) db.session.commit() result = user_schema.dump(user) return jsonify(result), 201
def init_role(requestor): permissions = UserPermissions(requestor, 'roles') permissions.check('create') role = Role() return role
def _create_user(username, rolename, data=None): if data is None: data = {} role = Role.select().where(Role.name==rolename).get() Profile.create(username=username, email=username+'@srv.pl', role=role, description=data.get('description', 'User ' + username + ' description'), title=data.get('title', 'User ' + username + ' title'), location=data.get('location', 'User ' + username + ' location'))
def create_co_person_role(co_person_id: int, co_cou_id: int) -> bool: response = False new_co_person_role = api.coperson_roles_add(coperson_id=co_person_id, cou_id=co_cou_id) if new_co_person_role: co_role_id = new_co_person_role.get('Id') ns_person = NotaryServiceUser.objects.filter( co_person_id=co_person_id).first() ns_role = Role() ns_role.co_role_id = co_role_id ns_role.co_person_id = co_person_id ns_role.co_cou = ComanageCou.objects.filter( co_cou_id=co_cou_id).first() ns_role.save() ns_person.roles.add(ns_role) ns_person.save() logger.info('{0} - Add CoPersonRole: {1} - {2}'.format( datetime.datetime.now().ctime(), ns_role.co_cou.name, ns_role.co_role_id)) response = True else: logger.info( '{0} - Failed to add CoPersonRole - CoPersonId: {1}'.format( datetime.datetime.now().ctime(), co_person_id)) return response
def add_co_person_roles(co_person: dict) -> None: co_person_id = co_person.get('Id') co_roles = api.coperson_roles_view_per_coperson( coperson_id=co_person_id).get('CoPersonRoles', []) ns_person = NotaryServiceUser.objects.filter( co_person_id=co_person_id).first() if co_roles and ns_person: for co_role in co_roles: co_role_id = co_role.get('Id') ns_role = Role.objects.filter(co_role_id=co_role_id).first() if ns_role: logger.info('{0} - Found CoPersonRole: {1} - {2}'.format( datetime.datetime.now().ctime(), ns_role.co_cou.name, ns_role.co_role_id)) else: co_cou_id = co_role.get('CouId', None) if co_cou_id: ns_role = Role() ns_role.co_role_id = co_role_id ns_role.co_person_id = co_person_id ns_role.co_cou = ComanageCou.objects.filter( co_cou_id=co_cou_id).first() ns_role.save() ns_person.roles.add(ns_role) ns_person.save() logger.info('{0} - Add CoPersonRole: {1} - {2}'.format( datetime.datetime.now().ctime(), ns_role.co_cou.name, ns_role.co_role_id)) else: logger.warning( '{0} - Missing CouId: CoPersonRole - {1}'.format( datetime.datetime.now().ctime(), co_role_id))
def get_user_role_list(self): key = self.get_user_role_list_key() list_data = self.handle.lrange(key) if not list_data: list_data = Role.filter_objects() if isinstance(list_data, Exception) or not list_data: return list_data self.handle.rpush(key, *list_data) return list_data
def test_create_role(self, alice): from users.models import Role save_role = Role.create(alice, {'role': 'TESTROLE'}) save_role.save() find_role = Role.objects.get(user=save_role.user) assert save_role.user.username == find_role.user.username assert save_role.type == find_role.type assert save_role.role == find_role.role assert save_role.type == 'Role'
def delete(rec_id=None): setExits() g.title = "Delete {} Record".format(g.title) if rec_id == None: rec_id = request.form.get('id', request.args.get('id', -1)) rec_id = cleanRecordID(rec_id) if rec_id <= 0: flash("That is not a valid record ID") return redirect(g.listURL) rec = Role(g.db).get(rec_id) if not rec: flash("Record not found") else: Role(g.db).delete(rec.id) g.db.commit() return redirect(g.listURL)
def add_role(): form = RoleForm() if form.validate_on_submit(): role = Role(form.description.data, form.is_read.data, form.is_create.data, form.is_edit.data, form.is_delete.data) db.session.add(role) db.session.commit() return redirect(url_for('view_roles')) return render_template('users/roleform.html', form=form, action='new')
def add_role(): form = RoleForm() if form.validate_on_submit(): organisation = Organisation.query.filter_by(id= session['organisation_id']).first() role= Role(form.name.data, organisation, form.manager.data, form.is_active.data) db.session.add(role) db.session.commit() return redirect(url_for('view_roles')) return render_template('users/roleform.html', form=form, action='new')
def setup_database(app): with app.app_context(): from users.models import User from users.models import RolesUsers from users.models import Role from users.models import Techademy db.create_all() # TODO setup admin role = Role() role.name = "Admin" role.description = "This is the admin role" db.session.add(role) try: db.session.commit() except IntegrityError as err: db.session.rollback() if "UNIQUE constraint" in str(err): print("Admin role already exists, this is ok") else: print("Error with admin role, this needs to be looked into") role = Role() role.name = "Generic" role.description = "Just a viewer of the site" db.session.add(role) try: db.session.commit() except IntegrityError as err: db.session.rollback() # TODO find admin user user = User.query.filter_by(username="******").first() if user is not None: if not user.has_role("Admin"): role = Role.query.filter_by(name="Admin").first() user.roles.append(role) try: db.session.commit() except IntegrityError as err: db.session.rollback() if "UNIQUE constraint" in str(err): print("Admin relationship duplicate constraint issue") else: print("Error with user-role relationship") print("Added admin role") else: print("Admin is already admin")
def test_user_delete(): from users.models import User, Role user = User(db) record_deleted = user.delete(2) assert record_deleted == True record_deleted = user.delete('John') assert record_deleted == True record_deleted = user.delete('John') # can't delete it twice assert record_deleted == False record_deleted = user.delete('none') # test that we can delete an inactive record assert record_deleted == True record_deleted = Role(db).delete(1) assert record_deleted == True db.rollback()
def add_role(): try: form = RoleForm() if form.validate_on_submit(): organisation = Organisation.query.filter_by(id= session['organisation_id']).first() role= Role(form.name.data, organisation, form.manager.data, form.is_active.data) db.session.add(role) db.session.commit() flash('Role created successfully','alert-success') return redirect(url_for('view_roles')) except exc.IntegrityError: flash('The role name ' + form.name.data + ' already exists','alert-danger') db.session.rollback() return redirect(url_for('view_roles')) return render_template('users/roleform.html', form=form, action='new')
def validForm(rec): # Validate the form goodForm = True if request.form['name'].strip() == '': goodForm = False flash('Name may not be blank') else: # name must be unique (but not case sensitive) where = 'lower(name)="{}"'.format( request.form['name'].lower().strip(), ) if rec.id: where += ' and id <> {}'.format(rec.id) if Role(g.db).select(where=where) != None: goodForm = False flash('Role names must be unique') # Rank must be in a reasonalble range temp_rank = cleanRecordID(request.form['rank']) if temp_rank < 0 or temp_rank > 1000: goodForm = False flash("The Rank must be between 0 and 1000") return goodForm
def roles(request): if request.POST: print request.POST from django.core.validators import validate_email from django.core.exceptions import ValidationError try: validate_email(request.POST['user']) try: user = User.objects.get(email=request.POST['user']) group = Group.objects.get(name=request.POST['group']) try: Role.objects.get(user=user, company=request.company, group=group) messages.error(request, 'User ' + user.username + ' (' + user.email + ') is already the ' + request.POST[ 'group'] + '.') except Role.DoesNotExist: role = Role(user=user, company=request.company, group=group) role.save() messages.success(request, 'User ' + user.username + ' (' + user.email + ') added as ' + request.POST[ 'group'] + '.') except User.DoesNotExist: messages.error(request, 'No users found with the e-mail address ' + request.POST['user']) except ValidationError: try: user = User.objects.get(username=request.POST['user']) group = Group.objects.get(name=request.POST['group']) try: Role.objects.get(user=user, company=request.company, group=group) messages.error(request, 'User ' + user.username + ' (' + user.email + ') is already the ' + request.POST[ 'group'] + '.') except Role.DoesNotExist: role = Role(user=user, company=request.company, group=group) role.save() messages.success(request, 'User ' + user.username + ' (' + user.email + ') added as ' + request.POST[ 'group'] + '.') except User.DoesNotExist: messages.error(request, 'No users found with the username ' + request.POST['user']) objs = Role.objects.filter(company=request.company) return render(request, 'roles.html', {'roles': objs})
def create(self, request): data = request.data.copy() permissions = data.pop('permissions', []) if not self.request.user.has_perm('users.add_role'): return Response("User has no permissions to create a Role", status=status.HTTP_403_FORBIDDEN) all_permissions_group = PermissionConfig.objects.first() try: with transaction.atomic(): group = Group(name='{}-{}'.format( data['name'], request.user.aerosimple_user.airport)) group.save() for perm in permissions: p = Permission.objects.get(id=perm) if p in all_permissions_group.permissions.all(): group.permissions.add(p) else: group.delete() return Response( "id {} is not a valid Permission".format(p.id), status=status.HTTP_400_BAD_REQUEST) role = Role(name=data['name']) role.permission_group = group role.airport = request.user.aerosimple_user.airport role.save() except ValidationError: raise return Response(RoleSerializer(role).data, status=status.HTTP_201_CREATED)
def _bootstrap_role(self, role): role = Role(role=role) role.save() return role
def get_perfect_validate_data(self, **cleaned_data): if 'role_id' in cleaned_data: role = Role.get_object(pk=cleaned_data['role_id']) cleaned_data['role'] = role.name cleaned_data.pop('role_id') return cleaned_data
def display(): setExits() g.title = "{} Record List".format(g.title) # get all records recs = Role(g.db).select() return render_template('role/role_list.html', recs=recs)
def edit(rec_id=None): setExits() g.title = "Edit {} Record".format(g.title) role = Role(g.db) rec = None if rec_id == None: rec_id = request.form.get('id', request.args.get('id', -1)) rec_id = cleanRecordID(rec_id) #import pdb;pdb.set_trace if rec_id < 0: flash("That is not a valid ID") return redirect(g.listURL) if not request.form: """ if no form object, send the form page """ if rec_id == 0: rec = role.new() else: rec = role.get(rec_id) if not rec: flash("Unable to locate that record") return redirect(g.listURL) else: #have the request form #import pdb;pdb.set_trace() if rec_id and request.form['id'] != 'None': rec = role.get(rec_id) else: # its a new unsaved record rec = role.new() role.update(rec, request.form) if validForm(rec): #update the record role.update(rec, request.form) # make names lower case rec.name = request.form['name'].lower().strip() try: role.save(rec) g.db.commit() except Exception as e: g.db.rollback() flash( printException( 'Error attempting to save ' + g.title + ' record.', "error", e)) return redirect(g.listURL) else: # form did not validate pass # display form return render_template('role/role_edit.html', rec=rec)
def create_db(): pswd = request.json['pswd'] if pswd == 'super secret key': db.create_all() role1 = Role('Admin', []) role2 = Role('Customer', []) category1 = Category('Табак', []) category2 = Category('Кальян', []) category3 = Category('Уголь', []) db.session.add(category1) db.session.add(category2) db.session.add(category3) db.session.add(role1) db.session.add(role2) db.session.commit() product1 = Product( manufacturer='JBR', name='JBR dragon berry', description='JBR dragon berry (Драконья ягода) 100грамм', price=170, category_id=1) product2 = Product( manufacturer='JBR', name='Табак Jibiar California Sun', description= 'Табак Jibiar California Sun (Дыня Лайм Лёд), 100 грамм', price=170, category_id=1) product3 = Product( manufacturer='Daim', name='Daim Spiced Peach', description='Daim Spiced Peach (Пряный Персик), 50 грамм', price=60, category_id=1) product4 = Product( manufacturer='Daim', name='Daim Ice Blueberry', description='Табак для кальяна Daim 50 грамм (Ice Blueberry)', price=60, category_id=1) product5 = Product( manufacturer='Dark Side', name='Dark Side Code Cherry Medium', description= 'Dark Side Code Cherry Medium (Дарксайд Вишня) 100грамм', price=460, category_id=1) product6 = Product( manufacturer='Dark Side', name='Dark Side Space Dessert Medium', description= 'Табак для кальяна Dark Side Space Dessert Medium (Спайс Десерт), 100 грамм', price=460, category_id=1) user = User(phone='0674004659', name='Admin', second_name=generate_password_hash('password'), address='1', email='1', delivery_type='1', pay_type='1', orders=[], role_id=2) product21 = Product( manufacturer='Amy', name='Кальян Amy Delux Unio 006.01 black', description= 'Модель кальяна отличается стильным внешним видом, ведь в ней соединены ' 'интересный цвет, сталь и дерево. В комплексе недорогой кальян выглядит очень ' 'эффектно, поэтому его часто выбирают в качестве подарка, или для домашнего ' 'использования и дополнения красивым изделием интерьера.', price=2075, category_id=2) product22 = Product( manufacturer='Dumok', name='Кальян Dumok Hookah(Украина) AL-09 MINOR', description= 'Качественный кальян с отличным внешним видом и передачей вкуса!', price=2070, category_id=2) product31 = Product( manufacturer='Phoenix', name='Уголь Phoenix (Феникс) 1кг 72 кубика', description= 'Отличный кокосовый уголь, содержащий натуральные компоненты. Достоинства его в' ' том, что он тлеет более одного часа, равномерно прогревая табак и не меняя ' 'его вкус. Соответственно, количество пепла - минимальное', price=100, category_id=3) product32 = Product( manufacturer='Panda', name='Кокосовый уголь Panda (Панда) 1кг 72шт.', description= 'Высококачественный кокосовый уголь для кальяна, созданный из скорлупы ' 'кокосового ореха. В упаковке 1 килограмма содержится 72 крупных кубика угля, ' 'которые обеспечат вкусное и дымное курение кальяна без посторонних запахов и ' 'изменения вкуса.', price=125, category_id=3) db.session.add(user) db.session.add(product1) db.session.add(product2) db.session.add(product3) db.session.add(product4) db.session.add(product5) db.session.add(product6) db.session.add(product21) db.session.add(product22) db.session.add(product31) db.session.add(product32) db.session.commit() return {'msg': 'Успешное заполнение бд для тестов'}
def get_role(role_id, raise_exception=False) -> Role: role: Role = Role.get(role_id) if not role and raise_exception: raise ObjNotFound() return role
def create_temp_roles(): Role.create(name='admin', level=100) Role.create(name='moderator', level=50) Role.create(name='user', level=1)
# CSV_PATH = 'C:/Users/leeso/OneDrive/바탕 화면/data/domain_index.csv' import csv from users.models import Role, Customer # 2. App이름.models from django.contrib.auth.models import User from django.contrib.auth import get_user_model bulk_list = [] with open(CSV_PATH, encoding='UTF-8') as csvfile: # 4. newline ='' data_reader = csv.reader(csvfile) next(data_reader, None) for row in data_reader: bulk_list.append( Role( # 5. class명.objects.create foreignkey=Customer.objects.get(name=row[0]), analysis_hearts=row[1], web_hearts=row[2], design_hearts=row[3], modeling_hearts=row[4], role_sum=row[5], )) Role.objects.bulk_create(bulk_list) Role.objects.values() # 6. Score 데이터 업로드 # class Score(models.Model): # foreignkey = models.ForeignKey( # Customer, related_name="score", on_delete=models.CASCADE, null=True # ) # web = models.IntegerField(default=0) # design = models.IntegerField(default=0) # machine_learning = models.IntegerField(default=0)
def test_roles(): from users.models import Role #db = get_test_db() assert Role(db).get(0) == None recs = Role(db).select() assert recs != None assert len(recs) == 3 assert recs[0].name != None rec = Role(db).new() rec.name = "Testing" rec.description = "A test role" recID = Role(db).save(rec) rec = Role(db).get(recID) assert rec.id == recID assert rec.name == 'Testing' assert rec.rank == 0 #Modify the record rec.name = "New Test" rec.rank = 300 Role(db).save(rec) rec = Role(db).get(rec.id) assert rec.name == "New Test" assert rec.rank == 300 db.rollback()
def handle(self, *args, **options): group = Group() group.name = 'Trainee' group.save() role = Role() role.code = 'trainee' role.name = 'Trainee' role.save() role = Roles() role.name = 'trainee' role.display_name = 'Trainee' role.save()
def edit(rec_handle=None): setExits() g.title = "Edit {} Record".format(g.title) #import pdb;pdb.set_trace() user = User(g.db) rec = None request_rec_id = cleanRecordID( request.form.get('id', request.args.get('id', -1))) is_admin = g.admin.has_access(g.user, User) no_delete = not is_admin session_roles = session["user_roles"] #roles of currnet user new_password = '' confirm_password = '' user_roles = ['user'] # default roles = Role(g.db).select() include_inactive = True if not is_admin: g.listURL = g.homeURL # Non admins can't see the list include_inactive = False if rec_handle != None: pass #rec_handle has to come from admin() at this point elif rec_handle == None and g.user != None and request_rec_id == -1: rec_handle = g.user else: rec_handle = request_rec_id if rec_handle < 0: flash("That is not a valid User ID") return redirect(g.listURL) if not request.form: """ if no form object, send the form page """ if rec_handle != g.user and not is_admin: flash("You do not have access to that area") return redirect(g.homeURL) elif rec_handle == 0: rec = user.new() else: rec = user.get(rec_handle, include_inactive=include_inactive) if not rec: flash("Unable to locate user record") return redirect('/') user_roles = get_user_role_names(rec) else: #have the request form #import pdb;pdb.set_trace() is_new_user = False if rec_handle and request.form['id'] != 'None': rec = user.get(rec_handle, include_inactive=include_inactive) user_roles = get_user_role_names(rec) else: # its a new unsaved record is_new_user = True rec = user.new() user.update(rec, request.form) if validForm(rec): #Are we editing the current user's record? editingCurrentUser = '' if (g.user == rec.username): if 'new_username' in request.form: editingCurrentUser = request.form['new_username'].strip() else: editingCurrentUser = g.user else: if (g.user == rec.email): editingCurrentUser = request.form['email'].strip() #update the record user.update(rec, request.form) set_username_from_form(rec) set_password_from_form(rec) try: user.save(rec) # update the user roles if 'roles_select' in request.form: #delete all the users current roles user.clear_roles(rec.id) for role_name in request.form.getlist('roles_select'): #find the role by name role = Role(g.db).select_one( where='name = "{}"'.format(role_name)) if role: user.add_role(rec.id, role.id) # if the username or email address are the same as g.user # update g.user if it changes if (editingCurrentUser != ''): setUserStatus(editingCurrentUser, rec.id) g.db.commit() except Exception as e: g.db.rollback() flash( printException( 'Error attempting to save ' + g.title + ' record.', "error", e)) return redirect(g.listURL) if is_new_user == True and rec.email: from takeabeltof.mailer import send_message # send an email to welcome the new user full_name = '{} {}'.format(rec.first_name, rec.last_name).strip() context = { 'rec': rec, 'full_name': full_name, } to_address_list = [(full_name, rec.email)] sent, msg = send_message( to_address_list, subject="Welcome to {{config.SITE_NAME}}", context=context, html_template='user/email/welcome.html', text_template='user/email/welcome.txt', ) if not sent: flash('The welcome message could not be sent. Error: {}'. format(msg)) return redirect(g.listURL) else: # form did not validate, give user the option to keep their old password if there was one #need to restore the username user.update(rec, request.form) if 'new_username' in request.form: rec.username = request.form[ 'new_username'] #preserve user input # preserve the selected roles #import pdb;pdb.set_trace() if 'roles_select' in request.form: user_roles = request.form.getlist('roles_select') #and password new_password = request.form.get('new_password', '') confirm_password = request.form.get('confirm_password', '') # display form return render_template( 'user/user_edit.html', rec=rec, no_delete=no_delete, is_admin=is_admin, user_roles=user_roles, roles=roles, session_roles=session_roles, new_password=new_password, confirm_password=confirm_password, )
def addCustomRoles(): add(Role(name='admin')) add(Role(name='company_admin')) add(Role(name='risk_owner'))