def init_db(self): engine = self.session.get_bind(mapper=None, clause=None) inspector = Inspector.from_engine(engine) if 'ab_user' not in inspector.get_table_names(): print "Security DB not found Creating..." Base.metadata.create_all(engine) print "Security DB Created" self.migrate_db() if self.session.query(Role).filter_by(name = self.auth_role_admin).first() is None: role = Role() role.name = self.auth_role_admin self.session.add(role) self.session.commit() print "Inserted Role for public access", self.auth_role_admin if not self.session.query(Role).filter_by(name = self.auth_role_public).first(): role = Role() role.name = self.auth_role_public self.session.add(role) self.session.commit() print "Inserted Role for public access", self.auth_role_public if not self.session.query(User).all(): user = User() user.first_name = 'Admin' user.last_name = 'User' user.username = '******' user.password = '******' user.active = True user.role = self.session.query(Role).filter_by(name = self.auth_role_admin).first() self.session.add(user) self.session.commit() print "Inserted initial Admin user" print "Login using Admin/general"
def test_roles(self): """ A test """ role = Role(id='none', role_id='none', ordinal=0) self.assertIsNotNone(role) role.put() found = Role.get_by_id('none') self.assertIsNotNone(found) self.assertEqual('none', found.key.id()) self.assertEqual('none', found.role_id)
def test_create_role(self): """Create a role for users.""" create_role('tester') t = Role.select().where(Role.role_name == 'tester') d = Role.delete().where(Role.role_name == 'tester') d.execute() self.assertEqual(str(t), ("<class 'models.Role'> SELECT `t1`.`id`," " `t1`.`role_name` FROM `role` AS t1 " "WHERE (`t1`.`role_name` = %s) ['tester']"))
def import_roles(role_dict): """Add any missing roles to django db""" for role in role_dict: try: update_role(role, role_dict[role]) except: new_role = Role(role_name=role) new_role.save() update_role(role, role_dict[role])
def role_add(): j = request.get_json() log('role-add json', type(j), j) r = Role(j) log('new role: ', r) r.save() responseData = { 'role_name': r.name, 'role_id': r.id, } return json.dumps(responseData, indent=2)
def test_create_user_no_duplicate(self): """Makes sure users can't have the same username and email.""" Role.create(role_name='tester') create_user('Tester', 'test', '0000000000', 'tester', 'ttest', 'testing', '*****@*****.**') from peewee import IntegrityError with self.assertRaises(IntegrityError): create_user('Tester', 'test', '0000000000', 'tester', 'ttest', 'testing', '*****@*****.**') delete_user = User.delete().where(User.username == 'ttest') delete_user.execute() delete_role = Role.delete().where(Role.role_name == 'tester') delete_role.execute()
def test_create_user(self): """Create an user.""" Role.create(role_name='tester') create_user('Tester', 'test', '0000000000', 'tester', 'ttest', 'testing', '*****@*****.**') user = User.select().where(User.username == 'ttest') delete_user = User.delete().where(User.username == 'ttest') delete_user.execute() delete_role = Role.delete().where(Role.role_name == 'tester') delete_role.execute() self.assertEqual(str(user), ("<class 'models.User'> SELECT `t1`.`id`, `t1`.`first_name`," " `t1`.`second_name`, `t1`.`phone`, `t1`.`role_id`," " `t1`.`username`, `t1`.`password`, `t1`.`email` FROM `user`" " AS t1 WHERE (`t1`.`username` = %s) ['ttest']"))
def deploy(): "Run deployment tasks" from flask.ext.migrate import upgrade from models import User,Role,Post #数据库迁移到最新修订版本 # upgrade() #创建用户角色 Role.insert_roles() #创建管理员账号 User.add_admin()
def update_role(role, membership_check): """Make sure role membership in db is set to val from csv col 2""" role_check = Role.objects.get(role_name=role) if role_check.membership != membership_check: try: new_membership = Role.objects.get(role_name=membership_check) role_check.membership = new_membership role_check.save() except: new_role = Role(role_name=membership_check) new_role.save() new_membership = new_role role_check.membership = new_membership role_check.save()
def test_create_outgoing(self): """Create an outgoing record.""" Category.create(category_id='001', description='Testing Stock') Project.create(project_id='001', project_description="Testing") Role.create(role_name='Admin') User.create(first_name='Jay', second_name='Palm', phone='9783978223', role='Admin', username='******', password='******', email='*****@*****.**') create_stock('001', 'Testing stock', 1, '001', 9.99) create_outgoing_stock(stock='001', project_id='001', date="2015-07-22", quantity='7', username='******') OutgoingStock.get(OutgoingStock.stock == '001').delete_instance() Stock.get(Stock.category == '001').delete_instance() User.get(User.username == 'JayPalm').delete_instance() Role.get(Role.role_name == 'Admin').delete_instance() Project.get(Project.project_id == '001').delete_instance() Category.get(Category.category_id == '001').delete_instance()
def role_add(): user = current_user() is_admin = is_administrator(user) log('Is admin?', is_admin) if is_admin: j = request.json log('role-add json', type(j), j) r = Role(j) log('new role: ', r) r.save() responseData = { 'role_name': r.name, 'role_id': r.id, } return json.dumps(responseData, indent=2) else: abort(401)
def validate_role(self, field): role = Role.role_by_name(field.data).one() try: User.user_by_role_id(role.id).one() except NoResultFound: pass else: raise ValidationError(u'%s уже зарегистрирован в системе' % self.role.data)
def test_create_role_duplicate(self): """Makes sure roles can't be created with the same role name.""" create_role('tester') from peewee import IntegrityError with self.assertRaises(IntegrityError): create_role('tester') t = Role.delete().where(Role.role_name == 'test') t.execute()
def wrapper(*args, **kwargs): if app.current_user is not None: r = Role.get(Role.role == role) if app.current_user.role.level >= r.level: return func(*args, **kwargs) app.flash(u'У Вас недостатньо прав для перегляду') redirect() app.flash(u'Увійдіть, щоб переглянути дану сторінку') redirect('/login?back=' + request.path)
def delete(self, request): authorise(request.person, request.token) try: role = Role.get_by_id(request.id) role.key.delete(); return message_types.VoidMessage() except (IndexError, TypeError): raise endpoints.NotFoundException('Role %s not found.' % (request.id,))
def role(id): if request.method == 'GET': rewards = Role.objects(name=id) return get_items(request, rewards) if request.method == 'POST': item = Role.objects(name=id).first() print 'Fetched Item' if request_has_json(): item.description = request.json['description'] item.save() return 'Updated' else: form = RoleForm(request.form) form.populate_obj(item) print 'Populated Item from Form' print item.description item.save() return render_template('list_roles.html',items=[item])
def list_roles(self, request): authorise(request.person, request.token) roles = Role.query(Role.parentId==request.id).fetch() # meetings = Meeting.query().fetch() res = RolesCollection() for role in roles: msg = RoleMsg(name=role.name, id=role.key.id(), importance=role.importance, parentId=role.parentId) res.items.append(msg) return res
def add_role(): for index, breadcrumb in enumerate(session["breadcrumbs"]): if "添加角色" == breadcrumb["text"]: session["breadcrumbs"] = session["breadcrumbs"][: index + 1] break else: session["breadcrumbs"].append({"text": "添加角色", "url": url_for("auth.add_role")}) if request.method == "POST": other_role = Role.query.filter_by(name=request.form["name"]).first() if other_role: flash(u"同名角色已存在", "danger") else: all_id = [str(menu_id) for menu_id in request.form.getlist("role_menu") if menu_id] query_sql = "SELECT DISTINCT parent_id FROM tms_menu WHERE id IN(%s)" % ",".join(all_id) for row in db.engine.execute(query_sql): if row[0] != "None" and row[0] != None: current_app.logger.info(row[0]) all_id.append(str(row[0])) role = Role() role.menu = ",".join(list(set(all_id))) role.name = request.form["name"] role.index_page = request.form["index_page"] db.session.add(role) db.session.commit() users = User.query.filter(User.id.in_(request.form.getlist("role_remember"))) for user in users: user.role = role db.session.add(user) db.session.commit() return redirect(url_for("auth.role_page")) menus = SystemMenu.query.filter_by(activate=True).order_by(SystemMenu.order).all() users = User.query.all() return render_template( "admin/account/role_edit.html", role=None, menus=menus, users=users, current_page="auth.role_page" )
def delete(self, request): authorise(request.person, request.token) try: person = Person.get_by_id(request.id) roles = Role.query(Role.parentId==request.id).fetch() for role in roles: role.key.delete() person.key.delete() return message_types.VoidMessage() except (IndexError, TypeError): raise endpoints.NotFoundException('Role %s not found.' % (request.id,))
def register_user(): if User.is_admin(g.user.username): form = RegisteredUserForm() if form.prev.data: return redirect(url_for('admin')) if form.validate_on_submit(): role = Role.role_by_name(form.role.data).one() User.create(username=form.username.data, password=form.password.data, role_id=role.id) flash(u'Пользователь "%s" успешно зарегистрирован в системе.' % form.username.data) return render_template('users/register.html', form=form) else: return u'Вы не можете получить доступ к этой странице.'
def init_db(self): try: engine = self.session.get_bind(mapper=None, clause=None) inspector = Inspector.from_engine(engine) if 'ab_user' not in inspector.get_table_names(): log.info("Security DB not found Creating") Base.metadata.create_all(engine) log.info("Security DB Created") self.migrate_db() if self.session.query(Role).filter_by(name=self.auth_role_admin).first() is None: role = Role() role.name = self.auth_role_admin self.session.add(role) self.session.commit() log.info("Inserted Role for public access %s" % (self.auth_role_admin)) if not self.session.query(Role).filter_by(name=self.auth_role_public).first(): role = Role() role.name = self.auth_role_public self.session.add(role) self.session.commit() log.info("Inserted Role for public access %s" % (self.auth_role_public)) if not self.session.query(User).all(): user = User() user.first_name = 'Admin' user.last_name = 'User' user.username = '******' user.password = generate_password_hash('general') user.email = '*****@*****.**' user.active = True user.role = self.session.query(Role).filter_by(name=self.auth_role_admin).first() self.session.add(user) self.session.commit() log.info("Inserted initial Admin user") log.info("Login using Admin/general") except Exception as e: log.error("DB Creation and initialization failed, if just upgraded to 0.7.X you must migrate the DB. {0}".format(str(e)))
def exitRolefragment(self, ctx): role = Role() role.source = self.context[-1] role.description = self.stack.pop() role.contact = self.stack.pop() status = self.stack.pop() if status == 'active' : role.status = Role.ACTIVE elif status == 'disabled' : role.status = Role.DISABLED else : role.status = Role.WORKING role.save() # Now that the role exists, we can create the other rows # which have FK constraints for row in self.rows : row.save() self.rows = []
def delete(self, request): authorise(request.person, request.token) try: meeting = Meeting.get_by_id(request.id) if meeting.originator == request.person: persons = Person.query(Person.parentId==request.id).fetch() for person in persons: roles = Role.query(Role.parentId==person.key.id()).fetch() for role in roles: role.key.delete() person.key.delete() meeting.key.delete() else: # just remove the person from the meeting persons = Person.query(Person.parentId==request.id).fetch() for person in persons: if(person.email == request.person): roles = Role.query(Role.parentId==person.key.id()).fetch() for role in roles: role.key.delete() person.key.delete() return message_types.VoidMessage() except (IndexError, TypeError): raise endpoints.NotFoundException('Role %s not found.' % (request.id,))
def test_user_role(self): """ A test """ setup_roles() user = LocalUser.new_user(user_id='xyz', email='no@mail', roles=['user']) user.put() user_found = LocalUser.get_by_id('xyz') self.assertIsNotNone(user_found) self.assertEqual('xyz', user_found.user_id) self.assertEqual('no@mail', user_found.email) self.assertEqual('user', Role.get_by_id(user_found.get_role('user').id()).role_id) self.assertIsNone(user_found.get_role('admin')) self.assertEqual('user', user_found.get_role('user').id()) self.assertEqual('user', user_found.get_role_id('user')) self.assertTrue(user_found.has_role('user')) self.assertFalse(user_found.has_role('admin'))
def roles(): if request.method == 'POST': form = RoleForm(request.form) if request_has_json(): try: json_data = json.dumps(request.json,default=json_util.default) model = Role.from_json(json_data) model.save() except ValidationError as e: return jsonify(item=str(e)) else: if form.validate(): form.save() else: return render_template('add_roles.html',form=form) return list_roles() else: return list_roles()
def new_role(address, newrole): if User.query.filter_by(email=address).first() != None: student = User.query.filter_by(email=address).first() if newrole == 'Delete User': db.session.delete(student) db.session.commit() return if Role.query.filter_by(name=newrole).first() != None: role = Role.query.filter_by(name=newrole).first() else: role = Role(name=newrole, description="") if len(student.roles) > 0: student.roles[0] = role else: student.roles.append(role) db.session.commit()
async def add_role(message): # Adds an assignable role splitmsg = message.content.split() rolename = ' '.join(splitmsg[1:]) role = discord.utils.get(message.server.roles, name=rolename) server = Server.get(Server.sid == message.server.id) r, created = Role.get_or_create( rid=role.id, defaults={ 'assignable': True, 'server': server } ) if not created: r.assignable = True r.save() await reply(f"The {rolename} role is now assignable", message)
async def add_leader_role(message): # Adds a leaderboard role splitmsg = message.content.split() rolename = ' '.join(splitmsg[1:]) role = discord.utils.get(message.server.roles, name=rolename) server = Server.get(Server.sid == message.server.id) r, created = Role.get_or_create(rid=role.id, defaults={ 'awardlevel': None, 'leaderboard': True, 'server': server }) if not created: r.leaderboard = True r.save() await reply( f"The {rolename} role will now be given when a user enters" " the leaderboard", message)
async def add_reward(message): # Adds an reward role splitmsg = message.content.split() rolename = ' '.join(splitmsg[1:-1]) level = splitmsg[-1] role = discord.utils.get(message.server.roles, name=rolename) server = Server.get(Server.sid == message.server.id) r, created = Role.get_or_create(rid=role.id, defaults={ 'awardlevel': level, 'server': server }) if not created: r.awardlevel = level r.save() await reply( f"The {rolename} role will now be given when a user" f" hits level {level}", message)
def userRegisteration(request: User, db: Session = Depends(get_db)): id_uid = id_uuids() organization = Organization(id=id_uid, name=request.organization_name) db.add(organization) db.commit() db.refresh(organization) id_uid = id_uuids() tenant = Tenant(id=id_uid, name=request.tenant_name, company_logo=request.company_logo, organization_id=organization.id) db.add(tenant) db.commit() db.refresh(tenant) role = db.query( models.Role).filter(models.Role.name == "tenentAdmin").first() if role: print(role.id) else: role = Role(id=id_uid, name="tenentAdmin") db.add(role) db.commit() db.refresh(role) # atuo generate password a = randoms() password = str(a) Tenantuser = TenantUser(id=id_uid, username=request.username, role_id=role.id, password=password, tenant_id=tenant.id) db.add(Tenantuser) db.commit() db.refresh(Tenantuser) return {organization, tenant, Tenantuser}
def update_profile(): user = User.find_by_username(username=current_user.username) city = City.get_id_by_name(_name=current_user.city) form = ProfileUpdateForm(city=city.uuid, bld_grp=user.bld_grp, sex=user.sex, pan=user.pan, organ_donation=bool(user.organ_donation), bld_donation=bool(user.bld_donation)) form.city.choices = [(city.uuid, city.name) for city in City.find_by_state('Kerala')] role = Role.find_by_id(current_user.role) print('user role is ', role.name) print(form.validate_on_submit()) print(form.errors) if 'pan' in form.errors: flash("PAN is a mandatory field \n PAN will always be a of 10 characters length") return render_template("update_profile.html", form=form, role=role.name) print('log') if form.validate_on_submit(): user.uname = form.uname.data user.mail = form.mail.data user.dob = form.dob.data user.age = get_age(form.dob.data) user.pan = form.pan.data user.name = form.name.data user.sex = form.sex.data user.bld_grp = form.bld_grp.data user.addr = form.addr.data user.state = form.state.data curr_city = City.get_by_id(form.city.data) user.city = curr_city.name user.po_num = form.pincode.data user.mobile = form.mobile.data user.aadhar = form.aadhar.data # user_role = form.role.data user.organ_donation = bool(strtobool(form.organ_donation.data)) user.bld_donation = bool(strtobool(form.bld_donation.data)) # role = Role.find_by_id(user_role) user.role = role.uuid user.save_to_db() print('user_id=', user.uuid, 'selected_role_id=', role.uuid, 'selected_role_name=', role.name) print('user_id=', user.uuid, 'role_id_db=', user.role, ) return redirect(url_for("view_profile")) return render_template("update_profile.html", form=form, role=role.name, auth=is_auth())
def init_db(): # Create the fixtures engineering = Department(name='Engineering') engineering.save() hr = Department(name='Human Resources') hr.save() manager = Role(name='manager') manager.save() engineer = Role(name='engineer') engineer.save() peter = Employee(name='Peter', department=engineering, role=engineer) peter.save() roy = Employee(name='Roy', department=engineering, role=engineer) roy.save() tracy = Employee(name='Tracy', department=hr, role=manager) tracy.save()
def role(): ''' {"rolename":"admin"} ''' if request.method == 'POST': args = request.json if args: abort = abort_if_id_doesnt_exist(Role, rolename=args['rolename']) if abort: data = 'rolename is exist' return task.json_message_401(mes=data), 401 else: db.session.add(Role(**args)) db.session.commit() data = 'ok' return task.json_message_200( data=data, info='Role add ok, rolename :%s ' % args) else: return task.json_message_401(mes='please check '), 401
def post_add_role(ser): """ 添加角色 :param ser: :return: """ session = ser.session slug = request.form.get('slug') name = request.form.get('name') if session.query(Role).filter(Role.name == name).first(): res = {'status': 0, 'message': '角色已经存在'} return json.dumps(res) role = Role(slug=slug, name=name) session.add(role) session.commit() res = {'status': 1, 'message': '角色添加成功'} return json.dumps(res)
def init(): ''' Initialize the database ''' print('Initializing') barrel.db.init(app) Role.create(name='admin') Role.create(name='mod') Role.create(name='user') Group.create( abbr=u'ACME', name=u'Administration, Control and Management Environment') add_user('admin', 'nidma', 'admin', group=Group.get_admin_group()) return 'Database initialized successfully'
def login(): form = LoginForm() login_page_name = "login_2.html" print(form.validate_on_submit()) print(form.errors) if form.validate_on_submit(): uname = form.uname.data passw = form.passw.data print(uname, passw) user = User.find_by_username(username=uname) if uname != '' or passw != '': if user is not None: print('found ', user.username) if check_password_hash(user.password, passw): login_user(user) user_role = Role.find_by_id(user.role) print('role_name=', user_role.name, 'role_id=', user_role.uuid) if user_role.name == "admin": print("Enabling admin view") admin.add_view(ModelView(Hospital, db.session)) admin.add_view(ModelView(City, db.session)) admin.add_view(ModelView(User, db.session)) admin.add_view(ModelView(Role, db.session)) admin.add_view(ModelView(Scheme, db.session)) admin.add_view(ModelView(Doctor, db.session)) next_page = request.args.get('next') print(next_page) return redirect(next_page or url_for('index')) flash('Invalid password for user ' + user.username) return render_template(login_page_name, form=form) flash('Invalid username ') return render_template(login_page_name, form=form) flash('Invalid username or/and password') return render_template(login_page_name, form=form) elif 'passw' in form.errors.keys(): flash('Invalid password') return render_template(login_page_name, form=form) elif current_user.is_authenticated: return redirect(url_for('index')) return render_template(login_page_name, form=form)
def test_role_1(self): """ Creates a role in the Role table, and then checks that the stored value matches the intended value. """ # Column values test_name = "Test_Role1" test_can_delete_adminlogins = True test_can_edit_adminlogins = False test_can_create_adminlogins = True test_analytics_access = False test_database_access = True test_role = Role(name=test_name, can_delete_adminlogins=test_can_delete_adminlogins, can_edit_adminlogins=test_can_edit_adminlogins, can_create_adminlogins=test_can_create_adminlogins, analytics_access=test_analytics_access, database_access=test_database_access) test_role_id = test_role.id with self.app.app_context(): self.db.session.add(test_role) self.db.session.commit() self.assertTrue(test_role in self.db.session) queried_role = self.db.session.query(Role).filter_by( name="Test_Role1").first() self.assertEqual(queried_role.id, test_role_id) self.assertEqual(queried_role.name, test_name) self.assertEqual(queried_role.can_delete_adminlogins, test_can_delete_adminlogins) self.assertEqual(queried_role.can_edit_adminlogins, test_can_edit_adminlogins) self.assertEqual(queried_role.can_create_adminlogins, test_can_create_adminlogins) self.assertEqual(queried_role.can_create_roles, False) self.assertEqual(queried_role.analytics_access, test_analytics_access) self.assertEqual(queried_role.database_access, test_database_access)
def edit(): form = InfoForm() if form.validate_on_submit(): role = Role.query.filter_by(name=form.name.data).first() user_role=g.user.role.all() if user_role==[]: roles= Role(position=form.position.data,name=form.name.data,tel=form.tel.data,author=g.user) db.session.add(roles) db.session.commit() flash(u'信息添加成功!') else: if role is not None: if g.user.role[0].name==role.name: role.position=form.position.data role.tel=form.tel.data db.session.add(role) db.session.commit() flash(u'信息修改成功!') else: flash(u'真实姓名不符,无法修改!') else: flash(u'真实姓名不符,无法修改!') role_list= models.Role.query.all() position_list=[] name_list=[] tel_list=[] positions=[] names=[] tels=[] for role in role_list: position_list.append(role.position) name_list.append(role.name) tel_list.append(role.tel) return render_template('edit.html', title='Home', form=form, position_list=position_list,name_list=name_list,tel_list=tel_list,role_list=role_list)
def check(action: int, resource: Resource): """ Function to check the user access for a particular action on resource :return: bool """ logged_in_user = User.get( filters={'username': UserLogin.check_session().username})[0] user_roles = Role.get(filters={'id': logged_in_user.roles}) policies = [] for role in user_roles: policies.extend(role.policies) user_policies = Policy.get(filters={'id': policies}) resource_policies = [ policy for policy in user_policies if policy.resource == '*' or policy.resource == resource ] # check for the denied policy denied_policy = next( (policy for policy in resource_policies if policy.effect == 'deny' and ( policy.action == '*' or policy.action == action)), None) if denied_policy: return False # check for an allowed policy allowed_policy = next( (policy for policy in resource_policies if policy.effect == 'allow' and ( policy.action == '*' or policy.action == action)), None) if allowed_policy: return True return False
def userRegisteration(request: User, db: Session = Depends(get_db)): id_uid = id_uuids() organization = Organization(id=id_uid, name=request.organization_name) db.add(organization) db.commit() db.refresh(organization) id_uid = id_uuids() tenant = Tenant(id=id_uid, name=request.tenant_name, organization_id=organization.id) db.add(tenant) db.commit() db.refresh(tenant) role = db.query(models.Role).filter(models.Role.name == "admin").first() if role: role_id = role.id else: role_id = Role(id=id_uid, name="tenentAdmin") db.add(role_id) db.commit() db.refresh(role_id) print(role_id) tenantuser = TenantUser(id=id_uid, username=request.username, first_name=request.firstname, last_name=request.lastname, email=request.email, role_id=role_id, tenant_id=tenant.id) db.add(tenantuser) db.commit() db.refresh(tenantuser) return {organization, tenant, tenantuser}
async def server_info(self, ctx): guild = ctx.guild custom_roles = [ role.name for role in Role.where('guild_id', ctx.guild.id).get() ] custom_roles.append("@everyone") guild_roles = " ".join( role.mention if role.name not in custom_roles else "" for role in guild.roles) created_at = ut.get_uk_time( guild.created_at).strftime("%Y-%m-%d %H:%M:%S") embed = (discord.Embed(title=f"{guild.name}", color=discord.Color.blurple()).set_thumbnail( url=str(guild.icon_url)).add_field( name="Owner", value=guild.owner.mention). add_field(name="Created at", value=created_at).add_field( name="Region", value=guild.region).add_field( name="Member Count", value=guild.member_count).add_field( name="Text Channel Count", value=len(guild.text_channels)).add_field( name="Voice Channel Count", value=len(guild.voice_channels)).add_field( name="Available Roles", value=guild_roles, inline=False).set_footer( text=f"Guild ID: {guild.id}")) for name, value_getter, inline in self._server_info: embed.add_field(name=name, value=value_getter(guild), inline=inline) await ctx.send(embed=embed)
def init_db(): # Create the fixtures engineering = Department(name="Engineering") engineering.save() hr = Department(name="Human Resources") hr.save() manager = Role(name="manager") manager.save() engineer = Role(name="engineer") engineer.save() debug = Task(name="Debug") test = Task(name="Test") tracy = Employee(name="Tracy", department=hr, roles=[engineer, manager], tasks=[]) tracy.save() peter = Employee( name="Peter", department=engineering, leader=tracy, roles=[engineer], tasks=[debug, test], ) peter.save() roy = Employee( name="Roy", department=engineering, leader=tracy, roles=[engineer], tasks=[debug], ) roy.save()
def post(self): # parsing arguments args = parser.parse_args() FirstName = args['FirstName'] LastName = args['LastName'] Email = args['Email'] Password = args['Password'] Mobile = args['Mobile'] DateOfBirth = args['DateOfBirth'] Address = args['Address'] Is_Admin = args['Is_Admin'] user_details = Details( FirstName=FirstName, LastName=LastName, Email=Email, DateOfBirth=DateOfBirth, Mobile=Mobile, Address=Address ) user_credentials = Credentials( Email=Email, Password=Password ) user_Role = Role( Email=Email, Is_Admin=Is_Admin ) my_session.add(user_details) my_session.commit() my_session.add(user_credentials) my_session.commit() my_session.add(user_Role) my_session.commit() employee = my_session.query(Details).filter(Details.Email == Email).first() return employee, 201
def sign_up(): if request.method == 'POST': email: str = request.form.get('email') password: str = request.form.get('password') password_repeat: str = request.form.get('password2') firstname: str = request.form.get('firstname') lastname: str = request.form.get('lastname') imgdata: str = request.form.get('imgdata') if not (email or password or password_repeat or firstname or lastname): flash('Please fill all fields!') elif password != password_repeat: flash('Passwords are not equal!') elif not imgdata: flash('Take a photo of the face.') else: face_img_filename: str = os.path.join(app.config['UPLOAD_FOLDER'], str(uuid.uuid4())) + '.jpeg' imgdata = imgdata.replace('data:image/jpeg;base64,', '') with open(face_img_filename, 'wb') as fh: fh.write(base64.decodebytes(imgdata.encode())) usr_role = Role.query.filter_by(name=Role.user().name).first() new_user = User(email=email, password=generate_password_hash(password), active=True, lastname=lastname, firstname=firstname, face_image_location=face_img_filename, roles=[usr_role]) db.session.add(new_user) db.session.commit() flash('User has been registrated !!!', 'success') return redirect(url_for('auth.sign_in')) return render_template('auth/sign-up.html')
def seed_users(db): print("++ Seeding users") role_usr = Role() role_usr.name = "user" role_usr.description = "Simple user" role_adm = Role() role_adm.name = "admin" role_adm.description = "Admin user" db.session.add(role_usr) db.session.add(role_adm) user_datastore.create_user( email="*****@*****.**", password=encrypt_password("fluttershy"), name="toto", timezone="UTC", roles=[role_adm], callsign="N0C4LL", locator="JN", ) db.session.commit() return
def init_db(): # Create the fixtures engineering = Department(name='Engineering') engineering.save() hr = Department(name='Human Resources') hr.save() manager = Role(name='manager') manager.save() engineer = Role(name='engineer') engineer.save() debug = Task(name='Debug') test = Task(name='Test') tracy = Employee(name='Tracy', department=hr, roles=[engineer, manager], tasks=[]) tracy.save() peter = Employee(name='Peter', department=engineering, leader=tracy, roles=[engineer], tasks=[debug, test]) peter.save() roy = Employee(name='Roy', department=engineering, leader=tracy, roles=[engineer], tasks=[debug]) roy.save()
async def remove_role(self, ctx, *, role_name): """ Removes the given role from the user. """ found_role = Role.where('name', role_name) \ .where('guild_id', ctx.guild.id).first() if found_role: discord_guild = self.bot.get_guild(found_role.guild_id) discord_role = discord_guild.get_role(found_role.role_id) if discord_role is None: await ctx.send("That custom role appears to be broken, " "please contact an admin") return await ctx.author.remove_roles(discord_role) await ctx.send(f"I have removed the role `{role_name}` from you") if len(discord_role.members) < 1: await ctx.send("I have also deleted the custom role since it " "is no longer used by anyone.") await discord_role.delete() return
def user(email, password, roles): """Create a new user to access the app with""" with app.app_context(): user = User.query.filter_by(email=email).count() if user: print("A user already exists with email: {}".format(email)) exit(1) user = current_app.user_datastore.create_user( email=email, password=encrypt_password(password)) current_app.db.session.add(user) if roles: for role in roles.split(','): db_role = Role.query.filter_by(name=role).first() if not db_role: db_role = Role(name=role, description=None) current_app.db.session.add(db_role) user.roles.append(db_role) current_app.db.session.commit()
def test_get_roles_of_actor(self): new_actor = Actor(**AppTestCase.test_actor) new_actor.insert() actor_id = new_actor.id new_movie = Movie(**AppTestCase.test_movie) new_movie.insert() new_role = Role(**AppTestCase.test_role) new_role.movie = new_movie new_role.actor = new_actor new_role.insert() res = self.client().get(f'/actors/{actor_id}/roles') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) self.assertEqual(data['actor_id'], actor_id) self.assertTrue('actor_id' not in data['roles'][0])
async def on_guild_role_delete(self, channel): async for entry in channel.guild.audit_logs( action=discord.AuditLogAction.role_delete, limit=1): latest = entry user = session.query(Role).filter_by(userId=latest.user.id).first() if user is None: d = Role(userId=latest.user.id, savedTime=(time.time() + 120), deleted=0) session.add(d) session.commit() user = session.query(Role).filter_by(userId=latest.user.id).first() elif (user.savedTime - time.time()) <= 0: user.savedTime = (time.time() + 120) user.deleted = 0 session.commit() user = session.query(Role).filter_by(userId=latest.user.id).first() if (user.savedTime - time.time()) > 0: user.deleted = user.deleted + 1 session.commit() user = session.query(Role).filter_by(userId=latest.user.id).first() if user.deleted == 5: d = Raiders(userId=latest.user.id, offense='Role') session.add(d) session.delete(user) session.commit() member = channel.guild.get_member(user.userId) for role in member.roles[1:]: await member.remove_roles(role) role = discord.utils.get(channel.guild.roles, name="Under Investigation") await member.add_roles(role)
def init(): config_file = os.path.join( os.path.abspath( os.path.dirname(__file__)), 'config.cfg') app.config.from_pyfile(config_file, silent=True) db.create_all() try: user = User.query.filter( User.name == 'admin').one() except: user = User(name='admin', password='******') db.session.add(user) db.session.commit() try: role = Role.query.filter( Role.name == 'admin').one() except: role = Role(name='admin') db.session.add(role) db.session.commit() if not user.has_role('admin'): user.roles.append(role) db.session.commit()
def post(self): # create/delete new role action = util.form_get('action') if action == 'delete': role_id = util.form_get('id', required=True, type=int) Role.delete_role(role_id) return redirect(url_for('.role')) name = util.form_get('name', required=True) preset = util.form_get('preset') if preset in {'on', 'true'}: preset = True else: preset = False res_list = request.form.getlist('resources') resources = Resource.query.filter(Resource.id.in_(res_list)) if action == 'edit': role_id = util.form_get('id', required=True, type=int) Role.update(role_id, name=name, resources=resources, preset=preset) else: Role.create_role(name=name, resources=resources, preset=preset) return redirect(url_for('.role'))
def get_roles(): roles_list = [('', '')] roles = Role.select() for r in roles: roles_list.append((r, r)) return roles_list
import os import sys from flask_security import utils sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from app import create_app from models import Page, db, Role, User app = create_app() with app.app_context(): admin_role = Role() admin_role.name = 'admin' db.session.add(admin_role) db.session.commit() root = User() root.email = '*****@*****.**' root.password = utils.hash_password("123456") root.active = True root.roles.append(admin_role) db.session.add(root) db.session.commit() page = Page() page.title = "Home Page" page.content = "<h1><b>Hello from flask - docker!<b></h1>" page.is_homepage = True
async def on_message(message): lmsg = None smsg = None if not message.author.bot: if message.content.startswith('cb.'): fields = message.content.split() cmd = fields[0].split('.')[1] await bot.call(cmd, message) return async with lock: if not message.author.bot: server, created = Server.get_or_create(sid=message.server.id) user, created = User.get_or_create(uid=message.author.id) local, created = LocalLevel.get_or_create(user=user, server=server) level, exp = await levelup(server.level, server.experience) try: if level > server.level: # Yay, the server leveled up if server.announce_channel: channel = client.get_channel( f'{server.announce_channel}') smsg = await client.send_message( channel, f"{party} {message.server.name} is now level" f" {level}! {party}") except Exception as e: pass server.level = level server.experience = exp server.save() level, exp = await levelup(user.level, user.experience) user.level = level user.experience = exp user.save() level, exp = await levelup(local.level, local.experience) try: if level > local.level: # User leveled up on the server leaders = LocalLevel.select().where( LocalLevel.server == server).order_by( LocalLevel.level.desc(), LocalLevel.experience.desc()).limit(1) if f"{leaders[0].user.uid}" == message.author.id: leaderboard_roles = Role.select().where( (Role.server == server) & (Role.leaderboard == True)).order_by( Role.awardlevel.desc()) leader_role = discord.utils.get( message.server.roles, id=f'{leaderboard_roles[0].rid}') for member in message.server.members: item = next((i for i in member.roles if i.id == f"{leader_role.id}"), None) if item: await client.remove_roles(member, leader_role) await client.add_roles(message.author, leader_role) try: try: role = Role.get((Role.server == server) & (Role.awardlevel == level)) except Role.DoesNotExist as e: role = None if role: r = discord.utils.get(message.server.roles, id=f'{role.rid}') try: logger.info(f"Adding role {r.name} to " f"{message.author.name}") await client.add_roles(message.author, r) except AttributeError as e: logger.exception("Could not add role") except Role.DoesNotExist as e: logger.exception("Count not find level up reward") except Exception as e: logger.exception("Could not process level up") local.level = level local.experience = exp local.save() await asyncio.sleep(10) if lmsg: await client.delete_message(lmsg) if smsg: await client.delete_message(smsg)
from models import Role, database r = Role() r.name = 'conversationee' r.description = 'day-to-day system user' with database.transaction(): r.save()
app.jinja_env.globals['momentjs'] = momentjs from app import views, models # make sure admin account is setup from models import User, Role, Permission """ @app.context_processor def inject_permissions(): return dict(Permission=Permission) """ # will throw an error if database or the table doesnt exist yet try: # initialize roles Role.insert_roles() # add admin if not yet added admin_email = ADMINS[0] # this returns result object admin_user = User.query.filter_by(email=admin_email).first() # this returns object values admin_role = db.session.query(Role).filter(Role.permissions==Permission.ADMINISTER).first() if not admin_user: defaultpassword = bcrypt.generate_password_hash('1234') user = User(username='******', email=admin_email, role=admin_role, password = defaultpassword) db.session.add(user) db.session.commit() # follow yourself
# Add to DB db.session.add_all([Bob, Steve]) db.session.commit() # Check DB Commit print(Employee.query.all()) Bob = Employee.query.filter_by( name='Bob').first() # Return the first value from the query Jim = Manager('Jim', Bob.id) # Assign roles role_primary = Role('Custodian', Bob.id) role_secondary = Role('Security Guard', Bob.Id) db.session.add_all([Jim, role, primary_role, role_secondary]) db.session.commit() # Query to confirm Bob = Employee.query.filter_by(name='Bob').first() print(Bob) print(Bob.IdentifyRoles())
def view_profile(): user_role = Role.find_by_id(current_user.role) return render_template('profile_page.html', title='My Details', user=current_user, role=user_role.name, auth=is_auth())
def create_role(role_name): """Takes the role name as an argument and create it.""" db.connect() Role.create(role_name=role_name) db.close()