Example #1
0
def graph (app_type) :
    """Class/association graph describing Auth partial object model"""
    result = MOM.Graph.Spec.Graph \
        ( app_type
        , ET.Auth.Account_in_Group
            ( Role.left
                ( offset = CD.W
                )
            , Role.right
                ( offset = CD.E
                )
            )
        , desc  = _T
            ("Class/association graph displaying Auth partial object model")
        , title = _T ("Auth graph")
        )
    if hasattr (GTW.OMP, "PAP") and hasattr (GTW.OMP.PAP, "Person_has_Account"):
        result ["Auth.Account"]._add \
            ( ET.PAP.Person_has_Account
                ( Role.left
                    ( offset       = CD.S)
                , Role.right
                    ( guide_offset = 1.0
                    )
                , offset      = CD.S
                )
            )
    return result
Example #2
0
File: Mixin.py Project: Tapyr/tapyr
 def pid_query_request(self, pid, E_Type=None, raise_not_found=True):
     if E_Type is None:
         E_Type = self.E_Type
     scope = self.top.scope
     Status = self.Status
     try:
         ipid = int(pid)
     except (ValueError, TypeError):
         pass
     else:
         try:
             result = scope.pid_query(ipid)
         except LookupError as exc:
             self._check_pid_gone(ipid, E_Type, scope)
         else:
             if result is None:
                 self._check_pid_gone(ipid, E_Type, scope)
             elif isinstance(result, E_Type):
                 return result
             elif raise_not_found:
                 error = _T("`%s` refers to %s, not %s") % (pid, _T(result.E_Type.ui_name), _T(E_Type.ui_name))
                 raise Status.Bad_Request(error)
     if raise_not_found:
         error = _T("%s `%s` doesn't exist!") % (_T(E_Type.ui_name), pid)
         raise Status.Not_Found(error)
Example #3
0
 def _test (self) :
     """This is a method doc string"""
     print (_T (ckw.title or "Baz"))
     print (_T ("Foo"))
     foo = _("Markup %d")
     print (_T(foo) % 42)
     print (_Tn ("Singular", "Plural", 4))
Example #4
0
File: SRM.py Project: JPilarr/tapyr
 def message (self, user, page, * args, ** kw) :
     obj = page.parent.obj
     if obj.is_cancelled :
         fmt = _T ("Regatta %s is cancelled")
     else :
         fmt = _T ("Registration for %s is closed")
     return fmt % (obj.ui_display, )
Example #5
0
 def _setup_attr (soc, E_Type, fn, name, op, value, q = None) :
     if q is None :
         try :
             q   = getattr (E_Type.AQ, name)
         except AttributeError as exc :
             raise AttributeError \
                 ( _T ("%s doesn't have an attribute named `%s`")
                 % (E_Type.type_name, name)
                 )
         else :
             ### XXX remove this when query machinery supports cached roles
             if isinstance (q._attr, MOM.Attr.A_Cached_Role) :
                 raise AttributeError \
                     ( _T ("Query for cached role attribute `%s` of %s not yet supported")
                     % (name, E_Type.type_name)
                     )
     qop     = getattr (q, op)
     fq      = qop (value)
     qate    = q.As_Template_Elem
     f       = dict \
         ( qate._kw
         , AQ     = q
         , attr   = q._attr
         , edit   = value
         , id     = fn
         , name   = fn
         , op     = soc._qop_desc (qop)
         , value  = value
         )
     return TFL.Record (** f), fq
Example #6
0
File: Error.py Project: Tapyr/tapyr
 def __init__ (self, new, old) :
     otn = _T (old.ui_name) if old else ""
     otd = ("`%s`" % (old.ui_display, )) if old else _T ("object")
     self.__super.__init__ \
         ( _T ("new definition of %s `%s` clashes with existing %s %s")
         % (_T (new.ui_name), new.ui_display, otn, otd)
         )
Example #7
0
File: Error.py Project: Tapyr/tapyr
 def head (self) :
     return \
         ( _T( "Syntax error for %s: "
               "\n  expected type `%s`\n  got value `%s`"
             )
         % (self.attributes [0], _T (self.attribute.typ), self.value)
         )
Example #8
0
 def _setup_attr (soc, E_Type, fn, name, op, value, q = None) :
     if q is None :
         try :
             q   = getattr (E_Type.AQ, name)
         except AttributeError as exc :
             raise AttributeError \
                 ( _T ("%s doesn't have an attribute named `%s`")
                 % (E_Type.type_name, name)
                 )
         else :
             ### XXX remove this when query machinery supports cached roles
             if isinstance (q._attr, MOM.Attr.A_Cached_Role) :
                 raise AttributeError \
                     ( _T ("Query for cached role attribute `%s` of %s not yet supported")
                     % (name, E_Type.type_name)
                     )
     qop     = getattr (q, op)
     fq      = qop (value)
     qate    = q.As_Template_Elem
     f       = dict \
         ( qate._kw
         , AQ     = q
         , attr   = q._attr
         , edit   = value
         , id     = fn
         , name   = fn
         , op     = soc._qop_desc (qop)
         , value  = value
         )
     return TFL.Record (** f), fq
Example #9
0
 def _test(self):
     """This is a method doc string"""
     print(_T(ckw.title or "Baz"))
     print(_T("Foo"))
     foo = _("Markup %d")
     print(_T(foo) % 42)
     print(_Tn("Singular", "Plural", 4))
Example #10
0
 def pid_query_request (self, pid, E_Type = None, raise_not_found = True) :
     if E_Type is None :
         E_Type = self.E_Type
     scope  = self.top.scope
     Status = self.Status
     try :
         ipid = int (pid)
     except (ValueError, TypeError) :
         pass
     else :
         try :
             result = scope.pid_query (ipid)
         except LookupError as exc :
             self._check_pid_gone (ipid, E_Type, scope)
         else :
             if result is None :
                 self._check_pid_gone (ipid, E_Type, scope)
             elif isinstance (result, E_Type) :
                 return result
             elif raise_not_found :
                 error = \
                     (  _T ("`%s` refers to %s, not %s")
                     % (pid, _T (result.E_Type.ui_name), _T (E_Type.ui_name))
                     )
                 raise Status.Bad_Request (error)
     if raise_not_found :
         error = (_T ("%s `%s` doesn't exist!") % (_T (E_Type.ui_name), pid))
         raise Status.Not_Found (error)
Example #11
0
 def _admin_page(self, admin_args):
     m_kw = admin_args.copy()
     short_title = _T("Admin")
     title = m_kw.pop("title", "%s: %s" % (self.title.rstrip("."), _T("Administration")))
     ETM = m_kw.pop("ETM", self.ETM)
     Type = m_kw.pop("Type", GTW.RST.TOP.MOM.Admin.E_Type)
     return Type(name="admin", parent=self, short_title=short_title, title=title, ETM=ETM, **m_kw)
Example #12
0
 def __init__ (self, new, old) :
     otn = _T (old.ui_name) if old else ""
     otd = ("`%s`" % (old.ui_display, )) if old else _T ("object")
     self.__super.__init__ \
         ( _T ("new definition of %s `%s` clashes with existing %s %s")
         % (_T (new.ui_name), new.ui_display, otn, otd)
         )
Example #13
0
 def _response_attr(self, resource, request, response, attr):
     result = dict \
         ( default_value = attr.raw_default
         , description   = _T (attr.description)
         , is_changeable = attr.is_changeable
         , is_required   = attr.is_required
         , is_settable   = attr.is_settable
         , kind          = _T (attr.kind)
         , name          = attr.name
         , type          = _T (attr.typ)
         )
     self._add_attr_props \
         ( attr
         , ("group", "max_length", "max_value", "min_value", "role_name")
         , result
         )
     self._add_attr_props(attr, ("explanation", "syntax"), result, _T)
     if attr.ui_name_T != attr.name:
         result["ui_name"] = attr.ui_name_T
     if isinstance(attr.E_Type, MOM.Meta.M_E_Type):
         result["type_name"] = tn = attr.E_Type.type_name
         if isinstance(attr.attr, MOM.Attr._A_Composite_):
             result ["attributes"] = list \
                 (   self._response_attr (resource, request, response, a)
                 for a in attr.E_Type.ui_attr
                 )
         else:
             result["url"] = resource.e_type_href(tn)
     else:
         self._add_attr_props(attr, ("Choices", "example"), result)
     if attr.P_Type:
         result["p_type"] = attr.P_Type.__name__
     return result
Example #14
0
 def head (self) :
     return \
         ( _T( "Syntax error for %s: "
               "\n  expected type `%s`\n  got value `%s`"
             )
         % (self.attributes [0], _T (self.attribute.typ), self.value)
         )
Example #15
0
 def message (self, user, page, * args, ** kw) :
     obj = page.parent.obj
     if obj.is_cancelled :
         fmt = _T ("Regatta %s is cancelled")
     else :
         fmt = _T ("Registration for %s is closed")
     return fmt % (obj.ui_display, )
Example #16
0
File: Doc.py Project: Tapyr/tapyr
 def _response_attr (self, resource, request, response, attr) :
     result = dict \
         ( default_value = attr.raw_default
         , description   = _T (attr.description)
         , is_changeable = attr.is_changeable
         , is_required   = attr.is_required
         , is_settable   = attr.is_settable
         , kind          = _T (attr.kind)
         , name          = attr.name
         , type          = _T (attr.typ)
         )
     self._add_attr_props \
         ( attr
         , ("group", "max_length", "max_value", "min_value", "role_name")
         , result
         )
     self._add_attr_props (attr, ("explanation", "syntax"), result, _T)
     if attr.ui_name_T != attr.name :
         result ["ui_name"] = attr.ui_name_T
     if isinstance (attr.E_Type, MOM.Meta.M_E_Type) :
         result ["type_name"] = tn = attr.E_Type.type_name
         if isinstance (attr.attr, MOM.Attr._A_Composite_) :
             result ["attributes"] = list \
                 (   self._response_attr (resource, request, response, a)
                 for a in attr.E_Type.ui_attr
                 )
         else :
             result ["url"] = resource.e_type_href (tn)
     else :
         self._add_attr_props (attr, ("Choices", "example"), result)
     if attr.P_Type :
         result ["p_type"] = attr.P_Type.__name__
     return result
Example #17
0
 def pid_query (self, pid, Type = None) :
     result = self.pm.query (int (pid))
     if Type is not None and not isinstance (result, Type.Essence) :
         raise LookupError \
             ( _T ("Pid `%r` is instance of type %s, not of type `%s`")
             % (pid, _T (result.ui_name), _T (Type.ui_name))
             )
     return result
Example #18
0
 def _rep (match) :
     return _obfuscator_format % dict \
         ( js_args  = obfuscated  (match.group (0))
         , need     =
             ( _T ("Need Javascript for displaying %s")
             % _T (scheme_map.get (scheme, scheme))
             )
         , text     = match.group (2)
         )
Example #19
0
 def Op_Map (self) :
     result = {}
     for k, v in pyk.iteritems (_Type_.Base_Op_Table) :
         sym = _T (v.op_sym)
         result [k] = dict \
             ( desc  = _T (v.desc)
             , sym   = sym
             )
     return result
Example #20
0
 def Op_Map(self):
     result = {}
     for k, v in pyk.iteritems(_Type_.Base_Op_Table):
         sym = _T(v.op_sym)
         result [k] = dict \
             ( desc  = _T (v.desc)
             , sym   = sym
             )
     return result
Example #21
0
 def _get_pages (self) :
     np     = _T ("Participants")
     nr     = _T ("Results")
     obj    = self.obj
     result = []
     scope  = self.scope
     sk     = TFL.Sorted_By \
         ("skipper.person.last_name", "skipper.person.first_name")
     Result_Type = None
     if obj.is_team_race :
         Registration_Type = self.Registration_Teamrace
         try :
             place = first (obj.teams).place
         except IndexError :
             pass
         else :
             if place :
                 Result_Type = self.Result_Teamrace
     else :
         Registration_Type = self.Registration
         if obj.races :
             Result_Type = self.Result
     if Result_Type :
         result.append \
             ( Result_Type
                 ( ETM         = obj.ETM
                 , name        = nr.lower ()
                 , obj         = obj
                 , parent      = self
                 , regatta     = obj
                 , short_title = nr
                 , title       = "%s %s" %
                     ( _T ("Results for"), self.short_title)
                 )
             )
     head = _T ("List of participants for")
     result.append \
         ( Registration_Type
             ( ETM         = obj.ETM
             , head_line   = "%s %s<br />%s, %s" %
                 ( _T ("Registration list"), obj.name
                 , obj.event.FO.short_title, obj.event.ui_date
                 )
             , name        = np.lower ()
             , nav_off_canvas = False
             , obj         = obj
             , parent      = self
             , regatta     = obj
             , short_title = np
             , title       = "%s %s" % (head, self.short_title)
             )
         )
     bir_admin = self._get_bir_admin ()
     if bir_admin :
         result.append (bir_admin)
     return result
Example #22
0
File: SRM.py Project: JPilarr/tapyr
 def _get_pages (self) :
     np     = _T ("Participants")
     nr     = _T ("Results")
     obj    = self.obj
     result = []
     scope  = self.scope
     sk     = TFL.Sorted_By \
         ("skipper.person.last_name", "skipper.person.first_name")
     Result_Type = None
     if obj.is_team_race :
         Registration_Type = self.Registration_Teamrace
         try :
             place = first (obj.teams).place
         except IndexError :
             pass
         else :
             if place :
                 Result_Type = self.Result_Teamrace
     else :
         Registration_Type = self.Registration
         if obj.races :
             Result_Type = self.Result
     if Result_Type :
         result.append \
             ( Result_Type
                 ( ETM         = obj.ETM
                 , name        = nr.lower ()
                 , obj         = obj
                 , parent      = self
                 , regatta     = obj
                 , short_title = nr
                 , title       = "%s %s" %
                     ( _T ("Results for"), self.short_title)
                 )
             )
     head = _T ("List of participants for")
     result.append \
         ( Registration_Type
             ( ETM         = obj.ETM
             , head_line   = "%s %s<br />%s, %s" %
                 ( _T ("Registration list"), obj.name
                 , obj.event.FO.short_title, obj.event.ui_date
                 )
             , name        = np.lower ()
             , nav_off_canvas = False
             , obj         = obj
             , parent      = self
             , regatta     = obj
             , short_title = np
             , title       = "%s %s" % (head, self.short_title)
             )
         )
     bir_admin = self._get_bir_admin ()
     if bir_admin :
         result.append (bir_admin)
     return result
Example #23
0
 def cooked(soc, value):
     if isinstance(value, datetime.datetime):
         value = value.time()
     elif isinstance(value, pyk.string_types):
         try:
             value = soc._from_string(value)
         except ValueError:
             raise TypeError(_T("Time expected, got %r") % (value, ))
     elif not isinstance(value, datetime.time):
         raise TypeError(_T("Time expected, got %r") % (value, ))
     return value
Example #24
0
 def cooked (soc, value) :
     if isinstance (value, datetime.datetime) :
         value = value.time ()
     elif isinstance (value, pyk.string_types) :
         try :
             value = soc._from_string (value)
         except ValueError :
             raise TypeError (_T ("Time expected, got %r") % (value, ))
     elif not isinstance (value, datetime.time) :
         raise TypeError (_T ("Time expected, got %r") % (value, ))
     return value
Example #25
0
 def recover(cls, request, value, ttl_s=None):
     """Recover a signed token from `value`"""
     root = request.root
     result = cls.__new__(cls)
     result.request = request
     result.x_value = value
     parts = value.split(cls.val_sep, 2)
     if len(parts) != 3:
         if value:
             fmt = _("Malformed %s value '%s'")
         else:
             fmt = _("Missing %s%s")
         result._invalid = _T(fmt) % (cls.__name__, value)
         return result
     (result.cargo, result.timestamp, result.x_signature) = parts
     enc = result.encoding
     try:
         result.data = data = base64.b64decode(result.cargo).decode(enc)
     except Exception as exc:
         result._invalid = str(exc)
         return result
     if not root.HTTP.safe_str_cmp(result.x_signature, result.signature):
         result._invalid = msg = \
             _T ("Invalid %s signature for '%s'") % (cls.__name__, data)
         logging.warning(msg)
     try:
         timestamp = base64.b64decode(result.timestamp).decode(enc)
     except Exception as exc:
         result._invalid = repr(exc)
     else:
         try:
             then = result.time = int(timestamp)
         except Exception as exc:
             result._invalid = repr(exc)
     if result:
         now = request.current_time
         ttl = ttl_s if ttl_s is not None else request.resource.session_ttl_s
         if then < (now - ttl):
             result._invalid = msg = \
                 ( _T ("Expired %s '%s' older then %s seconds")
                 % (cls.__name__, data, ttl)
                 )
             logging.warning(msg)
         elif then > now + 180:
             ### don't accept tokens with a timestamp more than 2 minutes in
             ### the future
             result._invalid = msg = \
                 ( _T ("Time-travelling %s '%s' [%s seconds ahead]")
                 % (cls.__name__, data, then - now)
                 )
             logging.warning(msg)
     return result
Example #26
0
 def recover (cls, request, value, ttl_s = None) :
     """Recover a signed token from `value`"""
     root   = request.root
     result = cls.__new__ (cls)
     result.request = request
     result.x_value = value
     parts  = value.split (cls.val_sep, 2)
     if len (parts) != 3 :
         if value :
             fmt = _ ("Malformed %s value '%s'")
         else :
             fmt = _ ("Missing %s%s")
         result._invalid = _T (fmt) % (cls.__name__, value)
         return result
     (result.cargo, result.timestamp, result.x_signature) = parts
     enc = result.encoding
     try:
         result.data = data = base64.b64decode (result.cargo).decode (enc)
     except Exception as exc :
         result._invalid = str (exc)
         return result
     if not root.HTTP.safe_str_cmp (result.x_signature, result.signature) :
         result._invalid = msg = \
             _T ("Invalid %s signature for '%s'") % (cls.__name__, data)
         logging.warning (msg)
     try :
         timestamp = base64.b64decode (result.timestamp).decode (enc)
     except Exception as exc :
         result._invalid = repr (exc)
     else :
         try :
             then = result.time = int (timestamp)
         except Exception as exc :
             result._invalid = repr (exc)
     if result :
         now = request.current_time
         ttl = ttl_s if ttl_s is not None else request.resource.session_ttl_s
         if then < (now - ttl) :
             result._invalid = msg = \
                 ( _T ("Expired %s '%s' older then %s seconds")
                 % (cls.__name__, data, ttl)
                 )
             logging.warning (msg)
         elif then > now + 180 :
             ### don't accept tokens with a timestamp more than 2 minutes in
             ### the future
             result._invalid = msg = \
                 ( _T ("Time-travelling %s '%s' [%s seconds ahead]")
                 % (cls.__name__, data, then - now)
                 )
             logging.warning (msg)
     return result
Example #27
0
File: graph.py Project: Tapyr/tapyr
def graph(app_type):
    """Class/association graph describing Auth partial object model"""
    result = MOM.Graph.Spec.Graph(
        app_type,
        ET.Auth.Account_in_Group(Role.left(offset=CD.W), Role.right(offset=CD.E)),
        desc=_T("Class/association graph displaying Auth partial object model"),
        title=_T("Auth graph"),
    )
    if hasattr(GTW.OMP, "PAP") and hasattr(GTW.OMP.PAP, "Person_has_Account"):
        result["Auth.Account"]._add(
            ET.PAP.Person_has_Account(Role.left(offset=CD.S), Role.right(guide_offset=1.0), offset=CD.S)
        )
    return result
Example #28
0
 def cooked(soc, value):
     if not isinstance(value, datetime.datetime):
         if isinstance(value, datetime.date):
             value = datetime.datetime(value.year, value.month, value.day)
         elif isinstance(value, pyk.string_types):
             try:
                 value = soc._from_string(value)
             except ValueError:
                 raise TypeError \
                     (_T ("Date/time expected, got %r") % (value, ))
         else:
             raise TypeError(_T("Date/time expected, got %r") % (value, ))
     return value
Example #29
0
 def as_html (self, o, renderer) :
     p = self._value_getter (o)
     if p == self.resource.user_restriction :
         icon  = "check-square-o"
         title = _T ("Owned by you")
     else :
         icon  = "square-o"
         title = _T ("Owned by %s") % self.value (o, renderer)
     result = \
         ( """<i class="fa fa-%(icon)s" title="%(title)s"></i>"""
         % dict (icon = icon, title = title)
         )
     return result
Example #30
0
 def cooked (soc, value) :
     if not isinstance (value, datetime.datetime) :
         if isinstance (value, datetime.date) :
             value = datetime.datetime (value.year, value.month, value.day)
         elif isinstance (value, pyk.string_types) :
             try :
                 value = soc._from_string (value)
             except ValueError :
                 raise TypeError \
                     (_T ("Date/time expected, got %r") % (value, ))
         else :
             raise TypeError (_T ("Date/time expected, got %r") % (value, ))
     return value
Example #31
0
 def as_unicode (self) :
     bindings = dict (self.bindings)
     result = \
         ( _T( "You are not allowed to change %s unless afterwards "
               "you [%s] are still either manager or owner"
             )
         % ( _T (" and ").join
               ( "'%s' %s '%s'"
               % (d, _T ("to"), bindings [k]) for k, d in self.changed
               )
           , self.user
           )
         )
     return result
Example #32
0
File: Error.py Project: Tapyr/tapyr
 def __init__ (self, obj, inv) :
     self.__super.__init__ (obj)
     pid               = getattr (obj, "pid", None)
     self.args         = (obj, ) if pid else (_T (obj.ui_name), )
     self.inv          = inv
     self.is_required  = inv.is_required
     self.attributes   = sorted (inv.attributes + inv.attr_none)
     self.extra_links  = list   (inv.extra_links)
     self.val_disp     = dict   (inv.val_disp)
     description       = _T     (inv.description)
     try :
         self.inv_desc = description % TFL.Caller.Object_Scope (obj)
     except TypeError :
         self.inv_desc = description
Example #33
0
 def __init__ (self, obj, inv) :
     self.__super.__init__ (obj)
     pid               = getattr (obj, "pid", None)
     self.args         = (obj, ) if pid else (_T (obj.ui_name), )
     self.inv          = inv
     self.is_required  = inv.is_required
     self.attributes   = sorted (inv.attributes + inv.attr_none)
     self.extra_links  = list   (inv.extra_links)
     self.val_disp     = dict   (inv.val_disp)
     description       = _T     (inv.description)
     try :
         self.inv_desc = description % TFL.Caller.Object_Scope (obj)
     except TypeError :
         self.inv_desc = description
Example #34
0
 def cooked (soc, value) :
     P_Type = soc.P_Type
     if isinstance (value, pyk.string_types) :
         try :
             value = soc._from_string (value)
         except MOM.Error.Attribute_Syntax :
             raise
         except ValueError :
             msg   = _T ("%s expected, got %r") % (_T (soc.typ), value)
             raise MOM.Error.Attribute_Syntax (None, soc, value, msg)
     elif not isinstance (value, P_Type) :
         raise MOM.Error.Wrong_Type \
             (_T ("Value `%r` is not of type %s") % (value, P_Type))
     return value
Example #35
0
File: Auth.py Project: Tapyr/tapyr
 def _response_body (self, resource, request, response) :
     req_data      = request.req_data
     top           = resource.top
     self.errors   = Errors ()
     username      = self.get_username (request)
     if username :
         self.get_account (resource, username)
         if self.account :
             self.errors ["username"].append \
                 (_T ( "Account with this Email address already "
                       "registered"
                     )
                 )
     new_password  = self.get_password \
         (request, "npassword", verify_field = "vpassword")
     if not self.errors :
         next           = req_data.get ("next", "/")
         host           = request.host
         Auth           = top.scope.Auth
         account, token = Auth.Account.create_new_account \
             (username, new_password)
         link  = resource.parent.href_action (account, token, request)
         top.scope.commit ()
         try :
             resource.send_email \
                 ( resource.email_template
                 , email_to      = username
                 , email_subject =
                     _T ("Email confirmation for %s") % (host, )
                 , email_from    = resource.email_from
                 , link          = link
                 , NAV           = top
                 , page          = resource
                 , host          = host
                 )
         except Exception as exc :
             self.errors [None].append (str (exc))
         else :
             response.add_notification \
                 (_T ( "A confirmation has been sent to your email "
                       "address %s."
                     )
                 % (username, )
                 )
             raise top.Status.See_Other (next)
     response.username = None
     response.errors   = self.errors
     result = resource.GET ()._response_body \
         (resource, request, response)
     return result
Example #36
0
File: Range.py Project: Tapyr/tapyr
 def cooked (soc, value) :
     P_Type = soc.P_Type
     if isinstance (value, pyk.string_types) :
         try :
             value = soc._from_string (value)
         except MOM.Error.Attribute_Syntax :
             raise
         except ValueError :
             msg   = _T ("%s expected, got %r") % (_T (soc.typ), value)
             raise MOM.Error.Attribute_Syntax (None, soc, value, msg)
     elif not isinstance (value, P_Type) :
         raise MOM.Error.Wrong_Type \
             (_T ("Value `%r` is not of type %s") % (value, P_Type))
     return value
Example #37
0
 def _response_body(self, resource, request, response):
     req_data = request.req_data
     top = resource.top
     self.errors = Errors()
     username = self.get_username(request)
     if username:
         self.get_account(resource, username)
         if self.account:
             self.errors ["username"].append \
                 (_T ( "Account with this Email address already "
                       "registered"
                     )
                 )
     new_password  = self.get_password \
         (request, "npassword", verify_field = "vpassword")
     if not self.errors:
         next = req_data.get("next", "/")
         host = request.host
         Auth = top.scope.Auth
         account, token = Auth.Account.create_new_account \
             (username, new_password)
         link = resource.parent.href_action(account, token, request)
         top.scope.commit()
         try:
             resource.send_email \
                 ( resource.email_template
                 , email_to      = username
                 , email_subject =
                     _T ("Email confirmation for %s") % (host, )
                 , email_from    = resource.email_from
                 , link          = link
                 , NAV           = top
                 , page          = resource
                 , host          = host
                 )
         except Exception as exc:
             self.errors[None].append(str(exc))
         else:
             response.add_notification \
                 (_T ( "A confirmation has been sent to your email "
                       "address %s."
                     )
                 % (username, )
                 )
             raise top.Status.See_Other(next)
     response.username = None
     response.errors = self.errors
     result = resource.GET ()._response_body \
         (resource, request, response)
     return result
Example #38
0
 def as_unicode(self):
     bindings = dict(self.bindings)
     result = \
         ( _T( "You are not allowed to change %s unless afterwards "
               "you [%s] are still either manager or owner"
             )
         % ( _T (" and ").join
               ( "'%s' %s '%s'"
               % (d, _T ("to"), bindings [k]) for k, d in self.changed
               )
           , self.user
           )
         )
     return result
Example #39
0
File: graph.py Project: Tapyr/tapyr
def graph (app_type) :
    """Class/association graph displaying SRM partial object model"""
    return MOM.Graph.Spec.Graph \
        ( app_type
        , ET.SRM.Boat_in_Regatta
            ( Role.left
                ( Role.left (offset = CD.W)
                , offset = CD.W
                )
            , Role.right
                ( Role.left
                    ( Attr.club (offset = CD.N * 2)
                    , ET.SRM.Page
                        ( Attr.event
                        , offset = CD.S
                        )
                    , offset = CD.E
                    )
                , offset = CD.E
                )
            , ET.SRM.Crew_Member
                ( Role.left  (anchor = False, source_side = "W")
                , Role.right (anchor = False, source_side = "W")
                , offset = CD.NE
                )
            , ET.SRM.Team_has_Boat_in_Regatta
                ( Role.left
                    ( ET.SRM.Regatta_C
                        ( IS_A.SRM.Regatta
                        , offset = CD.E
                        )
                    , offset = CD.S
                    )
                , offset = CD.S
                )
            , ET.SRM.Race_Result (offset = CD.SW)
            , Attr.skipper
                ( Role.left
                    ( IS_A.PAP.Subject (offset = CD.E * 2)
                    , offset = CD.N
                    )
                , Attr.club (IS_A.PAP.Subject)
                , offset = CD.N * 2
                )
            )
        , desc  = _T
            ("Class/association graph displaying SRM partial object model")
        , title = _T ("SRM graph")
        )
Example #40
0
def graph (app_type) :
    """Class/association graph describing MOM meta object model"""
    doc_p = hasattr (MOM, "Document")
    iht_p = hasattr (MOM, "Id_Entity_has_Tag")
    result = MOM.Graph.Spec.Graph \
        ( app_type
        , ET.MOM.Id_Entity
            ( Child.MOM.Object    (offset     = CD.N)
            , Child.MOM.Link1
                ( Attr.left       (guide_prio = 0.25)
                , offset     = CD.W
                )
            , Child.MOM._Link_n_
                ( Attr.left       (guide_prio = 0.25)
                , Attr.right      (guide_prio = 0.75)
                , Child.MOM.Link2
                    ( offset = CD.E
                    )
                , Child.MOM.Link3
                    ( Attr.middle ()
                    , offset = CD.W
                    )
                , guide_prio = 0.5
                , offset     = CD.S
                )
            ,
            )
        , desc  = _T ("Graph displaying MOM meta object model")
        , title = _T ("MOM graph")
        )
    if doc_p :
        result ["MOM.Link1"]._add \
            ( Child.MOM.Document
                ( offset     = CD.N
                )
            )
    if iht_p :
        result ["MOM.Id_Entity"]._add \
            ( ET.MOM.Id_Entity_has_Tag
                ( IS_A.MOM.Link2
                , Role.left  ()
                , Role.right
                    ( IS_A.MOM.Object
                    , offset     = CD.N
                    )
                , offset     = CD.E
                )
            )
    return result
Example #41
0
def graph (app_type) :
    """Class/association graph displaying SRM partial object model"""
    return MOM.Graph.Spec.Graph \
        ( app_type
        , ET.SRM.Boat_in_Regatta
            ( Role.left
                ( Role.left (offset = CD.W)
                , offset = CD.W
                )
            , Role.right
                ( Role.left
                    ( Attr.club (offset = CD.N * 2)
                    , ET.SRM.Page
                        ( Attr.event
                        , offset = CD.S
                        )
                    , offset = CD.E
                    )
                , offset = CD.E
                )
            , ET.SRM.Crew_Member
                ( Role.left  (anchor = False, source_side = "W")
                , Role.right (anchor = False, source_side = "W")
                , offset = CD.NE
                )
            , ET.SRM.Team_has_Boat_in_Regatta
                ( Role.left
                    ( ET.SRM.Regatta_C
                        ( IS_A.SRM.Regatta
                        , offset = CD.E
                        )
                    , offset = CD.S
                    )
                , offset = CD.S
                )
            , ET.SRM.Race_Result (offset = CD.SW)
            , Attr.skipper
                ( Role.left
                    ( IS_A.PAP.Subject (offset = CD.E * 2)
                    , offset = CD.N
                    )
                , Attr.club (IS_A.PAP.Subject)
                , offset = CD.N * 2
                )
            )
        , desc  = _T
            ("Class/association graph displaying SRM partial object model")
        , title = _T ("SRM graph")
        )
Example #42
0
File: Auth.py Project: Tapyr/tapyr
 def get_email ( self, request
               , field_name   = "nemail"
               , verify_field = "vemail"
               ) :
     email = self.get_required \
         (request, field_name, _T ("The Email is required."))
     if verify_field :
         verify = self.get_required \
         ( request, verify_field
         , _T ("Repeat the EMail for verification.")
         )
         if email and verify and (email != verify) :
             self.errors [field_name].append \
                 (_T ("The Email's don't match."))
     return email
Example #43
0
 def get_email(self,
               request,
               field_name="nemail",
               verify_field="vemail"):
     email = self.get_required \
         (request, field_name, _T ("The Email is required."))
     if verify_field:
         verify = self.get_required \
         ( request, verify_field
         , _T ("Repeat the EMail for verification.")
         )
         if email and verify and (email != verify):
             self.errors [field_name].append \
                 (_T ("The Email's don't match."))
     return email
Example #44
0
 def convert (cls, text) :
     cleaner  = TFL.HTML.Cleaner (text, "html.parser")
     comments = cleaner.remove_comments ()
     if comments :
         raise ValueError \
             ( _T ("HTML must not contain comments:\n%s")
             % ("\n    ".join (comments), )
             )
     forbidden = cleaner.remove_tags (* cls.forbidden)
     if forbidden :
         raise ValueError \
             ( _T ("HTML must not contain any of the tags:\n%s")
             % ("    ".join (forbidden), )
             )
     return pyk.text_type (cleaner)
Example #45
0
 def convert(cls, text):
     cleaner = TFL.HTML.Cleaner(text, "html.parser")
     comments = cleaner.remove_comments()
     if comments:
         raise ValueError \
             ( _T ("HTML must not contain comments:\n%s")
             % ("\n    ".join (comments), )
             )
     forbidden = cleaner.remove_tags(*cls.forbidden)
     if forbidden:
         raise ValueError \
             ( _T ("HTML must not contain any of the tags:\n%s")
             % ("    ".join (forbidden), )
             )
     return pyk.text_type(cleaner)
Example #46
0
 def _get_child (self, child, * grandchildren) :
     result = self.__super._get_child (child, * grandchildren)
     if result is None :
         if child == "admin" :
             result = self._get_bir_admin ()
             if result :
                 _entries = self._entries
                 if ((not _entries) or _entries [-1] is not result) :
                     self.add_entries (result)
                 if grandchildren :
                     result = result._get_child (* grandchildren)
         elif child == "register" :
             bir_admin = self._get_bir_admin ()
             result = GTW.RST.TOP.Alias \
                 ( name          = child
                 , hidden        = True
                 , parent        = self
                 , short_title   = child
                 , target        = bir_admin._get_child ("create")
                 , title         =
                     ( _T ("Register an entry for %s at %s")
                     % (self.short_title, self.parent.short_title)
                     )
                 )
     return result
Example #47
0
 def title (self) :
     return "%s: %s %s/%s" % \
         ( self.parent.title
         , _T ("picture")
         , self.number
         , self.parent.count
         )
Example #48
0
 def short_title(self):
     return "%s: %s %s/%s" % \
         ( self.parent.obj.short_title
         , _T ("picture")
         , self.obj.name
         , self.parent.count
         )
Example #49
0
 def _send_notification(self, response, account):
     response.add_notification \
         ( GTW.Notification
             ( _T ("Activation of account %s successful.")
             % (account.name, )
             )
         )
Example #50
0
 def _check_account(self, account, errors):
     if account and not account.activation:
         if errors:
             errors [None].append \
                 (_T ("No activation request for this account"))
         return False
     return True
Example #51
0
 def head_line(self):
     result = self.__super.head_line
     user = self.user_restriction
     if user:
         u = user.FO
         result = "%s: %s %s" % (result, _T(self.restriction_desc), u)
     return result
Example #52
0
 def title(self):
     return "%s: %s %s/%s" % \
         ( self.parent.title
         , _T ("picture")
         , self.number
         , self.parent.count
         )
Example #53
0
 def _handle_method_context (self, method, request, response) :
     with self.__super._handle_method_context (method, request, response) :
         try :
             qr = self.QR.from_request \
                 (self.scope, self.E_Type, request, ** self.default_qr_kw)
         except (AttributeError, TypeError, ValueError) as exc :
             error = _T ("Query restriction triggered error: %s '%s'") % \
                 (exc.__class__.__name__, exc)
             raise self.Status.Bad_Request (error)
         kw = dict (query_restriction = qr)
         if qr.attributes :
             kw ["attributes"] = qr.attributes
         if qr :
             ### temporarily invalidate cached information to trigger
             ### reload with `query_restriction`
             ### old caches will be restored after `_handle_method` completes
             kw.update \
                 ( _change_info = None
                 , _entries     = []
                 , _entry_map   = {}
                 , _objects     = []
                 , _old_cid     = object ()
                 )
         if "add_fields" in request.req_data :
             kw ["add_attributes"] = tuple \
                 ( self._gen_attr_kinds
                     (request.req_data ["add_fields"].split (","))
                 )
         with self.LET (** kw) :
             yield
Example #54
0
 def get_password \
         ( self, request
         , field_name   = "password"
         , verify_field = None
         ) :
     password = self.get_required \
         (request, field_name, _T ("The password is required."))
     if verify_field :
         verify = self.get_required \
             ( request, verify_field
             , _T ("Repeat the password for verification.")
             )
         if password and verify and (password != verify) :
             self.errors [field_name].append \
                 (_T ("The passwords don't match."))
     return password
Example #55
0
def graph(app_type):
    """Class/association graph displaying EVT partial object model"""
    return MOM.Graph.Spec.Graph \
        ( app_type
        , ET.EVT.Event
            ( Role.left     (offset = CD.W)
            , Attr.calendar (offset = CD.N)
            , ET.EVT.Recurrence_Spec
                ( ET.EVT.Recurrence_Rule (offset = CD.E)
                , offset = CD.E
                )
            )
        , desc  = _T
            ("Class/association graph displaying EVT partial object model")
        , title = _T ("EVT graph")
        )
Example #56
0
 def head_line (self) :
     result = self.__super.head_line
     user   = self.user_restriction
     if user :
         u = user.FO
         result = "%s: %s %s" % (result, _T (self.restriction_desc), u)
     return result
Example #57
0
 def csrf_check (self, request, response) :
     if self.csrf_check_p :
         error = None
         if not request.same_origin :
             error = \
                 ( _T ("Incorrect origin `%s` for request, expected `%r`")
                 % (request.origin_host, request.server_name)
                 )
         else :
             csrf_token = request.csrf_token
             if not csrf_token :
                 if self.DEBUG :
                     error  = "\n".join \
                         ( ( pyk.decoded (repr (csrf_token))
                           , "Client sig  : %s" % (csrf_token.x_signature, )
                           , "Client value: %s" % (csrf_token.x_value, )
                           , "Server value: %s" % (csrf_token.value, )
                           , "Session sid : %s" % (request.session.sid, )
                           )
                         )
                 else :
                     error  = csrf_token._invalid
         if error :
             exc = self.top.Status.See_Other (self.abs_href)
             self.send_error_email (request, "CSRF", xtra = error)
             raise exc