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

Crístian Viana vianac at linux.vnet.ibm.com
Wed Feb 26 18:09:51 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 6f34772..d7f5845 100644
--- a/src/kimchi/auth.py
+++ b/src/kimchi/auth.py
@@ -26,6 +26,7 @@ import base64
 import cherrypy
 import grp
 import PAM
+import pwd
 import re
 
 
@@ -83,6 +84,27 @@ class User(object):
     def get_user(self):
         return self.user
 
+    def exists(self):
+        try:
+            pwd.getpwnam(self.user[USER_ID])
+        except KeyError:
+            return False
+        else:
+            return True
+
+
+class Group(object):
+    def __init__(self, groupid):
+        self.groupid = groupid
+
+    def exists(self):
+        try:
+            grp.getgrnam(self.groupid)
+        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 24ce4bd..a93dad2 100644
--- a/tests/test_authorization.py
+++ b/tests/test_authorization.py
@@ -20,14 +20,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
@@ -122,3 +125,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