class PayPalForm(object): grok.implements(IPayPalPaymentForm) @property def notify_url(self): return None @property def return_url(self): return None @property def cancel_return(self): return None def __init__(self, business=None, item_name=None, amount=decimal.Decimal("0.00"), invoice=None): self.invoice = invoice self.business = business self.item_name = item_name self.amount = amount
class AdHocManagement(grok.Adapter): grok.context(IPrincipal) grok.implements(IAdHocManagement) grok.baseclass() def getData(self): return {} def checkRule(self, login): return True def validatePassword(self, given_password, saved_password): if given_password == saved_password: return True return False def getFormulare(self, id=None, type=None): raise NotImplementedError @property def clearname(self): daten = self.getUser() if not daten: return self.context.id username = daten.get('clearname') return username
class Endpoint(object): grok.implements(IBrowserPublisher, IEndpoint) def browserDefault(self, request): return self, None def __init__(self, request, context): self.request = request self.context = context def DELETE(self): pass def GET(self): pass def HEAD(self): pass def OPTIONS(self): pass def POST(self): pass def PUT(self): pass
class V2TokenRequest(grok.Model): ''' Represents a token exchange request. ''' grok.implements(ITokenRequest) uri = "" parms = {} info = { "access_token": "", "token_type": None, "expires_in": 0, "refresh_token": None, "id_token": None, "access_type": "offline" } def __init__(self, uri, client_id="", client_secret=""): self.uri = uri grant_type = "authorization_code" self.parms = dict(grant_type=grant_type, client_id=client_id, client_secret=client_secret) def set_redirect_uri(self, uri): self.parms['redirect_uri'] = uri self._p_changed = True @property def code(self): if 'code' in self.parms: return self.parms['code'] @code.setter def code(self, code): self.parms['code'] = code self._p_changed = True
class Z3CPTemplateFactory(grok.GlobalUtility): grok.implements(grok.interfaces.ITemplateFileFactory) grok.name('3pt') def __call__(self, filename, _prefix=None): return z3cPageTemplate(filename=filename, _prefix=_prefix)
class Partybuilder(grok.Application, grok.Container): grok.implements(ILayout, IOAuthSite, IBuilderApp) def __init__(self): super(Partybuilder, self).__init__() self['users'] = Users() self['parties'] = Parties()
class Unfallanzeigen(uvcsite.ProductFolder): """Container fuer die Speicherung der Lastschriftdokumente""" grok.implements(IUnfallanzeigenFolder) uvcsite.contenttype(Unfallanzeige) grok.title(u'Elektronische Unfallanzeigen') title = u"Unfallanzeigen" description = u"In diesem Ordner werden alle Elektronischen Unfallanzeigen gespeichert"
class InstantPaymentNotification(grok.Model): """Metadata about an instant payment notification as received by paypal (or other parties that pretend to be paypal). If `data` is given at construction time, we also set a timestamp of current datetime (UTC). Timestamps and final verdict can also be set via constructor (but won't be set automatically). """ grok.implements(IInstantPaymentNotification) def __init__(self, data=None, timestamp_received=None, timestamp_validation_requested=None, timestamp_validation_received=None, final_verdict=None): self.data = data if self.data and not timestamp_received: timestamp_received = datetime.datetime.utcnow() self.timestamp_received = timestamp_received self.timestamp_validation_requested = timestamp_validation_requested self.timestamp_validation_received = timestamp_validation_received self.final_verdict = final_verdict
class BearerTokenAuthCredentialsPlugin(grok.GlobalUtility): grok.name("creds.bearer") grok.implements(ICredentialsPlugin) @property def keys(self): return getUtility(ICryptographicKeys) def canHandle(self, environ): return ("HTTP_X_UVCSITE_REST" in environ or environ["REQUEST_METHOD"] == "OPTIONS") def extractCredentials(self, request): if self.canHandle(request._environ): import pdb pdb.set_trace() if request._auth: access_token = extract_token(request._auth) if access_token: return {"access_token": access_token} return None def challenge(self, request): if self.canHandle(request._environ): request.response.setStatus(401) return True return False def logout(self, request): return False
class AdHocApp(grok.Application, grok.Container): grok.implements(IAdHocApplication) grok.local_utility(AdHocAuthenticator, name=u"principals", provides=IAuthenticatorPlugin) grok.local_utility(PluggableAuthentication, IAuthentication, public=True, setup=setup_pau) grok.local_utility(intid_factory, IAdHocIdReference, public=True) def __init__(self): super(AdHocApp, self).__init__() self['dokumente'] = Dokumente() def getSiteManager(self): current = super(AdHocApp, self).getSiteManager() #import pdb; pdb.set_trace() #return adhocRegistry if adhocRegistry not in current.__bases__: adhocRegistry.__bases__ = tuple([x for x in adhocRegistry.__bases__ if x.__hash__() != zope.component.globalSiteManager.__hash__()]) current.__bases__ = (adhocRegistry,) + current.__bases__ else: if current.__bases__.index(adhocRegistry) == 1: current.__bases__ = current.__bases__[::-1] return current
class AfterSaveEvent(zope.component.interfaces.ObjectEvent): grok.implements(IAfterSaveEvent) def __init__(self, object, request): self.object = object self.request = request self.principal = request.principal
class Database(grok.LocalUtility): grok.implements(IDatabase) def session_factory(self): print "creating new session" return sa.orm.create_session(**self.configuration()) def scopefunc(self): # we use the application name as the unique per application id. # Can we use something more clever and universally working? result = (thread.get_ident(), self.__parent__.__name__) print "scopefunc:", result return result def engine(self): # we look up the engine with the name defined in the application return component.getUtility(IEngine, self.__parent__.engine_name) def configuration(self): # we return the configuration parameters as for an # SQLAlchemy sessionmaker return dict(bind=self.engine(), autocommit=True, autoflush=True, extension=ZopeTransactionExtension())
class Home(grok.MultiAdapter): grok.adapts(Cave, Fireplace) grok.implements(IHome) def __init__(self, cave, fireplace): self.cave = cave self.fireplace = fireplace
class AdHocDocumentInfo(grok.MultiAdapter): grok.adapts(IPrincipal, IHTTPRequest) grok.implements(IAdHocDocumentInfo) grok.baseclass() def __init__(self, principal, request): self.principal = principal self.request = request def getProductFolder(self): base = grok.getSite()['dokumente'] folder_name = time.strftime('%Y_%m_%d', time.localtime()) if not folder_name in base.keys(): base[folder_name] = AdHocProductFolder() return base[folder_name] def getAddLink(self, id, docart): obj = self.getObject(id) if obj: return grok.url(self.request, obj) datefolder = self.getProductFolder() data = {'form.field.docid': id} addlink = "@@%s" % ( docart.replace(' ', '_')) return grok.url(self.request, datefolder, addlink, data=data) def getObject(self, id): util = getUtility(IAdHocIdReference) return util.queryObject(id)
class FactFactory(grok.GlobalUtility): ''' Produces facts ''' grok.implements(IFact) def __call__(self, factData): if type(factData) is list: factFactory = FactFactory() ret = [factFactory(i) for i in factData] return [fact for fact in ret if fact] if type(factData) is dict: if 'type' in factData: ftype = factData['type'] try: if ftype == 'Adjust': return Adjust(factData) if ftype == 'Buff': return Buff(factData) if ftype == 'ComboField': return ComboField(factData) if ftype == 'ComboFinisher': return ComboFinisher(factData) if ftype == 'Damage': return Damage(factData) if ftype == 'Distance': return Distance(factData) if ftype == 'Duration': return Duration(factData) if ftype == 'Healing': return Healing(factData) if ftype == 'HealingAdjust': return HealingAdjust(factData) if ftype == 'NoData': return NoData(factData) if ftype == 'Number': return Number(factData) if ftype == 'Percent': return Percent(factData) if ftype == 'PrefixedBuff': return PrefixedBuff(factData) if ftype == 'Radius': return Radius(factData) if ftype == 'Range': return Range(factData) if ftype == 'Recharge': return Recharge(factData) if ftype == 'Time': return Time(factData) if ftype == 'Unblockable': return Unblockable(factData) except: return NoData(factData)
class AuthLogoutSupported(grok.Adapter): ''' An adapter that says our authentication utility supports logout ''' grok.context(OAuth2Authenticate) grok.implements(ILogoutSupported) def __new__(self, context): return LogoutSupported(context)
class OAuth2Authenticate(grok.LocalUtility): grok.implements(IAuthentication) grok.site(IOAuthSite) def authenticate(self, request): ''' We are already authenticated if the session contains a principal. ''' print 'authenticate called' sn = ISession(request)['OAuth2'] if 'principal' in sn.keys(): return sn['principal'] def unauthenticatedPrincipal(self): return UnauthenticatedPrincipal() def unauthorized(self, id, request): ''' Remove the session item to force re-authentication ''' sn = ISession(request)['OAuth2'] if 'principal' in sn.keys(): del sn['principal'] def getPrincipal(self, id): print 'getprincipal called: %s' % id source = IOAuthPrincipalSource(grok.getSite()) principal = source.find(id=id) if len(principal) == 1: return principal[0] raise PrincipalLookupError(id)
class PayPalIPNReceiver(grok.Container): """A receiver for IPN messages sent from paypal. """ grok.implements(IPayPalIPNReceiver) validation_url = "https://www.sandbox.paypal.com/cgi-bin/webscr/" def store_notification(self, post_var_string, uuid=None): """Store an instant payment notification (IPN). The `post_var_string` is the data payload sent by the notification. """ notification = InstantPaymentNotification(data=post_var_string) if uuid is None: uuid = get_uuid() self[uuid] = notification return uuid def validate(self, post_var_string): """Ask Paypal for validation. Sends an HTTP POST request to `validation_url` and returns the result, i.e. the content of the received document. Returns `None` if no `validation_url` is set or the `post_var_string` is empty. """ if not self.validation_url: return None if not post_var_string: return None response = requests.post(self.validation_url, data='cmd=_notify-validate&%s' % post_var_string) return response.text
class Parties(grok.Container): grok.implements(IParty, ILayout) sequence = 0 def __init__(self): super(Parties, self).__init__() self.sequence = 0
class PersonalMenu(Menu): grok.implements(IPersonalMenu) grok.context(Interface) grok.name('personalmenu') def render(self): template = getMultiAdapter((self, self.request), IPageTemplate) return template()
class UnfuteSources(grok.GlobalUtility): grok.implements(IVocabularyFactory) grok.name(u'uvc.unfute') def __call__(self, context): return vocabulary(('Verwaltung', 'Verwaltung', 'Verwaltung'), ('Druckerei', 'Druckerei', 'Druckerei'), ('Schreinerei', 'Schreinerei', 'Schreinerei'))
class CountryCodesVocabularyFactory(grok.GlobalUtility): grok.implements(IVocabularyFactory) grok.name("megrok.paypal.countrycodes") def __call__(self, context): terms = [SimpleTerm(value=x[0], token=x[0], title=x[1]) for x in COUNTRY_CODES_DICT.items()] return SimpleVocabulary(terms)
class CalculatorContentProvider(grok.MultiAdapter) grok.adapts(Calculator, IBrowserRequest, IBrowserView) grok.implements(IContentProvider) def __init__(self, context, request, view): self.context = context self.request = request self.view = view
class HiddenTextAdapter(grok.MultiAdapter): ''' Define an adapter for our schema field which selects our hidden text widget ''' grok.adapts(HiddenText, IBrowserRequest) grok.implements(IInputWidget) def __new__(self, field, request): return HiddenTextWidget(field, request)
class Uadbru1Sources(grok.GlobalUtility): grok.implements(IVocabularyFactory) grok.name(u'uvc.uadbru1') def __call__(self, context): return vocabulary(('Hausmeister', 'Hausmeister', 'Hausmeister'), ('Drucker', 'Drucker', 'Druker'), ('Bildhauer', 'Bildhauer', 'Bildhauer'))
class CharsetsVocabularyFactory(grok.GlobalUtility): grok.implements(IVocabularyFactory) grok.name("megrok.paypal.charsets") def __call__(self, context): terms = [SimpleTerm(value=x[0], token=x[0], title=x[1]) for x in CHARSETS_DICT.items()] return SimpleVocabulary(terms)
class PluginAuthenticacion(grok.LocalUtility): grok.implements(IAuthenticatorPlugin) grok.name('autenticacion') def __init__(self): self.contenedor_cuentas = ContenedorCuentas() def authenticateCredentials(self, credenciales): if not isinstance(credenciales, dict): return None if not ('login' in credenciales and 'password' in credenciales): return None cuenta = self.obtenerCuenta(credenciales['login']) if cuenta is None: return None if not cuenta.verificarPassword(credenciales['password']): return None return PrincipalInfo(id=cuenta.usuario, title=cuenta.nombre_real, description=cuenta.nombre_real) def principalInfo(self, id): cuenta = self.obtenerCuenta(id) if cuenta is None: return None return PrincipalInfo(id=cuenta.usuario, title=cuenta.nombre_real, description=cuenta.nombre_real) def obtenerCuenta(self, usuario): """Devuelve la cuenta del contenedor_cuentas[usuario]""" return usuario in self.contenedor_cuentas\ and self.contenedor_cuentas[usuario] or None def agregarUsuario(self, usuario, password, confirm_password, nombre_real, rol, seccion): if usuario not in self.contenedor_cuentas: user = Cuenta(usuario, password, nombre_real, rol, seccion) self.contenedor_cuentas[usuario] = user role_manager = IPrincipalRoleManager(grok.getSite()) if rol == u'empleado': role_manager.assignRoleToPrincipal('ct.empleadorol', usuario) if rol == u'administrador': role_manager.assignRoleToPrincipal('ct.adminrol', usuario) else: return u"El nombre de usuario ya existe" def borrarUsuario(self, usuario): if usuario in self.contenedor_cuentas: role_manager = IPrincipalRoleManager(grok.getSite()) rol = role_manager.getRolesForPrincipal(usuario)[0] role_manager.removeRoleFromPrincipal(rol[0], usuario) del self.contenedor_cuentas[usuario] def listarUsuarios(self): """Devuelve lista de cuentas creadas""" return [usuario for usuario in self.contenedor_cuentas.values()]
class PrincipalInfo(object): grok.implements(IPrincipalInfo) def __init__(self, id, title, description): self.id = id self.title = title self.description = description self.credentialsPlugin = None self.authenticatorPlugin = None
class App(grok.Application, grok.Container): grok.local_utility(Database, provides=IDatabase, public=True, name_in_container='database') grok.implements(IForm) engine_name = ''
class Home3(grok.MultiAdapter): grok.adapts(Cave, Fireplace) grok.implements(IHome, IFireplace) grok.provides(IHome) grok.name('home3') def __init__(self, cave, fireplace): self.cave = cave self.fireplace = fireplace