daily pastebin goal
74%
SHARE
TWEET

Untitled

a guest Jul 21st, 2017 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from django.shortcuts import render
  2. from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
  3. from django.core.mail import send_mail
  4. from django.conf import settings
  5. from .models import Setting,person_external_ca_status,gate,groupGate,group,workerGroup,employee,testResult
  6. from .models2 import Log
  7. from django.shortcuts import render_to_response
  8. from django.template import RequestContext
  9. from django.db import connection
  10. from django.contrib.auth.models import User
  11. from django.utils import timezone
  12. from django.utils.timezone import activate
  13. from django.core import serializers
  14. from .forms import gateAndGroups,gateForm,testForm,groupForm,groupRemoveForm,editAssignationForm,workerAssignationForm
  15. import datetime
  16. import json
  17. import smtplib
  18. import string
  19. import random
  20. #from __future__ import unicode_literals
  21. from os import getenv
  22. import sys
  23. reload(sys)
  24. sys.setdefaultencoding('utf-8')
  25. import pymssql
  26. import decimal
  27.  
  28. def groups(request):
  29.     if request.method == "POST":
  30.         if 'createGroup' in request.POST:
  31.             MyLoginForm = groupForm(request.POST)
  32.             if MyLoginForm.is_valid():
  33.                 groupInstance = group()
  34.                 groupInstance.groupID = int(MyLoginForm.cleaned_data['groupCreateID'])
  35.                 groupInstance.groupName = str(MyLoginForm.cleaned_data['groupCreateName'])
  36.                 groupInstance.save()
  37.         elif 'removeGroup' in request.POST:
  38.             MyLoginForm = groupRemoveForm(request.POST)
  39.             if MyLoginForm.is_valid():
  40.                 test = group.objects.filter(groupID=MyLoginForm.cleaned_data['groupRemoveID'])
  41.                 test.delete()
  42.         elif 'editGroup' in request.POST:
  43.             MyLoginForm = editAssignationForm(request.POST)
  44.             if MyLoginForm.is_valid():
  45.                 objectsToDelete = groupGate.objects.filter(group=group.objects.get(id=MyLoginForm.cleaned_data['realID']))
  46.                 objectsToDelete.delete()
  47.                 groupsList = MyLoginForm.cleaned_data['editGroup'].split(',')
  48.                 for groupToCreate in groupsList:
  49.                     groupInstance = groupGate()
  50.                     groupInstance.group = group.objects.get(id=MyLoginForm.cleaned_data['realID'])
  51.                     groupInstance.gate = gate.objects.get(id=groupToCreate)
  52.                     groupInstance.save()
  53.  
  54.                
  55.  
  56.     json_serializer = serializers.get_serializer("json")()
  57.     groupsAssignment = json_serializer.serialize(groupGate.objects.all(), ensure_ascii=False)
  58.     gates = json_serializer.serialize(gate.objects.all().order_by('gateID'), ensure_ascii=False)
  59.     groups = json_serializer.serialize(group.objects.all().order_by('groupID'), ensure_ascii=False)
  60.     return render(request, "groups.html", {'groupsAssignment':groupsAssignment,"gates":gates,"groups":groups})
  61.  
  62. def gates(request):
  63.     if request.method == "POST":
  64.         if 'gateID_' in request.POST:
  65.             MyLoginForm = gateAndGroups(request.POST)
  66.             if MyLoginForm.is_valid():
  67.                 groupGateInstance = groupGate()
  68.                 temporaryGate = gate.objects.get(id=MyLoginForm.cleaned_data['gateID'])
  69.                 temporaryGroup = group.objects.get(id=MyLoginForm.cleaned_data['groupID'])
  70.                 groupGateInstance.gate = temporaryGate
  71.                 groupGateInstance.group = temporaryGroup
  72.                 groupGateInstance.save()
  73.         elif 'createGate' in request.POST:
  74.             MyLoginForm = gateForm(request.POST)
  75.             if MyLoginForm.is_valid():
  76.                 gateInstance = gate()
  77.                 gateInstance.gateID = int(MyLoginForm.cleaned_data['gateCreateID'])
  78.                 gateInstance.description = str(MyLoginForm.cleaned_data['gateCreateDescription'])
  79.                 gateInstance.save()
  80.         elif 'removeGate' in request.POST:
  81.             MyLoginForm = testForm(request.POST)
  82.             if MyLoginForm.is_valid():
  83.                 test = gate.objects.filter(gateID=MyLoginForm.cleaned_data['gateRemoveID'])
  84.                 test.delete()
  85.  
  86.     gates = gate.objects.all().order_by('gateID')
  87.     #groups = groupGate.objects.all().order_by('id')
  88.     #groupxd = group.objects.all().order_by('id')
  89.     #return render(request, "gates.html", {"gates":gates,"groups":groups,"groupxd":groupxd})
  90.     return render(request, "gates.html", {"gates":gates})
  91.  
  92. def people(request):
  93.     if request.method == "POST":
  94.         if 'assignGroup' in request.POST:
  95.             MyLoginForm = workerAssignationForm(request.POST)
  96.             if MyLoginForm.is_valid():
  97.                 objectsToDelete = workerGroup.objects.filter(worker=employee.objects.get(id=MyLoginForm.cleaned_data['realWorkerID']))
  98.                 objectsToDelete.delete()
  99.                 connectionsList = MyLoginForm.cleaned_data['assignGroup'].split(',')
  100.                 for connectionToCreate in connectionsList:
  101.                     connectionInstance = workerGroup()
  102.                     connectionInstance.worker = employee.objects.get(id=MyLoginForm.cleaned_data['realWorkerID'])
  103.                     connectionInstance.group = group.objects.get(id=connectionToCreate)
  104.                     connectionInstance.save()
  105.     json_serializer = serializers.get_serializer("json")()
  106.     worker = json_serializer.serialize(workerGroup.objects.all(), ensure_ascii=False)
  107.     groups = json_serializer.serialize(group.objects.all(), ensure_ascii=False)
  108.     peoples = json_serializer.serialize(employee.objects.all(), ensure_ascii=False)
  109.     return render(request, "people.html", {'groups':groups,'worker':worker,'peoples':peoples})
  110.  
  111. def show_grid(request):
  112.     return render_to_response('show_grid.html',{},context_instance=RequestContext(request))
  113.  
  114. def get_data(request):
  115.     if 'posStart' in request.GET:
  116.         offset = request.GET["posStart"]
  117.         quantity = request.GET["count"]
  118.     else:
  119.         offset = 0
  120.         quantity = 2000
  121.  
  122.     data = employee.objects.all()[offset:offset+quantity]
  123.     total = employee.objects.all().count()
  124.     worker = workerGroup.objects.all()
  125.     return render_to_response ("get_data.xml", {'data':data,'worker':worker, 'total':total, 'pos':offset}, content_type='type/xml', context_instance=RequestContext(request))
  126.  
  127. def getGates(request):
  128.     data = gate.objects.all().order_by('gateID')
  129.     groups = groupGate.objects.all()
  130.     return render_to_response ("getGates.xml", {'data':data,'groups':groups}, content_type='type/xml', context_instance=RequestContext(request))
  131.  
  132. def getGroups(request):
  133.     xdata = group.objects.all().order_by('groupID')
  134.     return render_to_response ("getGroups.xml", {'xdata':xdata}, content_type='type/xml', context_instance=RequestContext(request))
  135. def updateGates(request):
  136.         test = gate.objects.get(id=request.GET['c2'])
  137.         test.gateID = request.GET['c0']
  138.         test.description = request.GET['c1']
  139.         test.save()
  140.    
  141.  
  142. def updateGroups(request):
  143.     try:
  144.         test = group.objects.get(id=request.GET['c2'])
  145.         test.groupID = request.GET['c0']
  146.         test.groupName = request.GET['c1']
  147.         test.save()
  148.     except:
  149.         return render_to_response(
  150.             'update_data_error.xml',
  151.             {},
  152.             mimetype='text/xml', context_instance=RequestContext(request))
  153.     else:
  154.         return render_to_response(
  155.             'update_data.xml',
  156.             {'id': rid},
  157.             mimetype='text/xml', context_instance=RequestContext(request))(request.GET['c1'])  
  158.  
  159. def update_data(request):
  160.     print('hello')
  161.  
  162. def admin_change_password(request):
  163.     if request.method == "POST":
  164.         mail = request.POST.get("mail")    
  165.         name = str(request.user)
  166.         record = User.objects.get(username=name)
  167.         record.email = mail
  168.         record.save()
  169.         return render(request, "admin_change_password.html", {"mail":mail})
  170.     else:
  171.         name = str(request.user)
  172.         record = User.objects.get(username=name)
  173.         mail = record.email
  174.         return render_to_response ("admin_change_password.html", {"mail":mail}, context_instance=RequestContext(request))
  175.  
  176.  
  177. def get_data_admin(request):
  178.     if 'posStart' in request.GET:
  179.         offset = request.GET["posStart"]
  180.         quantity = request.GET["count"]
  181.     else:
  182.         offset = 0
  183.         quantity = 20
  184.  
  185.     data = User.objects.exclude(username = "admin").exclude(username = "root")[offset:offset+quantity]
  186.     total = User.objects.all().count()
  187.     return render_to_response ("get_data_admin.xml", {'data':data, 'total':total, 'pos':offset}, content_type='type/xml', context_instance=RequestContext(request))
  188.  
  189. def update_data_admin(request):
  190.     global massage
  191.     global whom
  192.     try:       
  193.         rid = request.GET['gr_id']     
  194.         try:
  195.             if request.GET['!nativeeditor_status'] == "deleted":
  196.                 #print('1')
  197.                 r = User.objects.get(id=request.GET['gr_id'])
  198.                 #print('2')
  199.                 date = datetime.datetime.now()
  200.                 #print('3')
  201.                 my_datetime = timezone.make_aware(date, timezone.get_current_timezone())
  202.                 #print('4')
  203.                 name = str(request.user)
  204.                 massage = "Deleted user with ID %s" % request.GET['gr_id'] 
  205.                 #print('5')    
  206.                 recordToLog = Log(User_Name=name, Date_event=my_datetime, Whom=request.GET['gr_id'], Massage=massage)      
  207.                 #print('6')
  208.                 recordToLog.save() 
  209.                 re = User.objects.filter(id=request.GET['gr_id'])
  210.                 re.delete()
  211.             else:
  212.                 #print "w try"     
  213.                 r = User.objects.get(id=rid)
  214.                 #print "w try1"    
  215.                 r.username = request.GET['c0'] 
  216.                 #print "w try2"
  217.                 whom = r.username
  218.                 #print "w try3"
  219.                 r.set_password(request.GET['c1'])
  220.                 #print "w try4"
  221.                 if r.email != request.GET['c2']:
  222.                     massage = "Email set: from %s to %s " % (r.email, request.GET['c2'])           
  223.                 else:
  224.                     massage = "Password was changed"           
  225.                 r.email = request.GET['c2']    
  226.                 r.save()
  227.                 name = str(request.user)
  228.                 date = datetime.datetime.now()
  229.                 #print "w try5"
  230.                 my_datetime = timezone.make_aware(date, timezone.get_current_timezone())           
  231.                 recordToLog = Log(User_Name=name, Date_event=my_datetime, Whom=whom, Massage=massage)      
  232.                 recordToLog.save()
  233.         except:
  234.             #print "w else"
  235.             date = datetime.datetime.now()
  236.             my_datetime = timezone.make_aware(date, timezone.get_current_timezone())
  237.             name = str(request.user)
  238.             massage = "Add new user %s" % request.GET['c0']
  239.             #print str(massage)    
  240.             recordToLog = Log(User_Name=name, Date_event=my_datetime, Whom=request.GET['c0'], Massage=massage)     
  241.             recordToLog.save()
  242.             AddnewRecord = User(password = request.GET['c1'], last_login = my_datetime, is_superuser = False,
  243.                 username = request.GET['c0'], first_name = "", last_name = "", email = request.GET['c2'],
  244.                 is_staff = False, is_active = True, date_joined = my_datetime)         
  245.             AddnewRecord.save()
  246.     except:
  247.         return render_to_response(
  248.             'update_data_error.xml',
  249.             {},
  250.             content_type='text/xml',
  251.             context_instance=RequestContext(request))
  252.     else:
  253.         #print "update"
  254.         return render_to_response(
  255.             'update_data.xml',
  256.             {'id': rid},
  257.             content_type='text/xml',
  258.             context_instance=RequestContext(request))
  259.  
  260. def raporty(request):
  261.     print('hello')
  262.  
  263. #####################################
  264.  
  265. def zmiana(request):
  266.     global data
  267.     global num 
  268.     if request.method == "POST":
  269.         data = request.POST.get("data")
  270.         num = int(request.POST.get("num"))
  271.        
  272.         print "poluczeno"
  273.         print ":"+str(data)+":"
  274.         print ":"+str(num)+":"
  275.         connRTS = pymssql.connect(server='192.168.0.5', user='sa', password='red3fred4', database='KDSoftware')
  276.         cursor = connRTS.cursor()
  277.         sql = "INSERT INTO t_person_external_ca_status1 VALUES ('%s', '%s')" % (num, data)
  278.         print str(sql)
  279.         cursor.execute(sql)
  280.         connRTS.commit()
  281.     return render(request, "raporty.html", {})
  282. ###########################################
  283.  
  284. def saveTestResult(data):
  285.     print("DEBUG: Adding report - ID: "+data['ID_']+" Result: "+data['result'])
  286.     employeerz = employee.objects.get(badge=data['ID_'])
  287.     actualTime = datetime.datetime.now()                               
  288.     timeFinish = actualTime + datetime.timedelta(minutes = int(employeerz.accessTime))
  289.     newRecord = testResult(employeer = employeerz, timeStamp = actualTime, timeValid = timeFinish, result = bool(data['result']), leftLeg = data['leftLeg'], rightLeg = data['rightLeg'], wrist = data['wrist'])
  290.     newRecord.save()
  291.     return {'ex':'session'}
  292.  
  293. def checkEmployeeIsset(badge):
  294.     try:
  295.         result = employee.objects.get(badge=badge)
  296.         print("DEBUG: Employee found")
  297.     except:
  298.         print("DEBUG: Employee not found")
  299.         return False
  300.     return True
  301.  
  302. def checkEmployee(data):
  303.     returnValue = {"ex":"session"}
  304.     if checkEmployeeIsset(data['ID']):
  305.         returnValue["isset"] = "OK"
  306.     else:
  307.         #createNewEmployee(data['ID']) to bedzie gdzies dalej
  308.         returnValue["isset"] = "NO"
  309.     if checkEmployeeGroup(data['ID'],data['gateID']) : returnValue["group"] = "OK"
  310.     else                                             : returnValue["group"] = "NO"
  311.     if checkEmployeeTime(data['ID'])                 : returnValue["time"] = "OK"
  312.     else                                             : returnValue["time"] = "NO"
  313.  
  314.     return returnValue
  315.  
  316. def checkEmployeeRequirements(data):
  317.     employeeRequirements = employee.objects.get(badge=data['ID_'])
  318.     returnValue = {'ex':'session'}
  319.     if employeeRequirements.leftLeg : returnValue['leftLeg']  = 'Y'
  320.     if employeeRequirements.rightLeg: returnValue['rightLeg'] = 'Y'
  321.     if employeeRequirements.wrist   : returnValue['wrist']    = 'Y'
  322.     print("DEBUG: Checking employee requirements : "+str(returnValue))
  323.     return returnValue
  324.  
  325. def checkEmployeeGroup(badge,gateID):
  326.     groupCheck = ''
  327.     getGate = gate.objects.get(gateID=gateID)
  328.     getWorker = employee.objects.get(badge=badge)
  329.     availableGroups = groupGate.objects.filter(gate=getGate)
  330.     for _group in availableGroups:
  331.         if(groupCheck == ''):
  332.             try:
  333.                 groupCheck = workerGroup.objects.get(group=_group.group,worker=getWorker).group
  334.             except:groupCheck = ''
  335.     if groupCheck == '':
  336.         print("DEBUG: Employee has no access to this gate")
  337.         return False
  338.     else:
  339.         print("DEBUG: Employee have access to this gate")
  340.         return True
  341.  
  342. def createNewEmployee(badge):
  343.     AddnewRecord = employee(badge = badge, name = "unknown", lName= "unknown", leftLeg = True, rightLeg = True, wrist = False, accessTime = 30)
  344.     AddnewRecord.save()
  345.     print("DEBUG: Created new employee")
  346.  
  347. def checkEmployeeTime(badge):
  348.     result = checkLastTest(badge)
  349.     if result:
  350.         if not getTimeFromLastReport(result):
  351.             print("DEBUG: Test is required")
  352.             return False
  353.     else:
  354.         print("DEBUG: Test is required")
  355.         return False
  356.     return True
  357.  
  358. def getTimeFromLastReport(lastReport):
  359.     print('DEBUG: Checking access time from last report')
  360.     a = lastReport.timeValid + datetime.timedelta(minutes = 120)
  361.     b = datetime.datetime.now()
  362.     if a.date() >= b.date() and a.time() >= b.time(): return True
  363.     else                                            : return False
  364.  
  365. def checkLastTest(badge):
  366.     try:
  367.         _employee = employee.objects.get(badge=badge)
  368.         result = testResult.objects.order_by('-timeValid').get(employeer=_employee)
  369.         print("DEBUG: Found last test")
  370.         return result
  371.     except:
  372.         print("DEBUG: Last test not found")
  373.         return False
  374.  
  375. def connect(request):  
  376.     if request.method == "GET":
  377.         requestType = request.GET
  378.         if 'watchDog' in requestType:
  379.             return HttpResponse(json.dumps({"info" : str(request.get_host())}), content_type='application/json')
  380.         if 'wrist' in requestType:
  381.             return HttpResponse(json.dumps(saveTestResult(request.GET)), content_type='application/json')
  382.         if 'ID' in requestType:
  383.             return HttpResponse(json.dumps(checkEmployee(request.GET)), content_type='application/json')
  384.         if 'requirement' in requestType:
  385.             return HttpResponse(json.dumps(checkEmployeeRequirements(request.GET)), content_type='application/json')
  386.  
  387.  
  388. def settinds(request):
  389.     mySet = Setting.objects.get()
  390.     host = mySet.Host
  391.     port = mySet.Port
  392.     username = mySet.Username
  393.     password = mySet.Password
  394.     ssl_tls = mySet.UseSSL
  395.     on_off = mySet.ModeUnknown
  396.     #Str_random = id_generation()
  397.     #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  398.     #print "STR_RANDOM  " + str(Str_random)
  399.     #ID_unknown = "unknown_" + str(Str_random)
  400.     #print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  401.     #print "STR_RANDOM  " + str(ID_unknown)    
  402.     SMTP = {
  403.         "Host" : host,
  404.         "Port" : port,
  405.         "Username" : username,
  406.         "Password" : password,
  407.         "ssl" : ssl_tls,
  408.         "on" : on_off
  409.         }
  410.     return render(request, "settings.html", SMTP)
  411.  
  412. #funkcja do generowania id
  413.  
  414. def id_generation(size=9, chars=string.digits):
  415.     return ''.join(random.choice(chars) for _ in range(size))
  416.  
  417. def settingss(request):
  418.     global SMTP
  419.     if request.method == "POST":
  420.         name = str(request.user)
  421.         date = datetime.datetime.now()
  422.         my_datetime = timezone.make_aware(date, timezone.get_current_timezone())
  423.         massage = ""       
  424.         mySet = Setting.objects.get()
  425.         if mySet.Host != request.POST.get("host"):
  426.             massage = "Host set: from %s to %s" % (mySet.Host, request.POST.get("host"))           
  427.         mySet.Host = request.POST.get("host")
  428.  
  429.         if mySet.Port != int(request.POST.get("port")):
  430.             massage = "Port set: from %s to %s" % (mySet.Port, request.POST.get("port"))           
  431.         mySet.Port = int(request.POST.get("port"))
  432.  
  433.         if mySet.Username != request.POST.get("username"):
  434.             massage = "Username set: from %s to %s" % (mySet.Username, request.POST.get("username"))               
  435.         mySet.Username = request.POST.get("username")
  436.  
  437.         if mySet.Password != request.POST.get("password"):
  438.             massage = "Password set: from %s to %s" % (mySet.Password, request.POST.get("password"))           
  439.         mySet.Password = request.POST.get("password")
  440.  
  441.         ssl_tls = request.POST.get("ssl_tls")
  442.         #print ":"+str(ssl_tls)+":"    
  443.         ssl = True
  444.         tls = False
  445.        
  446.         if ssl_tls=="ssl":
  447.             ssl = True
  448.             tls = False
  449.             massage = "SSL set: %s " % ssl
  450.         else:
  451.             ssl = False
  452.             tls = True
  453.             massage = "TLS set: %s" % tls  
  454.         mySet.UseSSL = ssl
  455.         mySet.UseTTL = tls 
  456.  
  457.         on_off = request.POST.get("on_off")
  458.         on = True
  459.         off = False
  460.         if on_off=="on":
  461.             mode = True
  462.             massage = "Mode Unkown set: %s " % on
  463.         else:
  464.             mode = False
  465.             massage = "Mode Unkown set: %s " % off
  466.         mySet.ModeUnknown = mode
  467.  
  468.         SMTP = {
  469.             "Host" : mySet.Host,
  470.             "Port" : mySet.Port,
  471.             "Username" : mySet.Username,
  472.             "Password" : mySet.Password,
  473.             "ssl" : mySet.UseSSL,
  474.             "on" : mySet.ModeUnknown
  475.  
  476.             }
  477.         EMAIL_HOST_USER = mySet.Host
  478.         mySet.save()
  479.         #print "massage"
  480.         #print ":"+str(massage)+":"
  481.         if massage != "":      
  482.             recordToLog = Log(User_Name=name, Date_event=my_datetime, Whom="SMTP", Massage=massage)
  483.             recordToLog.save() 
  484.        
  485.     return render(request, "settings.html", SMTP)
  486.  
  487. def now():
  488.     if settings.USE_TZ:
  489.         return datetame.utc().replace(tzinfo=utc)
  490.     else:
  491.         return datetime.now()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top