Beispiel #1
0
	def DisableUser (self, *args, **kwargs) :
		from admtooCore.models import command
		import json
		_, cmd = args
		
		d = json.loads(cmd.data)

		fname = None
		if 'first_name' in d.keys() :
			fname = d['first_name']
		lname = None
		if 'last_name' in d.keys() :
			lname = d['last_name']
		
		asn = None
		if 'appSpecName' in d.keys() :
			asn = d['appSpecName']

		twiki = None
		if type(asn) is dict :
			if 'twiki' in asn.keys() :
				twiki = asn['twiki'].strip()
				if len(twiki) == 0 :
					twiki = None

		if twiki is None :
			twiki = self.gen_user_name (fname, lname)

		a = af.rem()
		res = a.twikiUserInactive(TWIKI_SERVER,TWIKI_BASE,twiki)
		if res :
			self._log(u'Successfully disabled twiki user '+unicode(twiki))
		else :
			self._log(u'Problem disabling twiki user '+unicode(twiki))
		return res
Beispiel #2
0
 def _update_photo(self, user_login):
     import os.path
     u = models.User.objects.get(login=user_login)
     if u.photo_path is None or len(u.photo_path) == 0:
         self._log(u"FATAL: no file name given for photo")
         return False
     spath = os.path.join(settings.USER_PHOTO_PATH, str(u.uidnumber),
                          u.photo_path)
     self._log(spath)
     dpathl = os.path.join(PHOTO_PATH_LARGE, u.login + '.jpg')
     dpaths = os.path.join(PHOTO_PATH_SMALL, u.login + '.jpg')
     self._log(dpathl)
     self._log(dpaths)
     # copy the original file
     a = af.rem()
     res = a.copy(PHOTO_SERVER, PHOTO_FILE_OWNER, PHOTO_FILE_GROUP, spath,
                  dpathl, PHOTO_FILE_MODE)
     if not res:
         a.log(u'FATAL: unable to copy file ' + unicode(spath) + u' to ' +
               unicode(PHOTO_SERVER) + u':' + unicode(dpathl))
         return False
     # resize the picture in a temp file
     import tempfile
     from PIL import Image
     try:
         img = Image.open(spath)
     except IOError as e:
         if e.errno == 21:
             a.log(
                 u"FATAL: the file corresponds to a directory, no picture")
             return False
     hpercent = (float(MINI_PHOTO_HEIGHT) / float(img.size[1]))
     wsize = int((float(img.size[0]) * float(hpercent)))
     img = img.resize((wsize, MINI_PHOTO_HEIGHT), Image.ANTIALIAS)
     f = tempfile.NamedTemporaryFile()
     spath_mini = f.name
     img.save(f,
              MINI_PHOTO_FORMAT,
              quality=MINI_PHOTO_QUALITY,
              optimize=True,
              progressive=True)
     f.flush()
     # copy the temp file
     res = a.copy(PHOTO_SERVER, PHOTO_FILE_OWNER, PHOTO_FILE_GROUP,
                  spath_mini, dpaths, PHOTO_FILE_MODE)
     f.close()
     if not res:
         a.log(u'FATAL: unable to copy minifile ' + unicode(spath_mini) +
               u' to ' + unicode(PHOTO_SERVER) + u':' + unicode(dpaths))
         return False
     return True
Beispiel #3
0
    def DestroyUserDir(self, *args, **kwargs):
        _, command = args
        if 'logger' in kwargs.keys():
            logger = kwargs['logger']
            if logger is not None:
                self._logger = logger

        c = json.loads(command.data)
        ck = c.keys()
        if 'machine' not in ck:
            self._log('missing \'machine\' name')
            return False
        machine = c['machine']

        # in debug mode, force the storage server from the settings
        from django.conf import settings
        if settings.DEBUG:
            try:
                settings.STORAGE_SERVER
            except NameError as e:
                # skip...
                self._log(
                    'FATAL: we are in DEBUG mode and settings.STORAGE_SERVER is not defined'
                )
                return False
            else:
                self._log(
                    'DEBUG MODE :\ndirectories should normally be removed from \''
                    + machine + '\'\nwill be removed from \'' +
                    settings.STORAGE_SERVER + '\' instead')
                machine = settings.STORAGE_SERVER

        if ('basedir' not in ck) and ('uid' not in ck):
            return False
        dirname = c['basedir'] + '/' + c['uid']
        uid = c['uid']

        # we have all we need to call the ansible stuff
        from admtooLib import AdminFunctions as af
        import os.path
        created_ok = af.destroyDirectory(machine, dirname, uid)
        if created_ok:
            self._log(u'SUCCESS destroying directoy ' + unicode(dirname))
            return True
        self._log(u'FAIL destroying directory ' + unicode(dirname))

        return False
Beispiel #4
0
	def _copy_file_to_twiki_server (self, s, encoding, basedir, filename) :
		# copy the contents of s to the twiki system, so as to update the contents of the group
		a = af.rem()
		# save to a temporary file
		import tempfile
		f = tempfile.NamedTemporaryFile ()
		f.write (s.encode(encoding))
		f.flush ()
		import os
		# call the remote access file copy
		res = a.copy (TWIKI_SERVER, TWIKI_FILE_OWNER, TWIKI_FILE_GROUP, f.name, 
					  os.path.join(basedir, filename), '0664')
		# destroy the temporary file		
		f.close()
		if not res : 
			return False
		# everything is fine
		return True
Beispiel #5
0
 def _fetch_photo(self, user):
     if user.photo_path is not None:
         self._log(u'SKIPPING ' + unicode(user.login) +
                   u' : already have a picture for user')
         return True
     self._log(u'obtaining photo for user ' + unicode(user.login))
     spath = os.path.join(PHOTO_PATH_LARGE, user.login + '.jpg')
     dpath = self._photo_local_path(user)
     self._log(spath)
     a = af.rem()
     fqdn = PHOTO_SERVER
     hostname = a.getHostname(fqdn)
     tpath = os.path.join(os.sep, 'tmp', hostname, spath[1:])
     self._log(u'temporary_path ' + unicode(tpath))
     # grab file from server
     res = a.fetch(fqdn, spath, os.path.join(os.sep, 'tmp'))
     if not res:
         a.log(u'FATAL: unable to fetch photo ' + unicode(spath) +
               u' from server to copy it to ' + unicode(tpath))
         return False
     # do stuff with file
     self._log(u'moving file to ' + unicode(dpath))
     import shutil
     import pwd
     import grp
     # create destination directory
     try:
         os.makedirs(os.path.dirname(dpath))
     except OSError as e:
         pass
     # move the file
     shutil.move(tpath, dpath)
     # remove the temp file
     shutil.rmtree(os.path.join(os.sep, 'tmp', hostname))
     # change owner of destination file
     uid = pwd.getpwnam(LOCAL_PHOTO_OWNER)[2]
     gid = grp.getgrnam(LOCAL_PHOTO_GROUP)[2]
     os.chown(dpath, uid, gid)
     # change mode of destination file
     os.chmod(dpath, int(PHOTO_FILE_MODE, 8))
     # add file to user
     user.photo_path = os.path.basename(dpath)
     user._save()
     return True
Beispiel #6
0
def SetupBackupPC(request):
    name = False
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        # one or multiple ips. for now, consider one ip
        ip = request.META['HTTP_X_FORWARDED_FOR']
        logger.error(ip)
        # get the PTR for that ip
        rname = reversename.from_address(ip)
        logger.error(rname)
        name = resolver.query(rname, 'PTR')
        # we should only have 1 object
        l = len(name)
        if l != 1:
            msg = 'problem, we have ' + str(l) + ' answers'
            logger.error(msg)
            return HttpResponse('NOK: ' + msg, 'text/plain', 412)

        name = str(name[0])
        if name[-1] == '.':
            name = name[:-1]
        logger.error(name)
    else:
        # other case, ip direcly accessible ?
        pass
    # at this point name should not be False
    if type(name) is bool:
        msg = 'FATAL: we don\'t have a machine name to muck with...'
        logger.error(msg)
        return HttpResponse('NOK: ' + msg, 'text/plain', 412)

    # find user
    m = models.Machine.objects.get(default_name__fqdn=name)
    logger.error(m)
    if m.owner is None:
        # problem with owner
        msg = 'FATAL: unable to find owner for machine ' + name
        logger.error(msg)
        return HttpResponse('NOK: ' + msg, 'text/plain', 412)

    user = m.owner.login
    logger.error(user)

    os = request.GET.get('os', None)
    if os is not None:
        if os == 'WINDOWS':
            os = af.MTYPE_WINDOWS
        elif os == 'LINUX':
            os = af.MTYPE_LINUX
        elif os == 'MACOS':
            os = af.MTYPE_MACOS
        else:
            msg = 'FATAL: unknown os type, expected one of WINDOWS, LINUX, MACOS'
            logger.error(msg)
            return HttpResponse('NOK: ' + msg, 'text/plain', 412)
    else:
        msg = 'FATAL: os needs to be specified for now, expected one of WINDOWS, LINUX, MACOS'
        logger.error(msg)
        return HttpResponse('NOK: ' + msg, 'text/plain', 412)

    logger.error(os)

    passwd = af.setupBackupPc(name, user, os)

    if type(passwd) is bool:
        # problem
        return HttpResponse('NOK: ' + msg, 'text/plain', 412)

    return HttpResponse(passwd, 'text/plain')
Beispiel #7
0
	def _gen_group_config (self, gdata) :
		# generate list of users
		#self._log ("_gen_group_config")
		members = []
		#self._log (gdata.keys())
		if 'appSpecName' in gdata.keys() :
			if gdata['appSpecName'] is None :
				self._log ('appSpecName is None, this groups is not a twiki group')
				# tell the caller that everything is fine, even if we didn't do anything
				return True
			asn = gdata['appSpecName']
			#self._log ("asn : "+str(asn))
			if ('twiki' in asn.keys()) and ('members' in gdata.keys()) :
				twiki_group_name = asn['twiki']
				#self._log (twiki_group_name)
				gdm = gdata['members']
				for m in gdm :
					n = None
					if 'appSpecName' in m.keys() :
						asn=m['appSpecName']
						try :
							asn = json.loads(asn)
						except ValueError as e :
							pass
						else :
							if 'twiki' in asn :
								n = asn['twiki']
					if (n is None) and ('first_name' in m.keys()) and ('last_name' in m.keys()) :
						n = self.gen_user_name (m['first_name'], m['last_name'])
					if n is None :
						continue
					members.append(n)
				# sort members
				members.sort()
				# generate members list
				members = ['Main.'+s for s in members]
				twiki_group_members = ', '.join(members)
				
				import time
				# generate file
				s = u'%META:TOPICINFO{author="adminToolCore-Twiki-module" date="'+str(int(time.time()))+u'"}%\n'
				s+= u'%META:TOPICPARENT{name="TWikiGroups"}%\n'
				s+= u'---+!! <nop>'+twiki_group_name+u'\n'
				s+= u'\n'
				s+= u'   * Member list:\n'
				s+= u'      * Set GROUP = '+twiki_group_members+u'\n'
				s+= u'\n'
				s+= u'   * Persons/group who can change the list:\n'
				s+= u'      * Set ALLOWTOPICCHANGE = '+twiki_group_name+u'\n'
				s+= u'\n'
				s+= u'__%MAKETEXT{"Related Topics:"}%__ %WIKIUSERSTOPIC%, TWikiGroups, %TWIKIWEB%.TWikiAccessControl\n'
				s+= u'---\n'
				s+= u'<small> <font color="#808080">\n'
				s+= u'_Dernière mise à jour : '+time.strftime('%d %B %Y')+u'_\n'
				s+= u'</small>\n'
				s+= u'\n'
				s+= u'<!--\n'
				s+= u'   * Set CACHEABLE = off\n'
				s+= u'-->\n'
				#self._log (s)
			
				# copy the contents of s to the twiki system, so as to update the contents of the group
				a = af.rem()
				# save to a temporary file
				import tempfile
				f = tempfile.NamedTemporaryFile ()
				f.write (s.encode('utf-8'))
				f.flush ()
				import os
				# call the remote access file copy
				res = a.copy (TWIKI_SERVER, TWIKI_FILE_OWNER, TWIKI_FILE_GROUP, f.name, 
							  os.path.join(TWIKI_MAIN, twiki_group_name+'.txt'), '0664')
				# destroy the temporary file		
				f.close()
				if not res : 
					a.log ('FATAL: Impossible to create twiki group '+twiki_group_name+'\nunable to copy file to it\'s destination')
					return False
				# everything is fine
				return True
			else :
				# need to log this better
				self._log('FATAL: missing bits in group data')
				return False
		else :
			self._log('no appSpecName defined')
			return False
Beispiel #8
0
    def CreateUserDir(self, *args, **kwargs):
        _, command = args
        if 'logger' in kwargs.keys():
            logger = kwargs['logger']
            if logger is not None:
                self._logger = logger

        c = json.loads(command.data)
        ck = c.keys()
        if 'machine' not in ck:
            self._log('missing \'machine\' name')
            return False
        machine = c['machine']

        # in debug mode, force the storage server from the settings
        from django.conf import settings
        if settings.DEBUG:
            try:
                settings.STORAGE_SERVER
            except NameError as e:
                # skip...
                self._log(
                    'FATAL: we are in DEBUG mode and settings.STORAGE_SERVER is not defined'
                )
                return False
            else:
                self._log(
                    'DEBUG MODE :\ndirectories should normally be created on \''
                    + machine + '\'\nwill be created on \'' +
                    settings.STORAGE_SERVER + '\' instead')
                machine = settings.STORAGE_SERVER

        if ('basedir' not in ck) and ('uid' not in ck):
            return False
        dirname = c['basedir'] + '/' + c['uid']
        if 'uidNumber' not in ck:
            return False
        try:
            uid = int(c['uidNumber'])
        except ValueError as e:
            return False
        if 'gidNumber' not in ck:
            self._log('missing \'gidNumber\' field')
            return False
        try:
            gid = int(c['gidNumber'])
        except ValueError as e:
            return False
        if 'modes' not in ck:
            return False
        modes = c['modes']
        if 'files' not in ck:
            files = None
        else:
            files = c['files']

        # NOTE: this is ok when the application server is running as root.
        # the case when it's not needs to be analyzed
        # also, this takes a long time, should be running in a separate
        # process
        from admtooLib import AdminFunctions as af
        created_ok = af.createDirectory(machine, dirname, uid, gid, modes,
                                        files)
        if created_ok:
            self._log('success')
            return True
        self._log('FAIL')
        return False