def login(self, forward_url=None, *args, **kwargs): '''Page to become authenticated to the Account System. This shows a small login box to type in your username and password from the Fedora Account System. :kwarg forward_url: The url to send to once authentication succeeds ''' login_dict = f_ctrlers.login(forward_url=forward_url, *args, **kwargs) if not identity.current.anonymous and identity.was_login_attempted() \ and not identity.get_identity_errors(): # Success that needs to be passed back via json return login_dict if identity.was_login_attempted() and request.fas_provided_username: if request.fas_identity_failure_reason == 'status_inactive': turbogears.flash( _('Your old password has expired. Please' ' reset your password below.')) if request_format() != 'json': redirect('/user/resetpass') if request.fas_identity_failure_reason == 'status_account_disabled': turbogears.flash( _('Your account is currently disabled. For' ' more information, please contact %(admin_email)s' % {'admin_email': config.get('accounts_email')})) if request_format() != 'json': redirect('/login') return login_dict
def search(self, *pattern, **kvargs): '''Builds search result :arg pattern: pattern to be looked for in apps. Pattern can be in both forms, <path>/<pattern>/ or <path>/?pattern=<pattern>. Search is performed on name, license, architecture, version, release, provides, requires, obsoletes, depends and files. Results are sorted according to relevancy. Parts where pattern was recognized are shown in listing. ''' if 'pattern' in kvargs: pattern = kvargs['pattern'] else: pattern = '/'.join(pattern) build_base = {} if len(pattern) == 0: flash('Insert search pattern...') s_pattern = self._parse_pattern(pattern) builds_raw = self._builds_search_query(s_pattern).statement.execute() for b in builds_raw: build_base[b.id] = self._score_build(b, s_pattern, build_base.get(b.id, None)) #build_list = sorted(build_base.values(), key=itemgetter('score'), reverse=True) return dict(title=self.app_title, version=release.VERSION, pattern=pattern, s_pattern=s_pattern, build_list=build_base.values())
def saveAddress(self,**kw): try: params = {} fields = ["billTo","address","contact","tel","fax","needVAT","needInvoice","flag"] for f in fields : if f == 'flag': params[f] = int(kw.get(f,0)) else: params[f] = kw.get(f,None) v = params["vendor"] = Vendor.get(kw["vendor_id"]) history = v.history if "update_type" in kw: va = VendorBillToInfo.get(kw["bill_id"]) va.set(**params) hisContent = "Update Vendor %s Address %s information in master" % (v.vendorCode,va.billTo) his = updateHistory(actionUser=identity.current.user,actionKind="Update Vendor Bill To Info",actionContent=hisContent) v.set(history="%s|%s" %(his.id,history) ) else: va = VendorBillToInfo(**params) hisContent = "Add Vendor bill TO %s for vendor %s" % (va.billTo,v.vendorCode) his = updateHistory(actionUser=identity.current.user,actionKind="Add New Vendor Bill To Info",actionContent=hisContent) v.set(history= "%s|%s" %(his.id,history) if history else "%s|" %(his.id)) except: traceback.print_exc() flash("Save the Bill To information successfully!") raise redirect("/vendor/review?id=%s" %kw["vendor_id"])
def edit(self,**kw): if kw.get('id'): item = ConfigItem.by_id(kw['id']) form_values = dict( id = item.id, numeric = item.numeric, value = item.current_value() ) else: flash(_(u"Error: No item ID specified")) raise redirect(".") # Show all future values, and the previous five config_values = item.values().filter(item.value_class.valid_from > datetime.utcnow()).order_by(item.value_class.valid_from.desc()).all() \ + item.values().filter(item.value_class.valid_from <= datetime.utcnow()).order_by(item.value_class.valid_from.desc())[:5] if item.readonly: form = None elif item.numeric: form = self.int_form else: form = self.string_form return dict( title = item.name, subtitle = item.description, form = form, action = './save', options = {}, value = form_values, list = config_values, grid = self.value_grid, warn_msg = item.readonly and "This item is read-only", )
def sendinvite(self, groupname, target): username = turbogears.identity.current.user_name person = People.by_username(username) group = Groups.by_name(groupname) if is_approved(person, group): invite_subject = _('Come join The Fedora Project!') invite_text = _(''' %(user)s <%(email)s> has invited you to join the Fedora Project! We are a community of users and developers who produce a complete operating system from entirely free and open source software (FOSS). %(user)s thinks that you have knowledge and skills that make you a great fit for the Fedora community, and that you might be interested in contributing. How could you team up with the Fedora community to use and develop your skills? Check out http://fedoraproject.org/join-fedora for some ideas. Our community is more than just software developers -- we also have a place for you whether you're an artist, a web site builder, a writer, or a people person. You'll grow and learn as you work on a team with other very smart and talented people. Fedora and FOSS are changing the world -- come be a part of it!''') % \ {'user': person.username, 'email': person.email} send_mail(target, invite_subject, invite_text) turbogears.flash(_('Message sent to: %s') % target) turbogears.redirect('/group/view/%s' % group.name) else: turbogears.flash(_("You are not in the '%s' group.") % group.name) person = person.filter_private() return dict(target=target, person=person, group=group)
def application_screen(self, groupname, targetname=None): username = turbogears.identity.current.user_name person = People.by_username(username) if not targetname: targetname = username target = person else: target = People.by_username(targetname) group = Groups.by_name(groupname) if username != targetname or group.apply_rules is None or len( group.apply_rules) < 1: turbogears.redirect('/group/apply/%s/%s' % (group.name, target.username)) if group in target.memberships: turbogears.flash('You are already a member of %s!' % group.name) turbogears.redirect('/group/view/%s' % group.name) if not can_apply_group(person, group, target): turbogears.flash(_('%(user)s can not apply to %(group)s.') % \ {'user': target.username, 'group': group.name }) turbogears.redirect('/group/view/%s' % group.name) return dict() else: return dict(group=group)
def show(self, shortname, buildname, epoch, version, rel, arch): try: repo = session.query(Repo).filter_by(shortname=shortname).one() except NoResultFound: flash('Repo "%s" was not found' % shortname) redirect('/builds') try: build = session.query(PackageBuild)\ .join(PackageBuild.repos)\ .filter(and_( PackageBuild.name==buildname, PackageBuild.epoch==epoch, PackageBuild.version==version, PackageBuild.release==rel, PackageBuild.architecture==arch, Repo.id==repo.id))\ .one() except NoResultFound: flash('Build (%s-%s:%s-%s.%s) was not found' % (buildname, epoch, version, rel, arch)) redirect('/builds') return dict(title=self.app_title, version=release.VERSION, build=build)
def reviseShipTo(self,**kw): try: s = VendorShipToInfo.get(id=kw["header_ids"]) except: flash("The Ship To doesn't exist!") return dict(obj = s, vendor_id = kw["vendor_id"])
def delete(self, id): """Destroy record in model""" r = validate_get(id) tareaID = r.tarea.id r.destroySelf() flash(_(u'El %s fue eliminado permanentemente.') % name) raise redirect('../list/%d' % tareaID)
def list(self, search='*', with_members=True): username = turbogears.identity.current.user_name person = People.by_username(username) memberships = {} groups = [] re_search = re.sub(r'\*', r'%', search).lower() results = Groups.query.filter(Groups.name.like(re_search)).order_by('name').all() if self.jsonRequest(): if with_members: membersql = sqlalchemy.select([PersonRoles.person_id, PersonRoles.group_id, PersonRoles.role_type], PersonRoles.role_status=='approved').order_by(PersonRoles.group_id) members = membersql.execute() for member in members: try: memberships[member[1]].append({'person_id': member[0], 'role_type': member[2]}) except KeyError: memberships[member[1]]=[{'person_id': member[0], 'role_type': member[2]}] else: memberships = [] for group in results: if can_view_group(person, group): groups.append(group) if not len(groups): turbogears.flash(_("No Groups found matching '%s'") % search) return dict(groups=groups, search=search, memberships=memberships)
def list(self, search='*', with_members=True): username = turbogears.identity.current.user_name person = People.by_username(username) memberships = {} groups = [] re_search = re.sub(r'\*', r'%', search).lower() results = Groups.query.filter(Groups.name.like(re_search)).order_by('name').all() if self.jsonRequest(): if with_members: membersql = sqlalchemy.select([PersonRoles.person_id, PersonRoles.group_id, PersonRoles.role_type], PersonRoles.role_status=='approved').order_by(PersonRoles.group_id) members = membersql.execute() for member in members: try: memberships[member[1]].append({'person_id': member[0], 'role_type': member[2]}) except KeyError: memberships[member[1]]=[{'person_id': member[0], 'role_type': member[2]}] else: memberships = [] if len(results) == 1 and results[0].name == search and can_view_group(person, results[0]): turbogears.redirect('/group/view/%s' % (results[0].name)) return dict() for group in results: if can_view_group(person, group): groups.append(group) if not len(groups): turbogears.flash(_("No Groups found matching '%s'") % search) return dict(groups=groups, search=search, memberships=memberships)
def remove(self, **kw): item = ConfigItem.by_id(kw['id']) item.set(None, None, identity.current.user) session.add(item) session.flush() flash(_(u"%s cleared") % item.description) raise redirect(".")
def members(self, groupname, search=u'a*', role_type=None, order_by='username'): '''View group''' sort_map = { 'username': '******', 'creation': 'person_roles_creation', 'approval': 'person_roles_approval', 'role_status': 'person_roles_role_status', 'role_type': 'person_roles_role_type', 'sponsor': 'people_2.username', } if not isinstance(search, unicode) and isinstance(search, basestring): search = unicode(search, 'utf-8', 'replace') re_search = search.translate({ord(u'*'): ur'%'}).lower() username = turbogears.identity.current.user_name person = People.by_username(username) group = Groups.by_name(groupname) if not can_view_group(person, group): turbogears.flash(_("You cannot view '%s'") % group.name) turbogears.redirect('/group/list') return dict() # return all members of this group that fit the search criteria members = PersonRoles.query.join('group').join('member', aliased=True).filter( People.username.like(re_search) ).outerjoin('sponsor', aliased=True).filter( Groups.name==groupname, ).order_by(sort_map[order_by]) if role_type: members = members.filter(PersonRoles.role_type==role_type) group.json_props = {'PersonRoles': ['member']} return dict(group=group, members=members, search=search)
def default(self, *args, **kw): # to handle the case one of the flask methods # have raised a 404 but the intention isn't to redirect # back to cherrypy, but legitimately 404 if cherrypy.request.method != 'GET': raise cherrypy.HTTPError(404) try: using_task_id = False if len(args) == 1: try: task_id = int(args[0]) using_task_id = True except ValueError: pass if using_task_id: task = Task.by_id(task_id) else: task = Task.by_name("/%s" % "/".join(args)) #Would rather not redirect but do_search expects task_id in URL #This is the simplest way of dealing with it redirect("/tasks/%s" % task.id) except DatabaseLookupError as e: flash(unicode(e)) redirect("/tasks") attributes = task.to_dict() attributes['can_disable'] = bool(identity.current.user and identity.current.user.is_admin()) return dict(attributes=attributes, url="/tasks/%s" % task.id, form=self.task_form, value=dict(task_id=task.id), options=dict(hidden=dict(task=1)), action='./do_search')
def save(self, targetname, yubikey_enabled, yubikey_prefix): person = People.by_username(turbogears.identity.current.user_name) target = People.by_username(targetname) if not can_edit_user(person, target): turbogears.flash( _("You do not have permission to edit '%s'") % target.username) turbogears.redirect('/yubikey') return dict() new_configs = {'enabled': yubikey_enabled, 'prefix': yubikey_prefix} cur_configs = Configs.query.filter_by(person_id=target.id, application='yubikey').all() for config in cur_configs: for new_config in new_configs.keys(): if config.attribute == new_config: config.value = new_configs[new_config] del (new_configs[new_config]) for config in new_configs: c = Configs(application='yubikey', attribute=config, value=new_configs[config]) target.configs.append(c) mail_subject = _('Fedora Yubikey changed for %s' % target) mail_text = _(''' You have changed your Yubikey on your Fedora account %s. If you did not make this change, please contact [email protected]''' % target) email = '*****@*****.**' % target send_mail(email, mail_subject, mail_text) turbogears.flash( _("Changes saved. Please allow up to 1 hour for changes to be realized." )) turbogears.redirect('/yubikey/') return dict()
def edit(self, **kw): if kw.get('id'): item = ConfigItem.by_id(kw['id']) form_values = dict(id=item.id, numeric=item.numeric, value=item.current_value()) else: flash(_(u"Error: No item ID specified")) raise redirect(".") # Show all future values, and the previous five config_values = item.values().filter(item.value_class.valid_from > datetime.utcnow()).order_by(item.value_class.valid_from.desc()).all() \ + item.values().filter(item.value_class.valid_from <= datetime.utcnow()).order_by(item.value_class.valid_from.desc())[:5] if item.readonly: form = None elif item.numeric: form = self.int_form else: form = self.string_form return dict( title=item.name, subtitle=item.description, form=form, action='./save', options={}, value=form_values, list=config_values, grid=self.value_grid, warn_msg=item.readonly and "This item is read-only", )
def view(self, groupname, order_by='username'): '''View group''' sort_map = { 'username': '******', 'creation': 'person_roles_creation', 'approval': 'person_roles_approval', 'role_status': 'person_roles_role_status', 'role_type': 'person_roles_role_type', 'sponsor': 'people_2.username', } username = turbogears.identity.current.user_name person = People.by_username(username) group = Groups.by_name(groupname) if not can_view_group(person, group): turbogears.flash(_("You cannot view '%s'") % group.name) turbogears.redirect('/group/list') return dict() # Also return information on who is not sponsored unsponsored = PersonRoles.query.join('group').join('member', aliased=True).outerjoin('sponsor', aliased=True).filter( and_(Groups.name==groupname, PersonRoles.role_status=='unapproved')).order_by(sort_map[order_by]) unsponsored.json_props = {'PersonRoles': ['member']} members = PersonRoles.query.join('group').join('member', aliased=True).filter( People.username.like('%') ).outerjoin('sponsor', aliased=True).filter( Groups.name==groupname, ).order_by(sort_map[order_by]) return dict(group=group, sponsor_queue=unsponsored, members=list(members))
def install_options(self, distro_tree_id, **kwargs): try: distro_tree = DistroTree.by_id(distro_tree_id) except NoResultFound: flash(_(u'Invalid distro tree id %s') % distro_tree_id) redirect('.') if 'ks_meta' in kwargs: distro_tree.activity.append(DistroTreeActivity( user=identity.current.user, service=u'WEBUI', action=u'Changed', field_name=u'InstallOption:ks_meta', old_value=distro_tree.ks_meta, new_value=kwargs['ks_meta'])) distro_tree.ks_meta = kwargs['ks_meta'] if 'kernel_options' in kwargs: distro_tree.activity.append(DistroTreeActivity( user=identity.current.user, service=u'WEBUI', action=u'Changed', field_name=u'InstallOption:kernel_options', old_value=distro_tree.kernel_options, new_value=kwargs['kernel_options'])) distro_tree.kernel_options = kwargs['kernel_options'] if 'kernel_options_post' in kwargs: distro_tree.activity.append(DistroTreeActivity( user=identity.current.user, service=u'WEBUI', action=u'Changed', field_name=u'InstallOption:kernel_options_post', old_value=distro_tree.kernel_options_post, new_value=kwargs['kernel_options_post'])) distro_tree.kernel_options_post = kwargs['kernel_options_post'] flash(_(u'Updated install options')) redirect(str(distro_tree.id))
def doRegister(self, username, display_name, password1, password2, email_address): username = str(username) email_address = str(email_address) redirect_to_register = lambda:redirect("/register", {"username":username, "display_name":display_name, "email_address":email_address}) try: User.by_user_name(username) except sqlobject.SQLObjectNotFound: pass else: turbogears.flash("Error:User %s Already Exists"%username) raise redirect_to_register() try: User.by_email_address(email_address) except sqlobject.SQLObjectNotFound: pass else: turbogears.flash("Error:Email-Address %s Already Exists"%username) raise redirect_to_register() #create user user = User(user_name=username, email_address=email_address, display_name=str(display_name), password=str(password1)) #add user to user group user.addGroup(Group.by_group_name("user")) raise redirect("/")
def can_apply_group(person, group, applicant): '''Check whether the user can apply applicant to the group. :arg person: People object or username to test whether they can apply an applicant :arg group: Group object to apply to :arg applicant: People object for the person to be added to the group. :returns: True if the user can apply applicant to the group otherwise False ''' # User must satisfy all dependencies to join. # This is bypassed for people already in the group and for the # owner of the group (when they initially make it). prerequisite = group.prerequisite # TODO: Make this raise more useful info. if prerequisite: if prerequisite not in applicant.approved_memberships: turbogears.flash(_( '%s membership required before application to this group is allowed' ) % prerequisite.name) return False # group sponsors can apply anybody. if can_sponsor_group(person, group): return True # TODO: We can implement invite-only groups here instead. if group.group_type not in ('system',) and ( \ (isinstance(person, basestring) and person == applicant.username) \ or (person == applicant)): return True return False
def create(self, el_archivo, **kw): """Save or create record to model""" if el_archivo.filename: kw['archivos'] = el_archivo.file.read() # TODO verificar que es ZIP tareas = [] if 'tareas_fuente_to' in kw.keys(): t = kw['tareas_fuente_to'] del(kw['tareas_fuente_to']) if not isinstance(t, list): t = [t] tareas.extend(t) if 'tareas_prueba_to' in kw.keys(): t = kw['tareas_prueba_to'] del(kw['tareas_prueba_to']) if not isinstance(t, list): t = [t] tareas.extend(t) kw['tareas'] = tareas del(kw['tareas_prueba']) del(kw['tareas_fuente']) log.debug('Creating Enunciado with Tareas=%s' % kw['tareas']) validate_new(kw) flash(_(u'Se creó un nuevo %s.') % name) raise redirect('list')
def reject(self, person_name): '''Reject a user's CLA. This method will remove a user from the CLA group and any other groups that they are in that require the CLA. It is used when a person has to fulfill some more legal requirements before having a valid CLA. Arguments :person_name: Name of the person to reject. ''' show = {} show['show_postal_address'] = config.get('show_postal_address') exc = None user = People.by_username(turbogears.identity.current.user_name) if not is_admin(user): # Only admins can use this turbogears.flash(_('You are not allowed to reject CLAs.')) exc = 'NotAuthorized' else: # Unapprove the cla and all dependent groups person = People.by_username(person_name) for role in person.roles: if self._cla_dependent(role.group): role.role_status = 'unapproved' try: session.flush() except SQLError, error: turbogears.flash(_('Error removing cla and dependent groups' \ ' for %(person)s\n Error was: %(error)s') % {'person': person_name, 'error': str(error)}) exc = 'sqlalchemy.SQLError'
def eliminar(self, usuario): usuario = model.User.get(usuario) nombre = usuario.display_name usuario.delete() flash("Se ha eliminado el usuario %s" % nombre) return self.index()
def saveparticipant(self, new, eid, player, pseudonym="", id=0, submit=""): if (new): try: for q in Event.get(eid).participants: if (q.player.user_name == player): flash( "Error: %s is already a participant in this event" % player) raise redirect(url("/editevent/" + str(eid))) p = Participant(event=Event.get(eid), player=User.by_user_name(player), pseudonym=Pseudonym.byName(player)) except SQLObjectNotFound: flash( "Error: Tried to add a participant to a nonexistent event") raise redirect(url("/news")) else: try: p = Participant.get(id) except SQLObjectNotFound: flash("Error: Tried to edit a nonexistent participant") raise redirect(url("/news")) try: p.player = User.by_user_name(player) p.pseudonym = Pseudonym.byName(pseudonym) except SQLObjectNotFound: flash( "Error: Tried to change pseudonym to one that doesn't exist, or change pseudonym for a player that doesn't exist" ) raise redirect(url("/news")) flash("Participant updated!") raise redirect(url("/editevent/" + str(eid)))
def index(self, release=None): # /updates/metrics?tg_format=json API if request_format() == 'json': json = {} query = release and [Release.byName(release)] or Release.select() for release in query: json[release.name] = release.metrics return json try: if not release: rel = Release.select()[0] release = rel.name else: rel = Release.byName(release) except SQLObjectNotFound: flash("Unknown Release") raise redirect('/metrics') widgets = MetricData().get_widgets(release) if not widgets: return dict(metrics=[], title="Metrics currently unavailable") return dict(metrics=[ widgets[name.__name__] for name in metrics if name.__name__ in widgets ], title="%s Update Metrics" % rel.long_name)
def delete(self, id): """Destroy record in model""" r = validate_get(id) curso_id = r.cursoID r.destroySelf() flash(_(u'El %s fue eliminado permanentemente.') % name) raise redirect('../list/%s' % curso_id)
def save(self, targetname, yubikey_enabled, yubikey_prefix): person = People.by_username(turbogears.identity.current.user_name) target = People.by_username(targetname) if not can_edit_user(person, target): ff.error(_("You do not have permission to edit '%s'") % target.username) turbogears.redirect('/yubikey') return dict() new_configs = {'enabled': yubikey_enabled, 'prefix': yubikey_prefix} cur_configs = Configs.query.filter_by(person_id=target.id, application='yubikey').all() for config in cur_configs: for new_config in new_configs.keys(): if config.attribute == new_config: config.value = new_configs[new_config] del(new_configs[new_config]) for config in new_configs: c = Configs(application='yubikey', attribute=config, value=new_configs[config]) target.configs.append(c) mail_subject=_('Fedora Yubikey changed for %s' % target) mail_text=_(''' You have changed your Yubikey on your Fedora account %s. If you did not make this change, please contact [email protected]''' % target) email='*****@*****.**' % target send_mail(email, mail_subject, mail_text) turbogears.flash(_("Changes saved. Please allow up to 1 hour for changes to be realized.")) turbogears.redirect('/yubikey/') return dict()
def default(self, *args, **kw): try: using_task_id = False if len(args) == 1: try: task_id = int(args[0]) using_task_id = True except ValueError: pass if using_task_id: task = Task.by_id(task_id) else: task = Task.by_name("/%s" % "/".join(args)) #Would rather not redirect but do_search expects task_id in URL #This is the simplest way of dealing with it redirect("/tasks/%s" % task.id) except DatabaseLookupError as e: flash(unicode(e)) redirect("/tasks") return dict(task=task, form=self.task_form, value=dict(task_id=task.id), options=dict(hidden=dict(task=1)), action='./do_search')
def addinnocentkill(self, eid): try: return {'event': Event.get(eid)} except SQLObjectNotFound: flash( "Error: Tried to add an innocent kill to a nonexistent event.") raise redirect(url("/news"))
def index(self, search=None, tg_errors=None, *args, **kw): if tg_errors: flash(tg_errors) if search: raise redirect('/search/%s' % search) return dict(form=search_form, values={}, action=url('/search/'), title='Search Updates')
def agregar(self, **kw): usuario = model.User(**kw) usuario.flush() flash("Se ha agregado el usuario") return self.default(usuario.id)
def eliminar(self, beneficiario): beneficiario = model.Beneficiario.get(beneficiario) seguro = beneficiario.seguro beneficiario.delete() flash('Se ha eliminado el beneficiario') raise redirect('/seguro/{0}'.format(seguro.id))
def password(self, thepass, submit=None): char = Character.byName(turbogears.identity.current.user.character) thenode = Node.byHex(char.currentNode) found = False if thenode.deaduntil > today(): flash("There's nobody there to talk to!") raise turbogears.redirect("/"+str(thenode.hex)) for secret in thenode.secrets: if secret.password == thepass: found = True thenode.notifyWatchers(char, "whispered something to") inter = Interaction(character=char.name, day=today(), node=thenode.hex, item="PASSWORD_"+thepass) if secret.moneycost != 0 or secret.othercost != "": raise turbogears.redirect("/req/"+str(secret.id)) else: pwstring = thenode.name + " says: <blockquote>" + secret.passtext + "</blockquote>" char.notify(thenode.name + " told you a secret:<br/><i>"+secret.passtext + "</i>") thenode.notifyWatchers(char, " heard a secret from ") if (not found): pwstring = thenode.name + " gives you a funny look." goback = "<a href='/"+str(thenode.hex)+"'>Go back to " + thenode.name + ".</a>" return dict(pwstring=pwstring, goback=goback)
def anular(self, entregaid): e = validate_get_entrega(entregaid) e.inicio = e.fin = datetime.now() e.exito = 0 e.observaciones = u'La entrega fue anulada por %s' % identity.current.user.shortrepr() flash(_(u'Se anuló la entrega %s' % e.shortrepr())) raise redirect('/entregas/statistics')
def update(self, id, el_archivo, **kw): """Save or create record to model""" log.debug('Updating Enunciado...') if el_archivo.filename: kw['archivos'] = el_archivo.file.read() tareas = [] if 'tareas_fuente_to' in kw.keys(): t = kw['tareas_fuente_to'] del(kw['tareas_fuente_to']) if not isinstance(t, list): t = [t] tareas.extend(t) if 'tareas_prueba_to' in kw.keys(): t = kw['tareas_prueba_to'] del(kw['tareas_prueba_to']) if not isinstance(t, list): t = [t] tareas.extend(t) kw['tareas'] = tareas del(kw['tareas_prueba']) del(kw['tareas_fuente']) log.debug('Saving Enunciado with Tareas=%s' % kw['tareas']) r = validate_set(id, kw) flash(_(u'El %s fue actualizado.') % name) raise redirect('../list')
def reviseBillTo(self,**kw): try: h = VendorBillToInfo.get(id=kw['header_ids']) except: flash("The Bill To doesn't exist!") return dict(obj=h, vendor_id = kw["vendor_id"],)
def create(self, **kwargs): if not kwargs.has_key('hostid'): turbogears.flash("Error: form did not provide hostid") raise redirect("/") hostid = kwargs['hostid'] del kwargs['hostid'] try: host = Host.get(hostid) except SQLObjectNotFound: turbogears.flash("Error: invalid hostid - foul play?") raise turbogears.redirect("/") try: category = Category.get(kwargs['category']) except SQLObjectNotFound: turbogears.flash("Error: invalid category - foul play?") raise turbogears.redirect("/host_category/0/new?hostid=%s" % hostid) del kwargs['category'] try: hostcategory = HostCategory(host=host, category=category, **kwargs) except: turbogears.flash("Error: Host already has category %s. Try again." % category.name) raise turbogears.redirect("/host_category/0/new?hostid=%s" % hostid) turbogears.flash("HostCategory created.") raise turbogears.redirect("/host_category/%s" % hostcategory.id)
def view(self, groupname, order_by='username'): '''View group''' sort_map = { 'username': '******', 'creation': 'person_roles_creation', 'approval': 'person_roles_approval', 'role_status': 'person_roles_role_status', 'role_type': 'person_roles_role_type', 'sponsor': 'people_2.username', } username = turbogears.identity.current.user_name person = People.by_username(username) group = Groups.by_name(groupname) if not can_view_group(person, group): turbogears.flash(_("You cannot view '%s'") % group.name) turbogears.redirect('/group/list') return dict() # Also return information on who is not sponsored unsponsored = PersonRoles.query.join('group').join( 'member', aliased=True).outerjoin('sponsor', aliased=True).filter( and_(Groups.name == groupname, PersonRoles.role_status == 'unapproved')).order_by( sort_map[order_by]) unsponsored.json_props = {'PersonRoles': ['member']} return dict(group=group, sponsor_queue=unsponsored)
def delete_job_page(self, t_id): try: self._delete_job(t_id) flash(_(u'Succesfully deleted %s' % t_id)) except (BeakerException, TypeError), e: flash(_(u'Unable to delete %s' % t_id)) redirect('.')
def edit_osmajor(self, id=None, *args, **kw): try: osmajor = OSMajor.by_id(id) except InvalidRequestError: flash(_(u"Invalid OSMajor ID %s" % id)) redirect(".") return dict(title="OSMajor", value=osmajor, form=self.osmajor_form, action="./save_osmajor", options=None)
def remove(self, id, *args, **kw): try: labcontroller = LabController.by_id(id) labcontroller.removed = datetime.utcnow() systems = System.query.filter_by(lab_controller_id=id).values(System.id) for system_id in systems: sys_activity = SystemActivity(identity.current.user, 'WEBUI', \ 'Changed', 'lab_controller', labcontroller.fqdn, None, system_id=system_id[0]) system_table.update().where(system_table.c.lab_controller_id == id).\ values(lab_controller_id=None).execute() watchdogs = Watchdog.by_status(labcontroller=labcontroller, status='active') for w in watchdogs: w.recipe.recipeset.job.cancel(msg='LabController %s has been deleted' % labcontroller.fqdn) for lca in labcontroller._distro_trees: lca.distro_tree.activity.append(DistroTreeActivity( user=identity.current.user, service=u'WEBUI', action=u'Removed', field_name=u'lab_controller_assocs', old_value=u'%s %s' % (lca.lab_controller, lca.url), new_value=None)) session.delete(lca) labcontroller.disabled = True LabControllerActivity(identity.current.user, 'WEBUI', 'Changed', 'Disabled', unicode(False), unicode(True), lab_controller_id=id) LabControllerActivity(identity.current.user, 'WEBUI', 'Changed', 'Removed', unicode(False), unicode(True), lab_controller_id=id) session.commit() finally: session.close() flash( _(u"%s removed") % labcontroller.fqdn ) raise redirect(".")
def add_user(self, show, username, human_name, email, telephone=None, postal_address=None, age_check=False): if identity.not_anonymous(): identity.current.logout() try: user = \ self._root.user.create_user(username, human_name, email, telephone, postal_address, age_check, redirect='/show/join/%s' % show) show = Show.by_name(show) user.show = show except IntegrityError: turbogears.flash( _("Your account could not be created. Please contact a Fedora Ambassador for assistance." )) turbogears.redirect('/show/fail/%s' % show) return dict() else: turbogears.flash( _('Your password has been emailed to you. Please log in with it and change your password' )) turbogears.redirect('/show/success/%s' % show) turbogears.redirect('/show/join/%s' % show)
def index(self, release=None): # /updates/metrics?tg_format=json API if request_format() == "json": json = {} query = release and [Release.byName(release)] or Release.select() for release in query: json[release.name] = release.metrics return json try: if not release: rel = Release.select()[0] release = rel.name else: rel = Release.byName(release) except SQLObjectNotFound: flash("Unknown Release") raise redirect("/metrics") widgets = MetricData().get_widgets(release) if not widgets: return dict(metrics=[], title="Metrics currently unavailable") return dict( metrics=[widgets[name.__name__] for name in metrics if name.__name__ in widgets], title="%s Update Metrics" % rel.long_name, )
def reject(self, person_name): '''Reject a user's FPCA. This method will remove a user from the FPCA group and any other groups that they are in that require the FPCA. It is used when a person has to fulfill some more legal requirements before having a valid FPCA. Arguments :person_name: Name of the person to reject. ''' show = {} show['show_postal_address'] = config.get('show_postal_address') exc = None user = People.by_username(turbogears.identity.current.user_name) if not is_admin(user): # Only admins can use this turbogears.flash(_('You are not allowed to reject FPCAs.')) exc = 'NotAuthorized' else: # Unapprove the cla and all dependent groups person = People.by_username(person_name) for role in person.roles: if self._cla_dependent(role.group): role.role_status = 'unapproved' try: session.flush() except SQLError, error: turbogears.flash(_('Error removing cla and dependent groups' \ ' for %(person)s\n Error was: %(error)s') % {'person': person_name, 'error': str(error)}) exc = 'sqlalchemy.SQLError'
def save(self, id=None, **kw): """Save or create record to model""" #update kw log.info('kw: ' + str(kw)) log.info('kw: ' + str(kw)) log.info('kw: ' + str(kw)) log.info('kw: ' + str(kw)) log.info('kw: ' + str(kw)) try: if isinstance(kw['user_groups'], list): groups = Group.select(Group.c.group_id.in_(*kw['user_groups'])) else: groups = Group.select(Group.c.group_id.in_(kw['user_groups'])) except: groups = [] #create if not id: kw['groups'] = groups User(**kw) flash("User was successfully created.") raise redirect("list") #update else: record = User.get_by(user_id=int(id)) for attr in kw: setattr(record, attr, kw[attr]) record.groups = groups log.info("Saved update on user " + record.user_name + str(kw)) flash("User was successfully updated.") raise redirect("../list")
def can_apply_group(person, group, applicant): '''Check whether the user can apply applicant to the group. :arg person: People object or username to test whether they can apply an applicant :arg group: Group object to apply to :arg applicant: People object for the person to be added to the group. :returns: True if the user can apply applicant to the group otherwise False ''' # User must satisfy all dependencies to join. # This is bypassed for people already in the group and for the # owner of the group (when they initially make it). prerequisite = group.prerequisite # TODO: Make this raise more useful info. if prerequisite: if prerequisite not in applicant.approved_memberships: turbogears.flash( _('%s membership required before application to this group is allowed' ) % prerequisite.name) return False # group sponsors can apply anybody. if can_sponsor_group(person, group): return True # TODO: We can implement invite-only groups here instead. if group.group_type not in ('system',) and ( \ (isinstance(person, basestring) and person == applicant.username) \ or (person == applicant)): return True return False
def corregir(self, afiliado, asamblea, departamento, banco, cuenta, municipio, telefono): afiliado = model.Affiliate.get(afiliado) asamblea = model.Asamblea.get(asamblea) departamento = model.Departamento.get(departamento) afiliado.departamento = departamento afiliado.municipio = model.Municipio.get(municipio) log(identity.current.user, u"Inscrito afiliado {0} en asamblea {1}".format( afiliado.id, asamblea.id), afiliado) banco = model.Banco.get(banco) afiliado.banco = banco.id afiliado.cuenta = cuenta afiliado.phone = telefono kw = {'afiliado': afiliado, 'asamblea': asamblea, 'viatico': model.Viatico.selectBy(asamblea=asamblea, municipio=afiliado.municipio ).limit(1).getOne()} model.Inscripcion(**kw) flash(inscripcionRealizada(afiliado)) raise redirect('/asamblea/inscripcion/{0}'.format(asamblea.id))
def deleteevent(self, id): try: Event.delete(id) flash("Event deleted!") raise redirect(url("/news")) except SQLObjectNotFound: flash("Error: Tried to delete an event that doesn't exist") raise redirect(url("/news"))
def delete_job_page(self, t_id): try: self._delete_job(t_id) flash(_(u'Succesfully deleted %s' % t_id)) except (BeakerException, TypeError): flash(_(u'Unable to delete %s' % t_id)) redirect('.') redirect('./mine')
def save_edit(self, id=None, **kw): retention_tag = Tag.by_id(id) retention_tag.tag = kw['tag'] retention_tag.default = kw['default'] retention_tag.expire_in_days = kw['expire_in_days'] retention_tag.needs_product = kw['needs_product'] flash(_(u"OK")) redirect("./admin")
def delete(self, id): tag = Tag.by_id(id) if not tag.can_delete(): # Trying to be funny... flash(u'%s is not applicable for deletion' % tag.tag) redirect('/retentiontag/admin') session.delete(tag) flash(u'Successfully deleted %s' % tag.tag) redirect('/retentiontag/admin')
def save(self, id=None, **kw): retention_tag = Tag(tag=kw['tag'], default=kw['default'], needs_product=kw['needs_product'], expire_in_days=kw['expire_in_days']) session.add(retention_tag) flash(_(u"OK")) redirect("./admin")
def index(self, *args, **kw): notice = config.get('newupdate_notice') if notice: flash(notice) return dict(form=update_form, values=kw, action=url("/save"), title='New Update Form')
def admin(self, task=''): if task == 'resolve_all_albums': #closest_mb_albums_to_db' : mbrainz_resolver = gordon.db.mbrainz_resolver.GordonResolver() flash("Running mbrainz_resolver.resolve_all_albums()") mbrainz_resolver.resolve_all_albums() return dict()
def really_return_reservation(self, id, msg=None): try: recipe = Recipe.by_id(id) except InvalidRequestError: raise BX(_("Invalid Recipe ID %s" % id)) recipe.return_reservation() flash(_(u"Successfully released reserved system for %s" % recipe.t_id)) redirect('/jobs/mine')