views.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. from django.shortcuts import render
  2. from django.http import HttpResponseRedirect
  3. from django.urls import reverse
  4. from django import template
  5. from .models import *
  6. from .forms import *
  7. from supporto import managepassword
  8. from sicurezza.views import *
  9. from logger.views import *
  10. from comunicazioni.views import *
  11. from datetime import date
  12. from configurazione.views import *
  13. from mqtt import views as m
  14. from random import randint
  15. @securitywrap
  16. def FtpList(request):
  17. session = getSessionParms(request)
  18. userauth = session['_userauth_']
  19. ftp2edit = session['_ftp2edit_']
  20. domain2edit = session['_domain2edit_']
  21. request.session['_from_']="Ftp:FtpList"
  22. _from_ = session['_from_']
  23. print("_from_",_from_)
  24. print("next",next)
  25. try:
  26. utenteautorizzato = User.objects.get(pk=userauth)
  27. except User.DoesNotExist as dne:
  28. return HttpResponseRedirect(reverse('Login:login',args={}))
  29. c = m.start()
  30. m.publish(c,'Messaggio/Ftp',json.dumps({'me':"Accesso al ftp di {}".format(utenteautorizzato.nome)}))
  31. if not domain2edit:
  32. domain2edit = utenteautorizzato.domain.id
  33. dominio = Domini.objects.get(pk=domain2edit)
  34. ftplist = FTPUser.objects.filter(dominio=domain2edit).order_by('utente')
  35. value={}
  36. value['utenteautorizzato'] = utenteautorizzato
  37. value['ftp'] = None
  38. value['ftplist'] = ftplist
  39. value['dominio'] = dominio
  40. value['navbar'] = True
  41. print("livello autorizzazione",utenteautorizzato.securitylevel_id)
  42. securitylevel = getSecurityLevel(utenteautorizzato.securitylevel_id)
  43. securityrow = getSecurityRow(utenteautorizzato.securitylevel_id)
  44. securitylist = getSecurityList(securityrow)
  45. value['securitylist'] = securitylist
  46. value['securityrow'] = securityrow
  47. value['securityrowLen'] = len(securityrow)
  48. value['CANWRITE']=True #per il momento, questo flag serve a capire se e' un record nuovo
  49. if request.method=="POST":
  50. if 'Ritorna' in request.POST:
  51. return HttpResponseRedirect(reverse('Login:welcome',args={}))
  52. if "Nuovo Accesso FTP" in request.POST:
  53. print('nuovo ftp')
  54. request.session['_ftp2edit_'] = 0
  55. return HttpResponseRedirect(reverse('Ftp:FtpEdit',args={}))
  56. if "BackupAllFTPHTTP" in request.POST:
  57. for d in value['ftplist']:
  58. q={}
  59. q['op']='backup'
  60. q['do']=d.dominio.nome
  61. q['dt']=d.dominio.http_server.path
  62. q['ho']=d.ftpgroup.directory % {'site':d.dominio.nome,'ftp':d.utente}
  63. if d.ftpgroup.section == 'http':
  64. q['su']='site'
  65. else:
  66. q['su'] = ''
  67. topic = 'ftp/' + d.dominio.http_server.nome.strip()
  68. print('topic:',topic,q)
  69. m.publish(c,topic,json.dumps(q))
  70. topic = '/Richiesta/Ftp/' + d.dominio.http_server.nome.strip()
  71. print('topic:',topic,q)
  72. m.publish(c,topic,json.dumps(q))
  73. '''
  74. record.dominio__id = formftp.cleaned_data.get('dominio')
  75. record.utente = formftp.cleaned_data.get('utente')
  76. record.clear = formftp.cleaned_data.get('password1')
  77. record.crypt = managepassword.GeneraPassword(record.clear)
  78. record.password_change_enabled = formftp.cleaned_data.get('password_change_enable')
  79. record.enabled = formftp.cleaned_data.get('enabled')
  80. record.tobedeleted = formftp.cleaned_data.get('tobedeleted')
  81. record.ftpgroup_id = formftp.cleaned_data.get('ftpgroup')
  82. record.ftpserver_id = formftp.cleaned_data.get('ftpserver')
  83. '''
  84. if "Edit" in request.POST:
  85. print('id da editare',request.POST['Edit'])
  86. request.session['_ftp2edit_'] = request.POST['Edit']
  87. return HttpResponseRedirect(reverse('Ftp:FtpEdit',args={}))
  88. if "enabledisablebutton" in request.POST:
  89. print('id da gestioree',request.POST['enabledisablebutton'])
  90. idpost = request.POST['enabledisablebutton']
  91. u = FTPUser.objects.get(pk=idpost)
  92. u.enabled= not u.enabled
  93. t = date.today()
  94. #u.account_date_disabled=t.strftime("%Y-%m-%d")
  95. u.save()
  96. if "BackupFTPHTTP" in request.POST:
  97. print('id da attivare',request.POST.get('BackupFTPHTTP'))
  98. idpost = request.POST.get('BackupFTPHTTP')
  99. u = FTPUser.objects.get(pk=idpost)
  100. q={}
  101. q['op']='backup'
  102. q['do']=u.dominio.nome
  103. q['dt']=u.dominio.http_server.path
  104. q['ho']=u.ftpgroup.directory % {'site':u.dominio.nome,'ftp':u.utente}
  105. if u.ftpgroup.section == 'http':
  106. q['su']='/site'
  107. else:
  108. q['su'] = ''
  109. topic = 'Ftp/' + u.dominio.http_server.nome.strip()
  110. print('topic:',topic,q)
  111. m.publish(c,topic,json.dumps(q))
  112. topic = '/Richiesta/Ftp/' + u.dominio.http_server.nome.strip()
  113. print('topic:',topic,q)
  114. m.publish(c,topic,json.dumps(q))
  115. return render(request,"Ftp.List.html",value)
  116. def FtpEdit(request):
  117. session = getSessionParms(request)
  118. userauth = session['_userauth_']
  119. ftp2edit = session['_ftp2edit_']
  120. domain2edit = session['_domain2edit_']
  121. _from_ = session['_from_']
  122. print("_from_",_from_)
  123. utenteautorizzato = User.objects.get(pk=userauth)
  124. print('utente autorizzato: ',utenteautorizzato.mail)
  125. try:
  126. dominio = Domini.objects.get(pk=domain2edit)
  127. except Domain.DoesNotExist as dne:
  128. print("errore, il dominio non e' correttamente gestito in ftpEdit")
  129. dominio = utenteautorizzato.domain
  130. if ftp2edit:
  131. record = FTPUser.objects.get(pk=ftp2edit)
  132. #aggiorna il record con il contenuto nuovo dei record relativi alla posizione e al server
  133. tmphomedir = record.ftpgroup.home
  134. if record.ftpgroup.l3:
  135. tmphomedir += record.utente + '.'
  136. tmphomedir += record.dominio.nome
  137. if len(record.ftpgroup.sub) > 0:
  138. tmphomedir += record.ftpgroup.sub + record.utente
  139. print('tmphomedir',tmphomedir)
  140. record.homedir = tmphomedir
  141. else:
  142. record = FTPUser()
  143. record.utente = str(randint(10000000,99999999))
  144. record.dominio = dominio
  145. record.enabled = dominio.enabled
  146. record.password_change_enabled = True
  147. record.edit = True #prima volta, si puo' modificare il campo.
  148. value={}
  149. value['utenteautorizzato'] = utenteautorizzato
  150. value['dominio'] = dominio
  151. value['registrar'] = Registrar.objects.all().filter(enabled=True)
  152. value['ftp_password_length'] = getConfigurazione('ftp_password_length')
  153. value['ftp_password_message'] = getConfigurazione('ftp_password_message')
  154. print(value)
  155. print("livello autorizzazione",utenteautorizzato.securitylevel_id)
  156. securitylevel = getSecurityLevel(utenteautorizzato.securitylevel.id)
  157. securityrow = getSecurityRow(securitylevel.id)
  158. securitylist = getSecurityList(securityrow)
  159. value['securityrow'] = securityrow
  160. value['securityrowLen'] = len(securityrow)
  161. value['securitylist'] = securitylist
  162. value['navbar']=True
  163. value['ftp'] = record
  164. ftpgroup = FTPGroup.objects.filter(enabled=1).order_by('nomegruppo')
  165. ftpserver = FTPServer.objects.filter(enabled=1).order_by('nome')
  166. value['ftpgroupv'] = ftpgroup
  167. value['ftpserverv'] = ftpserver
  168. if 'Ritorno' in request.POST:
  169. return HttpResponseRedirect(reverse('Ftp:FtpList'))
  170. if request.method == "POST":
  171. ## e' stato richiesto il post.
  172. formftp = formFtp(request.POST)
  173. formftp.update()
  174. if formftp.is_valid():
  175. print('record valido, via al salvataggio: ',formftp.is_valid())
  176. record.dominio__id = formftp.cleaned_data.get('dominio')
  177. record.utente = formftp.cleaned_data.get('utente')
  178. record.password_change_enabled = formftp.cleaned_data.get('password_change_enabled')
  179. if record.password_change_enabled:
  180. record.clear = formftp.cleaned_data.get('password1')
  181. record.crypt = managepassword.GeneraPassword(record.clear)
  182. print('password_change_enabled',record.password_change_enabled)
  183. if 'enabled' in formftp.cleaned_data:
  184. record.enabled = formftp.cleaned_data.get('enabled')
  185. print('enabled',formftp.cleaned_data.get('tobedeleted'))
  186. record.tobedeleted = formftp.cleaned_data.get('tobedeleted')
  187. record.ftpgroup_id = formftp.cleaned_data.get('ftpgroup')
  188. record.ftpserver_id = formftp.cleaned_data.get('ftpserver')
  189. record.mail = formftp.cleaned_data.get('mail')
  190. record.edit = formftp.cleaned_data.get('edit')
  191. record.save()
  192. c = m.start()
  193. topic = '/Messaggio/Ftp/{}/{}'.format(record.ftpgroup.home,record.dominio.nome)
  194. m.publish(c,topic,json.dumps({'ftp':'Accesso al ftp di {}@{}'.format(record.utente,record.dominio.nome)}))
  195. q = {}
  196. q['op'] = 'CreateSpace'
  197. q['do'] = record.dominio.nome
  198. q['dp'] = record.ftpgroup.home
  199. parametri = {}
  200. parametri['_defaultdomain_']=record.dominio.nome
  201. parametri['_defaulthome_']=record.ftpgroup.home
  202. parametri['_defaultip_']=record.ftpgroup.server
  203. parametri['_defaulthttpport_'] = record.ftpgroup.http_port
  204. q['pc'] = getConfigurazione('default_proxy_http_config').format(**parametri)
  205. q['pf'] = getConfigurazione('default_proxy_http_name').format(**parametri)
  206. q['wc'] = getConfigurazione('default_webserver_http_config').format(**parametri)
  207. q['wf'] = getConfigurazione('default_webserver_http_name').format(**parametri)
  208. print(q)
  209. m.publish(c,'Http',json.dumps(q))
  210. m.publish(c,'Richiesta/Http',json.dumps(q))
  211. # verifica cancellazione
  212. if record.tobedeleted:
  213. record.enabled = False
  214. record.save()
  215. sm = ServizioMail()
  216. sql_notifica = getConfigurazione('ftp:notifica')
  217. sql_notifica = re.split(',| ',sql_notifica)
  218. sm.set_listadestinatari(sql_notifica)
  219. if formftp.cleaned_data.get('mail_send'):
  220. mailweb = formftp.cleaned_data.get('mail')
  221. mailweb = re.split(',| ',mailweb)
  222. sm.add_listadestinatari(mailweb)
  223. # questo dovrebbe essere il profilo per la gestione via mail.
  224. #sm.add_listadestinatari(getConfigurazione('service'))
  225. #recuperiamo il template
  226. template = Template.objects.get(pk=getConfigurazione('ftp:template'))
  227. template_soggetto = template.soggetto
  228. sm.set_soggetto(template_soggetto)
  229. template_oggetto = template.oggetto
  230. sm.set_oggetto(template_oggetto)
  231. template_dati = {}
  232. template_dati['ftpuser'] = record
  233. sm.set_data(template_dati)
  234. sm.send()
  235. return HttpResponseRedirect(reverse('Ftp:FtpList',args={}))
  236. else:
  237. print("is_valid: ",formftp.is_valid())
  238. print("formftp.errors")
  239. print(formftp.errors)
  240. for e in formftp.errors:
  241. print("errors:",e)
  242. print("***")
  243. value['formftp'] = formFtp(request.POST)
  244. value['formftp'].update()
  245. else:
  246. ## verifica se e' post o meno....
  247. print('Post Non validato')
  248. temp={}
  249. temp['dominio'] = record.dominio.id
  250. temp['dominio_domain'] = record.dominio.nome
  251. temp['utente'] = record.utente
  252. if ftp2edit:
  253. print("ftp2edit presente")
  254. temp['ftpgroup'] = record.ftpgroup_id
  255. temp['ftpserver'] = record.ftpserver_id
  256. temp['home'] = record.ftpgroup.home
  257. temp['sub'] = record.ftpgroup.sub
  258. temp['l3'] = record.ftpgroup.l3
  259. temp['edit'] = record.edit
  260. '''
  261. 21.01.22
  262. home dir visualizza la path costruita attraverso la query sql
  263. sqlnamedquery user_by_name SELECT "concat(ftp_user.user,'@',domini.nome) as username,crypt as passwd,ftp_home.uid as uid,ftp_home.gid as gid,concat(ftp_home.home,if(l3,concat(ftp_user.user,'.'),''),domini.nome,if(ftp_home.sub != '',concat(ftp_home.sub,ftp_user.user),'')) as homedir,shell from ftp_user join domini on ftp_user.domain = domini.id join ftp_home on ftp_user.ftp_home = ftp_home.id where (ftp_user.user=substring_index('%U','@',1) and domini.nome=substring_index('%U','@',-1)) and ftp_user.enabled = 1 and ftp_user.tobedeleted = 0 and domini.enabled = 1 and domini.ftp = 1 and domini.tobedeleted = 0 and (ftp_user.server = '7109' or ftp_user.server= '0');"
  264. if record.l3 la stringa inizia col nome utente che e' il 3 livello
  265. poi viene il nome dominio
  266. poi vengono la path ftp e infine l'eventuale utente ftp nel caso sia un ftp non primario (web)
  267. '''
  268. tmphomedir = temp['home']
  269. if temp['l3']:
  270. tmphomedir += temp['utente'] + '.'
  271. tmphomedir += temp['dominio_domain']
  272. if len(temp['sub']) > 0:
  273. tmphomedir += temp['sub'] + temp['utente']
  274. print('tmphomedir',tmphomedir)
  275. temp['homedir'] = tmphomedir
  276. temp['password1'] = record.clear
  277. temp['password2'] = record.clear
  278. temp['clear'] = record.clear
  279. else:
  280. print("ftp2edit non presente")
  281. temp['ftpserver'] = 0
  282. temp['ftpgroup'] = 0
  283. newpassword = getPassword()
  284. temp['password1'] = newpassword
  285. temp['password2'] = newpassword
  286. temp['clear'] = newpassword
  287. temp['enabled'] = record.enabled
  288. temp['tobedeleted'] = record.tobedeleted
  289. temp['password_change_enabled'] = record.password_change_enabled
  290. print('password_change_enabled',record.password_change_enabled)
  291. temp['nota'] = record.nota
  292. temp['mail'] = record.mail
  293. temp['edit'] = record.edit
  294. value['formftp'] = formFtp(temp)
  295. value['formftp'].update()
  296. return render(request,"Ftp.Edit.html",value)