Ejemplo n.º 1
0
	def do(self):
		set_notifications()
		
		admins = User.objects.filter(is_staff = True)
		
		if admins.count() > 0:
			admin = admins[0]

			log = Log(component = "notifications", action = "cron", resource = "notifications", user = str(admin), user_id = admin.id, user_email = admin.email, context = {})
			log.save()
Ejemplo n.º 2
0
def add(request):
    if request.POST:
        username = request.POST.get('username',None)
        content = request.POST.get('content',None)
        level = request.POST.get('level',None)
        log = Log(username=username, content=content, level=level)
        log.save()
        
        return HttpResponse(simplejson.dumps({"statusCode":200, "navTabId":request.POST.get('navTabId','logindex'), "callbackType":request.POST.get('callbackType','closeCurrent'), "message":u'添加成功'}), mimetype='application/json')
    else:
        # 弹出新建窗口
        return render_to_response('log/add.html', {'log_level_dict':log_level_dict})
Ejemplo n.º 3
0
def delete(request, tcp_id):
    item  = None
    try:
        item = TCPInfo.objects.get(id=int(tcp_id))
    except BaseException:
        return HttpResponse(simplejson.dumps({"statusCode":400, "message":u'当前TCP服务不存在!'}), mimetype='application/json')
    item.delete()
    
    # 维护redis中当前应用的配置信息
    maintain_tcp_port_configuration(item.app)
    
    # 维护监控项信息
    maintain_monitoritem_delete(item)
    
    # 更新当前应用对应的时间戳
    update_app_timestamp(item.app)
    
    # 日志
    log = Log()
    log.username = request.user.username
    log.log_type = 0
    log.relate_id = item.id
    log.content="execute delete tcpinfo " + item.app.app_name + " " + item.port + " success!"
    log.level = 1
    log.save()
    return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/tcpinfo/index", "message":u'删除成功'}), mimetype='application/json')
Ejemplo n.º 4
0
def edit(request, nocip_id):
    nocip = NOCIP.objects.get(id=int(nocip_id))
    if request.POST:
        nocid = request.POST.get('nocid', None)
        ip = request.POST.get('ip', None)
        # 判断nocid+ip是否重复
        nocips = NOCIP.objects.filter(nocid__iexact=nocid, ip__iexact=ip).exclude(id=int(nocip_id))
        if nocips:
            return HttpResponse(simplejson.dumps({"statusCode":400, "url": "/nocip/index", "message":u'当前机房IP对应信息已经存在不能修改'}), mimetype='application/json')   
        
        nocip.nocid = nocid
        nocip.ip = ip
        nocip.save()
        
        # 更新机房IP对应信息
        maintain_noc_ip_map(nocid)
        
        # 更新当前机房下所有应用对应的时间戳
        update_timestamp_by_nocid(nocid)

        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 0
        log.relate_id = nocip.id
        log.content="execute edit nocip " + nocip.nocid + " " + nocip.ip + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200, "url": "/nocip/index", "message":u'编辑成功'}), mimetype='application/json')    
    return render_to_response('nocip/edit.html',{'nocip':nocip, 'noc_info_dict':noc_info_dict})
Ejemplo n.º 5
0
def edit(request, tcp_id):
    app_list = AppService.objects.filter(type = 3)
    tcpinfo = TCPInfo.objects.get(id=int(tcp_id))
    
    if request.POST:
        tcpinfo.responsetime = request.POST.get('responsetime', None)
        
        tcpinfo.save()
        
        # 维护redis中当前应用的配置信息
        maintain_tcp_port_configuration(tcpinfo.app)
        
        # 维护监控项
        maintain_monitoritem_add_or_update(tcpinfo)
        
        # 更新当前应用对应的时间戳
        update_app_timestamp(tcpinfo.app)

        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 0
        log.relate_id = tcpinfo.id
        log.content="execute edit tcpinfo " + tcpinfo.app.app_name + " " + tcpinfo.port + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200, "url": "/tcpinfo/index", "message":u'编辑成功'}), mimetype='application/json')    
    return render_to_response('tcpinfo/edit.html',{'app_list':app_list, 'tcpinfo':tcpinfo})
Ejemplo n.º 6
0
def add(request):
    pdict = {}
    for key in permission_type_dict:
        if key != 4:    # 节点权限的配置另外实现
            pdict[permission_type_dict[key]]=Permission.objects.filter(type=key).order_by('id')
    
    if request.POST:
        role_name = request.POST.get("role_name")
        role_desc = request.POST.get("role_desc")
        permission_id_list = request.POST.getlist("permission_id")
        # 保存角色信息
        role = Role();
        role.name = role_name
        role.desc = role_desc
        role.save()
        # 保存角色和权限对应关系
        for pid in permission_id_list:
            role.permissions.add(pid)
        
        # 日志
        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 2
        log.relate_id = role.id
        log.content="execute add role " + role.name + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/role/index", "message":u'添加成功'}), 
            mimetype='application/json')
    return render_to_response('role/add.html',{'pdict':pdict})
Ejemplo n.º 7
0
    def do(self):
        set_notifications()

        admins = User.objects.filter(is_staff=True)

        if admins.count() > 0:
            admin = admins[0]

            log = Log(component="notifications",
                      action="cron",
                      resource="notifications",
                      user=str(admin),
                      user_id=admin.id,
                      user_email=admin.email,
                      context={})
            log.save()
Ejemplo n.º 8
0
def formdelete(request, peminjaman_id=0, errormsg=''):
    try:
        object_peminjaman = Peminjaman.objects.get(id=peminjaman_id)
        new_log = Log(peminjaman=None,
                      peminjaman_str=object_peminjaman.__str__(),
                      tanggal=date.today(),
                      deskripsi="",
                      aksi="Hapus")
        new_log.save()
        if object_peminjaman.foto:
            object_peminjaman.foto.delete()
        object_peminjaman.delete()
    except Peminjaman.DoesNotExist:
        pass

    return redirect(reverse('peminjaman:index'))
Ejemplo n.º 9
0
def login(request):
    '''登陆视图'''
    template_var = {}
    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(request.POST.copy())
        if form.is_valid():
            ret = False
            ret = _login(request, form.cleaned_data["username"],
                         form.cleaned_data["password"])
            if ret:
                # 获取登录IP
                RemoteIp = request.META.get('REMOTE_ADDR')
                Log(username=request.user.username,
                    content="execute login user:"******" ip:" + RemoteIp + " success!",
                    level=1).save()
                if request.user.userprofile.user_type == 3:  # 超级管理员
                    return render_to_response(
                        "common/index.html",
                        {'account_usertype_dict': account_usertype_dict},
                        context_instance=RequestContext(request))
                else:  # 其他人员
                    retdir = {}
                    retdir['base_type'] = 0
                    hotspots = Hotspot.objects.order_by('-level')[:10]
                    retdir['hotspots'] = hotspots
                    retdir['account_usertype_dict'] = account_usertype_dict
                    return render_to_response(
                        'tender/index.html',
                        retdir,
                        context_instance=RequestContext(request))
            else:
                vardict = {"message": "登录失败!"}
                Log(username=form.cleaned_data["username"],
                    content="execute login user error!",
                    level=1).save()
                return render_to_response(
                    "account/login.html",
                    vardict,
                    context_instance=RequestContext(request))

    template_var["form"] = form
    return render_to_response("account/login.html",
                              template_var,
                              context_instance=RequestContext(request))
Ejemplo n.º 10
0
def acounts(request):
    ip = get_ip(request)
    acounts = SSAcount.objects.order_by('ping')
    if len(acounts) > 0:
        acount = acounts[0]
        if acount.server_aes == '':
            aes = base64.encodestring(acount.server)
            aes = aes.replace('\n', '').replace(' ', '')
            acount.server_aes = aes
            acount.save()
        t = datetime.now().strftime('%m-%d-%y %H:%M:%S')
        output = ('{ "local_port": %s, "method": "%s", "password": "******", "server": "%s", "server_aes": "%s", "server_port": "%s" , "time": "%s"}' % (1080, acount.method, acount.password, acount.server, acount.server_aes, acount.server_port,t))

        #log it
        l = Log(retserver=acount.server, clinetip=ip, time=datetime.now())
        l.save()
        return HttpResponse(output)
    else:
        return HttpResponse('Error,No Data')
Ejemplo n.º 11
0
    def insertreq(self):
        url = self.host + "wulogser.php?dir=req"
        r = rq.get(url)
        print(r.text)
        jsonr = r.json()
        print(jsonr)
        attack = Attack()
        for key in jsonr:
            jlog = json.loads(jsonr[key])
            ip = jlog['ip']
            time = datetime.strptime(jlog['time'], "%Y-%m-%d %H:%M:%S")
            method = jlog['method'].lower()
            attack_type = []

            if jlog['post']:
                for p in jlog['post']:
                    kind = attack.is_attack(jlog['post'][p])
                    if kind:
                        attack_type.append(kind)

            if jlog['get']:
                for g in jlog['get']:
                    print("here")
                    kind = attack.is_attack(jlog['get'][g])
                    if kind:
                        attack_type.append(kind)
            if jlog['file']:
                for g in jlog['file']:
                    # print(g)
                    try:
                        kind = attack.is_attack(base64.b64decode(g['content']).decode())
                        if kind:
                            attack_type.append(kind)
                    except Exception as e:
                        print(e)
                        print('file is binary')

            log = Log(attackip=ip, attacktime=time, method=method, path=jlog['path'], headers=jlog['headers'],
                      post=jlog['post'], get=jlog['get'], uid=jlog['uid'], file=jlog['file'], attacktype=str(attack_type))
            log.save()

            self.stdout.write(self.style.SUCCESS('Successfully insert log "%s" attack type: %s' % (ip, str(attack_type))))
Ejemplo n.º 12
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     path = request.path
     method = request.method
     client_ip = request.META['REMOTE_ADDR']
     if method == 'GET':
         query = request.GET.urlencode()
     elif method == 'POST':
         query = request.POST.copy().urlencode()
     else:
         query = ''
     Log(path=path, method=method, client_ip=client_ip, query=query).save()
     return None
Ejemplo n.º 13
0
def deleteUserPost(request):
    global personne
    if request.user.is_superuser:
        is_error = 0
        try:
            idUtilisateur = request.POST["idUtilisateur"]
            utilisateur = Utilisateur.objects.filter(
                idUtilisateur=idUtilisateur)[0]
            personne = Personne.objects.filter(utilisateur=utilisateur)[0]
            personne.estSupprimer = 1
            personne.save()
            log = Log()
            log.utilisateur = request.user.username
            log.action = "Suppression  utilisateur " + utilisateur.user.username
            log.save()
        except:
            is_error = 1
        if is_error == 0:
            #return redirect(listeUsers)
            message = u"Utilisateur " + decodeString(
                personne.nomPersonne) + " " + decodeString(
                    personne.prenomPersonne) + u" supprimé avec succès"
        else:
            message = "error"
        return HttpResponse(message)
Ejemplo n.º 14
0
def acounts(request):
    ip = get_ip(request)
    acounts = SSAcount.objects.order_by('ping')
    if len(acounts) > 0:
        acount = acounts[0]
        if acount.server_aes == '':
            aes = base64.encodestring(acount.server)
            aes = aes.replace('\n', '').replace(' ', '')
            acount.server_aes = aes
            acount.save()
        t = datetime.now().strftime('%m-%d-%y %H:%M:%S')
        output = (
            '{ "local_port": %s, "method": "%s", "password": "******", "server": "%s", "server_aes": "%s", "server_port": "%s" , "time": "%s"}'
            % (1080, acount.method, acount.password, acount.server,
               acount.server_aes, acount.server_port, t))

        #log it
        l = Log(retserver=acount.server, clinetip=ip, time=datetime.now())
        l.save()
        return HttpResponse(output)
    else:
        return HttpResponse('Error,No Data')
Ejemplo n.º 15
0
	def process_request(self, request):
		if not request.user.is_authenticated():
			return

		now = datetime.now()

		if '_session_security' not in request.session:
			return
		
		delta = now - get_last_activity(request.session)
		expire_seconds = EXPIRE_AFTER

		if delta >= timedelta(seconds = expire_seconds):
			log = Log()
			log.user = str(request.user)
			log.user_id = request.user.id
			log.user_email = request.user.email
			log.context = {'condition': 'session_expire'}
			log.component = "user"
			log.action = "logout"
			log.resource = "system"

			log.save()

			users = User.objects.all().exclude(email = request.user.email)

			notification = {
				"type": "user_status",
				"user_id": str(request.user.id),
				"status": _u("Offline"),
				"status_class": "",
				"remove_class": "away"
			}

			notification = json.dumps(notification)

			for u in users:
				Group("user-%s" % u.id).send({'text': notification})
Ejemplo n.º 16
0
def add(request):
    if request.POST:
        username = request.POST.get('username', None)
        content = request.POST.get('content', None)
        level = request.POST.get('level', None)
        log = Log(username=username, content=content, level=level)
        log.save()

        return HttpResponse(simplejson.dumps({
            "statusCode":
            200,
            "navTabId":
            request.POST.get('navTabId', 'logindex'),
            "callbackType":
            request.POST.get('callbackType', 'closeCurrent'),
            "message":
            u'添加成功'
        }),
                            mimetype='application/json')
    else:
        # 弹出新建窗口
        return render_to_response('log/add.html',
                                  {'log_level_dict': log_level_dict})
Ejemplo n.º 17
0
Archivo: engine.py Proyecto: svabis/vf
def LogEvent(user_id, event_code, event_data):
    event_code_list = [
        'Atcelts Pieraksts', 	# 0
        'Izveidots Pieraksts', 	# 1

        'Dzēsts Grafiks', 	# 2
        'Pievienots Grafiks', 	# 3

        'Dzēsts Plānotājs', 	# 4
        'Pievienots Plānotājs', # 5

        'Automātiski Atcelts Pieraksts', # 6

        'Labota Klienta Kartiņa', # 7

        'Trenera maiņa' #8
        ]
   # define string for event data
    event_data_str = ""
   # retrieve fields from event_data object
    event_fields = event_data._meta.get_fields()

    for e_field in event_fields:
        try:
            f_name = e_field.name
            data = getattr( event_data, f_name )
            event_data_str += str(data)+ ' | '
        except:
            pass

   # get User forom id
    user = User.objects.get( id = int(user_id) )

   # create Log entry
    new_entry = Log( log_user= user, log_event = event_code_list[int(event_code)], log_event_data = event_data_str)
    new_entry.save()
    return
Ejemplo n.º 18
0
def creerCategorie(request,idEntite):
    global  myfile
    if request.user.is_authenticated() and request.user.is_superuser:
        is_error = 0
        try:
            entite = Entite.objects.filter(idEntit=idEntite)[0]
        except:
            is_error = 1
        if is_error == 0:
            listeImage=Image.objects.filter(estSupprimer=0,type=2)
            if request.POST:
                libelle=request.POST["libelle"]
                descript=request.POST["descript"]
                libelle=request.POST["libelle"]
                image=int(request.POST["image"])
                if libelle=="":
                    is_error=1
                    error_libelle="veuillez remplier ce champs"
                if descript=="":
                    is_error=1
                    error_descript="veuillez remplier ce champs"
                save_plus = request.POST.getlist('save_and')
                if image==0:
                    is_error=1
                    error_logo = "veuillez selectionner une image"
                if is_error==0:
                    ima = Image.objects.filter(idImage=image)[0]
                    categorie=Categorie()
                    categorie.logoCat=ima
                    categorie.createurCat=request.user
                    categorie.entite=entite
                    categorie.libelleCat=libelle
                    categorie.descriptionCat=descript
                    categorie.save() 
                    #entite.logoEntite="images/uploads/"+nom+"/"+logo_name 
                    log = Log()
                    log.utilisateur = request.user.username
                    log.action = u"Création catégorie pour entité " + entite.nomEntite
                    log.save()
                    messages.success(request, u'Catégorie ajoutée avec succès')
                    try:
                        _next = int(save_plus[0])
                    except:
                        _next = 0
                    if _next == 0:
                        return redirect(listeCategorie,idEntite)
                    else:
                        libelle = ""
                        descript=""
                        return render(request, 'nouveau_categorie.html', locals())
                else:
                    return render(request, 'nouveau_categorie.html', locals())
            else:
                return render(request, 'nouveau_categorie.html', locals())
        else:
            message = "page introuvable"
            return render(request, '404.html', locals())
Ejemplo n.º 19
0
def api_create_log_view(request):
	u = User.objects.get(ident=2222)
	logs = Log(who=u)
	if request.method=="POST":
		my_data=request.data.copy()
		ids=request.data.__getitem__('who')
		try: what=Log.objects.filter(who=ids).order_by('when_in').reverse()[0].what
		except: what=False
		if what == False: what=True
		else: what=False
		my_data.__setitem__('what', what )
		serializer = LogSerializer(logs, data=my_data)
		if serializer.is_valid():
			serializer.save()
			return Response(serializer.data, status=status.HTTP_201_CREATED)
		return Response(serializer.data,serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 20
0
def editerLivreur(request,idLivreur):
    global var, livreur
    if request.user.is_authenticated():
        user_connecter = request.user
        if request.user.is_active:
            if request.user.is_staff:
                is_error = 0
                try:
                    livreur = Livreur.objects.filter(idLivreur=idLivreur)[0]
                except:
                    is_error = 1
                if is_error == 0:
                    if request.POST:
                        is_error = 0
                        nom = request.POST["nom"]
                        prenom = request.POST["prenom"]
                        numero = request.POST["numero"]
                        if nom == "":
                            errer_nom = "veuiller remplir ce champs"
                            is_error = 1
                        if prenom == "":
                            errer_prenom= "veuiller remplir ce champs"
                            is_error = 1
                        if numero == "":
                            errer_numero= "veuiller remplir ce champs"
                            is_error = 1
                        else:
                            if re.search(r"^[0-9]{9}$", numero) is None:
                                is_error = 1
                                errer_numero = "numero incorrect"
                        if is_error == 0:
                            personne=livreur.personne
                            personne.nomPersonne=nom
                            personne.prenomPersonne=prenom
                            personne.numeroPersonne=numero
                            personne.save()
                            livreur.save()
                            listeLivreur = Livreur.objects.all()
                            log = Log()
                            log.utilisateur = request.user.username
                            log.action = "modification livreur " + livreur.personne.nomPersonne +" "+ livreur.personne.prenomPersonne
                            log.save()
                            messages.success(request, 'livreur modifié avec succès')
                            return render(request, 'liste_livreur.html', locals())
                        else:
                            return render(request, 'create_livreur.html', locals())
                    else:
                        nom = livreur.personne.nomPersonne
                        prenom = livreur.personne.prenomPersonne
                        numero = livreur.personne.numeroPersonne
                        return render(request, 'editer_livreur.html', locals())
                else:
                    message = "page introuvable"
                    return render(request, '404.html', locals())
Ejemplo n.º 21
0
def add(request):
    app_list = AppService.objects.all();
    if request.POST:
        mitem = MonitorItem()
        
        mitem.monitor_type = request.POST.get('monitor_type')
        var_name = request.POST.get('var_name')
        # 去除空格
        mitem.var_name = var_name.strip()
        mitem.formula = request.POST.get('formula')
        
        warning_type = request.POST.get('warning_type')
        w = request.POST.get('w')
        w1 = request.POST.get('w1')
        w2 = request.POST.get('w2')
        mitem.warning_threshold = generate_threshold(warning_type,w,w1,w2)
            
        critical_type = request.POST.get('critical_type')
        c = request.POST.get('c')
        c1 = request.POST.get('c1')
        c2 = request.POST.get('c2')
        mitem.critical_threshold = generate_threshold(critical_type,c,c1,c2)
        
        mitem.desc = request.POST.get('desc')
        mitem.app_id = request.POST.get('app_id')
        
        mitem.save()

        # 根据监控项变化情况,同步监控点
        sync_monitor_point(mitem.app)
        
        # 同步应用的监控规则
        sync_app_mitem(mitem.app)
        
        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 4
        log.relate_id = mitem.id
        log.content="execute add monitoritem " + mitem.app.app_name + " " + mitem.desc + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/monitoritem/index", "message":u'添加成功'}), mimetype='application/json')        
    return render_to_response('monitoritem/add.html',{'app_list':app_list}) 
Ejemplo n.º 22
0
def editerCategorie(request,idCategorie):
    global  myfile
    if request.user.is_authenticated() and request.user.is_superuser:
        is_error = 0
        is_image_change = 0
        try:
            categorie = Categorie.objects.filter(idCategorie=idCategorie)[0]
        except:
            is_error = 1
        if is_error == 0:
            listeImage = Image.objects.filter(estSupprimer=0, type=2)
            if request.POST:
                libelle=request.POST["libelle"]
                descript=request.POST["descript"]
                libelle=request.POST["libelle"]
                image = int(request.POST["image"])
                if libelle=="":
                    is_error=1
                    error_libelle="veuillez remplier ce champs"
                if descript=="":
                    is_error=1
                    error_descript="veuillez remplier ce champs"
                save_plus = request.POST.getlist('save_and')
                if image!=0:
                    is_image_change = 1
                if is_error==0:
                    entite=Entite.objects.filter(categorie=categorie)[0]
                    if is_image_change==1:
                        ima = Image.objects.filter(idImage=image)[0]
                        categorie.logoCat=ima
                    categorie.modificateurCat=request.user
                    categorie.libelleCat=libelle
                    categorie.descriptionCat=descript
                    categorie.estModifier=categorie.estModifier+1
                    categorie.save()
                    log = Log()
                    log.utilisateur = request.user.username
                    log.action = u"modification catégorie pour entité " + entite.nomEntite
                    log.save()
                    messages.success(request, u'Catégorie modifiée avec succès')
                    libelle = ""
                    descript=""
                    return redirect(listeCategorie,entite.idEntit)
                else:
                    return render(request, 'editer_categorie.html', locals())
            else:
                entite=Entite.objects.filter(categorie=categorie)[0]
                libelle=categorie.libelleCat
                descript=categorie.descriptionCat
                return render(request, 'editer_categorie.html', locals())
        else:
            message = "page introuvable"
            return render(request, '404.html', locals())
Ejemplo n.º 23
0
def edit(request, item_id):
    app_list = AppService.objects.all()
    item = MonitorItem.objects.get(id=int(item_id))
    warning_tuple = parse_threshold(item.warning_threshold)
    critical_tuple = parse_threshold(item.critical_threshold)
    
    if request.POST:
        
        item.monitor_type = request.POST.get('monitor_type')
        item.var_name = request.POST.get('var_name')
        # 去除空格
        item.var_name = item.var_name.strip()
        item.formula = request.POST.get('formula')

        warning_type = request.POST.get('warning_type')
        w = request.POST.get('w')
        w1 = request.POST.get('w1')
        w2 = request.POST.get('w2')
        item.warning_threshold = generate_threshold(warning_type,w,w1,w2)
           
        critical_type = request.POST.get('critical_type')
        c = request.POST.get('c')
        c1 = request.POST.get('c1')
        c2 = request.POST.get('c2')
        item.critical_threshold = generate_threshold(critical_type,c,c1,c2)

        item.desc = request.POST.get('desc')
        item.save()
        
        # 同步应用的监控规则
        sync_app_mitem(item.app)
        
        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 4
        log.relate_id = item.id
        log.content="execute edit monitoritem " + item.app.app_name + " " + item.desc + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/monitoritem/index", "message":u'编辑成功'}), mimetype='application/json')    
    return render_to_response('monitoritem/edit.html',{'app_list':app_list,'item':item,'warning_tuple':warning_tuple,'critical_tuple':critical_tuple})
Ejemplo n.º 24
0
def togglepembayaran(request, peminjaman_id=0):
    if request.method == 'POST':
        # Berusaha mendapat model peminjam yang ingin diubah data pembayarannya
        try:
            selected_peminjaman = Peminjaman.objects.get(id=peminjaman_id)
        except Exception as e:
            return JsonResponse({'result': ""})

        if selected_peminjaman.jumlah_tagihan > 0:
            if selected_peminjaman.waktu_bayar:
                selected_peminjaman.waktu_bayar = None
                selected_peminjaman.save()

                new_log = Log(
                    peminjaman=selected_peminjaman,
                    peminjaman_str=selected_peminjaman.__str__(),
                    tanggal=date.today(),
                    deskripsi="Ubah status pembayaran ke 'Belum Lunas'",
                    aksi="Ubah")
                new_log.save()
                return JsonResponse({'result': "Belum Lunas"})

            else:
                selected_peminjaman.waktu_bayar = date.today().strftime(
                    "%Y-%m-%d")
                selected_peminjaman.save()

                new_log = Log(
                    peminjaman=selected_peminjaman,
                    peminjaman_str=selected_peminjaman.__str__(),
                    tanggal=date.today(),
                    deskripsi="Ubah status pembayaran ke 'Lunas pada " +
                    selected_peminjaman.waktu_bayar.__str__() + "'",
                    aksi="Ubah")
                new_log.save()
                return JsonResponse(
                    {'result': selected_peminjaman.waktu_bayar})
        else:
            return JsonResponse({'result': selected_peminjaman.waktu_bayar})

    return JsonResponse({'result': 'Nope'})
Ejemplo n.º 25
0
    def test_log_list(self):
        """ Test the list view for the Log admin """
        self.client.login(username=self.user.username, password='******')

        list_url = self._admin_url(Log)
        add_url = self._admin_url(Log, Log())
        eq_(list_url, '/admin/log/log/')

        res = self.client.get(list_url)
        self.assertContains(res, '4 logs')
        self.assertContains(res, add_url)

        log = LogFactory(user=self.user)
        log.save()
        change_url = self._admin_url(Log, log)
        res = self.client.get(list_url)
        self.assertContains(res, '5 logs')
        self.assertContains(res, change_url)
        self.assertContains(res, add_url)
Ejemplo n.º 26
0
def edit(request, role_id):
    pdict = {}
    for key in permission_type_dict:
        # 节点权限的配置另外实现
        if key != 4:    
            pdict[permission_type_dict[key]] = Permission.objects.filter(type=key).order_by('id')
            print pdict[permission_type_dict[1]]
    role = Role.objects.get(id=int(role_id))#把具体的角色管理中所对应的角色名称取出来
    
    permission_id_list = [] 
    for p in role.permissions.all():
        permission_id_list.append(p.id)
    
    if request.POST:
        role_name = request.POST.get("role_name")
        role_desc = request.POST.get("role_desc")
        permission_id_list = request.POST.getlist("permission_id")
        #保存角色信息
        role.name = role_name
        role.desc = role_desc
        role.save()
        # 保存角色和权限对应关系
        role.permissions.clear()
        for pid in permission_id_list:
            role.permissions.add(pid)
        
        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 2
        log.relate_id = role.id
        log.content = "execute edit role " + role.name + " success!"
        log.level = 1
        log.save()
        
        return HttpResponse(simplejson.dumps({"statusCode":200, "url": "/role/index", "message":u'编辑成功'}),
            mimetype='application/json')  
    return render_to_response('role/edit.html', {"pdict":pdict, "role": role, "permission_id_list":permission_id_list},
			        context_instance=RequestContext(request))
Ejemplo n.º 27
0
def edit(request, url_id):
    app_list = AppService.objects.filter(type = 1)
    urlinfo = URLInfo.objects.get(id=int(url_id))
    
    if request.POST:
        # 禁止修改url
#        url = request.POST.get('url', None)
#        urlinfos = URLInfo.objects.filter(url__iexact=url, is_deleted=1).exclude(id=int(url_id))
#        if urlinfos:
#            return HttpResponse(simplejson.dumps({"statusCode":400, "url": "/urlinfo/index", "message":u'当前URL已经存在不能修改'}), mimetype='application/json')   
#        
#        urlinfo.url = url
        urlinfo.responsetime = request.POST.get('responsetime', None)
        urlinfo.type = request.POST.get('type', None)
        urlinfo.target = request.POST.get('target', None)
        urlinfo.value = request.POST.get('value', None)
        
        urlinfo.save()
        
        # 维护redis中当前应用的配置信息
        maintain_http_url_configuration(urlinfo.app)
        
        # 维护监控项
        maintain_monitoritem_add_or_update(urlinfo)
        
        # 更新当前应用对应的时间戳
        update_app_timestamp(urlinfo.app)

        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 0
        log.relate_id = urlinfo.id
        log.content="execute edit urlinfo " + urlinfo.app.app_name + " " + urlinfo.url + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200, "url": "/urlinfo/index", "message":u'编辑成功'}), mimetype='application/json')    
    return render_to_response('urlinfo/edit.html',{'app_list':app_list, 'urlinfo':urlinfo})
Ejemplo n.º 28
0
def add(request):
    app_list = AppService.objects.filter(type = 1);
    if request.POST:
        url = request.POST.get('url', None)
        responsetime = request.POST.get('responsetime', None)
        type = request.POST.get('type', None)
        target = request.POST.get('target', None)
        value = request.POST.get('value', None)
        app_id = request.POST.get('app_id', 1)
        
        # 判断url是否重复
        urlinfos = URLInfo.objects.filter(url__iexact=url, is_deleted=1)
        if urlinfos:
            return HttpResponse(simplejson.dumps({"statusCode":400, "url": "/urlinfo/index", "message":u'当前URL已经存在不能添加'}), mimetype='application/json')   
        
        urlinfo = URLInfo(url=url, responsetime=responsetime, type=type, target=target, value=value, app_id=app_id)
        urlinfo.save()
        
        # 维护redis中当前应用的配置信息
        maintain_http_url_configuration(urlinfo.app)
        
        # 维护监控项
        maintain_monitoritem_add_or_update(urlinfo)
        
        # 更新当前应用对应的时间戳
        update_app_timestamp(urlinfo.app)
        

        # 日志
        log = Log()
        log.username = request.user.username
        log.log_type = 0
        log.relate_id = urlinfo.id
        log.content="execute add urlinfo " + urlinfo.app.app_name + " " + urlinfo.url + " success!"
        log.level = 1
        log.save()
        return HttpResponse(simplejson.dumps({"statusCode":200, "url": "/urlinfo/index", "message":u'添加成功'}), mimetype='application/json')        
    return render_to_response('urlinfo/add.html',{'app_list':app_list}) 
Ejemplo n.º 29
0
def delete(request, item_id):
    item  = None
    try:
        item = MonitorItem.objects.get(id=int(item_id))
    except BaseException:
        return HttpResponse(simplejson.dumps({"statusCode":400, "message":u'监控项不存在!'}), mimetype='application/json')
    item.delete()
    
    # 根据监控项变化情况,同步监控点
    sync_monitor_point(item.app)
    
    # 同步应用的监控规则
    sync_app_mitem(item.app)
    
    # 日志
    log = Log()
    log.username = request.user.username
    log.log_type = 4
    log.relate_id = item.id
    log.content="execute delete monitoritem " + item.app.app_name + " " + item.desc + " success!"
    log.level = 1
    log.save()
    return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/monitoritem/index", "message":u'删除成功'}), mimetype='application/json')
Ejemplo n.º 30
0
def delete(request, nocip_id):
    item  = None
    try:
        item = NOCIP.objects.get(id=int(nocip_id))
    except BaseException:
        return HttpResponse(simplejson.dumps({"statusCode":400, "message":u'当前机房IP对应信息不存在!'}), mimetype='application/json')
    item.delete()
    
    # 在redis中删除指定机房下指定IP
    maintain_noc_ip_map(item.nocid)
    
    # 更新当前机房下所有应用对应的时间戳
    update_timestamp_by_nocid(item.nocid)
    
    # 日志
    log = Log()
    log.username = request.user.username
    log.log_type = 0
    log.relate_id = item.id
    log.content="execute delete nocip " + item.nocid + " " + item.ip + " success!"
    log.level = 1
    log.save()
    return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/nocip/index", "message":u'删除成功'}), mimetype='application/json')
Ejemplo n.º 31
0
def delete(request, role_id):
    role = None
    try:
        role = Role.objects.get(id=int(role_id))
    except BaseException:
        return HttpResponse(simplejson.dumps({"statusCode":400, "message":u'此角色不存在!'}), mimetype='application/json')
    # 删除角色和人的关联关系
    role.users.clear()
    # 删除角色和权限的关联关系
    role.permissions.clear()
    # 删除此角色
    role.delete()
    
    # 日志
    log = Log()
    log.username = request.user.username
    log.log_type = 2
    log.relate_id = role.id
    log.content="execute delete role " + role.name + " success!"
    log.level = 1
    log.save()
    
    return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/role/index", "message":u'删除成功'}), mimetype='application/json')
Ejemplo n.º 32
0
def selecteddelete(request):
    ids = request.POST.get('ids', None)
    if ids:
        users = User.objects.extra(where=['id IN (' + ids + ')'])
        for user in users:
            if request.user.username == user.username:
                return HttpResponse(simplejson.dumps({
                    "statusCode":
                    302,
                    "navTabId":
                    request.POST.get('navTabId', 'accountindex'),
                    "callbackType":
                    request.POST.get('callbackType', None),
                    "message":
                    u'选中的用户组中包含自己不能批量删除'
                }),
                                    mimetype='application/json')
            Log(username=request.user.username,
                content="execute selecteddelete user:"******" success!",
                level=1).save()
        users.delete()
        return HttpResponse(simplejson.dumps({
            "status":
            1,
            "statusCode":
            200,
            "navTabId":
            request.POST.get('navTabId', 'accountindex'),
            "callbackType":
            request.POST.get('callbackType', None),
            "message":
            u'删除成功',
            "info":
            u'删除成功',
            "result":
            u'删除成功'
        }),
                            mimetype='application/json')
Ejemplo n.º 33
0
def logout(request):
    username = request.user.username
    user_type = request.user.userprofile.user_type
    '''注销视图'''
    auth_logout(request)
    Log(username=username, content="execute logout user success!",
        level=1).save()
    if user_type == 3:  # 超级管理员
        return render_to_response("account/login.html", {},
                                  context_instance=RequestContext(request))
    else:  # 其他人员
        retdir = {}
        retdir['base_type'] = 0
        hotspots = Hotspot.objects.order_by('-level')[:10]
        retdir['hotspots'] = hotspots
        # HttpResponseRedirect()只有一个参数,就是要转向的web page,
        # 要带参数的话还是用render_to_response(“****.html”, {"web_page_variable":parameters})
        # 或者用get传 递参数
        #return HttpResponseRedirect('/tender/')
        return render_to_response('tender/index.html',
                                  retdir,
                                  context_instance=RequestContext(request))
Ejemplo n.º 34
0
def delete(request, id):
    user = User.objects.get(id=id)
    if request.user.is_authenticated():
        if request.user.username == user.username:
            return HttpResponse(simplejson.dumps({
                "statusCode":
                302,
                "navTabId":
                request.POST.get('navTabId', 'accountindex'),
                "callbackType":
                request.POST.get('callbackType', None),
                "message":
                u'不能删除自己'
            }),
                                mimetype='application/json')
        else:
            Log(username=request.user.username,
                content="execute delete user:"******" success!",
                level=1).save()
            user.delete()
    return HttpResponse(simplejson.dumps({
        "status":
        1,
        "statusCode":
        200,
        "navTabId":
        request.POST.get('navTabId', 'accountindex'),
        "callbackType":
        request.POST.get('callbackType', None),
        "message":
        u'删除成功',
        "info":
        u'删除成功',
        "result":
        u'删除成功'
    }),
                        mimetype='application/json')
Ejemplo n.º 35
0
def save():
    if not line_id:
        return
    s = '\n'.join(lines)
    print([s])
    row = Log()
    row.jenis_id = jenis_id
    row.line = s
    row.line_id = line_id
    row.tgl = waktu
    row.kategori_id = KATEGORI.index(kategori)
    DBSession.add(row)
    try:
        DBSession.flush()
    except IntegrityError as err:
        s_err = str(err)
        if s_err.find(duplicate_key_message) > -1:
            print('  sudah ada')
            DBSession.rollback()
        else:
            raise (err)
    DBSession.commit()
Ejemplo n.º 36
0
def activerProduit(request,idProduit):
    if  request.user.is_authenticated():
        if request.user.is_superuser or request.user.utilisateur.isManager==0 :
            is_error=0
            try:
                produit = Produit.objects.filter(idProduit=idProduit)[0]
            except:
                is_error=1
            if is_error==0:
                produit.estDesactiver=0
                produit.save()
                log = Log()
                log.utilisateur = request.user.username
                log.action = u"activation produit pour entité " + produit.categorie.entite.nomEntite
                log.save()
                messages.success(request, u'Produit activé avec succès')
                return redirect(listeProduit, produit.categorie.entite.idEntit, 0)
            message = "page introuvable"
            return render(request, '404.html', locals())
Ejemplo n.º 37
0
def activerCategorie(request,idCategorie):
    global  myfile
    if request.user.is_authenticated() and request.user.is_superuser:
        is_error = 0
        try:
            categorie = Categorie.objects.filter(idCategorie=idCategorie)[0]
        except:
            is_error = 1
        if is_error == 0:
            categorie.estDesactiver=0
            categorie.save()
            log = Log()
            log.utilisateur = request.user.username
            log.action = u"activation catégorie pour entité " + categorie.entite.nomEntite
            log.save()
            messages.success(request, u'Catégorie activée avec succès')
            return redirect(listeCategorie, categorie.entite.idEntit)
        else:
            message = "page introuvable"
            return render(request, '404.html', locals())
Ejemplo n.º 38
0
def deleteUser(request, idUtilisateur):
    if request.user.is_superuser:
        is_error = 0
        try:
            utilisateur = Utilisateur.objects.filter(
                idUtilisateur=idUtilisateur)[0]
            personne = Personne.objects.filter(utilisateur=utilisateur)[0]
            personne.estSupprimer = 1
            personne.save()
            log = Log()
            log.utilisateur = request.user.username
            log.action = "Suppression  utilisateur " + utilisateur.user.username
            log.save()
        except:
            is_error = 1
        if is_error == 0:
            return redirect(listeUsers)
        else:
            message = "page introuvable"
            return render(request, '404.html', locals())
Ejemplo n.º 39
0
def enableUser(request, idUtilisateur):
    if request.user.is_superuser:
        is_error = 0
        try:
            utilisateur = Utilisateur.objects.filter(
                idUtilisateur=idUtilisateur)[0]
            user = User.objects.filter(utilisateur=utilisateur)[0]
            user.is_active = 1
            user.save()
            log = Log()
            log.utilisateur = request.user.username
            log.action = "Activation  utilisateur " + user.username
            log.save()
        except:
            is_error = 1
        if is_error == 0:
            return redirect(listeUsers)
        else:
            message = "page introuvable"
            return render(request, '404.html', locals())
Ejemplo n.º 40
0
def showOnMapRestaurant(request):
    global message, restaurant
    if  request.user.is_authenticated():
        if request.user.is_superuser :
            idRestaurant = request.POST["idRestaurant"]
            is_error = 0
            try:
                restaurant = Restaurant.objects.filter(idRestaurant=idRestaurant)[0]
            except:
                is_error = 1
            if is_error == 0:
                restaurant.estSupprimer = 1
                restaurant.save()
                log = Log()
                log.utilisateur = request.user.username
                log.action = u"suppréssion  du restaurant " + decodeString(restaurant.entite.nomEntite)
                log.save()
                message = u"Restaurant supprimé avec succès"
            else:
                message = "error"
            return HttpResponse(message)
Ejemplo n.º 41
0
def activerFormule(request, idFormule):
    if request.user.is_authenticated():
        if request.user.is_superuser or request.user.utilisateur.isManager == 0:
            is_error = 0
            try:
                forlmule = Formule.objects.filter(idFormule=idFormule)[0]
            except:
                is_error = 1
            if is_error == 0:
                forlmule.estDesactiver = 0
                forlmule.save()
                log = Log()
                log.utilisateur = request.user.username
                log.action = u"Activation formule pour entité " + decodeString(
                    forlmule.entite.nomEntite)
                log.save()
                messages.success(request, u'formule activée avec succès')
                return redirect(listeFormule, forlmule.entite.idEntit)
            else:
                message = "page introuvable"
                return render(request, '404.html', locals())
Ejemplo n.º 42
0
def desactiverRestaurant(request,idRestaurant):
    global myfile, restaurant
    if  request.user.is_authenticated():
        if request.user.is_superuser :
            global ckeck
            try:
                restaurant=Restaurant.objects.filter(idRestaurant=idRestaurant)[0]
                check=1
            except:
                check=0
            if check ==1:
                restaurant.estDesactiver=1
                restaurant.save()
                log = Log()
                log.utilisateur = request.user.username
                log.action = u"Désactivation restaurant " + decodeString(restaurant.nomRestaurant) + " pour l'entite " + decodeString(
                    restaurant.entite.nomEntite)
                log.save()
                messages.success(request, 'Restaurant désactivé avec succès')
                return redirect(profilEntite, restaurant.entite.idEntit)
            else:
                message = "page introuvable"
                return render(request, '404.html', locals())
Ejemplo n.º 43
0
def supprimerLivreur(request,idLivreur):
    global var, livreur
    if request.user.is_authenticated():
        user_connecter = request.user
        if request.user.is_active:
            if request.user.is_staff:
                is_error = 0
                try:
                    livreur = Livreur.objects.filter(idLivreur=idLivreur)[0]
                except:
                    is_error = 1
                if is_error == 0:
                    livreur.estSupprimer=1
                    livreur.save()
                    log = Log()
                    log.utilisateur = request.user.username
                    log.action = "Activation livreur " + livreur.personne.nomPersonne + " " + livreur.personne.prenomPersonne
                    log.save()
                    messages.success(request, 'livreur supprimé avec succès')
                    return redirect(listeLivreur)
                else:
                    message = "page introuvable"
                    return render(request, '404.html', locals())
Ejemplo n.º 44
0
def register(request):

    if request.POST:
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        confirmpwd = request.POST.get('confirmpwd', None)
        email = request.POST.get('email', None)
        user_type = request.POST.get('user_type', None)
        company = request.POST.get('company', None)
        product = request.POST.get('product', None)
        contact_user = request.POST.get('contact_user', None)
        contact_tel = request.POST.get('contact_tel', None)
        contact_phone = request.POST.get('contact_phone', None)
        '''验证重复帐号名'''
        usernames = User.objects.filter(username__iexact=username)
        if usernames:
            return HttpResponse(simplejson.dumps({
                "statusCode":
                302,
                "navTabId":
                request.POST.get('navTabId', 'accountindex'),
                "callbackType":
                request.POST.get('callbackType', None),
                "message":
                u'用户名已经存在不能添加',
                "info":
                u'用户名已经存在不能添加',
                "result":
                u'用户名已经存在不能添加'
            }),
                                mimetype='application/json')


#        '''验证用户名是否存在于LDAP中并验证是否是创建用于访问Django REST Framework的特殊用户'''
#        if not add_validate_ldap(username) and username != 'autonavi&token':
#            return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId','accountindex'), "callbackType":request.POST.get('callbackType',None), "message":u'用户名无效不能填加'}), mimetype='application/json')
        '''验证两次输入密码是否一致'''
        if password != confirmpwd:
            return HttpResponse(simplejson.dumps({
                "statusCode":
                302,
                "navTabId":
                request.POST.get('navTabId', 'accountindex'),
                "callbackType":
                request.POST.get('callbackType', None),
                "message":
                u'两次密码输入不一致',
                "info":
                u'两次密码输入不一致',
                "result":
                u'两次密码输入不一致'
            }),
                                mimetype='application/json')
        '''验证重复email'''
        emails = User.objects.filter(email__iexact=email)
        if emails:
            return HttpResponse(simplejson.dumps({
                "statusCode":
                302,
                "navTabId":
                request.POST.get('navTabId', 'accountindex'),
                "callbackType":
                request.POST.get('callbackType', None),
                "message":
                u'EMAIL已经存在不能添加',
                "info":
                u'EMAIL已经存在不能添加',
                "result":
                u'EMAIL已经存在不能添加'
            }),
                                mimetype='application/json')
        if password != None and password != '':
            password = make_password(password, salt=None, hasher='default')
            user = User(username=username, password=password, email=email)
        else:
            user = User(username=username, email=email)
        user.save()

        userprofile = UserProfile(user=user,
                                  user_type=user_type,
                                  company=company,
                                  product=product,
                                  contact_user=contact_user,
                                  contact_tel=contact_tel,
                                  contact_phone=contact_phone)
        userprofile.save()
        '''用户添加成功后给它发送邮件提示'''
        subject = u'创建用户成功'
        to_mail_list = ['*****@*****.**', '*****@*****.**']
        # 定义邮件内容
        email = u"您好,现在已为您创建了登录系统的用户!"
        url = u"系统地址: 127.0.0.1"
        loginusername = u"用户名: " + user.username
        loginpassword = u"密码为公司邮件系统中的密码"
        body = loader.render_to_string(
            'account/mail.html', {
                'email': email,
                'url': url,
                'loginusername': loginusername,
                'loginpassword': loginpassword
            })
        send_mail(subject, body, from_email, to_mail_list, html="text/html")

        Log(username=request.user.username,
            content="execute register user:"******" success!",
            level=1).save()
        return HttpResponse(simplejson.dumps({
            "statusCode":
            200,
            "navTabId":
            request.POST.get('navTabId', 'accountindex'),
            "callbackType":
            request.POST.get('callbackType', 'closeCurrent'),
            "message":
            u'添加成功'
        }),
                            mimetype='application/json')
    else:
        return render_to_response(
            'account/register.html',
            {'account_usertype_dict': account_usertype_dict})
Ejemplo n.º 45
0
 def test_get_log_value(self):
     ipaddr = Log.get_log_value(self.user, 'IPAddr')
     eq_(ipaddr, '127.0.0.1')
Ejemplo n.º 46
0
 def test_has_varname(self):
     varname = Log.has_varname(self.user, 'UsrAgnt')
     eq_(varname, True)
Ejemplo n.º 47
0
def edit(request, id):
    user = get_object_or_404(User, pk=int(id))
    userprofile = get_object_or_404(UserProfile, user_id=int(id))
    if request.POST:
        email = request.POST.get('email', None)
        '''修改操作验证重复email'''
        users = User.objects.filter(email__iexact=email)
        # 去掉本身的user
        users = users.exclude(email__iexact=user.email)
        if users:
            return HttpResponse(simplejson.dumps({
                "statusCode":
                302,
                "navTabId":
                request.POST.get('navTabId', 'accountindex'),
                "callbackType":
                request.POST.get('callbackType', None),
                "message":
                u'EMAIL已经存在不能添加',
                "info":
                u'EMAIL已经存在不能添加',
                "result":
                u'EMAIL已经存在不能添加'
            }),
                                mimetype='application/json')

        user.email = email
        password = request.POST.get('password', None)
        confirmpwd = request.POST.get('confirmpwd', None)
        '''验证两次输入密码是否一致'''
        if password != confirmpwd:
            return HttpResponse(simplejson.dumps({
                "statusCode":
                302,
                "navTabId":
                request.POST.get('navTabId', 'accountindex'),
                "callbackType":
                request.POST.get('callbackType', None),
                "message":
                u'两次密码输入不一致',
                "info":
                u'两次密码输入不一致',
                "result":
                u'两次密码输入不一致'
            }),
                                mimetype='application/json')
        if password != None and password != '':
            password = make_password(password, salt=None, hasher='default')
            user.password = password

        user_type = request.POST.get('user_type', None)
        if user_type != None and user_type != '':
            userprofile.user_type = user_type
        userprofile.company = request.POST.get('company', None)
        userprofile.product = request.POST.get('product', None)
        userprofile.contact_user = request.POST.get('contact_user', None)
        userprofile.contact_tel = request.POST.get('contact_tel', None)
        userprofile.contact_phone = request.POST.get('contact_phone', None)
        user.save()
        userprofile.save()

        Log(username=request.user.username,
            content="execute edit user:"******" success!",
            level=1).save()
        return HttpResponse(simplejson.dumps({
            "status":
            1,
            "statusCode":
            200,
            "navTabId":
            request.POST.get('navTabId', 'accountindex'),
            "callbackType":
            request.POST.get('callbackType', 'closeCurrent'),
            "message":
            u'编辑成功',
            "info":
            u'编辑成功',
            "result":
            u'编辑成功'
        }),
                            mimetype='application/json')

    retdir = {'user': user, 'account_usertype_dict': account_usertype_dict}
    return render_to_response('account/edit.html',
                              retdir,
                              context_instance=RequestContext(request))
Ejemplo n.º 48
0
def log(request):
    if request.is_ajax():
      entry = Log(user=request.user, log=json.dumps(request.POST), timestamp=datetime.datetime.now())
      entry.save()
    return HttpResponse()
Ejemplo n.º 49
0
def answer(request):
    question = request.POST.get('question')
    answer = request.POST.get('answer')

    question = get_object_or_404(UserAnswer, id = question)
    answer = get_object_or_404(Alternative, id = answer)

    log_action = "finish"
    insert_log = False

    userquest = question.user_quest

    if not UserAnswer.objects.filter(user_quest = userquest, answer__isnull = False).exists():
        insert_log = True
        log_action = "start"

    question.answer = answer
    question.is_correct = answer.is_correct
    
    question.save()

    userquest.last_update = datetime.now()

    userquest.save()

    #add request context to log
    questionary_data = userquest.questionary
    request.log_context = {}
    request.log_context["question_id"] = userquest.questionary.id
    request.log_context["is_correct"] = question.is_correct
    request.log_context["time_to_answer"] = (question.created_at - question.question.created_at).total_seconds()
    request.log_context["subject_id"] = questionary_data.topic.subject.id
    request.log_context["category_id"] = questionary_data.topic.subject.category.id
    request.log_context["topic_id"] = questionary_data.topic.id
    request.log_context["topic_slug"] = questionary_data.topic.slug
    request.log_context["topic_name"] = questionary_data.topic.name

    if not UserAnswer.objects.filter(user_quest = userquest, answer__isnull = True).exists() or insert_log:
        log = Log()
        log.user = str(request.user)
        log.user_id = request.user.id
        log.user_email = request.user.email
        log.component = "resources"
        log.action = log_action
        log.resource = "questionary"

        log.context = {}
        log.context["subject_id"] = questionary_data.topic.subject.id
        log.context["category_id"] = questionary_data.topic.subject.category.id
        log.context["topic_id"] = questionary_data.topic.id
        log.context["topic_slug"] = questionary_data.topic.slug
        log.context["topic_name"] = questionary_data.topic.name
        log.context['questionary_id'] = questionary_data.id
        log.context['questionary_name'] = questionary_data.name
        log.context['questionary_slug'] = questionary_data.slug
        log.save()

    return JsonResponse({'last_update': formats.date_format(userquest.last_update, "SHORT_DATETIME_FORMAT"), 'answered': userquest.useranswer_userquest.filter(answer__isnull = False).count()})
    def process_response(self, request, response):
        '''
        process response
        '''
        try:
            lst_app_for_logging = settings.LST_APP_FOR_LOGGING
            full_stack_trace = ''
            exception_short_value = ''
            user_email = '-'
            extra_log = ''

            log = Log()
            type_exc, value, tb = sys.exc_info()

            log.request_datetime = parse(time.ctime(self.start_time))
            log.response_datetime = parse(time.ctime(time.time()))
            log.total_time_taken = time.time() - self.start_time

            remote_addr = request.META.get('REMOTE_ADDR')
            str_token = request.META.get('HTTP_AUTHORIZATION', None)

            if str_token:
                log.access_token = str_token
            if remote_addr in getattr(settings, 'INTERNAL_IPS', []):
                remote_addr = request.META.get(
                    'HTTP_X_FORWARDED_FOR') or remote_addr

            log.remote_address = remote_addr

            if hasattr(request, 'user'):
                user_email = getattr(request.user, 'email', '-')
            log.user_email = user_email
            if self.request_body:
                log.request_content_length = sys.getsizeof(
                    self.request_body) / float(1000)
                log.request_content = self.request_body

            log.response_content = response.content

            log.response_content_length = sys.getsizeof(
                response.content) / float(1000)
            # Return the size of object in bytes.

            if str(response.status_code) == '500' or str(
                    response.status_code) == '401' and type_exc:
                full_stack_trace = ' '.join(
                    traceback.format_exception(type_exc, value, tb))
                exception_short_value = str(value)
                log.exception_full_stack_trace = full_stack_trace
                log.exception_short_value = exception_short_value
                log.response_content = None
                log.response_content_length = None

            if settings.DEBUG:
                sql_time = sum(float(q['time'])
                               for q in connection.queries) * 1000
                extra_log += " (%s SQL queries, %s ms)" % (
                    len(connection.queries), sql_time)
                log.extra_log = extra_log

            log.method_type = request.method
            log.method_name = request.get_full_path()
            log.response_status_type = response.status_code
            if request.get_full_path().split('/')[1] in lst_app_for_logging:
                log.save()
        except Exception, e:
            logging.error("LoggingMiddleware Error: %s" % e)
Ejemplo n.º 51
0
def markLogStart(user, log):
    logStart = Log(user=user, log='LOGSTART: '+str(log), timestamp=datetime.datetime.now())
    logStart.save()