[Kimchi-devel] [PATCH 3/5] Add functions to check if a user/group exists

Crístian Viana vianac at linux.vnet.ibm.com
Fri Feb 28 18:40:34 UTC 2014


The user/group validation is done on the current system.

Signed-off-by: Crístian Viana <vianac at linux.vnet.ibm.com>
---
 src/kimchi/auth.py          | 22 ++++++++++++++++++++++
 tests/test_authorization.py | 19 +++++++++++++++++++
 2 files changed, 41 insertions(+)

diff --git a/src/kimchi/auth.py b/src/kimchi/auth.py
index 990fa84..b783401 100644
--- a/src/kimchi/auth.py
+++ b/src/kimchi/auth.py
@@ -21,6 +21,7 @@ import base64
 import cherrypy
 import grp
 import PAM
+import pwd
 import re
 
 
@@ -78,6 +79,27 @@ class User(object):
     def get_user(self):
         return self.user
 
+    def exists(self):
+        try:
+            pwd.getpwnam(self.user[USER_NAME])
+        except KeyError:
+            return False
+        else:
+            return True
+
+
+class Group(object):
+    def __init__(self, groupname):
+        self.groupname = groupname
+
+    def exists(self):
+        try:
+            grp.getgrnam(self.groupname)
+        except KeyError:
+            return False
+        else:
+            return True
+
 
 def authenticate(username, password, service="passwd"):
     '''Returns True if authenticate is OK via PAM.'''
diff --git a/tests/test_authorization.py b/tests/test_authorization.py
index b211e06..ab98987 100644
--- a/tests/test_authorization.py
+++ b/tests/test_authorization.py
@@ -17,14 +17,17 @@
 # License along with this library; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
 
+import grp
 import json
 import os
+import pwd
 import unittest
 
 
 from functools import partial
 
 
+import kimchi.auth
 import kimchi.mockmodel
 from utils import get_free_port, patch_auth, request
 from utils import run_server
@@ -119,3 +122,19 @@ class AuthorizationTests(unittest.TestCase):
         self.assertEquals(403, resp.status)
         resp = self.request('/vms', '{}', 'DELETE')
         self.assertEquals(403, resp.status)
+
+
+class CurrentUserGroupTests(unittest.TestCase):
+    def test_current_user(self):
+        current_user = pwd.getpwuid(os.getuid()).pw_name
+        self.assertTrue(kimchi.auth.User(current_user).exists())
+
+        invalid_user = "userdoesnotexist"
+        self.assertFalse(kimchi.auth.User(invalid_user).exists())
+
+    def test_current_group(self):
+        current_group = grp.getgrgid(os.getgid()).gr_name
+        self.assertTrue(kimchi.auth.Group(current_group).exists())
+
+        invalid_group = "groupdoesnotexist"
+        self.assertFalse(kimchi.auth.Group(invalid_group).exists())
-- 
1.8.5.3




More information about the Kimchi-devel mailing list