root/lib/octofuss/users/__init__.py @ 28cfe355619da2e37dce8d3b8abd71da1de72ea3

Revision 28cfe355619da2e37dce8d3b8abd71da1de72ea3, 101.2 KB (checked in by iacopo <iacopo@…>, 6 years ago)

git-svn-id:  https://labs.truelite.it/svn/octofuss/trunk@340 5a101938-5c21-0410-9b5a-a83d6f3706a9

  • Property mode set to 100644
Line 
1#!/usr/bin/env python
2# -*- coding: latin-1 -*-
3#
4#
5#  File: __init__.py
6#
7#  Copyright (C) 2007 Iacopo Pecchi <iacopo@truelite.it>
8#
9#  This program is free software; you can redistribute it and/or modify
10#  it under the terms of the GNU General Public License as published by
11#  the Free Software Foundation; either version 2 of the License, or
12#  (at your option) any later version.
13#
14
15
16import os
17#import subprocess
18import datetime
19import gtk
20from octofuss.error import UserError
21from octofuss.error import GroupError
22from octofuss.error import LdapError
23from octofuss.error import MissingPermission
24from octofuss.error import MissingConfigurationFile
25from octofuss.error import ConfigurationError
26
27from octofuss import ldap
28
29from octofuss.ldap import objectclass
30from octofuss.ldap.objectclass import *
31
32
33passwdfile="/etc/passwd"
34shadowfile="/etc/shadow"
35groupfile="/etc/group"
36startUnixUID = 3000
37startLdapUID = 20000
38supLimit = 40000
39
40class Entry:
41        #An  has some objectClass associated with him.
42        # First: add all objectClasses
43        def __init__(self):
44                """ Default constructor. Name is a string, Groups is a list of Group object """
45                self.objectClass = {}
46
47        def __addObjectClass(self, name, objectClass):
48                """ Add an object class to entry """
49                if not self.objectClass.has_key(name):
50                        self.objectClass[name] = objectClass
51                else:
52                        raise UserError("User objectClass already present!")
53
54        def getRequiredAttrs(self):
55                """ Return a dictionary of required attributes without repetitions """
56                req = {}       
57                for obj in self.objectClass.keys():
58                # For each objectClass
59                        for attr in self.objectClass[obj].getRequiredAttrs().values():
60                        # For each required attribute
61                                if not req.has_key(attr.getName()):
62                                        req[attr.getName()]=attr                               
63                return req
64
65        def getOptionalAttrs(self):
66                """ Return a dictionary of optional attributes without repetitions """
67                opt = {}       
68                for obj in self.objectClass:
69                # For each objectClass
70                        for attr in self.objectClass[obj].getOptionalAttrs().values():
71                        # For each required attribute
72                                if not opt.has_key(attr.getName()):
73                                        opt[attr.getName()]=attr                               
74                return opt
75
76
77        def setAttribute(self, key, value, check=True):
78                """ Set the value for the attribute for each objectClass (set the value for all repetitions) """
79                found = False
80                if isinstance(value, Attribute):
81                        #For each object class
82                        for objKey in self.objectClass.keys():
83                                # If key found
84                                if key in self.objectClass[objKey].required.keys():
85                                        found = True
86                                        self.objectClass[objKey].required[key] = value
87                                if key in self.objectClass[objKey].optional.keys():
88                                        found = True
89                                        self.objectClass[objKey].optional[key] = value
90
91                        if not found:
92                                raise UserError("Could not set user attribute: object class key not found")
93                else:
94                        if isinstance(value, str):
95                                #For each object class
96                                for objKey in self.objectClass.keys():
97                                        # If key found
98                                        if key in self.objectClass[objKey].required.keys():
99                                                found = True
100                                                self.objectClass[objKey].required[key].setValue(value,check)
101                                        if key in self.objectClass[objKey].optional.keys():
102                                                found = True
103                                                self.objectClass[objKey].optional[key].setValue(value,check)
104                                if not found:
105                                        raise UserError("Could not set user attribute: object class key not found")
106                        else:
107                                raise UserError("Value is not a valid attribute!")
108                                         
109
110        def getAttribute(self, key):
111                """ Get the value of an attribute """
112                values = []
113                # For each objectClass
114                for obj in self.objectClass.keys(): 
115                        if self.objectClass[obj].required.has_key(key):
116                                values.append(self.objectClass[obj].required[key])
117                        if self.objectClass[obj].optional.has_key(key):
118                                values.append(self.objectClass[obj].optional[key])
119                #print "\nVal: ", values[0]
120                return values[0] 
121
122        def getDict(self):
123                """ Return user in a dict. This is used during inserting user in ldap """
124                dictionary = {}
125                for obj in self.objectClass.keys():
126                        for attr in self.objectClass[obj].required.keys():
127                                if self.objectClass[obj].required[attr].getValue():
128                                        dictionary[attr] =  self.objectClass[obj].required[attr].getValue() 
129
130                        for attr in self.objectClass[obj].optional.keys():
131                                if self.objectClass[obj].optional[attr].getValue():
132                                        dictionary[attr] =  self.objectClass[obj].optional[attr].getValue() 
133                dictionary['objectClass'] = self.objectClass.keys()
134               
135                return dictionary
136
137        def getDictLdapForm(self):
138                """ Return user in a dict. This is used during inserting user in ldap """
139                dictionary = {}
140                for obj in self.objectClass.keys():
141                        for attr in self.objectClass[obj].required.keys():
142                                if self.objectClass[obj].required[attr].getValue():
143                                        if type( self.objectClass[obj].required[attr].getValue()) == list:
144                                                dictionary[attr] =  self.objectClass[obj].required[attr].getValue() 
145                                        else:
146                                                dictionary[attr] =  [self.objectClass[obj].required[attr].getValue()] 
147
148
149                        for attr in self.objectClass[obj].optional.keys():
150                                if self.objectClass[obj].optional[attr].getValue():
151                                        if type(self.objectClass[obj].optional[attr].getValue()) == list:
152                                                dictionary[attr] =  self.objectClass[obj].optional[attr].getValue() 
153                                        else:
154                                                dictionary[attr] = [self.objectClass[obj].optional[attr].getValue()]
155 
156                dictionary['objectClass'] = self.objectClass.keys()
157               
158                return dictionary
159
160        def check(self):
161                """ Check every attribute of each object class """
162                for objClass in self.objectClass.keys():        # Each object class
163                        for attr in self.objectClass[objClass].required.keys():  # Each required attribute
164                                if not self.objectClass[objClass].required[attr].check():
165                                        print "REQ: "+ attr
166                                        print  self.objectClass[objClass].required[attr].getValue()
167                                        return False
168       
169                        for attr in self.objectClass[objClass].optional.keys():  # Each optional attribute
170                                if self.objectClass[objClass].optional[attr].getValue():
171                                        if not self.objectClass[objClass].optional[attr].check() and isSettable():
172                                                print "OPT: " +attr
173                                                print self.objectClass[objClass].optional[attr].getValue()
174                                                return False
175                                       
176                return True
177
178                               
179                               
180                                 
181
182
183
184                                       
185         
186class UnixUser(Entry):
187        def __init__(self):
188                Entry.__init__(self)
189                self.objectClass['posixAccount'] = objectclass.PosixAccount()
190
191        def getName(self):
192                return self.objectClass['posixAccount'].getAttribute('cn')
193
194        def getPassword(self):
195                return self.objectClass['posixAccount'].getAttribute('userPassword')
196               
197        def getUid(self):
198                return self.objectClass['posixAccount'].getAttribute('uid')
199
200        def getUidNumber(self):
201                return self.objectClass['posixAccount'].getAttribute('uidNumber')
202
203        def getGid(self):
204                return self.objectClass['posixAccount'].getAttribute('gidNumber')
205
206        def getGecos(self):
207                return self.objectClass['posixAccount'].getAttribute('gecos')
208
209        def getHome(self):
210                return self.objectClass['posixAccount'].getAttribute('homeDirectory')
211
212        def getShell(self):
213                return self.objectClass['posixAccount'].getAttribute('loginShell')
214
215        def getAttribute(self, objectClass, attribute):
216                """ Return attribute's value if attribute exists. """
217                try:   
218                       return self.objectClass[objectClass].getAttribute(attribute)
219                except:
220                       return None
221
222
223       
224class LdapUser(UnixUser):
225        def __init__(self):
226                UnixUser.__init__(self)
227                #self.objectClass['top'] = objectclass.Top()
228                self.objectClass['inetOrgPerson'] = objectclass.InetOrgPerson()
229                self.objectClass['shadowAccount'] = objectclass.ShadowAccount()
230                self.objectClass['sambaSamAccount'] = objectclass.SambaSamAccount()
231
232
233class UnixGroup(Entry):
234        def __init__(self):
235                Entry.__init__(self)
236                self.objectClass['posixGroup'] = objectclass.PosixGroup()
237
238        def getName(self):
239                return self.objectClass['posixGroup'].getAttribute('cn')
240
241        def getGid(self):
242                return self.objectClass['posixGroup'].getAttribute('gidNumber')               
243
244        def getUsersList(self):
245                return self.objectClass['posixGroup'].getAttribute('memberUid')
246
247        def setUserList(self, userlist):
248                """ Set memberUid attribute to userlist """
249                if isinstance(userlist, list):
250                        self.objectClass['posixGroup'].getAttribute('memberUid').setValue(userlist)
251                else:
252                        raise GroupError("Argument is not a list")
253
254        def hasUser(self, userName):
255                """ Returns true if group contains username """
256                if userName and isinstance(userName, str):
257                        if userName in self.objectClass['posixGroup'].getAttribute("memberUid").getValue():
258                                return True
259                        else:
260                                return False
261                else:
262                        raise UserError("Invalid username argument")
263       
264               
265
266        def addUser(self, user):
267                if isinstance(user, str):
268                        if not self.hasUser(user):
269                                self.objectClass['posixGroup'].getAttribute('memberUid').setValue(user)
270                else:
271                        raise GroupError("Argument is not a list")
272
273               
274
275       
276        def removeUser(self,userName):
277                """ Remove user from memberUid attribute list """
278                if userName and isinstance(userName, str):
279                        userlist = self.objectClass['posixGroup'].getAttribute('memberUid').getValue() 
280                        if userName in userlist:
281                                ind = userlist.index(userName)
282                                del(userlist[ind])
283                                self.setUserList(userlist)
284                        else:
285                                raise UserError("User not in group")
286                else:
287                        raise UserError("Not a valid username")
288               
289
290
291class LdapGroup(UnixGroup):
292        def __init__(self):
293                UnixGroup.__init__(self)
294                self.objectClass['sambaGroupMapping'] = objectclass.SambaGroupMapping()
295
296
297
298
299
300def __groups():
301        """ Creates group list """
302        groupList = {}
303        data = os.popen("cat "+groupfile,"r").readlines()
304        for line in data:
305                groupName,password,gid,usersString = line.strip().split(":")
306                if usersString == "":
307                        users = []
308                else: 
309                        users = usersString.split(",")
310                group = UnixGroup()
311                group.setAttribute("cn",groupName)
312                group.setAttribute("gidNumber",gid)
313                for us in users: 
314                        group.setAttribute("memberUid",us)
315
316                if groupList.has_key(group.getName().getValue()):
317                        raise GroupError("Duplicate group in unix group file")
318
319                groupList[groupName]=group
320                #print "Unix group: ", group.getAttribute("cn").getValue(),  group.getAttribute("userPassword").getValue(),  group.getAttribute("gidNumber").getValue(),group.getAttribute("memberUid").getValue()
321
322
323
324        return groupList
325
326
327def __ldap_group():
328        """ Create ldap groups """ 
329       
330        list = ldap.search(filter="(objectClass=posixGroup)", findattr=[])
331        objectList = {}
332        for group in list:
333                try:
334                        print group
335                        ldapgroup = LdapGroup()
336                        req = ldapgroup.getRequiredAttrs()
337                        opt = ldapgroup.getOptionalAttrs()
338
339                        # Insert required attributes
340                        for param in req.keys():
341                                try:
342                                        # The value of param could is a list. We have to decide when attribute is multiple.
343                                        if isinstance(req[param], ListAttribute):
344                                                value = group[0][1][param]                                       
345                                                for elem in value:
346                                                        ldapgroup.setAttribute(param,elem)
347
348                                        else:
349                                                value = group[0][1][param][0]                                       
350                                                ldapgroup.setAttribute(param,value)
351
352                                except:
353                                        raise GroupError("Could not add ldap group: required attribute missing!")
354
355                        # Insert optional attributes
356                        attrs_missing = []
357                        for param in opt.keys():
358                                try:
359                                        # The value of param could is a list. We have to decide when attribute is multiple.
360                                        if isinstance(opt[param], ListAttribute):
361                                                value = group[0][1][param]                                       
362                                                for elem in value:
363                                                        ldapgroup.setAttribute(param,elem)
364
365                                        else:
366                                                value = group[0][1][param][0]                                       
367                                                ldapgroup.setAttribute(param,value)
368
369                                except:
370                                        attrs_missing.append(param)
371                                        #print "Attribute %s not found"  % param
372
373                        #print "Ldap Group added: ", ldapgroup.getName().getValue()
374
375                except GroupError, e:
376                        print e
377                        try:
378                                p = ""
379                                for i in attrs_missing: p = p +" "+ i
380                                print "Group  not  added: option missing:\n"+p
381                                print group
382
383                        except:
384                                print "eccezione"
385                                pass
386                        continue
387                except NameError:
388                        print "Group not added: empty name"
389                        continue 
390                       
391
392                if objectList.has_key(ldapgroup.getName().getValue()):
393                        raise GroupError("Duplicate group name in ldap server")
394
395                # add user to list
396                objectList[ldapgroup.getName().getValue()]=ldapgroup
397 
398                 
399        return objectList
400
401
402
403def __ldap_user():
404        # Manca da convertire l'assegnazione dei parametri come viene fatto nella funzione di creazione gruppi ldap.
405        list = ldap.search(filter="(uid=*)", findattr=[])
406
407        objectList = {} 
408        # Parsing the list and create users object
409        for user in list:
410                #print user,"\n"
411                try:
412                        ldapuser = LdapUser()
413                        req = ldapuser.getRequiredAttrs()
414                        opt = ldapuser.getOptionalAttrs()
415
416
417                        # Insert required attributes
418                        for param in req.keys():
419                                try:
420                                        # The value of param could is a list. We have to decide when attribute is multiple.
421                                        if isinstance(req[param], ListAttribute):
422                                                value = user[0][1][param]                                       
423                                                for elem in value:
424                                                        ldapuser.setAttribute(param,elem)
425
426                                        else:
427                                                value = user[0][1][param][0]                                       
428                                                ldapuser.setAttribute(param,value)
429
430                                except Exception,e:
431                                        raise UserError(str(e))
432                                       
433
434                        # Insert optional attributes
435                        for param in opt.keys():
436                                try:
437                                        # The value of param could is a list. We have to decide when attribute is multiple.
438                                        if isinstance(opt[param], ListAttribute):
439                                                value = user[0][1][param]                                       
440                                                for elem in value:
441                                                        ldapuser.setAttribute(param,elem)
442
443                                        else:
444                                                value = user[0][1][param][0]                                       
445                                                ldapuser.setAttribute(param,value)
446
447                                except:
448                                        pass
449                                        #print "Attribute %s not found"  % param
450
451                        #print "Ldap User added: ", ldapuser.getName().getValue()
452
453                except UserError, e:
454                        print "Warning: User '"+ldapuser.getUid().getValue()+"' not added. Option missing: "+str(e)
455                        continue
456                except NameError:
457                        print "User not added: empty name"
458                        continue 
459
460                # add user to list
461                if objectList.has_key(ldapuser.getName().getValue()):
462                        raise UserError("Incongruous ldap tree\nDuplicate user name in ldap server: "+ldapuser.getName().getValue())
463                objectList[ldapuser.getName().getValue()]=ldapuser
464 
465                 
466        return objectList
467
468 
469def showDialog(message, type):
470        dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,type, gtk.BUTTONS_OK, message)
471        dialog.run()
472        dialog.destroy()   
473       
474
475
476def __local():
477        """ Create unix user list """
478        global grouplist
479        global passwdfile
480        userlist = {}
481        data = os.popen("cat "+passwdfile,"r").readlines()
482        for line in data:
483                #User groups
484                found = False
485                username,password,uid,gid,gecos,home,shell = line.strip().split(":")
486
487                user = UnixUser()
488                # Setting user attributes
489                user.setAttribute("cn",username)
490                #user.setAttribute("userPassword",password)
491                user.setAttribute("homeDirectory",home)
492                user.setAttribute("loginShell",shell)
493                user.setAttribute("gecos",gecos)       
494                user.setAttribute("gidNumber",gid)   
495                user.setAttribute("uidNumber",uid)       
496                # Set uidNumber to username
497                user.setAttribute("uid",username)       
498   
499
500
501
502                if userlist.has_key(user.getName().getValue()):
503                        raise UserError("Duplicate user in unix user file")
504                userlist[user.getName().getValue()]= user
505                #print "Unix user: ", user.getAttribute("cn").getValue(),  user.getAttribute("userPassword").getValue(), user.getAttribute("uidNumber").getValue(), user.getAttribute("gidNumber").getValue() , user.getAttribute("gecos").getValue(),  user.getAttribute("homeDirectory").getValue(),user.getAttribute("loginShell").getValue()
506
507
508        return userlist
509
510if not (os.access(passwdfile,os.F_OK)):
511        raise MissingConfigurationFile("Missing configuration file!")
512#if not (os.access(shadowfile,os.F_OK)):
513#        raise MissingConfigurationFile("Missing configuration file!")
514if not (os.access(groupfile,os.F_OK)):
515        raise MissingConfigurationFile("Missing configuration file!")
516
517"""
518if not (os.access(passwdfile,os.R_OK) and os.access(passwdfile,os.W_OK)):
519        raise MissingPermission("Missing permissions on configuration file!")
520
521if not (os.access(shadowfile,os.R_OK) and os.access(shadowfile,os.W_OK)):
522        raise MissingPermission("Missing permissions on configuration file!")
523
524if not (os.access(groupfile,os.R_OK) and os.access(groupfile,os.W_OK)):
525        raise MissingPermission("Missing permissions on configuration file!")
526"""
527
528def __getCurrentId():
529        """ Return the id of the octofuss user """
530        out = os.popen("id -u")
531        id = out.read()
532        res = int(id)
533
534        #out = subprocess.Popen("id -u", stdout=subprocess.PIPE, shell=True )
535        #res = int(out.communicate()[0])
536        return res
537
538
539if not __getCurrentId() == 0:
540        raise MissingPermission("Missing permission to manage users")
541# First = create UNIX groups
542grouplist =  __groups()
543# Second = create LDAP groups
544ldapgrouplist = __ldap_group()
545#Third = create LDAP users
546ldaplist = __ldap_user()
547#Fourth = create UNIX users
548locallist =  __local()
549
550
551def updateMainGroup():
552        """ Add user name to memberUid of local group because main group is never added before """
553        global locallist
554        global grouplist
555        for user in locallist:
556                gid = locallist[user].getGid().getValue()
557                for group in  grouplist.keys():
558                        if gid ==  grouplist[group].getGid().getValue():
559                                #Adding main group to group list
560                                grouplist[group].setAttribute("memberUid",locallist[user].getName().getValue())                 
561
562
563updateMainGroup()
564
565
566
567class  InheritableSingleton (object):
568    instances = {}
569
570    def __new__(cls, *args, **kargs): 
571        """ Singleton that create a user and a group list """
572        if InheritableSingleton.instances.get(cls) is None:
573                InheritableSingleton.instances[cls] = object.__new__(cls, *args, **kargs)
574                global grouplist     
575                global locallist
576                global ldaplist
577                global ldapgrouplist
578                InheritableSingleton.instances["groupList"]=  grouplist
579                InheritableSingleton.instances["ldapGroupList"]=  ldapgrouplist
580                InheritableSingleton.instances["ldapList"]= ldaplist
581                InheritableSingleton.instances["unixList"]= locallist
582
583               
584
585
586        return InheritableSingleton.instances[cls]
587                       
588
589class Backend(InheritableSingleton):
590               
591        global passwdfile
592        global shadowfile
593        global groupfile
594        ldapUid = startLdapUID
595        ldapMaxUid = supLimit
596        def groupsByUser(self, username):
597                """ Search all groups of username """
598                if self.isUser(username):
599
600                        groups = []
601                        # Unix groups
602                        for group in InheritableSingleton.instances['groupList'].keys():
603                                if username in InheritableSingleton.instances['groupList'][group].getUsersList().getValue():
604                                        groups.append(group)
605                        # Ldap groups
606                        for group in InheritableSingleton.instances['ldapGroupList'].keys():
607                                if username in InheritableSingleton.instances['ldapGroupList'][group].getUsersList().getValue():
608                                        groups.append(group)
609                        #We must add if is not already present "main user group"
610                        #print self.getUser(username).getName().getValue()
611                        #print self.getUser(username).getGid().getValue()
612
613                        mainGroupName = self.getGroupByGid(self.getUser(username).getGid().getValue()).getName().getValue()
614                        if mainGroupName:
615                                if not mainGroupName in groups:
616                                        groups.append(mainGroupName)
617                       
618                        return groups
619                               
620                else:
621                        raise UserError("User doesn't exist!")
622
623        def usersByGroup(self,groupname):
624                """ Search all users of group """
625                group = self.getGroup(groupname)
626                return group.getUsersList().getValue()
627       
628        def getUsersList(self):
629                """ Print a sorted list of users """
630                list = []
631                list = InheritableSingleton.instances['unixList'].keys() +  InheritableSingleton.instances['ldapList'].keys() 
632
633                list.sort()
634                return list
635                       
636
637        def getLdapUsers(self):
638                """ Print a sorted list of ldap users """
639                list = []
640                list =  InheritableSingleton.instances['ldapList'].keys() 
641                list.sort()
642                return list
643
644        def getUnixUsers(self):
645                """ Print a sorted list of unix users """
646                list = []
647                list = InheritableSingleton.instances['unixList'].keys() 
648                list.sort()
649                return list
650
651        def getGroupsList(self):
652                """ Print a sorted list of groups """
653                list = []
654                list = InheritableSingleton.instances['groupList'].keys() +  InheritableSingleton.instances['ldapGroupList'].keys() 
655                list.sort()
656                return list
657
658
659        def getLdapGroups(self):
660                """ Print a sorted list of ldap groups """
661                list = []
662                list =  InheritableSingleton.instances['ldapGroupList'].keys() 
663                list.sort()
664                return list
665
666
667        def getUnixGroups(self):
668                """ Print a sorted list of unix groups """
669                list = []
670                list = InheritableSingleton.instances['groupList'].keys() 
671                list.sort()
672                return list
673
674        def isUnixUser(self,username):
675                """ Returns true if username user exists """
676                if username in InheritableSingleton.instances['unixList'].keys():
677                        return True
678                else:
679                        return False
680
681        def isLdapUser(self,username):
682                """ Returns true if username user exists """
683                if username in InheritableSingleton.instances['ldapList'].keys():
684                        return True
685                else:
686                        return False
687
688        def isUnixGroup(self,groupname):
689                """ Returns true if username user exists """
690                if groupname in InheritableSingleton.instances['groupList'].keys():
691                        return True
692                else:
693                        return False
694
695        def isLdapGroup(self,groupname):
696                """ Returns true if username user exists """
697                if groupname in InheritableSingleton.instances['ldapGroupList'].keys():
698                        return True
699                else:
700                        return False
701
702
703
704        def isUser(self, username):
705                """ Returns true if username user exists """
706                if username in InheritableSingleton.instances['unixList'].keys() or username in InheritableSingleton.instances['ldapList'].keys():
707                        return True
708                else:
709                        return False
710
711        def isGroup(self, groupname):
712                """ Returns if groupname group exists """
713                if groupname in InheritableSingleton.instances['groupList'].keys() or groupname in InheritableSingleton.instances['ldapGroupList'].keys():
714                        return True
715                else:
716                        return False
717
718        def getUser(self, username):               
719                """ Returns UnixUser or LdapUser from given username """
720                if self.isUser(username):
721                        for user in  InheritableSingleton.instances['unixList'].keys():
722                                if username == user:
723                                        return InheritableSingleton.instances['unixList'][username]
724
725                        for user in InheritableSingleton.instances['ldapList']:
726                                if username == user:
727                                        return InheritableSingleton.instances['ldapList'][username]
728                else:
729                        raise UserError("User doesn't exist!")
730
731        def getGroup(self, groupname):
732                """ Returns UnixGroup or LdapGroup from given groupname """
733                if self.isGroup(groupname):
734                        for group in  InheritableSingleton.instances['groupList'].keys():
735                                if groupname == group:
736                                        return InheritableSingleton.instances['groupList'][groupname]
737
738                        for group in InheritableSingleton.instances['ldapGroupList']:
739                                if groupname == group:
740                                        return InheritableSingleton.instances['ldapGroupList'][groupname]
741                else:
742                        raise GroupError("Group doesn't exist!")
743
744        def getGroupByGid(self, gid):
745                """ Returns group by gid=groupId """
746                for group in  InheritableSingleton.instances['groupList'].keys():
747                        if gid ==  InheritableSingleton.instances['groupList'][group].getGid().getValue():
748                                return InheritableSingleton.instances['groupList'][group]
749
750                for group in  InheritableSingleton.instances['ldapGroupList'].keys():
751                        if gid ==  InheritableSingleton.instances['ldapGroupList'][group].getGid().getValue():
752                                return InheritableSingleton.instances['ldapGroupList'][group]
753
754                raise GroupError("Given gid doesn't exist!")
755       
756
757        # Promemoria da cancellare
758        # Seguono dei metodi privati che aggiungono, modificano, cancellano utenti e gruppi Unix utilizzando
759        # i binari useradd, userdel, usermod e groupadd, groupdel, groupmod
760        # Questi metodi non aggiornano la lista di oggetti in memoria e non creano le home directory degli utenti
761       
762        def __addUnixGroup(self, groupname, gid="" ):
763                """ Add  a unix group to local system """ 
764                """ This method use groupadd. groupadd doesn't add users to /etc/group """
765                if gid:
766                        #p = subprocess.Popen("groupadd" + " -g "+ gid +" "+groupname , shell=True)
767                        sts = os.system("groupadd" + " -g " + gid +" "+groupname)
768                        if sts != 0:
769                        #sts = os.waitpid(p.pid, 0)
770                        #if sts[1] != 0:
771                                raise GroupError("Problems adding group!")
772                else:
773                        #p = subprocess.Popen("groupadd" +" "+groupname , shell=True)
774                        sts = os.system("groupadd" +" "+groupname)
775                        if sts != 0:
776                        #sts = os.waitpid(p.pid, 0)
777                        #if sts[1] != 0:
778                                raise GroupError("Problems adding group!")
779
780        def __deleteUnixGroup(self, groupname):
781                """ Remove group from local system """
782                sts = os.system("groupdel" +" "+groupname)
783                if sts != 0:
784                #p = subprocess.Popen("groupdel " + groupname , shell=True)
785                #sts = os.waitpid(p.pid, 0)
786                #if sts[1] != 0:
787                        raise GroupError("Problems deleteing group!") 
788
789        def __modifyUnixGroup(self, oldname, newname):
790                """ Modify the name of group  """
791                sts = os.system("groupmod" +" -n "+newname+" "+oldname)
792                if sts != 0:
793                #p = subprocess.Popen("groupmod" +" -n "+newname+" "+oldname, shell=True)
794                #sts = os.waitpid(p.pid, 0)
795                #if sts[1] != 0:
796                        raise GroupError("Problems modifying group!")
797
798               
799               
800       
801        def __addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
802                """ Add unix user """
803                useradd = "useradd "
804                string  = "" 
805               
806                 
807                if username and password:
808                       
809                        string = username+":"+password+"\n" 
810                       
811                        if home:
812                                useradd = useradd + " -d " + home + " "
813                        else:
814                                useradd = useradd + " -d " + "/nonexistent" + " "
815
816                        useradd = useradd + " -s " + shell + " "
817
818                        if gid:
819                                useradd = useradd + " -g "+ gid + " "
820
821                        if uid:
822                                useradd = useradd + " -u "+ uid + " "
823
824                        groups = ""
825                        if len(grouplist) > 0:
826                                for a in grouplist:
827                                       groups = groups + a+"," 
828                                groups = groups.strip(",")
829                                useradd = useradd + " -G "+ groups + " "
830                        useradd = useradd + username
831                        print useradd
832                        sts = os.system(useradd)
833                        if sts != 0:
834                        #p = subprocess.Popen(useradd, shell=True)
835                        #sts = os.waitpid(p.pid, 0)               
836                        #if sts[1] != 0:
837                                print "Removing user..."
838                                os.system("userdel "+username)
839                                raise UserError("Problem adding user!")
840                else:
841                        raise UserError("Username or password not valid!")
842                       
843                p = os.popen("chpasswd",'w') 
844                p.write(string)
845                p.close()
846                #p = subprocess.Popen("chpasswd",shell=True, stdin=subprocess.PIPE).communicate(input=string)
847                #print p
848               
849               
850                 
851
852        def createHomeDirectory(self, name, uid, gid, path="/home"):
853                """ Create home directory with owner and group """
854                # Check if home already exists
855                if name:
856                        dir = os.path.join(path,name)
857                        if not os.path.isdir(dir):
858                                #os.mkdir(dir)
859                                os.system("/bin/cp -a /etc/skel "+dir)
860                                os.chown(dir, int(uid), int(gid))
861                                os.system("chown -R "+uid+"."+gid+" "+dir)
862                                os.chmod(dir,0700)
863                               
864                        else:
865                                raise UserError("Home directory "+dir+" already exists!")
866                else:
867                        raise UserError("Directory  must be not null!")
868
869
870
871        def getNewUnixID(self):
872                """ Get a new unix id returning max of ID + 1. Check Unix and Ldap users ID """       
873                # Inferior limit of Unix UID
874                global startUnixUID
875                # Inferior limit of Ldap UID
876                global startLdapUID
877
878                all = []               
879                # ALL = UnixUID + LdapUID
880                for unixUser in  InheritableSingleton.instances["unixList"].keys():
881                        uid =  int(InheritableSingleton.instances["unixList"][unixUser].getUidNumber().getValue())
882                        if uid < startLdapUID:
883                                all.append(int(uid))
884
885                for ldapUser in  InheritableSingleton.instances["ldapList"].keys():
886                        uid =  int(InheritableSingleton.instances["ldapList"][ldapUser].getUidNumber().getValue())
887                        if uid < startLdapUID:
888                                all.append(int(uid))
889
890                for unixGroup in  InheritableSingleton.instances["groupList"].keys():
891                        uid =  int(InheritableSingleton.instances["groupList"][unixGroup].getGid().getValue())
892                        if uid < startLdapUID:
893                                all.append(int(uid))
894
895                for ldapGroup in  InheritableSingleton.instances["ldapGroupList"].keys():
896                        uid =  int(InheritableSingleton.instances["ldapGroupList"][ldapGroup].getGid().getValue())
897                        if uid < startLdapUID:
898                                all.append(int(uid))
899                       
900
901                # NewUID = MAX(ALL) + 1
902                if all:
903                        newUid = max(all) + 1
904                else:
905                        newUid = 1 
906               
907                # If NewUID < Inf Unix   =>   NewUID = Inf Unix
908                if newUid < startUnixUID:
909                        newUid = startUnixUID
910
911                # If NewUID > Inf Ldap   =>   End of possible values! CHANGE USERS RANGE
912                if newUid >= startLdapUID:
913                        raise ConfigurationError("No more UID available. Check range!")
914
915       
916                # Return NewUID
917                return newUid
918
919
920
921        def getNewLdapID(self):
922                """ Get a new unix id returning max of ID + 1. Check Unix and Ldap users ID """       
923                # Inferior limit of Unix UID
924                global startUnixUID
925                # Inferior limit of Ldap UID
926                global startLdapUID
927                maxLimit = supLimit # Set to avoid nobody user with id > 60000
928                all = []               
929                # ALL = UnixUID + LdapUID
930                for unixUser in  InheritableSingleton.instances["unixList"].keys():
931                        uid =   int(InheritableSingleton.instances["unixList"][unixUser].getUidNumber().getValue())
932                        if uid >= startLdapUID and uid < maxLimit:
933                                all.append(int(uid))
934
935                for ldapUser in  InheritableSingleton.instances["ldapList"].keys():
936                        uid =   int(InheritableSingleton.instances["ldapList"][ldapUser].getUidNumber().getValue())
937                        if uid >= startLdapUID and uid < maxLimit:
938                                all.append(int(uid))
939
940
941                for unixGroup in  InheritableSingleton.instances["groupList"].keys():
942                        uid =  int(InheritableSingleton.instances["groupList"][unixGroup].getGid().getValue())
943                        if uid >= startLdapUID and uid < maxLimit:
944                                all.append(int(uid))
945
946
947
948                for ldapGroup in  InheritableSingleton.instances["ldapGroupList"].keys():
949                        uid =  int(InheritableSingleton.instances["ldapGroupList"][ldapGroup].getGid().getValue())
950                        if uid >= startLdapUID and uid < maxLimit:
951                                all.append(int(uid))
952
953
954
955
956                if all:
957                        # NewUID = MAX(ALL) + 1
958                        newUid = max(all) + 1
959                else:
960                        newUid = 1
961               
962                # If NewUID < Inf Unix   =>   NewUID = Inf Unix
963                if newUid < startLdapUID:
964                        newUid = startLdapUID
965
966                # If NewUID > Inf Ldap   =>   End of possible values! CHANGE USERS RANGE
967                if newUid >= maxLimit:
968                        raise ConfigurationError("No more UID available. Check range!")
969
970       
971                # Return NewUID
972                return newUid
973
974
975        """   
976        def getNewLdapUid(self):
977                global startLdapUID
978                list = []
979                for ldapUser in  InheritableSingleton.instances["ldapList"].keys():
980                        uid = InheritableSingleton.instances["ldapList"][ldapUser].getUidNumber().getValue()
981                        list.append(int(uid))
982                print list
983                value = max(list)
984                newValue = value + 1
985                if newValue < int(startLdapUID):
986                        if newValue >= 65000:
987                                raise UserError("Problem, ldap uid too big...!!")
988                        if not int(startLdapUID) in list:
989                                return int(startLdapUID)
990                else:
991                        return newValue
992        """
993               
994               
995               
996
997        def __deleteUnixUser(self, username, dir=False):
998                """ Delete unix group """ 
999                if username:
1000                        user = username
1001                        if dir:
1002                                user = "-r "+user
1003                        p = subprocess.Popen("userdel "+user, shell=True)
1004                        sts = os.waitpid(p.pid, 0)             
1005                        if sts[1] != 0:
1006                                raise UserError("Problem deleting user!")
1007                else:
1008                        raise UserError("Username must be not empty!")
1009
1010
1011        def __modifyUnixUser(self, username, grouplist=[], newname="" ):
1012                """ Modify username and group of user """
1013                if username:
1014                        usermod = "usermod"
1015                        if ( not grouplist ) and ( not newname):
1016                                raise UserError("You have to pass something to change to this method")
1017                        groups = ""
1018                        if len(grouplist) > 0:
1019                                for a in grouplist:
1020                                       groups = groups + a+"," 
1021                                groups = groups.strip(",")
1022                                usermod = usermod + " -G "+ groups + " "
1023                        if newname:
1024                                usermod = usermod + " -l " + newname + " " + username
1025                        else:
1026                                usermod = usermod + " " + username
1027                        #At first we change user attributes
1028                        p = subprocess.Popen(usermod, shell=True)
1029                        sts = os.waitpid(p.pid, 0)               
1030                        if sts[1] != 0:
1031                                raise UserError("Problem modifying user!")
1032                       
1033                       
1034                else:
1035                        raise UserError("Username must be not null!")
1036
1037                       
1038
1039        def __changePasswordUnixUser(self, username, password):
1040                """  Change user password """               
1041                try:       
1042                        if username and password:
1043                                string = username+":"+password+"\n"
1044                                p = subprocess.Popen("chpasswd",shell=True, stdin=subprocess.PIPE).communicate(input=string)
1045                except:
1046                        raise UserError("Error changing password!")
1047
1048        def changeLdapPassword(self, username,password):
1049                """ Change ldap password of user username  """
1050                try:
1051                        if self.isUser(username):
1052                                if not password:
1053                                        raise UserError("Password must be not empty!")
1054                                        return
1055                                #Change password
1056
1057                                user = self.getUser(username)     
1058                                user.setAttribute("userPassword", password)
1059                                self.modifyLdapUser(user)
1060                               
1061                        else:
1062                                raise UserError("User passed is not a valid user")
1063
1064
1065                except Exception, e:
1066                        raise UserError("Could not change password: "+str(e))
1067
1068
1069        def disableLdapUser(self, username):
1070                """ Change ldap password of user username  """
1071                try:
1072                        if self.isLdapUser(username):
1073                                import re
1074                                user = self.getUser(username)     
1075                                user.setAttribute("sambaAcctFlags", "[          D]")
1076                                user.setAttribute("loginShell", "/bin/false")
1077                                passwordHash = user.getPassword().getValue()
1078                                newPass = re.sub('(?P<name>{.*})','\g<name>?', passwordHash)
1079                                user.setAttribute("userPassword",newPass,False)
1080                                self.modifyLdapUser(user)
1081                               
1082                        else:
1083                                raise UserError("User passed is not a valid user")
1084
1085
1086                except Exception, e:
1087                        raise UserError("Could not change password: "+str(e))
1088
1089
1090        def enableLdapUser(self, username):
1091                """ Change ldap password of user username  """
1092                try:
1093                        if self.isLdapUser(username):
1094                                import re
1095                                user = self.getUser(username)
1096                                user.setAttribute("sambaAcctFlags", "[UX         ]")
1097                                user.setAttribute("loginShell", "/bin/sh")
1098                                passwordHash = user.getPassword().getValue()
1099                                newPass = re.sub('(?P<name>{.*})(\?)','\g<name>', passwordHash)
1100                                user.setAttribute("userPassword",newPass,False)
1101                                self.modifyLdapUser(user)
1102                               
1103                        else:
1104                                raise UserError("User passed is not a valid user")
1105
1106
1107                except Exception, e:
1108                        raise UserError("Could not change password: "+str(e))
1109
1110        def isEnabled(self, username):
1111                """ Returns true if user is enabled. """
1112                try:
1113                        if self.isLdapUser(username):
1114                                user = self.getUser(username)
1115                                flags = user.getAttribute('sambaSamAccount','sambaAcctFlags')
1116                                if flags.getValue() == "[          D]":
1117                                        return False 
1118                                else:
1119                                        if flags.getValue() == "[UX         ]":
1120                                                return True 
1121                                        else:
1122                                                raise UserError("Invalid sambaSamAccount attributes.")
1123                                               
1124                        else:                       
1125                                raise UserError("User passed is not a valid user")
1126                except Exception, e:
1127                        print e
1128                        raise UserError("Problems: "+str(e))
1129
1130
1131
1132               
1133               
1134               
1135                 
1136               
1137
1138       
1139        def prova(self):
1140                #self.__addUnixGroup("prova")
1141                #self.__modifyUnixGroup("prova", "provina")
1142                #self.__deleteUnixGroup("provina")
1143                #self.__addUnixUser("paolo", "paolo", "/home/paolo", uid="3002", grouplist=["cdrom","plugdev"])
1144                #self.__deleteUnixUser("prova", True)
1145                #self.__modifyUnixUser("ciao",grouplist=[],newname="carlo")
1146                #self.__changePasswordUnixUser("carlo", "prova")
1147                #print self.__getUnixNewUid()
1148                #print self.__getLdapNewUid()
1149                pass
1150
1151       
1152        def addUnixGroup2(self, l):                                                             
1153                """ Add unix group to local system and update memory list of groups """
1154                """ l argument must be an instance of UnixGroup """
1155                # Check l == UnixGroup
1156                if not isinstance(l, UnixGroup):
1157                        raise GroupError("Not a valid unix group!")
1158
1159                # Check l'attributes ( l.check() )
1160                if not l.check():
1161                        raise GroupError("Invalid Unix Group attributes! ")
1162
1163                # Does l group exist?
1164                if self.isGroup(l.getName().getValue()):
1165                        raise GroupError("Group already exists!")
1166
1167                # Check users attribute of the group:
1168                        # 1. users exist?
1169                for user in l.getUsersList().getValue():
1170                        if not self.isUser(user):
1171                                raise GroupError("Group contains users that doesn't exist!")
1172
1173                # Insert group
1174                self.__addUnixGroup(l.getName().getValue(), l.getGid().getValue())               
1175
1176                # Updating memory group list
1177                InheritableSingleton.instances['groupList'][l.getName().getValue()] = l
1178
1179                # Add users to group
1180                for user in l.getUsersList().getValue():
1181                        self.__appendUserToUnixGroup(user, l.getName().getValue())
1182
1183               
1184       
1185
1186
1187
1188        def deleteUnixGroup2(self, groupname):
1189                """ Delete Unix group from local system and update memory group list """
1190                # Check groupname == string
1191                if not isinstance(groupname, str):
1192                        raise GroupError("Groupname must be a string!")
1193                # Check groupname is a valid group
1194                if not self.isGroup(groupname):
1195                        raise GroupError("Group doesn't exist")
1196
1197                #Check users in group
1198                usList = self.getGroup(groupname).getUsersList().getValue()
1199               
1200                curGroupGID = self.getGroup(groupname).getGid().getValue()
1201                found = False
1202                #Because of usList doesn't contain users main group, we have to search it       
1203                for us in InheritableSingleton.instances['unixList'].keys():
1204                        if  InheritableSingleton.instances['unixList'][us].getGid().getValue() == curGroupGID:
1205                                found = True
1206
1207       
1208                if not usList:
1209                        if not found:
1210                                # Delete groupname
1211                                self.__deleteUnixGroup(groupname)
1212                        else:
1213                                raise GroupError("Could not delete group: group not empty")
1214                else:
1215                        raise GroupError("Could not delete group: group not empty")
1216
1217                # Update memory group list
1218                del(InheritableSingleton.instances['groupList'][groupname])
1219
1220
1221
1222        def modifyUnixGroup2(self, groupname, newname="", users=[]):
1223                """ Modify groupname and user that are part of this group """
1224                """ Old users will be replaced by users list """
1225                # Check gruopname == string
1226                if not isinstance(groupname, str):
1227                        raise GroupError("Groupname must be a string!")
1228
1229                # Check groupname is a valid group
1230                if not self.isGroup(groupname):
1231                        raise GroupError("Group doesn't exist")
1232
1233                if ( not newname ) and ( not users  ):
1234                        raise GroupError("All arguments are empty!")
1235
1236                # Check newname (if not empty)
1237                if newname:
1238                        # 1. Newname is a string
1239                        if not isinstance(newname, str):
1240                                raise GroupError("new name argument must be a string!")
1241                        # 2. Newname is not a group
1242                        if self.isGroup(newname):
1243                                raise GroupError("New group name already exist!")
1244                        # Modify group name
1245                        self.__modifyUnixGroup(groupname, newname)
1246
1247
1248                        # Check users (if not empty)
1249                        if users:
1250                                # 1. users exists
1251                                for user in users:
1252                                        if not self.isUser(user):
1253                                                print "Warning: User \""+user+"\" doesn't exist but is in unix group." 
1254                                                #TODO
1255                                                #raise GroupError("User doesn't exist!")
1256                                # Update users list       
1257                                self.__usersToUnixGroup(users, newname)
1258                else:
1259                        # Check users (if not empty)
1260                        if users:
1261                                # 1. users exists
1262                                for user in users:
1263                                        if not self.isUser(user):
1264                                                print "Warning: User \""+user+"\" doesn't exist but is in unix group." 
1265                                                #TODO: decide what to do
1266                                                #raise GroupError("User doesn't exist!")
1267                                # Update users list       
1268                                self.__usersToUnixGroup(users, groupname)
1269
1270
1271                # Update group in memory
1272                oldGroup = self.getGroup(groupname) 
1273                if newname:
1274                        # Delete old group
1275                        del(InheritableSingleton.instances['groupList'][groupname])
1276
1277                        # Update name
1278                        oldGroup.setAttribute("cn", newname)
1279                        if users:
1280                                # Update users
1281                                oldGroup.setUserList(users) 
1282
1283                        # Write to memory
1284                        InheritableSingleton.instances['groupList'][oldGroup.getName().getValue()] = oldGroup
1285                else:
1286                        if users:
1287                                InheritableSingleton.instances['groupList'][groupname].setUserList(users)
1288
1289
1290
1291               
1292
1293               
1294
1295
1296
1297        def addUnixUser2(self,l, maingroup="", groups=[]):
1298                """ Add unix user to local system and update memory list of users. Groups argument are Unix groups """
1299                """ l argument must be an instance of Unix User """
1300
1301       
1302                # Check l == UnixUser
1303                if not isinstance(l, UnixUser):
1304                        raise UserError("Not a valid unix user!")
1305                # Check l'attributes ( l.check() )
1306                if not l.check():
1307                        raise UserError("Invalid user attributes!")
1308
1309                # Does l User exist?
1310                if self.isUser(l.getName().getValue()):
1311                        raise UserError("User already exists!")
1312
1313                # Check groups:
1314                        # 1. groups is a list?
1315                if not isinstance(groups, list):
1316                        raise UserError("Check groups argument!")
1317                        # 2. groups exist?
1318                for group in groups:
1319                        if not self.isGroup(group): 
1320                                raise UserError("Group doesn't exist!")
1321
1322                # If maingroup = "" group will be automatically created
1323                if maingroup:
1324                        if not isinstance(maingroup, str):
1325                                raise UserError("Maingroup must be a string!") 
1326                        if not self.isGroup(maingroup):
1327                                # Create group with gid = userUid
1328                                g = UnixGroup()
1329                                g.setAttribute("cn", maingroup)
1330                                g.setAttribute("gidNumber", l.getUidNumber().getValue())
1331                                self.addUnixGroup2(g)
1332                               
1333                                # Updating group
1334                                InheritableSingleton.instances['groupList'][g.getName().getValue()] = g
1335
1336
1337                                # Insert user
1338                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1339                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), l.getUidNumber().getValue(),l.getShell().getValue(),groups)
1340
1341                        else:
1342                                # MainGroup exist
1343                                g = self.getGroup(maingroup)
1344                                # Insert user
1345                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1346                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), g.getGid().getValue(),l.getShell().getValue(),groups)
1347
1348                else:
1349                        if self.isGroup(l.getName().getValue()):
1350                                # Exist a group with same name of user
1351                                # User will be added to this group
1352                                print "Warning: a group with this name already exists. User will be added to this group."
1353                                g = self.getGroup(l.getName().getValue())
1354
1355                                # Insert user
1356                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1357                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), g.getGid().getValue(),l.getShell().getValue(),groups)
1358
1359
1360                               
1361                        else:
1362                                # Group will be created automatically with same name and gid of user
1363                                g = UnixGroup()
1364                                g.setAttribute("cn",l.getName().getValue() )
1365                                g.setAttribute("gidNumber",l.getUidNumber().getValue())
1366                                self.addUnixGroup2(g)
1367                               
1368                                # Updating group
1369                                InheritableSingleton.instances['groupList'][g.getName().getValue()] = g
1370
1371                                # Insert user
1372                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1373                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), g.getGid().getValue(),l.getShell().getValue(),groups)
1374
1375
1376
1377
1378                # Updating memory user list
1379                InheritableSingleton.instances['unixList'][l.getName().getValue()] = l
1380
1381               
1382                # Updating memory group list (add user to groups)
1383                # Update every group whose user is part
1384               
1385                # for each group
1386                for group in groups:
1387                        if not InheritableSingleton.instances['groupList'][group].hasUser(l.getName().getValue()):
1388                                InheritableSingleton.instances['groupList'][group].addUser(l.getName().getValue())
1389
1390                # Create user directory
1391                # __createHomeDirectory(self, name, uid, gid, path="/home/"):
1392                self.createHomeDirectory(l.getName().getValue(), l.getUidNumber().getValue(), l.getGid().getValue())
1393
1394
1395
1396         
1397
1398        def deleteUnixUser2(self, username, home=False):
1399                """ Delete Unix user from local system and update memory user list """
1400                # Check username == string
1401                if not isinstance(username, str):
1402                        raise UserError("Not a valid argument!")
1403                # Check username is a valid user
1404                if not self.isUser(username):
1405                        raise UserError("User doesn't exist!")
1406
1407                # Delete username
1408                self.__deleteUnixUser(username, home)               
1409 
1410                # Update memory user list
1411                del(InheritableSingleton.instances['unixList'][username])
1412               
1413
1414                # Update memory group list (username's groups)
1415                for group in InheritableSingleton.instances['groupList'].keys():
1416                        if InheritableSingleton.instances['groupList'][group].hasUser(username):
1417                                InheritableSingleton.instances['groupList'][group].removeUser(username)
1418
1419                for group in InheritableSingleton.instances['ldapGroupList'].keys():
1420                        if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1421                                InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1422
1423
1424                               
1425                       
1426                       
1427        def modifyUnixUser2(self, username, newname="", groups=[]):
1428                """ Modify username and/or group list. Main group could not be modified. """
1429                """ Newname is the new username """
1430                """ Groups are the new groups. Old groups will be removed """
1431                # Check username == string
1432                if not isinstance(username, str):
1433                        raise UserError("Not a valid argument!")
1434                # Check username is a valid user
1435                if not self.isUser(username):
1436                        raise UserError("User doesn't exist!")
1437
1438                if ( not newname ) and ( not groups  ):
1439                        raise UserError("All arguments are empty!")
1440
1441
1442                # Check newname (if not empty)
1443                if newname: 
1444                        # 1. Newname is a string
1445                        if not isinstance(newname, str):
1446                                raise UserError("Newname must be a string!")
1447                        # 2. Newname is not a user
1448                        if self.isUser(newname):
1449                                raise UserError("User with newname already exist!")
1450                        for group in groups:
1451                                if not self.isGroup(group):
1452                                        raise UserError("Group doesn't exist!")
1453                        #__modifyUnixUser(self, username, grouplist=[], newname="" ):
1454                        self.__modifyUnixUser(username, groups, newname)
1455
1456
1457                else:
1458                        for group in groups:
1459                                if not self.isGroup(group):
1460                                        raise UserError("Group doesn't exist!")
1461                        #__modifyUnixUser(self, username, grouplist=[], newname="" ):
1462                        self.__modifyUnixUser(username, groups, newname)
1463
1464
1465
1466                # Update user in memory
1467                if newname:
1468                        oldUser = InheritableSingleton.instances['unixList'][username]
1469                        del(InheritableSingleton.instances['unixList'][username])
1470                        oldUser.setAttribute("cn", newname)
1471                        oldUser.setAttribute("uid", newname)
1472                        InheritableSingleton.instances['unixList'][newname] = oldUser
1473               
1474                        #Update username in groups
1475                        for group in  InheritableSingleton.instances['groupList'].keys():
1476                                if InheritableSingleton.instances['groupList'][group].hasUser(username):
1477                                        InheritableSingleton.instances['groupList'][group].removeUser(username)
1478                                if group in groups:
1479                                        print "TRRR: "+group
1480
1481                                        InheritableSingleton.instances['groupList'][group].addUser(newname)
1482                               
1483                        for group in  InheritableSingleton.instances['ldapGroupList'].keys():
1484                                if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1485                                        InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1486                                if group in groups:
1487                                        print "TRRR: "+group
1488
1489                                        InheritableSingleton.instances['ldapGroupList'][group].addUser(newname)
1490                else:
1491                        for group in  InheritableSingleton.instances['groupList'].keys():
1492                                if InheritableSingleton.instances['groupList'][group].hasUser(username):
1493                                        InheritableSingleton.instances['groupList'][group].removeUser(username)
1494                                if group in groups:
1495                                        print "TRRR: "+group
1496                                        InheritableSingleton.instances['groupList'][group].addUser(username)
1497                               
1498                        for group in  InheritableSingleton.instances['ldapGroupList'].keys():
1499                                if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1500                                        InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1501                                if group in groups:
1502                                        print "TRRR: "+group
1503
1504                                        InheritableSingleton.instances['ldapGroupList'][group].addUser(username)
1505
1506                       
1507
1508
1509
1510
1511
1512        def addLdapGroup2(self, l, users=[]):
1513                """ Add a ldap user group and update memory groups """
1514                # Check l == LdapUser
1515                if not isinstance(l, LdapGroup):
1516                        raise GroupError("User must be an LdapUser instance")
1517                # Check l'attributes ( l.check() )
1518                if not l.check():
1519                        raise GroupError("Invalid user attributes!")
1520                # Does l User exist?
1521                if self.isGroup(l.getName().getValue()):
1522                        raise GroupError("Group already exists!")
1523
1524                # Check groups:
1525                        # 1. groups is a list?
1526
1527                if not isinstance(users, list):
1528                        raise GroupError("Groups argument must be a list!")
1529                for user in users:
1530                        if not self.isUser(user):
1531                                raise UserError("User doesn't exist")
1532               
1533               
1534                # Add user to ldapGroup                       
1535                if users:
1536                        l.setUserList(users)
1537               
1538                # Insert group
1539                self.__addLdapGroup(l)
1540
1541               
1542                # Updating memory user list
1543                InheritableSingleton.instances['ldapGroupList'][l.getName().getValue()]=l
1544
1545               
1546               
1547
1548               
1549       
1550        def __addLdapGroup(self, l):
1551                """ Add an ldap group to ldap server """
1552                # Insert tree insert position in global configuration
1553                try:
1554                        conn = ldap.conn()
1555                        if isinstance(l, LdapGroup):
1556                                dn=ldap.groupprefix+l.getName().getValue()+ldap.grouppostfix
1557                                d = l.getDict()       
1558                                modList = ldap.modlist.addModlist(d)
1559                                ret = conn.add_s(dn, modList)
1560                        else:
1561                                print "Not a valid Ldap Group!"
1562                except:
1563                        raise LdapError("Error: group not added!")
1564
1565        def deleteLdapGroup2(self, groupname):
1566                """ Delete group from ldap server and update memory group list """
1567                # Check groupname == strin
1568                if not isinstance(groupname, str):
1569                        raise GroupError("Groupname must be a string!")
1570                # Check groupname is a valid group
1571                if not self.isGroup(groupname):
1572                        raise GroupError("Group doesn't exist")
1573
1574                # Check if there are users in that group!!
1575                usList = self.getGroup(groupname).getUsersList().getValue()
1576               
1577
1578 
1579                curGroupGID = self.getGroup(groupname).getGid().getValue()
1580                found = False
1581                print curGroupGID
1582                #Because of usList doesn't contain users main group, we have to search it       
1583                for us in InheritableSingleton.instances['ldapList'].keys():
1584                        if  InheritableSingleton.instances['ldapList'][us].getGid().getValue() == curGroupGID:
1585                                found = True
1586                       
1587                       
1588                                                                                               
1589                       
1590                print usList
1591                if not usList:
1592                        if not found:
1593                                # Delete groupname
1594                                self.__deleteLdapGroup(groupname)
1595                        else:
1596                                raise GroupError("Could not delete group: group not empty")
1597                else:
1598                        raise GroupError("Could not delete group: group not empty")
1599
1600                # Update memory group list
1601                del(InheritableSingleton.instances['ldapGroupList'][groupname])
1602
1603
1604
1605
1606        def __deleteLdapGroup(self, groupname):
1607                """ Delete a group from ldap tree """ 
1608                try:
1609                        conn = ldap.conn()
1610                        if isinstance(groupname, str) and groupname:
1611                               
1612                                dn =ldap.groupprefix+groupname+ldap.grouppostfix
1613                                result = conn.delete_s(dn)
1614
1615                except:
1616                        raise LdapError("Error: could not delete group")     
1617
1618
1619        def modifyLdapGroup2(self, l, users=[]):
1620                """ Modify groupname and user that are part of this group """
1621                """ Old users will be replaced by users list """
1622                # Check gruopname == string
1623                if not isinstance(l, LdapGroup):
1624                        raise GroupError("Invalid group name.")
1625                # Check groupname is a valid group
1626                if not self.isGroup(l.getName().getValue()):
1627                        GroupError("Group doesn't exist!")
1628
1629
1630                # Check users (if not empty)
1631                        # 1. users exists
1632                for user in users:
1633                        if not self.isUser(user):
1634                                raise UserError("User doesn't exist!")
1635
1636                 
1637                # Update users               
1638                l.setUserList(users)
1639                # Modify group
1640                print l.getUsersList().getValue()
1641                self.__modifyLdapGroup(l)
1642
1643                # Update group in memory
1644                InheritableSingleton.instances['ldapGroupList'][l.getName().getValue()]=l
1645
1646
1647
1648
1649        def __modifyLdapGroup(self, l):
1650                """ Modify an ldap group """
1651                try:
1652                        if isinstance(l, LdapGroup):
1653                                dn=ldap.groupprefix+l.getName().getValue()+ldap.grouppostfix
1654                                d = l.getDict()       
1655                                ret = ldap.modifyEntry(dn,d) 
1656                        else:
1657                                print "Not a valid Ldap Group!"
1658                except:
1659                        raise LdapError("Error: could not modify group ")     
1660                       
1661        def modifyLdapGroup(self, l):
1662                  """ Modify an ldap group """
1663                  try:
1664                          if isinstance(l, LdapGroup):
1665                                  dn=ldap.groupprefix+l.getName().getValue()+ldap.grouppostfix
1666                                  d = l.getDict()       
1667                                  ret = ldap.modifyEntry(dn,d) 
1668                          else:
1669                                  print "Not a valid Ldap Group!"
1670                  except:
1671                          raise LdapError("Error: could not modify group ")     
1672
1673       
1674        def addLdapUser2(self,l, groups=[]):
1675                """ Add user to ldap server and update memory list of users """
1676                """ l argument must be an instance of LdapUser """
1677                # Check l == LdapUser
1678                if not isinstance(l, LdapUser):
1679                        raise UserError("Invalid user argument!")
1680                # Check l'attributes ( l.check() )
1681                if not l.check():
1682                        raise UserError("Invalid user attributes!")
1683
1684                # Does l User exist?
1685                if self.isUser(l.getName().getValue()):
1686                        raise UserError("User already exists!")
1687
1688                if os.path.isdir("/home/"+l.getName().getValue()):
1689                        raise UserError("Directory already exist")
1690
1691                # Check groups:
1692                if not isinstance(groups, list):
1693                        raise UserError("Invalid group argument!")
1694
1695                for group in groups:
1696                        if not self.isGroup(group):
1697                                raise GroupError("Group doesn't exist!")
1698
1699                # Insert user
1700                self.__addLdapUser(l)
1701
1702                               
1703                # Add user to the memberUid attribute of his main group
1704                mainGroup = self.getGroupByGid(l.getGid().getValue())
1705                mainGroup.addUser(l.getName().getValue())
1706                self.__modifyLdapGroup(mainGroup)
1707               
1708               
1709
1710                # Updating memory user list
1711                InheritableSingleton.instances['ldapList'][l.getName().getValue()]=l
1712
1713
1714
1715
1716
1717               # Update ldap group (can be ldap o unix)
1718                for group in groups:
1719                        g = self.getGroup(group)
1720                        groupUser = g.getUsersList().getValue()
1721                       
1722                        if isinstance(g, LdapGroup):
1723                                if not l.getName().getValue() in groupUser:
1724                                        groupUser.append(l.getName().getValue())
1725                                        self.modifyLdapGroup2(g, groupUser)
1726
1727                        if isinstance(g, UnixGroup):
1728                                if not l.getName().getValue() in groupUser:
1729                                        groupUser.append(l.getName().getValue())
1730                                        self.modifyUnixGroup2(g.getName().getValue(),"", groupUser)
1731
1732                # Updating memory group list (add user to groups)
1733                for group in  InheritableSingleton.instances['groupList'].keys():
1734                        if group in groups:
1735                                InheritableSingleton.instances['groupList'][group].addUser(l.getName().getValue())
1736                       
1737                for group in  InheritableSingleton.instances['ldapGroupList'].keys():
1738                        if group in groups:
1739                                InheritableSingleton.instances['ldapGroupList'][group].addUser(l.getName().getValue())
1740
1741                #Home directory work
1742                #Trying to create home
1743                self.createHomeDirectory(l.getName().getValue(),l.getUidNumber().getValue(),l.getGid().getValue())
1744               
1745               
1746               
1747
1748
1749
1750
1751
1752               
1753               
1754
1755
1756
1757       
1758        def __addLdapUser(self, l):
1759                """ Add an ldap user to ldap server """
1760                # Insert tree insert position in global configuration
1761                try:
1762                        conn = ldap.conn()
1763                        if isinstance(l, LdapUser):
1764                                dn=ldap.userprefix+l.getName().getValue()+ldap.userpostfix
1765                                d = l.getDict()       
1766                                modList = ldap.modlist.addModlist(d)
1767                                ret = conn.add_s(dn, modList)
1768                        else:
1769                                print "Not a valid Ldap User!"
1770                except Exception, e:
1771                        print e
1772                        print e.args
1773                        raise LdapError("Error: user not added!")
1774               
1775        def deleteLdapUser2(self, username):
1776                """ Delete user from ldap server and update memory user list """
1777                # Check username == string
1778                if not isinstance(username, str):
1779                        raise UserError("Invalid argument!")
1780                # Check username is a valid user
1781                if not self.isUser(username):
1782                        raise UserError("User doesn't exist!")
1783
1784                # Delete username
1785                self.__deleteLdapUser(username)
1786
1787
1788                # Delete user name from memberUid of user main group
1789                userObj = self.getUser(username)
1790                mainGroup = self.getGroupByGid(userObj.getGid().getValue())
1791                if mainGroup.hasUser(username):
1792                        mainGroup.removeUser(username)
1793                self.__modifyLdapGroup(mainGroup)
1794
1795
1796 
1797                #Delete user from ldap groups
1798                self.__removeUserFromLdapGroups(username)
1799
1800                #Delete user from unix groups
1801                self.__removeUserFromUnixGroups(username) # TODO: check, sometimes doesn't remove users
1802
1803               # Update memory user list
1804                del(InheritableSingleton.instances['ldapList'][username])
1805
1806               
1807                # Update memory group list (username's groups)
1808                for group in InheritableSingleton.instances['groupList'].keys():
1809                        if InheritableSingleton.instances['groupList'][group].hasUser(username):
1810                                InheritableSingleton.instances['groupList'][group].removeUser(username)
1811
1812                for group in InheritableSingleton.instances['ldapGroupList'].keys():
1813                        if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1814                                InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1815
1816
1817                #Remove home directory and save it /var/backups
1818                #Create backup
1819                 
1820                home = "/home"
1821                dir = os.path.join(home,username)
1822                backup = "/var/backups"
1823                fileBackup = os.path.join(backup,username)
1824                try:
1825                        now = datetime.datetime.now()
1826                        stringTime = now.isoformat()
1827                        os.system("tar cvzf "+fileBackup+"_"+stringTime+".tar.gz "+ dir)
1828                        try:
1829                                os.system("rm -rf "+dir) 
1830                        except:
1831                                print "Problems removing "+username+"'s home directory!"
1832                                return
1833                except:
1834                        print "Problems saving "+username+"'s home directory!"
1835
1836               
1837
1838
1839
1840       
1841               
1842
1843
1844
1845        def __deleteLdapUser(self, username):
1846                """ Delete a user from ldap tree """ 
1847                try:
1848                        conn = ldap.conn()
1849                        if isinstance(username, str) and username:
1850                               
1851                                dn =ldap.userprefix+username+ldap.userpostfix
1852                                result = conn.delete_s(dn)
1853                                #How to decide if delete has happened?
1854                except Exception, e:
1855                        error = e[0]['desc']
1856                        raise LdapError("Error: could not delete user %s" % username + "\n"+error)     
1857
1858        def modifyLdapUser2(self, l):
1859                # modifyLdapUser
1860                pass
1861
1862        def modifyLdapUser(self, l):
1863                """ Modify an ldap user """
1864                try:
1865                        if isinstance(l, LdapUser):
1866                                dn=ldap.userprefix+l.getName().getValue()+ldap.userpostfix
1867                                d = l.getDict()       
1868
1869                                ret = ldap.modifyEntry(dn,d) 
1870                                InheritableSingleton.instances['ldapList'][l.getName().getValue()]=l
1871                        else:
1872                                print "Not a valid Ldap User!"
1873                       
1874                except:
1875                        raise LdapError("Error: could not modify user ")     
1876
1877        def __appendUserToUnixGroup(self, username, group):
1878                """ Add user to group in /etc/group """
1879                if not isinstance(username, str):
1880                        raise UserError("Username must be a string")
1881                if not isinstance(group, str):
1882                        raise GroupError("Group must be a string")
1883
1884                groupFile = open("/etc/group",'r') 
1885                groupLines = groupFile.readlines() 
1886                groupFile.close()
1887                newGroup = []
1888                for line in groupLines:
1889                        # Split :
1890                        # Take last (it's the list of unix users)
1891                        # Find username and remove it
1892                        if line.startswith(group+":"):
1893                                groupSplit = line.strip("\n").split(":")
1894                                usersList = groupSplit[len(groupSplit)-1].split(",")
1895                                if not username in usersList:
1896                                        if groupSplit[3]:
1897                                                line = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":"+groupSplit[3]+","+username
1898                                        else:
1899                                                line = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":"+groupSplit[3]+username
1900                       
1901                        newGroup.append(line)
1902       
1903                # Write together
1904                groupFile = open("/etc/group", "w") 
1905                groupFile.write("")
1906                groupFile.close()
1907
1908                groupFile = open(groupfile, "a") 
1909                for line in newGroup:
1910                        groupFile.write(line) 
1911                groupFile.close()
1912
1913        def __usersToUnixGroup(self, users, group):
1914                """ Add user to group in /etc/group """
1915                if not isinstance(users, list):
1916                        raise UserError("Username must be a string")
1917                if not isinstance(group, str):
1918                        raise GroupError("Group must be a string")
1919
1920                groupFile = open("/etc/group",'r') 
1921                groupLines = groupFile.readlines() 
1922                groupFile.close()
1923                newGroup = []
1924                for line in groupLines:
1925                        # Split :
1926                        # Take last (it's the list of unix users)
1927                        # Find username and remove it
1928                        if line.startswith(group+":"):
1929                                groupSplit = line.strip("\n").split(":")
1930                                usersList = groupSplit[len(groupSplit)-1].split(",")
1931                                userString = ""
1932                                for user in users:
1933                                        userString = userString + user + ","
1934                                userString = userString.strip(",")
1935                                line = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":"+userString+"\n"       
1936                        newGroup.append(line)
1937       
1938                # Write together
1939                groupFile = open("/etc/group", "w") 
1940                groupFile.write("")
1941                groupFile.close()
1942
1943                groupFile = open(groupfile, "a") 
1944                for line in newGroup:
1945                        groupFile.write(line) 
1946                groupFile.close()
1947
1948
1949               
1950
1951                               
1952
1953        def __removeUserFromUnixGroups(self,username):
1954                """ Remove an user from unix groups """
1955                global groupfile
1956                if username:
1957                        # group
1958                        groupFile = open(groupfile,'r') 
1959                        groupLines = groupFile.readlines() 
1960                        groupFile.close()
1961                        newGroup = []
1962                        for line in groupLines:
1963                                # Split :
1964                                # Take last (it's the list of unix users)
1965                                # Find username and remove it
1966                                groupSplit = line.strip("\n").split(":")
1967                                usersList = groupSplit[len(groupSplit)-1].split(",")
1968                                if username in usersList:
1969                                        ind = usersList.index(username)
1970                                        del usersList[ind]
1971                                        if username in usersList:
1972                                                print "Warning: duplicate user in group"
1973                                newLine = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":" 
1974                               
1975                                 
1976                                for user in usersList:
1977                                        if user:
1978                                                newLine = newLine + user + ","
1979                                newLine = newLine.strip(",")+"\n"
1980                                newGroup.append(newLine)
1981
1982                        # Write together
1983                        groupFile = open(groupfile, "w") 
1984                        groupFile.write("")
1985                        groupFile.close()
1986
1987                        groupFile = open(groupfile, "a") 
1988                        for line in newGroup:
1989                                groupFile.write(line) 
1990                        groupFile.close()
1991                       
1992
1993                else:
1994                        raise UserError("Not a valid group or group does not exist!")           
1995
1996        def __addUserToUnixGroup(self, username, groups):
1997                """ Add user to /etc/group """
1998                if not self.isUser(username):
1999                        raise UserError("User doesn't exist")
2000               
2001                for g in groups:
2002                        if not self.isGroup(g):
2003                                raise GroupError("Invalid group!\nGroup doesn't exist.")
2004                groupFile = open("/etc/group",'r') 
2005                groupLines = groupFile.readlines() 
2006                groupFile.close()
2007                newGroup = []
2008
2009                for line in groupLines:
2010                       
2011                        groupStart = line.strip().split(":")[0]
2012                        if groupStart in groups:
2013                                groupSplit = line.strip("\n").split(":")
2014                                usersList = groupSplit[len(groupSplit)-1].split(",")
2015                                if not username in usersList:
2016                                        usersList.append(username)
2017                                newLine = ""
2018                                newLine = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":" 
2019                                for us in usersList:
2020                                        newLine = newLine + us + ","
2021                                newLine = newLine.strip(",")+"\n"
2022                                newGroup.append(newLine)
2023                        else:
2024                                newGroup.append(line)
2025
2026                # Write together
2027                groupFile = open(groupfile, "w") 
2028                groupFile.write("")
2029                groupFile.close()
2030
2031                groupFile = open(groupfile, "a") 
2032                for line in newGroup:
2033                        groupFile.write(line) 
2034                groupFile.close()
2035               
2036                               
2037                                       
2038                                       
2039                               
2040
2041               
2042
2043        def updateUserLocalGroups(self, username, groups):
2044                """ Remove username from unix group and add user to groups """
2045                try:
2046                        #Check if group are unix group
2047                        for gr in groups:
2048                                if not self.isGroup(gr):
2049                                        raise GroupError("Not a valid group!")
2050
2051                                groupInstance = self.getGroup(gr)
2052                               
2053                                if not isinstance(groupInstance, UnixGroup):
2054                                        raise GroupError("Not a valid group!")
2055                               
2056                        #Remove user from /etc/group
2057                        self.__removeUserFromUnixGroups(username)
2058
2059                        #Remove user from memory groups
2060                        for group in InheritableSingleton.instances['groupList'].keys():
2061                                if InheritableSingleton.instances['groupList'][group].hasUser(username):
2062                                        InheritableSingleton.instances['groupList'][group].removeUser(username)
2063
2064                         
2065                       
2066
2067                        #Add user to /etc/group
2068                        self.__addUserToUnixGroup(username, groups)
2069                        #Add user to groups in memory
2070                        for group in InheritableSingleton.instances['groupList'].keys():
2071                                if group in groups:
2072                                        if not InheritableSingleton.instances['groupList'][group].hasUser(username):
2073                                                InheritableSingleton.instances['groupList'][group].addUser(username)
2074                except Exception, e:
2075                        print e.args
2076                       
2077                        raise UserError("Problem updating system groups:\n"+str(e))
2078
2079
2080
2081
2082
2083
2084
2085        def __removeUserFromLdapGroups(self,username):
2086                """ Remove user from all ldap groups """ 
2087                if username:
2088                        groups =  self.groupsByUser(username)
2089                        for group in groups:
2090                                ldapGroup = self.getGroup(group)
2091
2092                                if isinstance(ldapGroup, LdapGroup):
2093                                        # Take the group
2094                                                                         
2095                                        # Modify memberUid, remove username
2096                                        usersList = ldapGroup.getUsersList().getValue()
2097                                        if username in usersList:
2098                                                ind = usersList.index(username) 
2099                                                del(usersList[ind])
2100                                                ldapGroup.setUserList(usersList)
2101                                        # Modify ldap entry
2102                                                self.__modifyLdapGroup(ldapGroup)
2103                else:
2104                        raise UserError("Not a valid user")
2105               
2106
2107        def addUserToUnixGroup(self, username, group):
2108                """ Add an user to unix group """
2109                #Group could be a string or a list o groups
2110                if not isinstance(username, str) and username:
2111                        raise UserError("Username argument not a string")
2112
2113                if isinstance(group, str):
2114                        if self.isGroup(group):
2115                                #Add username to group                               
2116                                g = None
2117                                g=self.getGroup(group)
2118                                if not g.hasUser(username):
2119                                        g.addUser(username)                                 
2120                                        self.deleteUnixGroup(g.getName().getValue())
2121                                        self.addUnixGroup(g)
2122                        else:
2123                                raise UserError("User does not exist")
2124
2125                else:
2126                        if isinstance(group, list):
2127                                for gr in group:
2128                                        if self.isGroup(gr):
2129                                                #Add username to group
2130                                                g = None
2131                                                g = self.getGroup(gr)
2132                                                if not g.hasUser(username):
2133                                                        g.addUser(username)                                 
2134                                                        self.deleteUnixGroup(g.getName().getValue())
2135                                                        self.addUnixGroup(g)
2136
2137                                        else:
2138                                                raise GroupError("Group does not exist")
2139               
2140                                 
2141                        else:
2142                                raise GroupError("Not a valid group argument")
2143
2144       
2145                       
2146               
2147        def addUserToLdapGroup(self, username, group):
2148                """ Add an user to unix group """
2149                #Group could be a string or a list o groups
2150                if not isinstance(username, str) and username:
2151                        raise UserError("Username argument not a string")
2152
2153                if isinstance(group, str):
2154                        if self.isGroup(group):
2155                                #Add username to group                               
2156                                g = None
2157                                g=self.getGroup(group)
2158                                if not g.hasUser(username):
2159                                        g.addUser(username)                                 
2160                                        self.modifyLdapGroup(g)
2161                        else:
2162                                Error("User does not exist")
2163
2164                else:
2165                        if isinstance(group, list):
2166                                for gr in group:
2167                                        if self.isGroup(gr):
2168                                                #Add username to group
2169                                                g = None
2170                                                g = self.getGroup(gr)
2171                                               
2172                                                if not g.hasUser(username):
2173                                                        g.addUser(username)                                 
2174                                                        self.modifyLdapGroup(g)
2175
2176                                        else:
2177                                                raise GroupError("Group does not exist")
2178               
2179                                 
2180                        else:
2181                                raise GroupError("Not a valid group argument")
2182
2183
2184        def searchLocalSid(self):
2185                """ Returns the samba sid of the server"""
2186                res = ldap.search(filter="(sambaDomainName=*)",findattr=["sambaSID"]) 
2187                return res[0][0][1]['sambaSID'][0]
2188               
2189
2190        def getUserSID(self, uid):
2191                """ Return user security id  """
2192               
2193                #out = os.popen("net getlocalsid")
2194                #res = out.read()
2195                #out = subprocess.Popen("net getlocalsid", stdout=subprocess.PIPE, shell=True )
2196                #res = out.communicate()[0]
2197                #sidPrefix = res.split(":")[1].strip()
2198                sidPrefix = self.searchLocalSid()
2199                sidPostfix = (int(uid)*2) + 1000                 
2200                return sidPrefix+"-"+str(sidPostfix)
2201 
2202        def getGroupSID(self, gid):
2203                """ Return group security id """
2204                #out = os.popen("net getlocalsid")
2205                #res = out.read()
2206                #out = subprocess.Popen("net getlocalsid", stdout=subprocess.PIPE, shell=True )
2207                #res = out.communicate()[0]
2208                #sidPrefix = res.split(":")[1].strip()
2209                sidPrefix = self.searchLocalSid()
2210                sidPostfix = int(gid)                 
2211                return sidPrefix+"-"+str(sidPostfix)
2212
2213
2214
2215        def genPassword(self,pwlen=8):
2216                """ Generate a random password """
2217                from random import sample
2218                import string
2219                password = "".join(sample(string.ascii_letters+string.digits,pwlen))
2220                return password
2221
2222
2223backendSingleton = Backend()
2224
2225               
2226
2227           
2228       
2229if __name__ == "__main__":
2230        b = Backend()
2231        print b.searchLocalSid() 
2232        """
2233        g = UnixGroup()
2234        g.setAttribute("cn","GroupAntani")
2235        gid = b.getNewUnixID()
2236        g.setAttribute("gidNumber", str(gid))
2237        g.setAttribute("memberUid","pippo")
2238
2239        #b.addUnixGroup2(g)
2240        #b.deleteUnixGroup2("GroupAntani")
2241        #b.modifyUnixGroup2("GroupAntani", "gruppo")
2242        #b.modifyUnixGroup2("ploii", "ploi", ["giorgio","pluto"])
2243        """
2244        """
2245        u = UnixUser()
2246        u.setAttribute("cn","carly")
2247        uid = b.getNewUnixID()
2248        u.setAttribute("gidNumber", str(uid))
2249        u.setAttribute("homeDirectory","/home/carly")
2250        u.setAttribute("uid","carly")
2251        u.setAttribute("uidNumber", str(uid))
2252        u.setAttribute("gecos","")
2253        u.setAttribute("loginShell","/bin/bash")
2254        u.setAttribute("userPassword","carly")
2255        """
2256        #b.addUnixUser2(u,"", ["dhcp"])
2257        #print b.groupsByUser("carly")
2258        #b.deleteUnixUser2("carly", True)
2259        #b.modifyUnixUser2("carl","" , groups=["list","irc","src"])
2260        #b.deleteUnixGroup2("jackpop")
2261        """
2262        g = LdapGroup()
2263        g.setAttribute("cn","catalogo")
2264        uid = b.getNewLdapID()
2265        g.setAttribute("gidNumber", "20033")
2266
2267        g.setAttribute("sambaSID","S-1-5-21-3532783127-313077556-2689386559-553")
2268        g.setAttribute("sambaGroupType","2")
2269
2270        b.addLdapGroup2(g,["pippo"])
2271        """
2272        #b.deleteLdapGroup2("provaGrouppiiii")
2273       
2274        #b.modifyLdapGroup2(g,["pluto","prova","admin","giorgio"])
2275        """
2276        n = LdapUser()
2277        n.setAttribute("cn","bonzio")
2278        n.setAttribute("sn","bonzio")
2279        uid = b.getNewLdapID()
2280        n.setAttribute("gidNumber", "513")
2281        n.setAttribute("homeDirectory","/bin/bash")
2282        n.setAttribute("uid","bonzio")
2283        n.setAttribute("uidNumber", str(uid))
2284        n.setAttribute("sambaSID","S-1-5-21-3532783127-313077556-2689386559-5002")
2285        """
2286        #b.addLdapUser2(n,["direzione","scanner","Domain Users","users"])
2287        #b.removeUserFromUnixGroups("claus")
2288        #b.removeUserFromLdapGroups("bonzio")
2289
2290        #b.deleteLdapUser2("bonzio")
2291       
2292        """
2293        b.updateUserLocalGroups("aa",["floppy","cdrom"])
2294
2295        """
2296
2297               
2298
2299
2300
2301
2302
2303               
Note: See TracBrowser for help on using the browser.