Revisión 343
Añadido por Manu Mora Gordillo hace casi 13 años
controlies/trunk/applications/controlies/models/menu.py | ||
---|---|---|
response.menu+=[('Gestión', False, None,[
|
||
('Servidores de Aula', False,URL( 'gestion', 'servidores_aula')),
|
||
('Importación de Rayuela', False, URL( 'gestion', 'rayuela')),
|
||
]
|
||
)]
|
||
|
||
response.menu+=[('Base Datos', False, None,[
|
||
('Portátiles', False,URL( 'database', 'laptops')),
|
||
]
|
||
)]
|
||
|
||
|
||
#('Mantenimiento de LDAP', False, None,
|
||
# [
|
||
... | ... | |
# ('Detección de uid o gid duplicados', False, URL( 'gestion', 'duplicados')),
|
||
|
||
# ]),
|
||
]
|
||
)]
|
controlies/trunk/applications/controlies/views/database/laptops.html | ||
---|---|---|
<!-- Libreria Multiselect -->
|
||
{{response.files.append(URL('static','js/multiselect/jquery.multiselect.css'))}}
|
||
{{response.files.append(URL('static','js/multiselect/jquery.multiselect.min.js'))}}
|
||
{{response.files.append(URL('static','js/multiselect/jquery.multiselect.es.js'))}}
|
||
{{#response.files.append(URL('static','css/helper.css'))}}
|
||
{{#response.files.append(URL('static','css/dropdown.css'))}}
|
||
{{#response.files.append(URL('static','css/default.advanced.css'))}}
|
||
|
||
{{extend 'layout.html'}}
|
||
|
||
<div id="tabla_clientes" class="centerGrid">
|
||
<table width="100%" align="center">
|
||
<tr>
|
||
<td style="width:2%"></td>
|
||
<td style="text-align:center;"><table id="list" width="100%"></table></td>
|
||
<td style="width:2%"></td>
|
||
</tr>
|
||
</table>
|
||
<div id="pager" style=""></div>
|
||
<div id="filter" style="margin-left:30%;display:none">Buscar nada</div>
|
||
</div>
|
||
|
||
<div id="dialog-form"></div>
|
||
<div id="dialog-form2"></div>
|
||
|
||
<div id="dialog-confirm" title="¿Borrar el registro seleccionado?" style="display:none;">
|
||
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Este elemento quedará permanentemente eliminado. ¿Está seguro?</p>
|
||
</div>
|
||
|
||
<div id="dialog-alert" title="Atención" style="display:none;">
|
||
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Para operar sobre un registro debe seleccionarlo previamente.</p>
|
||
</div>
|
||
|
||
|
||
<script type="text/javascript">
|
||
|
||
jQuery(function() {
|
||
jQuery("#dialog-confirm").dialog({ autoOpen: false });
|
||
jQuery("#dialog-alert").dialog({ autoOpen: false });
|
||
});
|
||
|
||
|
||
function print_grid(){
|
||
jQuery("#list").jqGrid({
|
||
url:"{{=URL(c='laptops',f='call',args=['json','list'])}}",
|
||
data: "{}",
|
||
datatype: 'json',
|
||
mtype: 'GET',
|
||
contentType: "application/json; charset=utf-8",
|
||
complete: function(jsondata, stat) {
|
||
if (stat == "success") {
|
||
var thegrid = jQuery("#list")[0];
|
||
thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
|
||
}
|
||
},
|
||
|
||
colNames:['Marca','Modelo','Número Serie'],
|
||
colModel:[
|
||
{name:'marca',index:'marca', width:60, align:"center"},
|
||
{name:'modelo',index:'modelo', width:115, align:"center"},
|
||
{name:'numero_serie',index:'numero_serie', width:115, align:"center"}
|
||
],
|
||
rowNum:25,
|
||
height:335,
|
||
width: 900,
|
||
rowList:[25,50,75],
|
||
pager: '#pager',
|
||
sortname: 'marca',
|
||
autowidth: false,
|
||
viewrecords: true,
|
||
sortorder: "desc",
|
||
caption:"Portátiles"
|
||
|
||
});
|
||
jQuery("#list").jqGrid('navGrid','#pager',{add:false,edit:false,del:false,search:false,refresh:false});
|
||
|
||
jQuery("#list").jqGrid('navButtonAdd','#pager',{
|
||
caption: "Insertar",
|
||
buttonicon :'ui-icon-plus',
|
||
onClickButton : function (){
|
||
addRecord();
|
||
}
|
||
});
|
||
jQuery("#list").jqGrid('navButtonAdd','#pager',{
|
||
caption: "Modificar",
|
||
buttonicon :'ui-icon-pencil',
|
||
onClickButton : function (){
|
||
modifyRecord();
|
||
}
|
||
});
|
||
jQuery("#list").jqGrid('navButtonAdd','#pager',{
|
||
caption: "Borrar",
|
||
buttonicon :'ui-icon-trash',
|
||
onClickButton : function (){
|
||
deleteRecord();
|
||
}
|
||
});
|
||
|
||
|
||
jQuery("#list").jqGrid('filterToolbar');
|
||
|
||
}
|
||
|
||
|
||
function rowSelected(){
|
||
var uid = jQuery("#list").jqGrid('getGridParam','selrow');
|
||
|
||
if( uid == null ){
|
||
jQuery( "#dialog-alert" ).dialog({
|
||
resizable: false,
|
||
height:150,
|
||
width:290,
|
||
modal: true,
|
||
buttons: { "Aceptar": function() { $( this ).dialog( "close" ); }}
|
||
}).dialog('open');
|
||
return false;
|
||
}
|
||
return uid;
|
||
}
|
||
|
||
function addRecord(){
|
||
|
||
jQuery("#messageLoading").show();
|
||
|
||
jQuery("#dialog-form").html("").css("display","none");
|
||
jQuery("#dialog-form").load("form.html", function() {
|
||
getAllGroups();
|
||
jQuery("#form_data #action").val("add");
|
||
jQuery("#form_data #homeDirectoryP").css("display","block");
|
||
|
||
jQuery("#form_data #messageForm").html("Todos los campos son obligatorios");
|
||
|
||
x = (jQuery(window).width()-350)/2;
|
||
y = (jQuery(window).height()-500)/2;
|
||
|
||
jQuery("#messageLoading").hide();
|
||
|
||
jQuery("#dialog-form").dialog({
|
||
resizable: false,
|
||
position: top,
|
||
modal: true,
|
||
width: 350,
|
||
title: "Añadir Portátil"
|
||
}).dialog('option', 'position', [x, y]);
|
||
});
|
||
}
|
||
|
||
function modifyRecord(){
|
||
var uid;
|
||
|
||
jQuery("#messageLoading").show();
|
||
|
||
var uid = rowSelected();
|
||
if(uid==false)
|
||
return false;
|
||
|
||
jQuery("#dialog-form").html("").css("display","none");
|
||
jQuery("#dialog-form").load("form.html", function() {
|
||
|
||
getAllGroups();
|
||
|
||
jQuery("#form_data #action").val("modify");
|
||
jQuery("#form_data #user").attr("readonly","true");
|
||
jQuery("#form_data #user").css("background-color","#DDD");
|
||
jQuery("#form_data #messageForm").html("Si deja la contraseña en blanco no se modificará<br>El resto de campos son obligatorios");
|
||
|
||
jQuery.post('call/json/getUserData',{ username: uid }, function(result) {
|
||
//var result = jQuery.parseJSON(data);
|
||
|
||
if(result.response['type']=="teacher")
|
||
var textType = "Profesor";
|
||
else
|
||
var textType = "Alumno";
|
||
|
||
var dep = Array(result.response['groups']['departments']);
|
||
|
||
jQuery("#form_data #type").replaceWith(textType+"<input type='hidden' id='type' name='type' value='"+result.response['type']+"'/>");
|
||
jQuery("#form_data #name").val(result.response['name']);
|
||
jQuery("#form_data #nif").val(result.response['nif']);
|
||
jQuery("#form_data #user").val(result.response['user']);
|
||
jQuery("#form_data #surname").val(result.response['surname']);
|
||
if (result.response['photo']!='')
|
||
jQuery("#form_data #photo").attr("src","data:image/png;base64,"+result.response['photo']);
|
||
|
||
$.each(result.response['groups']['departments'], function(i, l){
|
||
jQuery('#form_data input:checkbox[value='+l+']').attr('checked', true);
|
||
});
|
||
|
||
$.each(result.response['groups']['classrooms'], function(i, l){
|
||
jQuery('#form_data input:checkbox[value='+l+']').attr('checked', true);
|
||
});
|
||
|
||
x = (jQuery(window).width()-350)/2;
|
||
y = (jQuery(window).height()-500)/2;
|
||
|
||
jQuery("#messageLoading").hide();
|
||
|
||
jQuery("#dialog-form").dialog({
|
||
resizable: false,
|
||
modal: true,
|
||
width: 350,
|
||
title: "Modificar Usuario"
|
||
}).dialog('option', 'position', [x, y]);
|
||
});
|
||
});
|
||
}
|
||
|
||
function deleteRecord(){
|
||
|
||
var uid = rowSelected();
|
||
if(uid==false)
|
||
return false;
|
||
|
||
jQuery( "#dialog-confirm" ).dialog({
|
||
resizable: false,
|
||
height:160,
|
||
width:350,
|
||
modal: true,
|
||
buttons: {
|
||
"Borrar": function() {
|
||
jQuery.post("call/json/delete","user="+uid, function(data){
|
||
jQuery("#dialog-confirm").dialog( "close" );
|
||
jQuery("#list").trigger("reloadGrid");
|
||
});
|
||
},
|
||
"Cancelar": function() {
|
||
$(this).dialog( "close" );
|
||
}
|
||
}
|
||
}).dialog('open');
|
||
}
|
||
|
||
</script>
|
||
|
||
<script type="text/javascript">
|
||
jQuery(document).ready(function(){ print_grid();});
|
||
</script>
|
||
controlies/trunk/applications/controlies/controllers/laptops.py | ||
---|---|---|
# coding: utf8
|
||
from applications.controlies.modules.Laptops import Laptops
|
||
from applications.controlies.modules.MySQLConnection import MySQLConnection
|
||
from applications.controlies.modules.Utils import Utils
|
||
|
||
def index():
|
||
return dict()
|
||
|
||
@service.json
|
||
@auth.requires_login()
|
||
def list():
|
||
my = MySQLConnection()
|
||
l = Laptops(my,"","")
|
||
response = l.list(request.vars)
|
||
#my.close()
|
||
return response
|
||
|
||
@service.json
|
||
@auth.requires_login()
|
||
def searchUsername():
|
||
l=conecta()
|
||
u = Users(l,"",request.vars['name'],request.vars['name'],"","","","","","")
|
||
response = u.searchNewUsername()
|
||
l.close()
|
||
return dict(response=response)
|
||
|
||
@service.json
|
||
def getUserData():
|
||
l=conecta()
|
||
u = Users(l,"","","","",request.vars['username'],"","","","")
|
||
response = u.getUserData()
|
||
l.close()
|
||
return dict(response=response)
|
||
|
||
|
||
@service.json
|
||
def getAllUsers():
|
||
import applications.controlies.modules.Utils.LdapUtils as LdapUtils
|
||
l=conecta()
|
||
response = LdapUtils.getAllUsers(l)
|
||
l.close()
|
||
return response
|
||
|
||
@service.json
|
||
@auth.requires_login()
|
||
def delete():
|
||
l=conecta()
|
||
u = Users(l,"","","","",request.vars['user'],"","","","")
|
||
response = u.delete()
|
||
l.close()
|
||
return dict(response=response)
|
||
|
||
@service.json
|
||
@auth.requires_login()
|
||
def modify_user():
|
||
|
||
l=conecta()
|
||
departments=[]
|
||
classrooms=[]
|
||
if 'multiselect_departments' in request.vars: departments = request.vars['multiselect_departments']
|
||
if 'multiselect_classrooms' in request.vars:classrooms = request.vars['multiselect_classrooms']
|
||
|
||
u = Users(l,request.vars['type'],request.vars['name'],request.vars['name'],request.vars['nif'],request.vars['user'],request.vars['password'],request.vars['password2'],departments,classrooms)
|
||
response = u.process(request.vars['action'])
|
||
l.close()
|
||
return dict(response = response)
|
||
#return dict(response = "OK")
|
||
|
||
@service.json
|
||
@auth.requires_login()
|
||
def create_home_directory_withoutpass():
|
||
from applications.controlies.modules.SSHConnection import SSHConnection
|
||
|
||
c = SSHConnection("servidor","root","")
|
||
response = c.connectWithoutPass("/var/web2py/applications/controlies/.ssh/id_rsa")
|
||
|
||
if response != True:
|
||
return dict(response = response)
|
||
|
||
l=conecta()
|
||
u = Users(l,"","","","",request.vars['username'],"","","","")
|
||
responseUser = u.getUserData()
|
||
l.close()
|
||
|
||
homeDirectory = Utils.homeDirectory(request.vars['type'])+responseUser["user"]
|
||
|
||
c.exec_command("cp -r /etc/skel "+homeDirectory)
|
||
c.exec_command("chown -R "+responseUser["uidnumber"]+":"+responseUser["gidnumber"]+" "+homeDirectory)
|
||
c.close()
|
||
|
||
return dict(response = "OK")
|
||
|
||
|
||
@service.json
|
||
@auth.requires_login()
|
||
def create_home_directory():
|
||
from applications.controlies.modules.SSHConnection import SSHConnection
|
||
|
||
#c = SSHConnection(request.vars['host'],request.vars['user'],request.vars['password'])
|
||
c = SSHConnection("servidor","root",request.vars['password'])
|
||
response = c.process()
|
||
print request.vars
|
||
if response != True:
|
||
return dict(response = response)
|
||
|
||
l=conecta()
|
||
u = Users(l,"","","","",request.vars['username'],"","","","")
|
||
responseUser = u.getUserData()
|
||
l.close()
|
||
|
||
homeDirectory = Utils.homeDirectory(request.vars['type'])+responseUser["user"]
|
||
|
||
c.exec_command("cp -r /etc/skel "+homeDirectory)
|
||
c.exec_command("chown -R "+responseUser["uidnumber"]+":"+responseUser["gidnumber"]+" "+homeDirectory)
|
||
|
||
try:
|
||
if request.vars["trustRelationship"] == "on":
|
||
dir_ssh = "/var/web2py/applications/controlies"
|
||
Utils.generateRSAkeys(dir_ssh)
|
||
c.open_ftp()
|
||
c.removeFile("/tmp/controlIES_rsa.pub")
|
||
c.putFile(dir_ssh+"/.ssh/id_rsa.pub","/tmp/controlIES_rsa.pub")
|
||
c.exec_command('cat /tmp/controlIES_rsa.pub >> /root/.ssh/authorized_keys')
|
||
c.close_ftp()
|
||
except:
|
||
pass
|
||
|
||
c.close()
|
||
return dict(response = "OK")
|
||
|
||
def form():
|
||
return dict()
|
||
|
||
def form_home_directory():
|
||
return dict()
|
||
|
||
def call():
|
||
"""
|
||
exposes services. for example:
|
||
http://..../[app]/default/call/jsonrpc
|
||
decorate with @services.jsonrpc the functions to expose
|
||
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
|
||
"""
|
||
session.forget()
|
||
return service()
|
||
controlies/trunk/applications/controlies/modules/Laptops.py | ||
---|---|---|
##############################################################################
|
||
# -*- coding: utf-8 -*-
|
||
# Project: ControlIES
|
||
# Module: Users.py
|
||
# Purpose: Users class
|
||
# Language: Python 2.5
|
||
# Date: 7-Feb-2011.
|
||
# Ver: 7-Feb-2011.
|
||
# Author: Manuel Mora Gordillo
|
||
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
|
||
#
|
||
# ControlIES is free software: you can redistribute it and/or modify
|
||
# it under the terms of the GNU General Public License as published by
|
||
# the Free Software Foundation, either version 3 of the License, or
|
||
# (at your option) any later version.
|
||
# ControlIES is distributed in the hope that it will be useful,
|
||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
# GNU General Public License for more details.
|
||
# You should have received a copy of the GNU General Public License
|
||
# along with ControlIES. If not, see <http://www.gnu.org/licenses/>.
|
||
#
|
||
##############################################################################
|
||
|
||
from math import floor
|
||
|
||
class Laptops(object):
|
||
|
||
def __init__(self):
|
||
pass
|
||
|
||
def __init__(self,MySQL,numero_serie,marca_modelo):
|
||
self.MySQL = MySQL
|
||
self.numero_serie = numero_serie
|
||
self.marca_modelo = marca_modelo
|
||
|
||
def validation(self,action):
|
||
|
||
if self.numero_serie == "":
|
||
return "numero_serie"
|
||
|
||
if self.marca_modelo == "":
|
||
return "marca_modelo"
|
||
|
||
return "OK"
|
||
|
||
def process(self,action):
|
||
if action == "add":
|
||
val = self.validation(action)
|
||
|
||
if val != "OK":
|
||
return val
|
||
else:
|
||
response = self.add()
|
||
return response
|
||
|
||
if action == "modify":
|
||
val = self.validation(action)
|
||
|
||
if val != "OK":
|
||
return val
|
||
else:
|
||
response = self.modify()
|
||
return response
|
||
|
||
|
||
def list(self,args):
|
||
|
||
sql="SELECT p.id_portatil, pmm.marca, pmm.modelo, p.numero_serie FROM portatiles p, portatiles_marca_modelo pmm "
|
||
sql=sql+"WHERE p.id_marca_modelo=pmm.id_marca_modelo"
|
||
|
||
try:
|
||
sql = sql+" AND p.numero_serie LIKE '%"+args['numero_serie']+"%'"
|
||
except LookupError:
|
||
pass
|
||
|
||
try:
|
||
sql = sql+" AND pmm.marca LIKE '%"+args['marca']+"%'"
|
||
except LookupError:
|
||
pass
|
||
|
||
try:
|
||
sql = sql+" AND pmm.modelo LIKE '%"+args['modelo']+"%'"
|
||
except LookupError:
|
||
pass
|
||
|
||
sql = sql +" ORDER BY "+args['sidx']+" "+args['sord']
|
||
result = self.MySQL.process(sql)
|
||
|
||
rows = []
|
||
for reg in result:
|
||
|
||
row = {
|
||
"id":reg[0],
|
||
"cell":[reg[1],reg[2],reg[3]],
|
||
"marca":reg[1],
|
||
"modelo":reg[2],
|
||
"numero_serie":reg[3]
|
||
}
|
||
rows.append(row)
|
||
|
||
# grid parameters
|
||
limit = int(args['rows'])
|
||
page = int(args['page'])
|
||
start = limit * page - limit
|
||
finish = start + limit;
|
||
|
||
# grid parameters
|
||
if len(rows) > 0:
|
||
totalPages = floor( len(rows) / int(limit) )
|
||
module = len(rows) % int(limit)
|
||
|
||
if module > 0:
|
||
totalPages = totalPages+1
|
||
else:
|
||
totalPages = 0
|
||
|
||
if page > totalPages:
|
||
page = totalPages
|
||
|
||
return { "page":page, "total":totalPages, "records":len(rows), "rows":rows[start:finish] }
|
||
|
||
|
||
"""def add(self):
|
||
|
||
|
||
attr = [
|
||
('objectclass', ['top','posixAccount','shadowAccount','person','inetOrgPerson']),
|
||
('uid', [self.user]),
|
||
('cn', [self.name] ),
|
||
('employeenumber', [self.nif] ),
|
||
('sn', [self.name] ),
|
||
('uidnumber', [maxID] ),
|
||
('gidnumber', [maxID] ),
|
||
('loginshell', ['/bin/bash'] ),
|
||
('homeDirectory', [LdapUtils.whatHome(self.type) + self.user] ),
|
||
#('jpegPhoto', ['jpegPhoto'] ),
|
||
('userpassword', [passwd])
|
||
]
|
||
if self.foto is not None:
|
||
attr.append(('jpegPhoto',[self.foto]))
|
||
|
||
self.ldap.add("uid="+self.user+",ou=People", attr)
|
||
|
||
# Add private group
|
||
attr = [
|
||
('objectclass', ['top','posixGroup','lisGroup']),
|
||
('grouptype', ['private']),
|
||
('gidnumber', [maxID] ),
|
||
('cn', [self.user] ),
|
||
('description', [self.name+' personal group'] )
|
||
]
|
||
|
||
self.ldap.add("cn="+self.user+",ou=Group", attr)
|
||
|
||
|
||
# Add selected groups
|
||
attr = [
|
||
(ldap.MOD_ADD, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
|
||
(ldap.MOD_ADD, 'memberUid', [self.user] )
|
||
]
|
||
|
||
if self.departments != ['']:
|
||
for n in self.departments:
|
||
self.ldap.modify('cn='+ n +',ou=Group', attr)
|
||
|
||
if self.classrooms != ['']:
|
||
for n in self.classrooms:
|
||
self.ldap.modify('cn='+ n +',ou=Group', attr)
|
||
|
||
if self.type=='teacher':
|
||
self.ldap.modify('cn=teachers,ou=Group', attr)
|
||
elif self.type=='student':
|
||
self.ldap.modify('cn=students,ou=Group', attr)
|
||
|
||
return "OK"
|
||
|
||
|
||
def modify(self):
|
||
attr = [
|
||
(ldap.MOD_REPLACE, 'cn', [self.name] ),
|
||
(ldap.MOD_REPLACE, 'employeenumber', [self.nif] ),
|
||
(ldap.MOD_REPLACE, 'sn', [self.surname] )
|
||
]
|
||
|
||
if self.password!="":
|
||
passwd = '{SSHA}' + Utils.encrypt(self.password)
|
||
attr.append((ldap.MOD_REPLACE, 'userpassword', [passwd]))
|
||
|
||
self.ldap.modify("uid="+self.user+",ou=People", attr)
|
||
|
||
# Get current groups
|
||
currentGroups = self.getUserGroups()
|
||
|
||
groupsDepartments = Utils.cmpLists(currentGroups["departments"], self.departments)
|
||
groupsClassrooms = Utils.cmpLists(currentGroups["classrooms"], self.classrooms)
|
||
|
||
# Delete unselected groups
|
||
deleteDepartments = groupsDepartments["onlyInList1"]
|
||
deleteClassrooms = groupsClassrooms["onlyInList1"]
|
||
|
||
attr = [
|
||
(ldap.MOD_DELETE, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
|
||
(ldap.MOD_DELETE, 'memberUid', [self.user] )
|
||
]
|
||
|
||
for d in deleteDepartments:
|
||
self.ldap.modify('cn='+ d +',ou=Group', attr)
|
||
|
||
for d in deleteClassrooms:
|
||
self.ldap.modify('cn='+ d +',ou=Group', attr)
|
||
|
||
# Add selected groups
|
||
newDepartments = groupsDepartments["onlyInList2"]
|
||
newClassrooms = groupsClassrooms["onlyInList2"]
|
||
|
||
attr = [
|
||
(ldap.MOD_ADD, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
|
||
(ldap.MOD_ADD, 'memberUid', [self.user] )
|
||
]
|
||
|
||
for n in newDepartments:
|
||
self.ldap.modify('cn='+ n +',ou=Group', attr)
|
||
|
||
for n in newClassrooms:
|
||
self.ldap.modify('cn='+ n +',ou=Group', attr)
|
||
|
||
return "OK"
|
||
|
||
|
||
def delete(self):
|
||
|
||
self.ldap.delete('uid='+ self.user +',ou=People')
|
||
self.ldap.delete("cn="+self.user+",ou=Group")
|
||
|
||
# Delete unselected groups
|
||
currentGroups = self.getUserGroups()
|
||
|
||
attr = [
|
||
(ldap.MOD_DELETE, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
|
||
(ldap.MOD_DELETE, 'memberUid', [self.user] )
|
||
]
|
||
|
||
for d in currentGroups["departments"]:
|
||
self.ldap.modify('cn='+ d +',ou=Group', attr)
|
||
|
||
for d in currentGroups["classrooms"]:
|
||
self.ldap.modify('cn='+ d +',ou=Group', attr)
|
||
|
||
return "OK"
|
||
|
||
|
||
def existsUsername(self):
|
||
|
||
result = self.ldap.search("ou=People","uid="+self.user,["uid"])
|
||
|
||
if len(result) > 0:
|
||
return True
|
||
|
||
return False
|
||
|
||
|
||
def searchNewUsername(self):
|
||
|
||
result = self.ldap.search("ou=People","uid=*",["uid"])
|
||
users = []
|
||
for i in result:
|
||
users.append(i[0][1]['uid'][0])
|
||
|
||
n = self.name.lower().split(" ")
|
||
|
||
username = ""
|
||
if len(n) > 0:
|
||
username = n[0][0:1]
|
||
|
||
if len(n) > 1:
|
||
username = username + n[1]
|
||
|
||
if len(n) > 2:
|
||
username = username + n[2][0:1]
|
||
|
||
num = 1
|
||
searching = username + "0" + str(num)
|
||
|
||
found = True
|
||
while found:
|
||
try:
|
||
users.index(searching)
|
||
num = num + 1
|
||
|
||
if len(str(num)) == 1:
|
||
searching = username + "0" + str(num)
|
||
else:
|
||
searching = username + str(num)
|
||
except:
|
||
found = False
|
||
|
||
return searching
|
||
|
||
def getUserGroups(self):
|
||
result = self.ldap.search("ou=Group","(&(memberUid="+self.user+")(|(groupType=school_department)(groupType=school_class)))",["cn","groupType"])
|
||
|
||
departments = []
|
||
classrooms = []
|
||
for g in result:
|
||
if g[0][1]["groupType"][0] == "school_department":
|
||
departments.append(g[0][1]["cn"][0])
|
||
elif g[0][1]["groupType"][0] == "school_class":
|
||
classrooms.append(g[0][1]["cn"][0])
|
||
|
||
departments.sort()
|
||
classrooms.sort()
|
||
return { "departments":departments, "classrooms":classrooms }
|
||
|
||
def getUserData(self):
|
||
self.getUserGroups()
|
||
result = self.ldap.search("ou=People","uid="+self.user,["uid","cn","sn","employeenumber","homedirectory","uidnumber","gidnumber","jpegPhoto"])
|
||
|
||
if len(result) == 0:
|
||
return { "user":"", "name":"", "surname":"", "nif":"", "photo":"", "type":"","uidnumber":"","gidnumber":"", "groups":[] }
|
||
|
||
type = "student"
|
||
if result[0][0][1]["homeDirectory"][0][0:14]=="/home/profesor":
|
||
type = "teacher"
|
||
|
||
try:
|
||
photo = base64.b64encode(result[0][0][1]["jpegPhoto"][0])
|
||
except:
|
||
photo = ""
|
||
userdata=result[0][0][1]
|
||
if "employeeNumber" not in userdata: userdata["employeeNumber"]=["0"]
|
||
dataUser = {
|
||
"user":userdata["uid"][0],
|
||
"name":userdata["cn"][0],
|
||
"surname":userdata["sn"][0],
|
||
"nif":userdata["employeeNumber"][0],
|
||
"uidnumber":userdata["uidNumber"][0],
|
||
"gidnumber":userdata["gidNumber"][0],
|
||
"photo":photo,
|
||
"type":type,
|
||
"groups":self.getUserGroups()
|
||
}
|
||
|
||
return dataUser"""
|
||
controlies/trunk/applications/controlies/modules/MySQLConnection.py | ||
---|---|---|
##############################################################################
|
||
# -*- coding: utf-8 -*-
|
||
# Project: ControlIES
|
||
# Module: MySQLConnection.py
|
||
# Purpose: Connection with mysql-server
|
||
# Language: Python 2.5
|
||
# Date: 23-May-2012.
|
||
# Ver: 23-May-2012.
|
||
# Authores: Manuel Mora Gordillo
|
||
# Francisco Damian Mendez Palma
|
||
# Copyright: 2012 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
|
||
# 2012 - Francisco Damian Mendez Palma <fmendezpalma @no-spam@ gmail.com>
|
||
#
|
||
# ControlIES is free software: you can redistribute it and/or modify
|
||
# it under the terms of the GNU General Public License as published by
|
||
# the Free Software Foundation, either version 3 of the License, or
|
||
# (at your option) any later version.
|
||
# ControlIES is distributed in the hope that it will be useful,
|
||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||
# GNU General Public License for more details.
|
||
# You should have received a copy of the GNU General Public License
|
||
# along with ControlAula. If not, see <http://www.gnu.org/licenses/>.
|
||
#
|
||
##############################################################################
|
||
|
||
import MySQLdb
|
||
|
||
class MySQLConnection(object):
|
||
|
||
def __init__(self):
|
||
self.host = "172.23.36.3"
|
||
self.user = "controlies"
|
||
self.passwd = "controlies"
|
||
self.database = "controlies"
|
||
|
||
def process(self,sql):
|
||
self.connect()
|
||
result = self.execute(sql)
|
||
return result
|
||
|
||
def connect(self):
|
||
self.db = MySQLdb.connect(host=self.host,user=self.user, passwd=self.passwd,db=self.database)
|
||
|
||
return True
|
||
|
||
def execute(self,sql):
|
||
self.cursor=self.db.cursor()
|
||
self.cursor.execute(sql)
|
||
result = self.cursor.fetchall()
|
||
self.cursor.close()
|
||
return result
|
||
|
||
def close(self):
|
||
self.db.close()
|
||
Exportar a: Unified diff
Gestión BD portátiles