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 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 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 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 login(self, forward_url=None, previous_url=None, *args, **kw): if not identity.current.anonymous and identity.was_login_attempted() \ and not identity.get_identity_errors(): redirect(tg.url(forward_url or previous_url or '/', kw)) forward_url = None previous_url = request.path if identity.was_login_attempted(): msg = _("The credentials you supplied were not correct or " "did not grant access to this resource.") elif identity.get_identity_errors(): msg = _("You must provide your credentials before accessing " "this resource.") else: msg = _("Please log in.") forward_url = request.headers.get("Referer", "/") response.status = 403 return dict(message=msg, previous_url=previous_url, logging_in=True, original_parameters=request.params, forward_url=forward_url)
def switchToCustomer(customer, redirect_url=None, check_permission=False): if not identity.current.anonymous: current_user = identity.current.user else: current_user = None if current_user and customer == current_user.customer: if redirect_url: redirect(redirect_url) else: return if check_permission and current_user: if not current_user.hasModeratePermission(): raise identity.IdentityFailure( "User %s was not authenticated to change the customer" % current_user.email_address ) if check_permission: try: user = masterdb.User.selectBy(_customer=customer, deleted=False)[0] switchToUser(user, check_permission=check_permission) except: pass if redirect_url: redirect(redirect_url)
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 save_edit(self, builds, notes, expiration=None, **kw): log.debug(repr(locals())) if len(builds) > 1: flash('Unable to add builds to an existing override') raise redirect('/override') builds = builds[0] if expiration: if datetime.utcnow() > expiration: flash('Cannot set an expiration in the past') if request_format() == 'json': return dict() raise redirect('/override/edit?build=' + builds) try: override = BuildRootOverride.byBuild(builds) except SQLObjectNotFound: flash('Cannot find override to edit %r' % builds) raise redirect('/override') override.notes = notes override.expiration = expiration if override.date_expired: log.debug('Retagging expired override: %s' % override.build) override.date_expired = None override.tag() flash('%s successfully edited' % builds) if request_format() == 'json': return override.__json__() raise redirect('/override')
def purchase(self): if not httpsession.has_key("cart"): redirect("/cart") session.begin() print "in transaction" invoice = Invoice() print invoice.invoice_date line_items = [] for item in httpsession['cart']: li = LineItem() li.work_id = item li.quantity = 1 li.unit_price = 1 line_items.append(li) invoice.line_items = line_items session.commit() session.flush() host = request.headers['Host'] if request.headers.has_key('X-Forwarded-Host'): host = request.headers['X-Forwarded-Host'] url = fpys_client.getPipelineUrl( invoice.caller_reference, "Image Download", str(invoice.total), "http://%s/capture/%d" % (host, invoice.id)) raise redirect(url)
def capture(self, invoice_id, **params): print params path = "/capture/%s?" % invoice_id # is amazon not url encoding the signature? sig = params['awsSignature'].replace(" ", "+") if not fpys_client.validate_pipeline_signature(sig, path, params): return ("invalid signature") if params['status'] in ['SA', 'SB', 'SC']: invoice = Invoice.query().filter( Invoice.c.id == int(invoice_id)).first() invoice.sender_token = params['tokenID'] invoice.install_recipient_token(fpys_client) response = invoice.pay(fpys_client, config.get("default_caller_token")) import xml.etree.ElementTree as ET print response.transaction.status print response.transaction.transactionId for li in invoice.line_items: works_users_table.insert( dict(work_id=li.work_id, user_id=identity.current.user.user_id)).execute() redirect("/mine") else: return ("The payment didn't succeed")
def newAssessment(self, level, childid = 0): if childid != 0: cherrypy.session['current_child'] = int(childid) if 'current_child' in cherrypy.session: a = Assessment(childID=cherrypy.session['current_child'], ownerID=identity.current.user.id, level=level) raise redirect("/assessment?id=" + str(a.id)) raise redirect("/")
def _new_group(self, group_id, display_name, group_name, ldap, root_password): user = identity.current.user if ldap and not user.is_admin(): flash(_(u'Only admins can create LDAP groups')) redirect('.') try: Group.by_name(group_name) except NoResultFound: pass else: flash( _(u"Group %s already exists." % group_name) ) redirect(".") group = Group() session.add(group) activity = Activity(user, u'WEBUI', u'Added', u'Group', u"", display_name) group.display_name = display_name group.group_name = group_name group.ldap = ldap if group.ldap: group.refresh_ldap_members() group.root_password = root_password if not ldap: # LDAP groups don't have owners group.user_group_assocs.append(UserGroup(user=user, is_owner=True)) group.activity.append(GroupActivity(user, service=u'WEBUI', action=u'Added', field_name=u'User', old_value=None, new_value=user.user_name)) group.activity.append(GroupActivity(user, service=u'WEBUI', action=u'Added', field_name=u'Owner', old_value=None, new_value=user.user_name)) return group
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 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 addProgram(self, name): p = Program.selectBy(name=name) if p.count() == 0: Program(name=name) raise redirect("/admin") else: raise redirect("/admin?message='A program with this name already exists'")
def save_upgrade_registration(self, **form_data): ERROR_CRED_INVALIDAS =_(u'No fue posible completar la operación. Revisar que el padrón y el password sean correctos.') ERROR_FORMAT =_(u'No fue posible completar la operación. El padrón se compone solamente de números.') curso = Curso.get(form_data['curso']) if not curso.inscripcion_abierta: flash('La inscripción al curso elegido se encuentra cerrada.') raise redirect(url('/')) try: if not form_data['padron'].isdigit(): error_msg = ERROR_FORMAT else: alumno = Alumno.by_padron(form_data['padron']) if alumno.equals_password(form_data['password']): if not curso in alumno.cursos: curso.add_alumno(alumno) flash(_(u'La inscripción ha sido exitosa.')) else: flash(_(u'¡Ya estabas inscripto a este curso!')) raise redirect(url('/')) else: error_msg = ERROR_CRED_INVALIDAS except SQLObjectNotFound: error_msg = ERROR_CRED_INVALIDAS except DuplicateEntryError, e: error_msg = _(u'Ya estás registrado en el curso %s.' % curso)
def size(self, width, id, tg_errors=None): if tg_errors: if "width" in tg_errors.keys(): idx = tg_errors.keys().index("width") flash("Error: Invalid photo size: %s" % tg_errors.values()[idx]) else: flash("Error: Invalid photo ID.") raise redirect(request.headers.get("Referer", url("/"))) try: photo = Photo.get(id) except: # log.debug(traceback.format_exc()) flash("Error: Photo %d does not exist." % id) raise redirect(request.headers.get("Referer", "/")) try: fullpath = os.path.join(self.photo_dir, photo.filename) img = IMG.open(fullpath) if img.size[0] > img.size[1]: height = int(img.size[1] * (float(float(width) / float(img.size[0])))) else: height = width width = int(img.size[0] * (float(float(height) / float(img.size[1])))) img = self._orient(img) out = img.resize((width, height), IMG.ANTIALIAS) return out.tostring("jpeg", "RGB") except: # log.debug(traceback.format_exc()) flash("Error resizing photo, sending full photo.") raise redirect(url("/static/photos/%s" % photo.filename))
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 delete(self, id, tg_errors=None): if tg_errors: flash("Error: ID is not an integer.") raise redirect(request.headers.get("Referer", url("/"))) try: album = Album.get(id) except: flash("Error: Album %d does not exist." % id) raise redirect(request.headers.get("Referer", url("/"))) for photo in album.photos(): fullname = os.path.join(config.get("photo_dir"), photo.filename) if os.path.exists(fullname): os.remove(fullname) try: photo.destroySelf() except: pass # log.debug(traceback.format_exc()) # get rough page number to return to after delete. allalbums = list(Album.select(orderBy="-date")) idx = allalbums.index(album) page = (idx / 8) + 1 album.destroySelf() flash("Album deleted successfully.") raise redirect(url("/?page=%d" % page))
def delete(self, id, tg_errors=None): if tg_errors: flash("Error: ID is not an int.") return redirect(cherrypy.request.headers.get("Referer", url("/"))) try: photo = Photo.get(id) except: flash("Error: Photo %d does not exist.") return redirect(cherrypy.request.headers.get("Referer", url("/"))) albumid = photo.albumID fullname = os.path.join(self.photo_dir, photo.filename) if os.path.exists(fullname): os.remove(fullname) album = Album.get(albumid) idx = album.photos().index(photo) photo.destroySelf() page = (idx / 8) + 1 raise redirect(url("/album/%d?page=%d" % (albumid, page)))
def login(self,destination="",ticketid=""): if destination == "": destination = "/" if ticketid: # verify a wind ticket and log them in (success,uni,groups) = validate_wind_ticket(ticketid) if int(success) == 0: return "WIND authentication failed. Please Try Again." u = find_or_create_user(uni) if 'tlc.cunix.local:columbia.edu' in groups or \ 'staff.cunix.local:columbia.edu' in groups or \ 'tlcxml.cunix.local:columbia.edu' in groups: # it's good cherrypy.session['uni'] = uni set_cookie("candyman_auth",uni, path="/", expires=10 * 365 * 24 * 3600) raise redirect(destination) else: # they're not ccnmtl. kick them out return "This application is restricted to CCNMTL staff. See an admin if you need to get in." else: location = cherrypy.request.browser_url location = "/".join(location.rsplit("/")[:3]) + "/login" winddest = "%s?destination=%s" % (location,urllib.quote(destination)) dest = "https://wind.columbia.edu/login?destination=%s&service=cnmtl_full_np" % winddest raise redirect(dest)
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 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 force_create(self, archivo, **kw): """Sube una entrega en lugar de un alumno""" instancia = kw['instancia'] entregador = kw['entregador'] archivo = archivo.file.read() try: zfile = ZipFile(StringIO(archivo), 'r') except BadZipfile: flash(_(u'El archivo ZIP no es válido')) raise redirect('force_new', kw) if zfile.testzip() is not None: flash(_(u'El archivo ZIP tiene errores de CRC')) raise redirect('force_new',kw) entregador_id = int(entregador) instancia = InstanciaDeEntrega.get(int(instancia)) if instancia.ejercicio.grupal: entregador = Grupo.get(entregador_id) else: entregador = AlumnoInscripto.get(entregador_id) kw['instancia'] = instancia kw['archivos'] = archivo kw['entregador'] = entregador kw['observaciones'] = 'Entrega realizada manualmente por el docente %s' % identity.current.user.shortrepr() Entrega(**kw) flash('Se creo una nueva entrega') raise redirect('list')
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 otp_verify(uid, otp): import sys, os, re import urllib2 target = People.by_id(uid) configs = get_configs( Configs.query.filter_by(person_id=target.id, application='yubikey').all()) if not otp.startswith(configs['prefix']): raise AuthException('Unauthorized/Invalid OTP') server_prefix = 'http://localhost/yk-val/verify?id=' auth_regex = re.compile('^status=(?P<rc>\w{2})') server_url = server_prefix + client_id + "&otp=" + otp fh = urllib2.urlopen(server_url) for line in fh: match = auth_regex.search(line.strip('\n')) if match: if match.group('rc') == 'OK': return else: raise AuthException(line.split('=')[1]) break turbogears.redirect('/yubikey/') return dict()
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 savereport(self, new, eid, player, text, id=0): if (new): try: r = Report(speaker=User.by_user_name(player), event=Event.get(eid), content=text) except SQLObjectNotFound: flash( "Error: Tried to add report by a nonexistent player, or to a nonexistent event" ) raise redirect(url("/news")) else: try: r = Report.get(id) r.content = text #nothing else really should be being edited, but will update it all for future compatibility r.speaker = User.by_user_name(player) r.event = Event.get(eid) except SQLObjectNotFound: flash( "Error: Tried to edit a nonexistent report, or a report for a nonexistent event, or write a report as a nonexistent player." ) raise redirect(url("/news")) flash("Report updated!") raise redirect(url("/news"))
def createauction(self, **data): try: inventory = cur_user().gear startingbid = int(data['startbid']) length = int(data['auctionlength']) if length < 1 or length > 7: flash('Auctions may only last up to 7 days') elif startingbid < 1: flash('Starting bid must be at least 1') else: item = Equipment.selectBy(name=data['auctionitem'])[0] if ((item in inventory) and (not inUse(item))): auction = Auction(item=item, owner=me(), bid=startingbid, expiry=(datetime.now() + timedelta(days=length))) cur_user().removeEquipment(item) Feed(owner=me(), msg = 'Created auction for %s' %item.name, category = 'Auction', time = datetime.now()) flash('Auction created successfully') else: flash('You cannot auction off gear that is in use') raise redirect('./auction') except ValueError: flash('Auction could not be created: Starting bid must be a numeric value') raise redirect('./auction') except: raise redirect('./auction')
def join(self, show=None): if not show: turbogears.redirect('/show/list/') if identity.not_anonymous(): identity.current.logout() show = Show.by_name(show) return dict(show=show)
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 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 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 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 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 create(self, tg_errors=None, **kwargs): if not kwargs.has_key('siteid'): turbogears.flash("Error: form didn't provide siteid") raise redirect("/") siteid = kwargs['siteid'] try: site = Site.get(siteid) except sqlobject.SQLObjectNotFound: turbogears.flash("Error: Site %s does not exist" % siteid) raise redirect("/") errordict = dict(form=site_to_site_form, values=None, action=submit_action, page_title="Create Site to Site", site=site) # handle the validation error if tg_errors: turbogears.flash("Error creating SiteToSite: %s" % (createErrorString(tg_errors))) return errordict siteadmin_check(site, identity) sites = kwargs['sites'] username = kwargs.get('username') password = kwargs.get('password') for dssite in sites: if dssite == site.id: continue try: site2site = SiteToSite(upstream_site=site, downstream_site=dssite, username=username, password=password) except: pass turbogears.flash("SiteToSite created.") raise turbogears.redirect("/site/%s" % siteid)
def user_update(self, id=None, **form_data): if not id: flash(_(u'Error accediendo al panel de control de usuario.')) raise redirect('/dashboard') if (identity.current.user_id == int(id)): usuario = val.validate_get(Usuario, 'usuario', id) if form_data['pwd_new'] and usuario.equals_password(form_data['pwd_old']): usuario.reset_password(form_data['pwd_new']) msg = u'Contraseña modificada correctamente.' else: msg = u'No se modificó la contraseña' usuario.nombre = form_data['nombre'] usuario.telefono = form_data['telefono'] usuario.paginador = form_data['paginador'] identity.current.user.paginador = usuario.paginador flash(u'Datos actualizados correctamente.\n'+msg) raise redirect('/dashboard') else: flash(_(u'Solo podés editar tus propios datos.')) raise redirect('/dashboard')
def edit_action(self, id, item_id, assign_to, text): act = Action.get(id) user = User.get(assign_to) act.text = text act.assigned_to = user redirect("/idea", redirect_params={'id': item_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 otp_verify(uid, otp): import sys, os, re import urllib2 target = People.by_id(uid) configs = get_configs(Configs.query.filter_by(person_id=target.id, application='yubikey').all()) if not otp.startswith(configs['prefix']): raise AuthException('Unauthorized/Invalid OTP') server_prefix = 'http://localhost/yk-val/verify?id=' auth_regex = re.compile('^status=(?P<rc>\w{2})') server_url = server_prefix + client_id + "&otp=" + otp fh = urllib2.urlopen(server_url) for line in fh: match = auth_regex.search(line.strip('\n')) if match: if match.group('rc') == 'OK': return else: raise AuthException(line.split('=')[1]) break 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 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 save_edit(self, builds, notes, expiration=None, **kw): log.debug(repr(locals())) if len(builds) > 1: flash("Unable to add builds to an existing override") raise redirect("/override") builds = builds[0] if expiration: if datetime.utcnow() > expiration: flash("Cannot set an expiration in the past") if request_format() == "json": return dict() raise redirect("/override/edit?build=" + builds) try: override = BuildRootOverride.byBuild(builds) except SQLObjectNotFound: flash("Cannot find override to edit %r" % builds) raise redirect("/override") override.notes = notes override.expiration = expiration if override.date_expired: log.debug("Retagging expired override: %s" % override.build) override.date_expired = None override.tag() flash("%s successfully edited" % builds) if request_format() == "json": return override.__json__() raise redirect("/override")
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 default(self, id): try: kickstart = RenderedKickstart.by_id(id) except NoResultFound: raise cherrypy.NotFound(id) if kickstart.url: redirect(kickstart.url) return kickstart.kickstart.encode('utf8')
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_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 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 index(self): if turbogears.identity.not_anonymous(): if request_format() == 'json': # redirects don't work with JSON calls. This is a bit of a # hack until we can figure out something better. return dict() turbogears.redirect('/home') return dict(now=time.ctime())
def save_system(self, **kw): try: with convert_db_lookup_error('No such system: %s' % kw['system']['text']): system = System.by_fqdn(kw['system']['text'], identity.current.user) except DatabaseLookupError, e: flash(unicode(e)) redirect("./edit?group_id=%s" % kw['group_id'])
def new(self): '''Display create group form''' username = turbogears.identity.current.user_name person = People.by_username(username) if not can_create_group(person): turbogears.flash(_('Only FAS administrators can create groups.')) turbogears.redirect('/') 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')
def test_redirect(self): config.update({"server.webpath": "/coolsite/root"}) startup.startTurboGears() testutil.create_request("/coolsite/root/subthing/") try: redirect("/foo") assert False, "redirect exception should have been raised" except cherrypy.HTTPRedirect, e: assert "http://localhost/coolsite/root/subthing/foo" in e.urls