def trade_redirect(state): if state == 'new': return httpexc.HTTPSeeOther('/trade') elif state == 'build': return httpexc.HTTPSeeOther('/trade/build') elif state == 'confirm': return httpexc.HTTPSeeOther('/trade/confirm')
def logout(context, request): if request.params['csrf_token'] == request.session.get_csrf_token(): headers = pyramid.security.forget(request) return httpexc.HTTPSeeOther('/', headers=headers) else: request.session.flash('Invalid CSRF token; the logout link probably ' 'expired. Try again.') return httpexc.HTTPSeeOther('/')
def register_commit(context, request): """Process a registration form. Send the user back to the form if there are any errors; create their account otherwise. """ form = RegistrationForm(request.POST, csrf_context=request.session) if not form.validate(): return {'form': form} # Create a new user username = form.username.data identifier = 'temp-{0}'.format(username) user = db.Trainer(name=username, identifier=identifier, email=form.email.data) db.DBSession.add(user) db.DBSession.flush() # Set their ID user.set_password(form.password.data) user.update_identifier() # Log them in headers = pyramid.security.remember(request, user.id) return httpexc.HTTPSeeOther('/validate', headers=headers)
def bank_approve_process(context, request): """Process the bank approval form.""" approver = request.user form = approval_form(request.user, request.POST, csrf_context=request.session) if not form.validate(): return {'form': form} for field in form.transactions: transaction = field.transaction if field.notes.data: db.DBSession.add(db.BankTransactionNote( bank_transaction_id=transaction.id, trainer_id=approver.id, note=field.notes.data )) if field.what_do.data == 'ignore': continue elif field.what_do.data == 'approve': if field.correction.data is not None: transaction.amount = field.correction.data transaction.trainer.money += transaction.amount transaction.state = 'approved' elif field.what_do.data == 'deny': transaction.state = 'denied' transaction.approver_id = approver.id return httpexc.HTTPSeeOther('/bank/approve')
def trade_confirm(lot, request): """Process a ConfirmTradeForm.""" form = ConfirmTradeForm(request.POST, csrf_context=request.session) if not form.validate(): return {'trade': lot.trade, 'confirm_form': form} if form.edit.data: return httpexc.HTTPSeeOther(request.resource_path(lot.trade, 'edit')) elif form.confirm.data: lot.state = 'proposed' lot.notify_recipient = True return httpexc.HTTPSeeOther(request.path) elif form.cancel.data: return cancel_lot(lot, request)
def staff_remove(request): """Remove a user from the staff.""" username = request.params['remove'] user = models.User.get_by_username(username) user.staff = False return httpexceptions.HTTPSeeOther( location=request.route_url('admin_staff'))
def edit_battle_process(battle, request): """Process a request to edit a battle.""" form = BattleEditForm(request.POST, csrf_context=request.session) if not form.validate(): return {'form': form, 'battle': battle} for ref in battle.all_refs: db.DBSession.delete(ref) for row in form.refs: if row.ref.trainer is not None: db.DBSession.add(db.BattleReferee( battle_id=battle.id, trainer_id=row.ref.trainer.id, is_current_ref=row.current.data, is_emergency_ref=row.emergency.data )) if form.title.data: battle.name = form.title.data battle.set_identifier() return httpexc.HTTPSeeOther(request.resource_path(battle))
def manage_pokemon_commit(context, request): """Process a request to deposit or withdraw Pokémon.""" trainer = request.user deposit = pokemon_deposit_form(trainer, request) withdraw = pokemon_withdraw_form(trainer, request) # Handle forms if deposit.submit.data: form = deposit is_in_squad = False elif withdraw.submit.data: form = withdraw is_in_squad = True else: form = None if form is None or not form.validate(): return {'trainer': trainer, 'deposit': deposit, 'withdraw': withdraw} # Move Pokémon pokemon = ( db.DBSession.query(db.Pokemon) .filter(db.Pokemon.id.in_(form.pokemon.data)) .all() ) for a_pokemon in pokemon: a_pokemon.is_in_squad = is_in_squad return httpexc.HTTPSeeOther('/pokemon/manage')
def _login_handler(request): try: return handler(request) except LoginRequired as e: raise httpexceptions.HTTPSeeOther(e.next_url(request)) except APIError as e: raise httpexceptions.HTTPBadRequest(detail=e.message)
def reset_password_request_process(context, request): """Process a password reset request.""" # Process form form = PasswordResetRequestForm(request.POST, csrf_context=request.session) if not form.validate(): return {'form': form} trainer = form.username.trainer # Add a password reset token pw_request = db.PasswordResetRequest(trainer_id=trainer.id, token=new_token()) db.DBSession.add(pw_request) # Send it # XXX Pull all this info from config, and also figure out how to format # weird usernames/emails in the "To" field message = email.mime.text.MIMEText(email_template.format(pw_request.token)) message['Subject'] = 'TCoD ASBdb password reset' message['From'] = ('The Cave of Dragonflies ASB Database ' '<*****@*****.**>') message['Reply-To'] = 'Zhorken <*****@*****.**>' message['To'] = '{0} <{1}>'.format(trainer.name, trainer.email) with smtplib.SMTP('localhost') as smtp: smtp.sendmail('*****@*****.**', [trainer.email], message.as_string()) return httpexc.HTTPSeeOther('/reset-password/sent')
def reports_delete_report(request, block=False): """ A view to delete a report but leave the translation in tact :param request: a request object :param block: whether or not to block the user who made the report :return: a redirect to the reports home page """ url = urllib.unquote(urllib.unquote(request.matchdict["page"])) page = annotran.pages.models.Page.get_by_uri(url) public_language_id = request.matchdict["language"] language = annotran.languages.models.Language.get_by_public_language_id(public_language_id) report = annotran.reports.models.Report.get_by_id(request.matchdict["report"]) user_object = h.accounts.models.User.query.filter( h.accounts.models.User.username == report.Reporter.username).first() public_group_id = request.matchdict["group"] group = h.groups.models.Group.get_by_pubid(public_group_id) translation = annotran.translations.models.Translation.get_translation(page, language, group) if block: dummy_user = h.accounts.models.User.get_by_username("ADummyUserForGroupCreation") user_object.activation_id = dummy_user.activation_id request.db.flush() delete_report(translation, user_object, reporter=True) return exc.HTTPSeeOther("/admin/reports")
def add_page(request): """ Add a page to the database :param request: a request object :return: a redirect to the translation_read URL """ if request.authenticated_userid is None: raise exc.HTTPNotFound() name = request.matchdict["language_name"] page_id = urllib.unquote(urllib.unquote(request.matchdict["page_url"])) public_group_id = request.matchdict["public_group_id"] language = annotran.languages.models.Language.get_by_name(name) page = annotran.pages.models.Page.get_by_uri(page_id) if not page: page = annotran.pages.models.Page(uri=page_id) request.db.add(page) request.db.flush() url = request.route_url('translation_read', public_language_id=language.pubid, public_group_id=public_group_id) return exc.HTTPSeeOther(url)
def super_edit_commit(pokemon, request): """Process a request to super-edit a Pokémon.""" form = SuperEditPokemonForm(request.POST, csrf_context=request.session) form.add_evolution_choices(pokemon) if not form.validate(): return {'form': form, 'pokemon': pokemon} pokemon.experience = form.experience.data pokemon.happiness = form.happiness.data if form.unlocked_evolutions is not None: (db.DBSession.query(db.PokemonUnlockedEvolution).filter_by( pokemon_id=pokemon.id).delete()) for evo_id in form.unlocked_evolutions.data: db.DBSession.add( db.PokemonUnlockedEvolution(pokemon_id=pokemon.id, evolved_species_id=evo_id)) if form.trainer is not None: pokemon.trainer_id = form.trainer.id pokemon.is_in_squad = False if pokemon.trainer_item is not None: pokemon.trainer_item.trainer_id = form.trainer.id return httpexc.HTTPSeeOther(request.resource_url(pokemon))
def add_translation(request): """ This view adds a translation :param request: a request object :return: a redirect to the translation_read method """ if request.authenticated_userid is None: raise exc.HTTPNotFound() name = request.matchdict["language"] public_group_id = request.matchdict["public_group_id"] page_url = urllib.unquote(urllib.unquote(request.matchdict["page_url"])) page = annotran.pages.models.Page.get_by_uri(page_url) group = h.groups.models.Group.get_by_pubid(public_group_id) language = annotran.languages.models.Language.get_by_name(name) translation = None if page and language and group: translation = annotran.translations.models.Translation.get_by_composite_id( page.id, language.id, group.id) else: return {} if translation is None: translation = annotran.translations.models.Translation( page=page, language=language, group=group) request.db.add(translation) request.db.flush() url = request.route_url('translation_read', public_language_id=language.pubid, public_group_id=public_group_id) return exc.HTTPSeeOther(url)
def newtweet(request): # Post a tweet TWEET_TEXT = "Partoo is the best Product to make your business known!" api.request('statuses/update', {'status': TWEET_TEXT}) raise exc.HTTPSeeOther('/')
def reports_delete(request, block=False): """ Delete a report and a a translation :param request: a request object :param block: whether or not to block the user who owns the translation :return: a redirect to the reports home page """ url = urllib.unquote(urllib.unquote(request.matchdict["page"])) user = request.matchdict["user"] public_language_id = request.matchdict["language"] public_group_id = request.matchdict["group"] page = annotran.pages.models.Page.get_by_uri(url) language = annotran.languages.models.Language.get_by_public_language_id(public_language_id) group = h.groups.models.Group.get_by_pubid(public_group_id) translation = annotran.translations.models.Translation.get_translation(page, language, group) user_object = h.accounts.models.User.query.filter( h.accounts.models.User.username == h.util.split_user(user)["username"]).first() delete_annotations(request, group=group, language=language, search_url=url, user=user) delete_report(translation, user_object) annotran.votes.models.Vote.delete_votes(page, language, group, user_object) if block: dummy_user = h.accounts.models.User.get_by_username("ADummyUserForGroupCreation") user_object.activation_id = dummy_user.activation_id request.db.flush() return exc.HTTPSeeOther("/admin/reports")
def group_leave(request): """ Leave the given group. Remove the authenticated user from the given group and redirect the browser to the search page. """ if not request.feature('search_page'): raise httpexceptions.HTTPNotFound() pubid = request.POST['group_leave'] try: group = request.db.query(models.Group).filter_by(pubid=pubid).one() except exc.NoResultFound: raise httpexceptions.HTTPNotFound() groups_service = request.find_service(name='groups') groups_service.member_leave(group, request.authenticated_userid) new_params = request.POST.copy() del new_params['group_leave'] location = request.route_url('activity.search', _query=new_params) return httpexceptions.HTTPSeeOther(location=location)
def buy_pokemon_process(context, request): """Process a request to quick-buy a Pokémon, add one to the user's cart, or remove one from the user's cart. """ stuff = get_pokemon_buying_stuff(request) if stuff['quick_buy'].quickbuy.data: if not stuff['quick_buy'].validate(): return stuff species = stuff['quick_buy'].pokemon.data[1] stuff['cart'].append((species.identifier, None)) elif stuff['browse'].add.data: if not stuff['browse'].validate(): return stuff stuff['cart'].append((stuff['browse'].add.data, None)) elif stuff['cart_form'].remove.data: if not stuff['cart_form'].validate(): return stuff pokemon, sep, promotion = stuff['cart_form'].remove.data.partition(':') stuff['cart'].remove((pokemon, promotion or None)) else: for (promotion, form) in stuff['promotions']: if form.add.data: if not form.validate(): return stuff stuff['cart'].append((form.add.data, promotion.identifier)) break return httpexc.HTTPSeeOther('/pokemon/buy')
def staff_remove(request): """Remove a user from the staff.""" username = request.params['remove'] user = models.User.get_by_username(username) if user is not None: user.staff = False index = request.route_path('admin_staff') return httpexceptions.HTTPSeeOther(location=index)
def staff_remove(request): """Remove a user from the staff.""" userid = request.params['remove'] user = request.db.query(models.User).filter_by(userid=userid).first() if user is not None: user.staff = False index = request.route_path('admin_staff') return httpexceptions.HTTPSeeOther(location=index)
def sign_out(request): sign_out_form = forms.SignOutForm(request.POST, csrf_context=request) if sign_out_form.validate(): headers = security.forget(request) else: raise httpexceptions.HTTPBadRequest() return httpexceptions.HTTPSeeOther( request.route_url('alpaca.users.sign_in'), headers=headers)
def admins_remove(request): """Remove a user from the admins.""" if len(models.User.admins()) > 1: username = request.params['remove'] user = models.User.get_by_username(username) user.admin = False return httpexceptions.HTTPSeeOther( location=request.route_url('admin_admins'))
def nipsa_add(request): user = _form_request_user(request, 'add') nipsa_service = request.find_service(name='nipsa') nipsa_service.flag(user) index = request.route_path("admin_nipsa") return httpexceptions.HTTPSeeOther(index)
def nipsa_remove(request): user = _form_request_user(request, 'remove') nipsa_service = request.find_service(name='nipsa') nipsa_service.unflag(user.userid) index = request.route_path("admin_nipsa") return httpexceptions.HTTPSeeOther(index)
def cohorts_add(request): """Create a new feature cohort.""" cohort_name = request.params["add"] cohort = models.FeatureCohort(name=cohort_name) request.db.add(cohort) url = request.route_url("admin.cohorts") return httpexceptions.HTTPSeeOther(url)
def _redirect_to_user_or_group_search(request, params): if request.matched_route.name == 'activity.group_search': location = request.route_url('activity.group_search', pubid=request.matchdict['pubid'], _query=params) elif request.matched_route.name == 'activity.user_search': location = request.route_url('activity.user_search', username=request.matchdict['username'], _query=params) return httpexceptions.HTTPSeeOther(location=location)
def admins_remove(request): """Remove a user from the admins.""" n_admins = request.db.query(models.User).filter(models.User.admin).count() if n_admins > 1: userid = request.params['remove'] user = request.db.query(models.User).filter_by(userid=userid).first() if user is not None: user.admin = False index = request.route_path('admin_admins') return httpexceptions.HTTPSeeOther(location=index)
def gift_accept(lot, request): """Process an AcceptGiftForm.""" form = AcceptGiftForm(request.POST, csrf_context=request.session) trade = lot.trade if not form.validate(): return {'trade': trade, 'accept_form': form} if form.accept.data: lot.state = 'accepted' if lot.money is not None: lot.recipient.money += lot.money for item in lot.items: item.trainer_id = lot.recipient_id for pokemon in lot.pokemon: pokemon.trainer_id = lot.recipient_id trade.completed_date = datetime.datetime.utcnow().date() request.session.flash('Gift accepted!') return httpexc.HTTPSeeOther( request.resource_path(request.user.__parent__, request.user.__name__)) elif form.decline.data: lot.state = 'rejected' if lot.money is not None: lot.sender.money += lot.money trade.completed_date = datetime.datetime.utcnow().date() request.session.flash('Gift declined.') return httpexc.HTTPSeeOther( request.resource_path(request.user.__parent__, request.user.__name__)) else: # ????? return {'trade': trade, 'accept_form': form}
def nipsa_remove(request): userid = request.params["remove"] user = request.db.query(models.User).filter_by(userid=userid).first() if user is None: raise UserNotFoundError(_("Could not find user with userid %s" % userid)) nipsa_service = request.find_service(name="nipsa") nipsa_service.unflag(user) index = request.route_path("admin.nipsa") return httpexceptions.HTTPSeeOther(index)
def on_success(appstruct): groups_service = self.request.find_service(name='group') group = groups_service.create_private_group( name=appstruct['name'], description=appstruct.get('description'), userid=self.request.authenticated_userid) url = self.request.route_path('group_read', pubid=group.pubid, slug=group.slug) return httpexceptions.HTTPSeeOther(url)