def default(message=None): # Authentication ok = Role.user_has_roles([Role.ROLE_UPLOADER, Role.ROLE_ADMIN]) if not ok: auth = Auth.Auth() if not auth.is_logged_in(): return CTK.HTTP_Redir('/auth') return CTK.HTTP_Redir('/') collections_dict = Collection.get_collections_dict() collections_lst = collections_dict.keys() acl = ACL() collections = acl.filter_collections("co", collections_lst) # Render page = Page.Default() if Role.user_has_role(Role.ROLE_ADMIN): page += CTK.RawHTML("<h1>%s: Colecciones</h1>" % (ADMIN_LINK)) else: page += CTK.RawHTML("<h1>Administración de Colecciones</h1>") if len(collections): cols = [(Collection.Collection, x) for x in collections] page += Paginate(cols, WidgetCollection.DefaultWidget) page += CTK.RawHTML("<p>%s</p>" % LINK_HREF % ('%s/new' % LOCATION, 'Añadir colección')) if message: page += Message(message) return page.Render()
def buttonPressedOwner(update, context): query = update.callback_query chat_id = query.message.chat.id callbackdata = query.data user = Role.Verify(chat_id=chat_id) #if user unregchat if re.match(r"unregchat(.*)", callbackdata): userchat_id = re.findall(r"unregchat(.*)", callbackdata)[0] msg = open_message("owner","unregchat") user.unregChat(userchat_id) update.callback_query.edit_message_reply_markup(reply_markup=None) #update.callback_query.message.reply_text(text=f"Done, those chat/group were deleted") update.callback_query.message.reply_text(text=msg) #if owner klik approve button elif re.match(r"insert.*", callbackdata): #extract callbackdata from format "insertUserchat_id,chat_name,owner_id" datachat = re.findall(r"insert(.*)", callbackdata) #convert it to list of string hasildatachat = datachat[0].split(',') userchat_id = hasildatachat[0] userchat_name = hasildatachat[1] owner_id = hasildatachat[2] msgowner = open_message("owner","approvedchat") msgrequestor = open_message("user","requestornotify") #insert to db user = Role.Verify(userchat_id) user.registerChat(userchat_id, userchat_name, owner_id) query.edit_message_reply_markup(reply_markup=None) #query.message.reply_text(text=f'Done, those chat has been registered to your token.\nYou can unregister by /unregchat', parse_mode=ParseMode.HTML) query.message.reply_text(text=msgowner, parse_mode=ParseMode.HTML) #send notif to requestor context.bot.send_message(chat_id=userchat_id, text=msgrequestor, parse_mode=ParseMode.HTML)
def testapp(request): app = create_app('{{cookiecutter.app_name}}.settings.TestConfig') client = app.test_client() db.app = app db.create_all() if getattr(request.module, "create_user", True): admin = User(username="******", password="******") admin.insert() my_role = Role(name='admin') my_role.insert() admin.add_roles('admin') non_admin = User(username="******", password="******") non_admin.insert() safe_commit() def teardown(): db.session.remove() db.drop_all() request.addfinalizer(teardown) return client
def __init__(self, parent): GGrule.__init__(self, 29) self.TimeDelay = ATOM3Integer(2) self.exactMatch = 1 self.LHS = ASG_omacs(parent) self.obj2255 = Role(parent) self.obj2255.preAction(self.LHS.CREATE) self.obj2255.isGraphObjectVisual = True if (hasattr(self.obj2255, '_setHierarchicalLink')): self.obj2255._setHierarchicalLink(False) # name self.obj2255.name.setValue('') self.obj2255.name.setNone() self.obj2255.GGLabel.setValue(1) self.obj2255.graphClass_ = graph_Role if parent.genGraphics: new_obj = graph_Role(100.0, 60.0, self.obj2255) new_obj.layConstraints = dict() # Graphical Layout Constraints new_obj.layConstraints['scale'] = [1.0, 1.0] else: new_obj = None self.obj2255.graphObject_ = new_obj # Add node to the root: self.LHS self.LHS.addNode(self.obj2255) self.obj2255.postAction(self.LHS.CREATE) self.RHS = ASG_omacs(parent)
def test_roles(self): role = Role(name='admin') role.save() u = UserFactory() u.roles.append(role) u.save() assert role in u.roles
def test_roles(self): """Add a role to a user.""" role = Role(name='admin') role.save() user = UserFactory() user.roles.append(role) user.save() assert role in user.roles
def test_roles(self): """Add a role to a user.""" role = Role(name="admin") role.save() user = UserFactory() user.roles.append(role) user.save() assert role in user.roles
def check_if_authorized (content): """Checks""" if Role.user_has_role (Role.ROLE_ADMIN): return # OK if Role.user_has_role (Role.ROLE_UPLOADER): user_id = get_user_id() if user_id == content['creator_id']: return raise Error.Unauthorized
def check_if_authorized(content): """Checks""" if Role.user_has_role(Role.ROLE_ADMIN): return # OK if Role.user_has_role(Role.ROLE_UPLOADER): user_id = get_user_id() if user_id == content['creator_id']: return raise Error.Unauthorized
def Add(self, asset): assert isinstance(asset, Asset.Asset) asset_id = asset['id'] linkname, linkdel = str(asset_id), '' if asset_id in self.acl.filter_assets("co", [asset_id]): linkname = LINK_HREF % ("/consume/a=%s" % (asset_id), asset_id) # Delete asset link if asset_id in self.acl.filter_assets("rm", [asset_id]): dialog = CTK.Dialog({ 'title': "Eliminar activo #%d?" % (asset_id), 'autoOpen': False }) dialog += CTK.RawHTML(NOTE_DELETE) dialog.AddButton('Cancelar', "close") dialog.AddButton('Borrar', "%s/del/%s" % (PageAsset.LOCATION, asset_id)) linkdel = LINK_JS_ON_CLICK % (dialog.JS_to_show(), "Borrar") self += dialog entries = [ CTK.RawHTML(linkname), CTK.RawHTML(asset['title']), CTK.RawHTML(asset['Type']), CTK.RawHTML(linkdel) ] try: Auth.check_if_authorized(asset) link = LINK_HREF % ("/acl/asset/%d" % (asset['id']), 'Permisos') entries.append(CTK.RawHTML(link)) except Error.Unauthorized: pass if Role.user_has_role (Role.ROLE_UPLOADER) and\ asset_id in self.acl.filter_assets ("co" , [asset_id]): entries.append( CTK.RawHTML(LINK_HREF % ('%s/evolve/parent=%d' % (PageUpload.LOCATION, asset_id), 'Evolucionar'))) if Role.user_has_role (Role.ROLE_EDITOR) and\ asset_id in self.acl.filter_assets ("ed" , [asset_id]): entries.append( CTK.RawHTML(LINK_HREF % ('%s/edit/%d' % (PageAsset.LOCATION, asset_id), 'Editar'))) self.n += 1 self.table[(self.n, 1)] = entries
def sample_data(): """ Creates a set of sample data """ from {{cookiecutter.app_name}}.models import Role user = User(username="******", password="******") my_role = Role(name='admin') my_role.add_abilities('create_users', 'delete_users') user.add_roles('admin', 'superadmin') db.session.add(user) db.session.add(my_role) db.session.commit()
def reqtoken_handler(update, context): chat_id = update.effective_chat.id user = Role.Verify(chat_id) hasilpasscode = user.reqPasscode(chat_id, nexttoken=None) if hasilpasscode: passcode = hasilpasscode[0] username = hasilpasscode[1] button = [] msg = open_message("user","reqtoken") #create dict for button buttondict = {'next60': 'next 60s', 'next3600': 'next 1h', 'next7200': 'next 2h', 'next14400': 'next 4h'} #build button for next token from buttondict for callbackdata, teks in buttondict.items(): button.append(InlineKeyboardButton( text=teks, callback_data=callbackdata ) ) buttonmarkup = InlineKeyboardMarkup(messageformat.buildButton(button, 2)) #update.message.reply_text(text=f"<code>username: {username}</code>\nHere is the passcode <code>{passcode}</code>", parse_mode=ParseMode.HTML, reply_markup=buttonmarkup) update.message.reply_text(text=msg.format(username, passcode), parse_mode=ParseMode.HTML, reply_markup=buttonmarkup) else: msg = open_message("user","reqtokennotreg") #update.message.reply_text(text=f"Sorry, this chat/group does not belong to any token.\n please register by clicking this /registerchat", parse_mode=ParseMode.HTML) update.message.reply_text(text=msg, parse_mode=ParseMode.HTML)
def test(): import sys import OpLookup import Auth import Role try: username = sys.argv[1] asset_id = int(sys.argv[2]) asset = Asset(asset_id) user = Auth.get_user(username) roles = Role.get_user_roles(username) params = {'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user sample_asset_id' sys.exit(1) # Create asset for testing new_asset = Asset() new_asset._db = asset._db new_asset._tags = asset._tags flag = id(new_asset) new_asset['title'] = flag oa = OpAsset(new_asset, params) assert oa print '#1 OpAsset (): Creation OK' ret = oa.add() assert ret == True print '#2 OpAsset.add(): Addition OK' ol = OpLookup.OpLookup() new_asset_id = ol({'title': flag})[0] new_asset = Asset(new_asset_id) assert int(new_asset['title']) == int(flag) print '#3 OpAsset.add(): Retrieval after addition OK' oa = OpAsset(new_asset, params) assert oa print '#4 OpAsset (new_asset): Creation after retrieval OK' new_asset['description'] = flag oa = OpAsset(new_asset, params) ret = oa.update() assert ret == True print '#5 OpAsset.update(): Modification OK' ol = OpLookup.OpLookup() updated_asset_id = ol({'description': int(flag)})[0] updated_asset = Asset(new_asset_id) assert int(updated_asset['description']) == int(flag) print '#6 OpAsset.update(): Retrieval after modification OK' assert updated_asset['id'] == new_asset['id'] print '#7 OpAsset.update(): Comparison with original OK' ret = oa.delete() assert ret['ret'] == True print '#8 OpAsset.delete(): Deletion OK'
def edit_collection(): # Authentication ok = Role.user_has_roles([Role.ROLE_UPLOADER, Role.ROLE_ADMIN]) if not ok: return CTK.HTTP_Redir('/') # Table url = clear_params(CTK.request.url) collection_id = url.split('/')[-1] acl = ACL() editable = acl.filter_collections("ed", [collection_id]) if not int(collection_id) in editable: return CTK.HTTP_Error(401) q = "SELECT collections_id, collections.name,"\ "GROUP_CONCAT(assets.id) AS parts "\ "FROM assets JOIN collections ON collections.id=collections_id "\ "WHERE collections_id='%(collection_id)s';" % locals() table = PropsAutoSQL('%s/edit/apply' % LOCATION, q) table.AddConstant('collection_id', str(collection_id)) table.Add('Nombre', CTK.TextField(), 'name', 'Nombre de la colección') page = Page.Default() page += CTK.RawHTML("<h1>%s: Editar colección</h1>" % (MENU_LINK)) page += table page += ClaimedWidget(c_id=collection_id) page += UnclaimedWidget(c_id=collection_id) return page.Render()
def add_new (self, content, refresh): # Add new entry c_id, c_type = get_id_and_type (content) url = '%s/%s' % (URL_APPLY, c_type) roles = ["Administrator", "Ingestador", "Editor", "Publicador", "Consumidor"] role_options = [(None,'Todos')] + [(Role.name_to_role(x), x) for x in roles] user_options = [(None,'Todos')] + Auth.get_users() entries = [CTK.RawHTML (''), CTK.Checkbox ({'name': "ad", 'checked':False, 'class':'required'}), CTK.Checkbox ({'name': "ed", 'checked':False, 'class':'required'}), CTK.Checkbox ({'name': "rm", 'checked':False, 'class':'required'}), CTK.Checkbox ({'name': "co", 'checked':False, 'class':'required'}), CTK.Combobox ({'name':'role', 'class':'required'}, role_options), CTK.Combobox ({'name':'user_id', 'class':'required'}, user_options)] self.table[(self.n,1)] = entries + [CTK.SubmitterButton('Enviar')] self.n += 1 form = CTK.Submitter(url) form += self.table form += CTK.HiddenField({'name':'type', 'value':c_type}) form += CTK.HiddenField({'name':'id', 'value':c_id}) form.bind ('submit_success', refresh.JS_to_refresh()) self += form
def test(): import sys import OpLookup import Auth import Role try: username = sys.argv[1] asset_id = int (sys.argv[2]) asset = Asset (asset_id) user = Auth.get_user(username) roles = Role.get_user_roles (username) params = { 'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user sample_asset_id' sys.exit(1) # Create asset for testing new_asset = Asset () new_asset._db = asset._db new_asset._tags = asset._tags flag = id (new_asset) new_asset['title'] = flag oa = OpAsset (new_asset, params) assert oa print '#1 OpAsset (): Creation OK' ret = oa.add() assert ret == True print '#2 OpAsset.add(): Addition OK' ol = OpLookup.OpLookup () new_asset_id = ol({'title': flag})[0] new_asset = Asset (new_asset_id) assert int(new_asset['title']) == int(flag) print '#3 OpAsset.add(): Retrieval after addition OK' oa = OpAsset (new_asset, params) assert oa print '#4 OpAsset (new_asset): Creation after retrieval OK' new_asset['description'] = flag oa = OpAsset (new_asset, params) ret = oa.update() assert ret == True print '#5 OpAsset.update(): Modification OK' ol = OpLookup.OpLookup () updated_asset_id = ol({'description': int(flag)})[0] updated_asset = Asset (new_asset_id) assert int(updated_asset['description']) == int(flag) print '#6 OpAsset.update(): Retrieval after modification OK' assert updated_asset['id'] == new_asset['id'] print '#7 OpAsset.update(): Comparison with original OK' ret = oa.delete() assert ret['ret'] == True print '#8 OpAsset.delete(): Deletion OK'
def edit_collection_apply(): # Authentication ok = Role.user_has_roles([Role.ROLE_UPLOADER, Role.ROLE_ADMIN]) if not ok: return CTK.HTTP_Redir('/') collection_id = CTK.post.pop('collection_id') if not collection_id: return CTK.HTTP_Error(400) acl = ACL() editable = acl.filter_collections("ed", [collection_id]) if not int(collection_id) in editable: return CTK.HTTP_Error(401) collection = Collection.Collection(collection_id) if 'name' in CTK.post: collection['name'] = CTK.post['name'] if 'parts' in CTK.post: parts = CTK.post['parts'] if parts: parts = parts.replace(',', ' ') result = parts.split() acl = ACL() result = acl.filter_assets("co", result) collection['assets'] = [int(x) for x in result] oa = OpCollection(collection) ret = oa.update() if ret == True: return {'ret': "ok"} else: return {'ret': "error"}
def steer (filename): """Given an input page and role, return a destination""" page = __get_page_name (filename) user = Auth.get_user() roles = Role.get_user_roles () request = CTK.request.url params = request.split('/')[-1] profile_name = '__default__' profile_id = user.get('profile_id') user_id = user.get('id') user_name = user.get('username') profiles = Profile.get_profiles () for x in profiles: if x['id'] == profile_id: profile_name = x['name'] break entry = Workflow.SCRIPT[page] if profile_name in entry: destination = entry[profile_name] % locals() else: destination = entry['__default__'] % locals() return CTK.HTTP_Redir (destination)
def __init__ (self, params = None): if params: self.roles = params['roles'] self.user_id = params['user_id'] else: self.roles = Role.get_user_roles() self.user_id = Auth.get_user_id()
def __init__(self, params=None): if params: self.roles = params['roles'] self.user_id = params['user_id'] else: self.roles = Role.get_user_roles() self.user_id = Auth.get_user_id()
def test(): import sys try: username = sys.argv[1] asset_id = int(sys.argv[2]) collection_id = int(sys.argv[3]) user = Auth.get_user(username) roles = Role.get_user_roles(username) params = {'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user asset_id collection_id' sys.exit(1) acl = ACL(params) assert acl print '#1 ACL() --> OK' asset_acl_full = acl.acl_asset(asset_id, summarize=False) assert asset_acl_full print '#2 ACL().acl_asset (asset_id, summarize = False) --> OK' asset_acl_compact = acl.acl_asset(asset_id, summarize=True) assert asset_acl_compact print '#3 ACL().acl_asset (asset_id, summarize = True) --> OK' assert asset_acl_compact == acl.compact_acl(asset_acl_full) print '#4 ACL().compact_acl (asset_acl_full) --> OK' collection_acl_full = acl.acl_collection(collection_id, summarize=False) assert collection_acl_full print '#5 ACL().acl_asset (collection_id, summarize = False) --> OK' collection_acl_compact = acl.acl_collection(collection_id, summarize=True) assert collection_acl_compact print '#6 ACL().acl_asset (collection_id, summarize = True) --> OK' assert collection_acl_compact == acl.compact_acl(collection_acl_full) print '#7 ACL().compact_acl (collection_acl_full) --> OK' n = 7 for key in ['ad', 'ed', 'rm', 'co']: filtered = acl.filter_assets(key, [asset_id]) if asset_acl_compact[key]: assert asset_id in filtered else: assert asset_id not in filtered n += 1 print '#%s ACL().filter_assets (%s, [asset_id]) --> OK' % (n, key) for key in ['ad', 'ed', 'rm', 'co']: filtered = acl.filter_collections(key, [collection_id]) if collection_acl_compact[key]: assert collection_id in filtered else: assert collection_id not in filtered n += 1 print '#%s ACL().filter_collections (%s, [collection_id]) --> OK' % ( n, key)
def unregtoken_handler(update, context): chat_id = update.effective_chat.id user = Role.Verify(chat_id=chat_id) user.unregToken(chat_id=chat_id) msg = open_message("owner","unregtoken") #update.message.reply_text(text=f"Done, your token has been unregistered.\nYou could always import it again using /registertoken") update.message.reply_text(text=msg)
def default(message=None): # Authentication fail = Auth.assert_is_role(Role.ROLE_UPLOADER) if fail: return fail # List of assets lookup = OpLookup() search = {'creator_id': Auth.get_user_id(), '__order__': 'id'} if Role.user_has_role(Role.ROLE_ADMIN): search = {'__order__': 'id'} try: result = lookup(search) except: result = [] contents = [(Asset, x) for x in result] page = Page.Default() # Render if Role.user_has_role(Role.ROLE_ADMIN): page += CTK.RawHTML("<h1>%s: Activos</h1>" % (ADMIN_LINK)) else: page += CTK.RawHTML("<h1>Administración de Activos</h1>") if Role.user_has_role(Role.ROLE_UPLOADER): page += CTK.RawHTML( "<p>%s</p>" % LINK_HREF % ('%s/upload/new' % LOCATION, 'Añadir activo')) if Role.user_has_role(Role.ROLE_PUBLISHER): page += CTK.RawHTML("<p>%s</p>" % LINK_HREF % ('%s/publish' % LOCATION, 'Publicar activos')) if Role.user_has_role(Role.ROLE_EDITOR): page += CTK.RawHTML("<p>%s</p>" % LINK_HREF % ('%s/edit' % LOCATION, 'Editar activos')) if len(contents): page += Paginate(contents, DefaultWidget) if message: page += Message(message) return page.Render()
def assert_is_role (x): # Is he logged? auth = Auth() if not auth.is_logged_in(): return CTK.HTTP_Redir('/auth') # Check the roles if type(x) == int: if Role.user_has_role (x): return None # ok elif type(x) == list: for role in x: if Role.user_has_role (role): return None # ok # Does not have the role return CTK.HTTP_Redir('/')
def assert_is_role(x): # Is he logged? auth = Auth() if not auth.is_logged_in(): return CTK.HTTP_Redir('/auth') # Check the roles if type(x) == int: if Role.user_has_role(x): return None # ok elif type(x) == list: for role in x: if Role.user_has_role(role): return None # ok # Does not have the role return CTK.HTTP_Redir('/')
def test (): import sys try: username = sys.argv[1] asset_id = int(sys.argv[2]) collection_id = int(sys.argv[3]) user = Auth.get_user(username) roles = Role.get_user_roles (username) params = { 'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user asset_id collection_id' sys.exit(1) acl = ACL(params) assert acl print '#1 ACL() --> OK' asset_acl_full = acl.acl_asset (asset_id, summarize = False) assert asset_acl_full print '#2 ACL().acl_asset (asset_id, summarize = False) --> OK' asset_acl_compact = acl.acl_asset (asset_id, summarize = True) assert asset_acl_compact print '#3 ACL().acl_asset (asset_id, summarize = True) --> OK' assert asset_acl_compact == acl.compact_acl(asset_acl_full) print '#4 ACL().compact_acl (asset_acl_full) --> OK' collection_acl_full = acl.acl_collection (collection_id, summarize = False) assert collection_acl_full print '#5 ACL().acl_asset (collection_id, summarize = False) --> OK' collection_acl_compact = acl.acl_collection (collection_id, summarize = True) assert collection_acl_compact print '#6 ACL().acl_asset (collection_id, summarize = True) --> OK' assert collection_acl_compact == acl.compact_acl(collection_acl_full) print '#7 ACL().compact_acl (collection_acl_full) --> OK' n=7 for key in ['ad','ed','rm','co']: filtered = acl.filter_assets (key, [asset_id]) if asset_acl_compact[key]: assert asset_id in filtered else: assert asset_id not in filtered n += 1 print '#%s ACL().filter_assets (%s, [asset_id]) --> OK' % (n,key) for key in ['ad','ed','rm','co']: filtered = acl.filter_collections (key, [collection_id]) if collection_acl_compact[key]: assert collection_id in filtered else: assert collection_id not in filtered n += 1 print '#%s ACL().filter_collections (%s, [collection_id]) --> OK' % (n,key)
def onLoginRequest(self, user_data): req = Request() req.ParseFromString(user_data["msg_data"]) if req.HasField('login'): Log().d('onLoginRequest(' + req.login.username + "," + req.login.password + ")") # TODO role = Role() role.setUserData(user_data) RoleManager().addRole() res = Response() res.result = True res.last_response = True res.login.token = 1234 res_str = res.SerializeToString() Log().d("len(reponse)=" + str(len(res_str))) self.sendMsg(user_data, Login_Response, res_str)
def default( message = None): # Authentication fail = Auth.assert_is_role (Role.ROLE_UPLOADER) if fail: return fail # List of assets lookup = OpLookup() search = {'creator_id': Auth.get_user_id(), '__order__': 'id'} if Role.user_has_role (Role.ROLE_ADMIN): search = {'__order__': 'id'} try: result = lookup(search) except: result = [] contents = [(Asset, x) for x in result] page = Page.Default () # Render if Role.user_has_role (Role.ROLE_ADMIN): page += CTK.RawHTML ("<h1>%s: Activos</h1>"%(ADMIN_LINK)) else: page += CTK.RawHTML ("<h1>Administración de Activos</h1>") if Role.user_has_role (Role.ROLE_UPLOADER): page += CTK.RawHTML ("<p>%s</p>"%LINK_HREF%('%s/upload/new'%LOCATION, 'Añadir activo')) if Role.user_has_role (Role.ROLE_PUBLISHER): page += CTK.RawHTML ("<p>%s</p>"%LINK_HREF%('%s/publish'%LOCATION, 'Publicar activos')) if Role.user_has_role (Role.ROLE_EDITOR): page += CTK.RawHTML ("<p>%s</p>"%LINK_HREF%('%s/edit'%LOCATION, 'Editar activos')) if len(contents): page += Paginate(contents, DefaultWidget) if message: page += Message(message) return page.Render()
def revoke_all_roles(self, member): ''' (MemberDatabase, Member) -> None Revokes all the roles that have been granted to member. ''' memberRoleNameList = member.role_list() for memberRoleName in memberRoleNameList: Role.Role(self._directory, self._database, memberRoleName).revoke(member)
def default (message = None): # Authentication fail = Auth.assert_is_role (Role.ROLE_ADMIN) if fail: return fail # List of profiles q = "SELECT * FROM profiles;" profiles = Query(q) table = CTK.Table() title = [CTK.RawHTML(x) for x in ['Profile', 'Descripcion', 'Role']] table[(1,1)] = title table.set_header (row=True, num=1) page = Page.Default() n = 2 for profile in profiles: # Fetch data profile_id = profiles[profile]['id'] profile_name = profiles[profile]['name'] profile_desc = profiles[profile]['description'] # Role q = "SELECT * FROM profiles_has_roles WHERE profiles_id='%s';" %(profile_id) roles = Query(q) profile_roles_str = ', '.join([Role.role_to_name(roles[x]['roles_id']) for x in roles]) # Delete profile dialog = CTK.Dialog ({'title': "Eliminando profile %s?"%(profile_name), 'autoOpen': False}) dialog += CTK.RawHTML (NOTE_DELETE) dialog.AddButton ('Cancelar', "close") dialog.AddButton ('Borrar', "/admin/profile/del/%s" %(profile_id)) del_img = '<img src="/CTK/images/del.png" alt="Borrar"' linkdel = LINK_JS_ON_CLICK %(dialog.JS_to_show(), del_img) linkname = LINK_HREF %("/admin/profile/%s"%profile_id, profile_name) table[(n,1)] = [CTK.RawHTML(linkname), CTK.RawHTML(profile_desc), CTK.RawHTML(profile_roles_str), CTK.RawHTML(linkdel)] page += dialog n += 1 # Render page += CTK.RawHTML ("<h1>%s: Administración de Profiles</h1>" %(ADMIN_PREFIX)) page += CTK.RawHTML (LINK_HREF%('/admin/profile/new', 'Añadir profile')) page += table if message: page += Message (message) return page.Render()
def createNewRole(self, wherex, wherey, screenCoordinates=1): self.fromClass = None self.toClass = None # try the global constraints... res = self.ASGroot.preCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode = self.IDLEMODE return new_semantic_obj = Role(self) res = new_semantic_obj.preCondition(ASGNode.CREATE) if res: return self.constraintViolation(res) new_semantic_obj.preAction(ASGNode.CREATE) ne = len(self.ASGroot.listNodes["Role"]) if new_semantic_obj.keyword_: new_semantic_obj.keyword_.setValue( new_semantic_obj.keyword_.toString() + str(ne)) if screenCoordinates: new_obj = graph_Role(self.UMLmodel.canvasx(wherex), self.UMLmodel.canvasy(wherey), new_semantic_obj) else: # already in canvas coordinates new_obj = graph_Role(wherex, wherey, new_semantic_obj) new_obj.DrawObject(self.UMLmodel, self.editGGLabel) self.UMLmodel.addtag_withtag("Role", new_obj.tag) new_semantic_obj.graphObject_ = new_obj self.ASGroot.addNode(new_semantic_obj) res = self.ASGroot.postCondition(ASG.CREATE) if res: self.constraintViolation(res) self.mode = self.IDLEMODE return res = new_semantic_obj.postCondition(ASGNode.CREATE) if res: self.constraintViolation(res) self.mode = self.IDLEMODE return new_semantic_obj.postAction(ASGNode.CREATE) self.mode = self.IDLEMODE if self.editGGLabel: self.statusbar.event(StatusBar.TRANSFORMATION, StatusBar.CREATE) else: self.statusbar.event(StatusBar.MODEL, StatusBar.CREATE) return new_semantic_obj
def registerchat_handler(update, context): chat_id = update.effective_chat.id role = Role.Verify(chat_id) #clear groupdict and button messageformat.groupdict = {} messageformat.markupdept = {} hasil = role.listToken() keyboardmarkup = hasil[0] teks = hasil[1] msg = open_message("alluser", "registerchat") update.message.reply_text(text=msg.format(teks), reply_markup=keyboardmarkup,parse_mode=ParseMode.HTML)
def listtoken_handler(update, context): chat_id = update.effective_chat.id role = Role.Verify(chat_id) #clear groupdict and button messageformat.groupdict = {} messageformat.markupdept = {} keyboard, teks = role.listToken() msg = open_message("alluser","listtoken") #update.message.reply_text(text=f"Token registered to this bot.\n<code>{teks}</code>", parse_mode=ParseMode.HTML) update.message.reply_text(text=msg.format(teks), parse_mode=ParseMode.HTML)
def __init__(self, db): DBUtil.__init__(self, db) self.collection = db.Machine self.passHelper = PasswordHelper.PasswordHelper(key) self.userdb = Users.Users(db) self.roleDb = Role.Role(db) self.tagDB = Tags.Tags() # indexes self.collection.create_index([('username', ASCENDING), ('host', ASCENDING)], unique=True)
def __init__(self, **kwargs): CTK.Container.__init__(self, **kwargs) try: auth = Auth.Auth() if not auth.is_logged_in(): return except AttributeError: return self.roles = Role.get_user_roles() self.user = Auth.get_user() self.menu()
def __init__ (self, **kwargs): CTK.Container.__init__ (self, **kwargs) try: auth = Auth.Auth() if not auth.is_logged_in (): return except AttributeError: return self.roles = Role.get_user_roles () self.user = Auth.get_user() self.menu ()
def add_new(self, content, refresh): # Add new entry c_id, c_type = get_id_and_type(content) url = '%s/%s' % (URL_APPLY, c_type) roles = [ "Administrator", "Ingestador", "Editor", "Publicador", "Consumidor" ] role_options = [(None, 'Todos')] + [(Role.name_to_role(x), x) for x in roles] user_options = [(None, 'Todos')] + Auth.get_users() entries = [ CTK.RawHTML(''), CTK.Checkbox({ 'name': "ad", 'checked': False, 'class': 'required' }), CTK.Checkbox({ 'name': "ed", 'checked': False, 'class': 'required' }), CTK.Checkbox({ 'name': "rm", 'checked': False, 'class': 'required' }), CTK.Checkbox({ 'name': "co", 'checked': False, 'class': 'required' }), CTK.Combobox({ 'name': 'role', 'class': 'required' }, role_options), CTK.Combobox({ 'name': 'user_id', 'class': 'required' }, user_options) ] self.table[(self.n, 1)] = entries + [CTK.SubmitterButton('Enviar')] self.n += 1 form = CTK.Submitter(url) form += self.table form += CTK.HiddenField({'name': 'type', 'value': c_type}) form += CTK.HiddenField({'name': 'id', 'value': c_id}) form.bind('submit_success', refresh.JS_to_refresh()) self += form
def buttonPressedNext(update, context): query = update.callback_query chat_id = query.message.chat.id message_id = query.message.message_id callbackdata = query.data from_userfirstname = query.from_user.first_name nexttoken = int(re.findall(r"next(.*)", callbackdata)[0]) msg = open_message("user","reqtokennext") user = Role.Verify(chat_id) passcode, waktu, username = user.reqPasscode(chat_id, nexttoken) query.edit_message_reply_markup(reply_markup=None) #query.message.reply_text(text=f"<code>username: {username}</code>\n{from_userfirstname} here is your passcode:\n\n<code>{passcode}active until {waktu}</code>", parse_mode=ParseMode.HTML) query.message.reply_text(text=msg.format(username, from_userfirstname, passcode, waktu), parse_mode=ParseMode.HTML)
def edit_user(): # Authentication is_admin = Role.user_has_role(Role.ROLE_ADMIN) user_id = CTK.request.url.split('/')[3] profile_id = Profile.get_user_profile(user_id) current_id = Auth.get_user_id() try: is_self = (int(user_id) == current_id) except: is_self = False if not is_admin and not is_self: return CTK.HTTP_Redir('/') user_query = "SELECT * FROM users WHERE id = '%(user_id)s';" % (locals()) profile_query = "SELECT id, description FROM profiles;" # Table table = PropsAutoSQL('/admin/user/apply', user_query) table.AddConstant('userid', user_id) table.AddConstant('old_password', table.SQL_result['password'][0]) if is_admin: props = {} if int(current_id) == int(user_id): props['disabled'] = '' props['selected'] = profile_id profiles = ComboboxSQL(props, profile_query) table.Add('Profile', profiles, 'profile_id', 'Profile del usuario') table.Add('Login', CTK.TextField({'disabled': True}), 'username', 'Login de usuario') table.Add('Password', CTK.TextFieldPassword(), 'password', 'Clave de acceso') table.Add('Nombre', CTK.TextField(), 'forename', 'Nombre propio') table.Add('Apellido 1', CTK.TextField(), 'surname1', 'Primer Apellido') table.Add('Apellido 2', CTK.TextField(), 'surname2', 'Segundo Apellido') table.Add('E-Mail', CTK.TextField(), 'email', 'Cuenta de correo electronico') page = Page.Default() if is_admin: title = '%s: %s' % (ADMIN_LINK, LINK_HREF % (LOCATION, 'Usuarios')) else: title = '%s Edición de usuario' % BACK_LINK page += CTK.RawHTML("<h1>%s</h1>" % title) page += table return page.Render()
def listchat_handler(update, context, unreg=False): chat_id = update.effective_chat.id user = Role.Verify(chat_id=chat_id) listchat, markupchat = user.listChat(chat_id=chat_id) print(listchat) if unreg: #update.message.reply_text(text=f"Ini list chat yang udah approved \n{listchat}\n <b>Klik button di bawah buat unreg chat yang lu approve boss.</b>", reply_markup=markupchat,parse_mode=ParseMode.HTML) msg = open_message("owner","listchatunreg") update.message.reply_text(text=msg.format(listchat), reply_markup=markupchat,parse_mode=ParseMode.HTML) else: #update.message.reply_text(text=f"Ini list chat yang udah approved \n{listchat}\n Kalo mau unreg chatnya, klik /unregchat", parse_mode=ParseMode.HTML) msg = open_message("owner","listchat") update.message.reply_text(text=msg.format(listchat), parse_mode=ParseMode.HTML) return
def default (): # Authentication fail = Auth.assert_is_role (Role.ROLE_CONSUMER) if fail: return fail if not Role.user_has_role(Role.ROLE_ADMIN): return report_assets() page = Page.Default() page += CTK.RawHTML ("<h1>%s: Reportes</h1>"%(ADMIN_LINK)) table = CTK.Table() table[(1,1)] = CTK.RawHTML (LINK_HREF % ("%s/assets" % LOCATION, 'Reportes de activos')) table[(2,1)] = CTK.RawHTML (LINK_HREF % ("%s/system" % LOCATION, 'Reportes del sistema')) page += table return page.Render()
def edit_user(): # Authentication is_admin = Role.user_has_role (Role.ROLE_ADMIN) user_id = CTK.request.url.split('/')[3] profile_id = Profile.get_user_profile (user_id) current_id = Auth.get_user_id() try: is_self = (int(user_id) == current_id) except: is_self = False if not is_admin and not is_self: return CTK.HTTP_Redir('/') user_query = "SELECT * FROM users WHERE id = '%(user_id)s';" %(locals()) profile_query = "SELECT id, description FROM profiles;" # Table table = PropsAutoSQL ('/admin/user/apply', user_query) table.AddConstant ('userid', user_id) table.AddConstant ('old_password', table.SQL_result['password'][0]) if is_admin: props = {} if int(current_id) == int(user_id): props['disabled'] = '' props['selected'] = profile_id profiles = ComboboxSQL (props, profile_query) table.Add ('Profile',profiles, 'profile_id', 'Profile del usuario') table.Add ('Login', CTK.TextField({'disabled':True}), 'username', 'Login de usuario') table.Add ('Password', CTK.TextFieldPassword(), 'password', 'Clave de acceso') table.Add ('Nombre', CTK.TextField(), 'forename', 'Nombre propio') table.Add ('Apellido 1', CTK.TextField(), 'surname1', 'Primer Apellido') table.Add ('Apellido 2', CTK.TextField(), 'surname2', 'Segundo Apellido') table.Add ('E-Mail', CTK.TextField(), 'email', 'Cuenta de correo electronico') page = Page.Default() if is_admin: title = '%s: %s' % (ADMIN_LINK, LINK_HREF % (LOCATION, 'Usuarios')) else: title = '%s Edición de usuario' % BACK_LINK page += CTK.RawHTML ("<h1>%s</h1>" % title) page += table return page.Render()
def Add (self, collection): collection_id = collection['id'] coll = self.collections_dict[collection_id] linkname, linkdel = str(collection_id),'' if collection_id in self.acl.filter_collections ("co" , [collection_id]): url = "%s/edit/%s" % (PageCollection.LOCATION, collection_id) linkname = LINK_HREF %(url, collection_id) # Delete collection link if collection_id in self.acl.filter_collections ("rm" , [collection_id]): dialog = self.__get_del_dialog ("del/%s" %(collection_id), NOTE_DELETE) linkdel = LINK_JS_ON_CLICK %(dialog.JS_to_show(), "Borrar") self += dialog entries = [CTK.RawHTML(linkname), CTK.RawHTML(coll['name']), CTK.RawHTML(coll['username']), CTK.RawHTML(linkdel)] try: Auth.check_if_authorized (collection) link = LINK_HREF % ("/acl/collection/%d" % (collection['id']), 'Permisos') entries.append(CTK.RawHTML(link)) except Error.Unauthorized: entries.append(CTK.RawHTML('')) pass if collection_id in self.acl.filter_collections ("ed" , [collection_id])\ and Role.user_has_role (Role.ROLE_EDITOR): url = '%s/edit/%d'%(PageCollection.LOCATION,collection_id) link = LINK_HREF%(url, 'Editar') entries.append(CTK.RawHTML (link)) if collection_id in self.acl.filter_collections ("co" , [collection_id]): url = "%s/meta/%s" % (PageCollection.LOCATION, collection_id) link = LINK_HREF%(url, 'Metadatos') entries.append(CTK.RawHTML (link)) self.n += 1 self.table[(self.n, 1)] = entries
def edit_user_apply(): # Authentication is_admin = Role.user_has_role (Role.ROLE_ADMIN) user_id = CTK.post['userid'] current_id = Auth.get_user_id() try: is_self = (int(user_id) == current_id) except: is_self = False if not is_admin and not is_self: return CTK.HTTP_Error(403) if not user_id: return CTK.HTTP_Error(406) # Update the database sql_values = [] for key in ['username', 'forename', 'surname1', 'surname2', 'email']: if key in CTK.post: sql_values.append ("%s='%s'" %(key, CTK.post[key])) if 'password' in CTK.post: password = CTK.post['password'] hashed_password = md5(password).hexdigest() old_password = CTK.post['old_password'] if not password == old_password: sql_values.append ("password='******'"%(hashed_password)) if is_admin: key = 'profile_id' if key in CTK.post: sql_values.append ("%s=%s" %(key, CTK.post[key])) q = "UPDATE users SET %s WHERE id = %s;" %(','.join(sql_values), user_id) if not query_check_success (q): return {'ret': "error"} return {'ret': "ok"}
def report_assets (): """Report info for users""" # Authentication fail = Auth.assert_is_role (Role.ROLE_CONSUMER) if fail: return fail page = Page.Default() if Role.user_has_role (Role.ROLE_ADMIN): page += CTK.RawHTML ("<h1>%s</h1>"%(MENU_LINK)) report = get_24h_task() if report: page += CTK.RawHTML('<h2>Activos de las últimas 24 horas</h2>') page += get_section (report) report = get_views_task() if report: page += CTK.RawHTML('<h2>Activos más populares</h2>') page += get_section (report, ('Visitas','views')) return page.Render()
def __init__ (self, refreshable, content,**kwargs): CTK.Container.__init__(self) self.table = CTK.Table() # Header row = ['','Añadir', 'Editar', 'Borrar', 'Consumir', 'Rol', 'Usuario'] self.table[(1,1)] = [CTK.RawHTML(x) for x in row] self.table.set_header (row=True, num=1) # Entries self.n = 2 acl = ACL() entries = acl.acl_generic(content, summarize=False) c_id, c_type = get_id_and_type (content) for entry in entries: user_id = entry.get('user_id') role_id = entry.get('role') id_acl = entry.get('id_acl') user, role = 'Todos','Todos' if user_id: user = Auth.get_user_name (user_id) if role_id: role = Role.role_to_name (role_id) ad,ed,rm,co = entry['tuple'] delete = CTK.Image ({'src': '/CTK/images/del.png', 'alt': 'Del'}) delete.bind('click', CTK.JS.Ajax ('%s/del/%s/%s/%s' % (LOCATION, c_type, c_id, id_acl), data = {'id_acl': id_acl}, complete = refreshable.JS_to_refresh())) row = [delete] + [CTK.RawHTML(str(x)) for x in [ad,ed,rm,co,role,user]] self.table[(self.n,1)] = row self.n += 1 self.add_new (content, refreshable)
def test(): import sys import OpLookup import Auth import Role try: username = sys.argv[1] asset_id = int (sys.argv[2]) asset = Asset.Asset (asset_id) user = Auth.get_user(username) roles = Role.get_user_roles (username) params = { 'roles': roles, 'user_id': user['id']} except IndexError: print 'Required test parameters: user sample_asset_id' sys.exit(1) # Create asset for testing new_asset = Asset.Asset () new_asset._db = asset._db new_asset._tags = asset._tags flag = id (new_asset) new_asset['title'] = flag oa = OpAsset.OpAsset (new_asset, params) ret = oa.add() assert ret == True print '#1 OpCollection: Creation of test asset OK' ol = OpLookup.OpLookup () new_asset_id = ol({'title': flag})[0] new_asset = Asset.Asset (new_asset_id) oa = OpAsset.OpAsset (new_asset, params) assert oa and int(new_asset['title']) == int(flag) print '#2 OpCollection: Retrieval of test asset OK' test = Collection.Collection () flag = str(id(test)) test._db['name'] = flag test._db['creator_id'] = user['id'] test['assets'] = [new_asset['id']] oc = OpCollection (test, debug_params = params) assert oc print '#3 OpCollection (%d): OK' % test['id'] ret = oc.add() assert ret == True print '#4 OpCollection.add (): OK' new = Collection.Collection (name_collection = test['name']) oc = OpCollection (new, debug_params = params) assert new['name'] == test['name'] print '#5 OpCollection (%d): Retrieval after creation OK' % new['id'] new['name'] = flag*2 ret = oc.update() assert ret == True print '#6 OpCollection.update (): Modification OK' new = Collection.Collection (name_collection = new['name']) oc = OpCollection (new, debug_params=params) assert new['name'] == flag*2 print '#7 OpCollection (%d): Retrieval after modification OK' % new['id'] ret = oc.delete() assert ret == True print '#8 OpCollection.delete(): Deletion OK'
mdb = MemberDatabase.MemberDatabase(helper.ldapcfg, helper.dbcfg, helper.logger) l,s = mdb.get_connectors() if __name__ == "__main__": # Parse arguments usage = "./remove_role.py <role> <username>" parser = OptionParser(usage) (options, args) = parser.parse_args() if len(args) != 2: parser.error("I require two arguments") roleName = str(args[0]) username = str(args[1]) # Check validity of arguments if not Role.is_valid_role_name(roleName): parser.error("Not a valid role name. Aborting...") role = Role.Role(l,s,roleName) if not role.exists(): helper.logger.error("Role %s does not exist. Aborting..." % roleName) sys.exit() if not Member.is_valid_username(username): parser.error("Not a valid username. Aborting...") helper.logger.debug("Looking up username %s." % username) try: member = Member.Member.from_username(l,s,username) except Member.UsernameError: helper.logger.error("Username %s does not exist. Aborting..." % username) sys.exit() if not member in role.members(): helper.logger.error("User %s does not have role %s. Aborting..." % (username, roleName))