Fix E256 with stricter pep8 error checker
[cascardo/ipsilon.git] / ipsilon / providers / saml2 / admin.py
index 4e9741d..a9fb9e0 100755 (executable)
@@ -22,12 +22,16 @@ from ipsilon.util.page import Page
 from ipsilon.providers.saml2.provider import ServiceProvider
 from ipsilon.providers.saml2.provider import ServiceProviderCreator
 from ipsilon.providers.saml2.provider import InvalidProviderId
+import re
+
+
+VALID_IN_NAME = r'[^\ a-zA-Z0-9]'
 
 
 class NewSPAdminPage(Page):
 
     def __init__(self, site, parent):
-        super(NewSPAdminPage, self).__init__(site)
+        super(NewSPAdminPage, self).__init__(site, form=True)
         self.parent = parent
         self.title = 'New Service Provider'
         self.backurl = parent.url
@@ -47,8 +51,8 @@ class NewSPAdminPage(Page):
     def POST(self, *args, **kwargs):
 
         if self.user.is_admin:
-            #TODO: allow authenticated user to create SPs on their own
-            #      set the owner in that case
+            # TODO: allow authenticated user to create SPs on their own
+            #       set the owner in that case
             name = None
             meta = None
             if 'content-type' not in cherrypy.request.headers:
@@ -62,6 +66,12 @@ class NewSPAdminPage(Page):
                             cherrypy.request.content_type,))
             for key, value in kwargs.iteritems():
                 if key == 'name':
+                    if re.search(VALID_IN_NAME, value):
+                        message = "Invalid name!" \
+                                  " Use only numbers and letters"
+                        message_type = "error"
+                        return self.form_new(message, message_type)
+
                     name = value
                 elif key == 'meta':
                     if hasattr(value, 'content_type'):
@@ -93,16 +103,19 @@ class NewSPAdminPage(Page):
 
         return self.form_new(message, message_type)
 
-    def root(self, *args, **kwargs):
-        op = getattr(self, cherrypy.request.method, self.GET)
-        if callable(op):
-            return op(*args, **kwargs)
+
+class InvalidValueFormat(Exception):
+    pass
+
+
+class UnauthorizedUser(Exception):
+    pass
 
 
 class SPAdminPage(Page):
 
     def __init__(self, sp, site, parent):
-        super(SPAdminPage, self).__init__(site)
+        super(SPAdminPage, self).__init__(site, form=True)
         self.parent = parent
         self.sp = sp
         self.title = sp.name
@@ -121,65 +134,118 @@ class SPAdminPage(Page):
     def GET(self, *args, **kwargs):
         return self.form_standard()
 
+    def change_name(self, key, value):
+
+        if value == self.sp.name:
+            return False
+
+        if self.user.is_admin or self.user.name == self.sp.owner:
+            if re.search(VALID_IN_NAME, value):
+                err = "Invalid name! Use only numbers and letters"
+                raise InvalidValueFormat(err)
+
+            self._debug("Replacing %s: %s -> %s" % (key, self.sp.name, value))
+            return {'name': value, 'rename': [self.sp.name, value]}
+        else:
+            raise UnauthorizedUser("Unauthorized to rename Service Provider")
+
+    def change_owner(self, key, value):
+        if value == self.sp.owner:
+            return False
+
+        if self.user.is_admin:
+            self._debug("Replacing %s: %s -> %s" % (key, self.sp.owner, value))
+            return {'owner': value}
+        else:
+            raise UnauthorizedUser("Unauthorized to set owner value")
+
+    def change_default_nameid(self, key, value):
+        if value == self.sp.default_nameid:
+            return False
+
+        if self.user.is_admin:
+            self._debug("Replacing %s: %s -> %s" % (key,
+                                                    self.sp.default_nameid,
+                                                    value))
+            if not self.sp.is_valid_nameid(value):
+                raise InvalidValueFormat('Invalid default nameid value')
+            return {'default_nameid': value}
+        else:
+            raise UnauthorizedUser("Unauthorized to set default nameid value")
+
+    def change_allowed_nameids(self, key, value):
+        v = set([x.strip() for x in value.split(',')])
+        if v == set(self.sp.allowed_nameids):
+            return False
+
+        if self.user.is_admin:
+            self._debug("Replacing %s: %s -> %s" % (key,
+                                                    self.sp.allowed_nameids,
+                                                    list(v)))
+            for x in v:
+                if not self.sp.is_valid_nameid(x):
+                    l = ', '.join(self.sp.valid_nameids())
+                    err = 'Invalid nameid [%s]. Available [%s].' % (x, l)
+                    raise InvalidValueFormat(err)
+            return {'allowed_nameids': list(v)}
+        else:
+            raise UnauthorizedUser("Unauthorized to set alowed nameids values")
+
     def POST(self, *args, **kwargs):
 
         message = "Nothing was modified."
         message_type = "info"
-        save = False
-
-        for key, value in kwargs.iteritems():
-            if key == 'name':
-                if value != self.sp.name:
-                    if self.user.is_admin or self.user.name == self.sp.owner:
-                        self._debug("Replacing %s: %s -> %s" %
-                                    (key, self.sp.name, value))
-                        self.sp.name = value
-                        save = True
-                    else:
-                        message = "Unauthorized to rename object"
-                        message_type = "error"
-                        return self.form_standard(message, message_type)
-
-            elif key == 'owner':
-                if value != self.sp.owner:
-                    if self.user.is_admin:
-                        self._debug("Replacing %s: %s -> %s" %
-                                    (key, self.sp.owner, value))
-                        self.sp.owner = value
-                        save = True
-                    else:
-                        message = "Unauthorized to set owner value"
-                        message_type = "error"
-                        return self.form_standard(message, message_type)
-
-            elif key == 'default_nameid':
-                if value != self.sp.default_nameid:
-                    if self.user.is_admin:
-                        self._debug("Replacing %s: %s -> %s" %
-                                    (key, self.sp.default_nameid, value))
-                        self.sp.default_nameid = value
-                        save = True
-                    else:
-                        message = "Unauthorized to set default nameid value"
-                        message_type = "error"
-                        return self.form_standard(message, message_type)
-
-            elif key == 'allowed_nameids':
-                v = set([x.strip() for x in value.split(',')])
-                if v != set(self.sp.allowed_nameids):
-                    if self.user.is_admin:
-                        self._debug("Replacing %s: %s -> %s" %
-                                    (key, self.sp.allowed_nameids, list(v)))
-                        self.sp.allowed_nameids = list(v)
-                        save = True
-                    else:
-                        message = "Unauthorized to set allowed nameids value"
-                        message_type = "error"
-                        return self.form_standard(message, message_type)
+        results = dict()
 
-        if save:
+        try:
+            for key, value in kwargs.iteritems():
+                if key == 'name':
+                    r = self.change_name(key, value)
+                    if r:
+                        results.update(r)
+                elif key == 'owner':
+                    r = self.change_owner(key, value)
+                    if r:
+                        results.update(r)
+
+                elif key == 'default_nameid':
+                    r = self.change_default_nameid(key, value)
+                    if r:
+                        results.update(r)
+
+                elif key == 'allowed_nameids':
+                    r = self.change_allowed_nameids(key, value)
+                    if r:
+                        results.update(r)
+
+        except InvalidValueFormat, e:
+            message = str(e)
+            message_type = "warning"
+            return self.form_standard(message, message_type)
+        except UnauthorizedUser, e:
+            message = str(e)
+            message_type = "error"
+            return self.form_standard(message, message_type)
+        except Exception, e:  # pylint: disable=broad-except
+            self._debug("Error: %s" % repr(e))
+            message = "Internal Error"
+            message_type = "error"
+            return self.form_standard(message, message_type)
+
+        if len(results) > 0:
             try:
+                if 'name' in results:
+                    self.sp.name = results['name']
+                if 'owner' in results:
+                    self.sp.owner = results['owner']
+                if 'default_nameid' in results:
+                    self.sp.default_nameid = results['default_nameid']
+                if 'allowed_nameids' in results:
+                    self.sp.allowed_nameids = results['allowed_nameids']
                 self.sp.save_properties()
+                if 'rename' in results:
+                    rename = results['rename']
+                    self.parent.rename_sp(rename[0], rename[1])
                 message = "Properties succssfully changed"
                 message_type = "success"
             except Exception:  # pylint: disable=broad-except
@@ -188,11 +254,6 @@ class SPAdminPage(Page):
 
         return self.form_standard(message, message_type)
 
-    def root(self, *args, **kwargs):
-        op = getattr(self, cherrypy.request.method, self.GET)
-        if callable(op):
-            return op(*args, **kwargs)
-
     def delete(self):
         self.parent.del_sp(self.sp.name)
         self.sp.permanently_delete()
@@ -216,6 +277,11 @@ class AdminPage(Page):
         self.providers.append(sp)
         return page
 
+    def rename_sp(self, oldname, newname):
+        page = getattr(self.sp, oldname)
+        self.sp.del_subtree(oldname)
+        self.sp.add_subtree(newname, page)
+
     def del_sp(self, name):
         try:
             page = getattr(self.sp, name)