Пример #1
0
def hr_application_create_view(request, form_id=None):
    if form_id:
        app_form = get_object_or_404(ApplicationForm, id=form_id)
        if request.method == "POST":
            if Application.objects.filter(user=request.user).filter(form=app_form).exists():
                logger.warn("User %s attempting to duplicate application to %s" % (request.user, app_form.corp))
            else:
                application = Application(user=request.user, form=app_form)
                application.save()
                for question in app_form.questions.all():
                    response = ApplicationResponse(question=question, application=application)
                    response.answer = request.POST.get(
                        str(question.pk), "Failed to retrieve answer provided by applicant."
                    )
                    response.save()
                logger.info("%s created %s" % (request.user, application))
            return redirect("auth_hrapplications_view")
        else:
            questions = app_form.questions.all()
            return render_to_response(
                "registered/hrapplicationcreate.html",
                {"questions": questions, "corp": app_form.corp},
                context_instance=RequestContext(request),
            )
    else:
        choices = []
        for app_form in ApplicationForm.objects.all():
            if not Application.objects.filter(user=request.user).filter(form=app_form).exists():
                choices.append((app_form.id, app_form.corp.corporation_name))
        return render_to_response(
            "registered/hrapplicationcorpchoice.html", {"choices": choices}, context_instance=RequestContext(request)
        )
Пример #2
0
	def _apply(self, command, stock, price, shares):
		application = Application(stock = stock, applicant = self, price = price, command = command, shares = shares)
		application.clean()
		application.save()
		application_updated.send(self, application = application)
		
		return application
Пример #3
0
def createApplication():
    """ User creation """
    try:   
        if "username" in session:
            if request.method == 'POST':
                myApp=Application(
                    systemname=request.form["inputSystemName"],
                    systemdescription=request.form["inputSystemDescription"],
                    systemtechnology=request.form["inputSystemTechnology"],
                    systemprovider=request.form["inputSystemProvider"],
                    systemowner=request.form["inputSystemOwner"],
                    systemstatus=request.form["inputSystemStatus"],
                    systemurl=request.form["inputSystemUrl"],
                    systemcategory=request.form["inputSystemCat"]
                    )
                myApp.save()
                flash('Application saved !!! ', 'message')
                return redirect(url_for('listeApplication'))
            if request.method == 'GET':
                return render_template('createapplication.html')
        else:
            flash('Unknown user !!! ','error')
            return render_template('login.html')    
    except:
        return redirect(url_for('appError'))
Пример #4
0
def applyForExam():
    examID = request.json['examID']
    exam = Exam.query.filter(Exam.id == examID).first()
    if exam:
        print('User {} is trying to apply for exam id {}'.format(
            current_identity.username, exam.id))
        application = Application(user_id=current_identity.id, exam_id=exam.id)
        application.save()
        return custom_response({'message': 'Application successful.'})
    else:
        return custom_response({'message': 'Application failed.'}, 400)
Пример #5
0
    def post(self):
        json = request.json
        abort_if_invalid_request_params(json, ['job', 'resume'])

        application = Application()
        application.job = json['job']
        application.resume = json['resume']

        if 'cover_letter' in json:
            application.cover_letter = json['cover_letter']

        application.save()

        return me_obj_to_serializable(application)
Пример #6
0
def request_put(request):
    header_title, path1, path2 = '添加申请', '用户管理', '填写申请'
    if request.method == 'POST':
        description = request.POST.get('description', '')
        uuid_r = request.user.uuid
        user = get_object(User, uuid=uuid_r)
        a = Application(description=description, applicant=user)
        a.save()

        users = User.objects.filter(role='SU')
        for u in users:
            print u.username, u.name, u.role
            title = '新的申请'
            msg = description
            user = u
            mail_notify(title, msg, user)

    return my_render('juser/request_put.html', locals(), request)
Пример #7
0
def applications_register():
    request_body = request.get_json()
    application_id = request_body.get('applicationId')
    server_key = request_body.get('serverKey')

    application = Application(application_id, server_key)
    application = application.save()

    if application is None:
        return jsonify({'message': 'Could not subsribe!'})

    return jsonify(application.json())
Пример #8
0
def server_apply(request):
    config_all = Config.objects.all()
    if request.method == 'POST':
        username = request.session.get('username')
        server_type = request.POST.get('server_type')
        server_os = request.POST.get('server_os')
        server_num = request.POST.get('server_num')
        users = request.POST.get('users')
        leader_email = request.POST.get('leader_email')
        apply_reason = request.POST.get('apply_reason')
        print server_type, server_os, server_num, users, leader_email, apply_reason

        #try:
        # 检查输入的用户是不是LDAP用户
        status = check_ldap_user(users)
        if status.startswith('error'):
            print "$$$$$$$$$$$$$$$$$$$$"
            print status
            print "$$$$$$$$$$$$$$$$$$$$"
            return HttpResponse(status)
        print "!!!!!!!!!!!!!!!!!"
        config_get = Config.objects.get(id=server_type)
        application = Application(username=username,
                                  config=config_get,
                                  os=server_os,
                                  server_num=server_num,
                                  users_add=users,
                                  status=1,
                                  leader_email=leader_email,
                                  apply_reason=apply_reason)
        application.save()
        print "@@@@@@@@@@@@@@@@@@@@"
        status = mail_to_reviewer.delay(application)
        print status

        #except Exception,e:
        #       print e
        return HttpResponse(u'送审成功')
    return render_to_response('server_apply.html', locals())
Пример #9
0
def workspace_test():
	print_data('workspaces objects', br=False)

	for index in range(3):
		w = Workspace()
		w.name = 'New workspace name'
		w.description = 'Some new description'
		w.save()

	workspaces = Workspace.all()
	print_data('new objects -> model.all()', workspaces)

	w.name = 'Updated name'
	w.save()

	workspaces = Workspace.all()
	print_data('UPDATED -> model.all()', workspaces)

	workspaces = Workspace.get(id=w.id, name=w.name)
	print_data('GET -> model.get()', [workspaces])

	workspaces = Workspace.filter(name='New workspace name')
	print_data('FILTER -> model.filter()', workspaces)

	for index in range(2):
		o = Application()
		o.workspace_id = w.guid
		o.save()

	a = View()
	a.application_id = o.guid
	a.save()

	a = Resource()
	a.application_id = o.guid
	a.save()

	for index in range(3):
		o = Widget()
		o.workspace_id = w.guid
		o.save()

	for index in range(3):
		o = DataSource()
		o.workspace_id = w.guid
		o.save()

	objects = Workspace.all() + Resource.all() + Application.all() + Widget.all() + DataSource.all() + View.all()
	print_data('All objects in db', objects)

#	[w.delete() for w in Workspace.all()]
	workspaces = Workspace.all()
	print_data('cleaned', workspaces)

	workspaces = Workspace.filter(include_deleted=True)
	print_data('cleaned with deleted if exists', workspaces)

	objects = Workspace.all() + Resource.all() + Application.all() + Widget.all() + DataSource.all() + View.all()
	print_data('no objects left', objects)
Пример #10
0
def hr_application_create_view(request, form_id=None):
    if form_id:
        app_form = get_object_or_404(ApplicationForm, id=form_id)
        if request.method == "POST":
            if Application.objects.filter(user=request.user).filter(
                    form=app_form).exists():
                logger.warn(
                    "User %s attempting to duplicate application to %s" %
                    (request.user, app_form.corp))
            else:
                application = Application(user=request.user, form=app_form)
                application.save()
                for question in app_form.questions.all():
                    response = ApplicationResponse(question=question,
                                                   application=application)
                    response.answer = request.POST.get(
                        str(question.pk),
                        "Failed to retrieve answer provided by applicant.")
                    response.save()
                logger.info("%s created %s" % (request.user, application))
            return redirect('auth_hrapplications_view')
        else:
            questions = app_form.questions.all()
            return render_to_response('registered/hrapplicationcreate.html', {
                'questions': questions,
                'corp': app_form.corp
            },
                                      context_instance=RequestContext(request))
    else:
        choices = []
        for app_form in ApplicationForm.objects.all():
            if not Application.objects.filter(user=request.user).filter(
                    form=app_form).exists():
                choices.append((app_form.id, app_form.corp.corporation_name))
        return render_to_response('registered/hrapplicationcorpchoice.html',
                                  {'choices': choices},
                                  context_instance=RequestContext(request))
Пример #11
0
def apply_form(request):
    if request.method == 'GET':
        symbols = range(ord('a'), ord('z')) + range(ord('A'), ord('Z')) + range(ord('0'), ord('9'))
        random.seed()
        form_data = {'auth_key': ''.join([chr(symbols[random.randrange(len(symbols))]) for i in range(8)])}
        t = loader.get_template('vtb_apply.html')
        return HttpResponse(t.render(Context(form_data)))

    if request.method == 'POST':
        form = ApplicationForm(request.POST)
        #print smart_str(form.data['region']), isinstance(smart_str(form.data['region']), unicode) 
        data = Application(
            job_id = form.data['job_id'],
            email = form.data['email'],
            firstname = form.data['fname'],
            lastname = form.data['lname'],
            surname = form.data['mname'],
            sex = form.data['sex'] or  None,
            birthday = form.data['birthdate'],
            region_id = form.data['region'],
            address = form.data['address'],
            home_phone = form.data['phone_home'],
            work_phone = form.data['phone_work'],
            mobile_phone = form.data['phone_cell'],
            specializations = form.data['prof_sect'],
            post = form.data['title'],
            employment_type = form.data['type'],
            desirable_compensation_ammount = form.data['salary'],
            desirable_compensation_currency = form.data['scurrency'],
            ready_to_movement = 'True' if 'reloc' in form.data else 'False',
            last_place_of_work_and_position = form.data['latest_job'],
            cv = form.data['resume'],
        )
        data.save()
        return HttpResponse('import_success')
    
    return HttpResponse('Method not allowed: {0} for path {0}'.format(request.method, request.path), status = 400)
Пример #12
0
def device_update(request, device_uid):
    if request.method == "GET":
        try:
            update = DeviceUpdate.objects.filter(device=Device.objects.get(uid=device_uid)).latest("date")
            vulnerabilities = find_vulnerabilities(update)
            return HttpResponse(vulnerabilities.count())
        except DeviceUpdate.DoesNotExist:
            return HttpResponse("0")
    elif request.method == "POST":
        safe = 0
        unsafe = 0
        similar = 0
        unique_apps = {}
        json_data = json.loads(request.body.decode("unicode_escape"))
        try:
            device = Device.objects.get(uid=device_uid)
            device.os = json_data['meta']['os_name']
            device.save()
        except Device.DoesNotExist:
            return HttpResponse("Device does not exist", status=404)
        device.last_updated = datetime.now()
        device.save()

        #Next, Munge the software list at json_data['software'] to find CPEs, etc.
        for software in json_data['software']:
            name = unicode(software['name'].lower())
            version = unicode(software['versionString'].lower())
            publisher = unicode(software['publisher'].lower())

            #Remove version strings in the software name
            match = re.match("(.*?)[Vv \.]*(ersion\.)?(\d+(\.\d*)+)(.*)", name)
            if match:
                if version == "null" and match.group(3) is not None:
                    version = match.group(3)
                name = match.group(1)

            if version == "null":
                continue

            #Publisher like "Microsoft Corporation" will find "Microsoft"
            publisher = publisher.split(",")[0] #Removes ", Inc" etc.
            publisher_words = publisher.split(" ")

            #Attempt to grab things like "amd"
            if len(publisher_words) > 2: #Only 3 or more words
                acronym = ""
                for word in publisher_words:
                    if len(word) > 0:
                        acronym += word[0]
                publisher_words.append(acronym)

            #Remove some brackets (Usually x64 stuff)
            brackets = re.search("(\(.*\))", name)
            if brackets:
                name = name.replace(brackets.group(1), "").strip()

            #Remove publisher names at the start, if we can
            for word in publisher_words:
                #Try and compare
                if word in name:
                    publisher = word
                    replaced_name = name.replace(word, "").strip()
                    #Products with a single name, e.g. Evernote by Evernote
                    if len(replaced_name) > 5: #Less than 3 characters
                        name = replaced_name

            if name == publisher + "t":
                name = publisher

            publisher = publisher.strip().replace(" ", "_")
            name = name.strip().replace(" ", "_")

            out = publisher +" - " + name + " - " + version

            try:
                #Try to do stuff
                unique_apps[out] = App(publisher, name, version, software["name"])
            except KeyError:
                unique_apps[out] = App(publisher, name, version, software["name"])


        for key,app in sorted(unique_apps.items(), key=lambda x: x[1].publisher):
            out = key

            matched = False

            matches = Cpe.objects.filter(product=app.name, version=app.version)
            non_match = Cpe.objects.filter(product=app.name)
            if matches.count() > 0 and "RELATED" not in matches[0].cpe:
                matched = True
                out += " VULNERABLE"
                unsafe += 1
                app.cpe = matches[0]
            elif non_match.count() > 0:
                matched = True
                out += " SAFE"
                safe += 1
                app.related_cpe = non_match[0]

            if not matched:

                vendor_family = Cpe.objects.filter(vendor=app.publisher, product__contains=app.name)
                vendor_match = Cpe.objects.filter(vendor=app.publisher, product__contains=app.name, version=app.version)
                if vendor_match.count() > 0 and "RELATED" not in vendor_match[0].cpe:
                    matched = True
                    out += " VULNERABLE"
                    unsafe += 1
                    app.cpe = vendor_match[0]
                elif vendor_family.count() > 0:
                    matched = True
                    out +="SAFE"
                    safe += 1
                    app.related_cpe = vendor_family[0]

                if not matched:
                    prods = Cpe.objects.filter(version__contains=app.version)
                    for prod in prods:
                        if prod.product.replace("_", " ") in app.title.lower():
                            matched = True
                            out += " SIMILAR-------------- " + prod.product
                            similar += 1
                            app.cpe = prod

            print out

        print safe, "safe"
        print unsafe, "unsafe"
        print similar, "similar"
        print len(unique_apps), "total"

        #Add a new device update
        d = DeviceUpdate(date=datetime.now(), device=device)
        d.save()

        #For each app, find if it has been added for this device
        matched_apps = [ app for key,app in unique_apps.items() if app.cpe is not None]
        for app in matched_apps:
            #Attach to an application
            #This shouldnt exist, Application objects for Vulns should exist already
            newApp, created = Application.objects.get_or_create(cpe=app.cpe)
            if created:
                newApp.save()

            up = UpdateApplications(update=d, application=newApp)
            up.save()

        detected_apps = [ app for key,app in unique_apps.items() if app.related_cpe is not None]
        for app in detected_apps:
            #Make a new CPE from the related CPE
            cpe, created = Cpe.objects.get_or_create(  
                        cpe=app.related_cpe.cpe + ":RELATED:" + app.version,
                        part=app.related_cpe.part,
                        vendor=app.related_cpe.vendor,
                        product=app.related_cpe.product,
                        version=app.version,
                        update=app.related_cpe.update,
                        edition=app.related_cpe.edition,
                        language=app.related_cpe.language,
                        sw_edition=app.related_cpe.sw_edition,
                        target_sw=app.related_cpe.target_sw,
                        target_hw=app.related_cpe.target_hw,
                        other=app.related_cpe.other,
                        title=app.related_cpe.title
                    )
            if created:
                cpe.save()
                #Create a new application
                newApp = Application(cpe=cpe)
                newApp.save()
            else:
                newApp = Application.objects.get(cpe=cpe)

            upApp = UpdateApplications(update=d, application=newApp)
            upApp.save()


    response = HttpResponse(device_uid)
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response
Пример #13
0
def upload():
    """ Retrieving the file from the request object """ 
    
    # creation of the folder on disk and upload the file selected
    target=os.path.join(APP_ROOT,"upload")
    
    if not os.path.isdir(target):
        os.mkdir(target)

    try :

        file=request.files["InputFile"]
        filename=file.filename
        destination="/".join((target,filename))
        file.save(destination)

        myTable=request.form["inputTable"]
        recImported=0
        
        # Management of the scripts
        if myTable=="Script" :
            with open(destination,"r") as f:
                for line in f:
                    # Init the variables for the process
                    fields=[]
                    fields=line.split(",")

                    # Retrieving the values of the fields
                    if len(fields)== 5 :
                        myScript=Script()
                        myScript.scriptname=fields[0]
                        myScript.scriptdescription=fields[1]
                        myScript.scripttechnology=fields[2]
                        myScript.businessowner=fields[3]
                        myScript.executionfrequency=fields[4]
                        myScript.save()
                        recImported+=1
            flash('Congratulations, {} Script(s) records have been imported recently !!! '.format(recImported), 'message')

        # Management of the scripts
        if myTable=="Application" :
            with open(destination,"r") as f:
                for line in f:
                    # Init the variables for the process
                    fields=[]
                    fields=line.split(",")

                    # Retrieving the values of the fields
                    if len(fields)== 8 :
                        myApplication=Application()
                        myApplication.systemname=fields[0]
                        myApplication.systemdescription=fields[1]
                        myApplication.systemtechnology=fields[2]
                        myApplication.systemprovider=fields[3]
                        myApplication.systemowner=fields[4]
                        myApplication.systemstatus=fields[5]
                        myApplication.systemurl=fields[6]
                        myApplication.systemcategory=fields[7]
                        myApplication.save()
                        recImported+=1
            flash('Congratulations, {} Application(s) records have been imported recently !!! '.format(recImported), 'message')

        # Management of the scripts
        if myTable=="Contract" :
            with open(destination,"r") as f:
                for line in f:
                    # Init the variables for the process
                    fields=[]
                    fields=line.split(",")

                    # Retrieving the values of the fields
                    if len(fields)== 8 :
                        myContract=Contract()
                        myContract.contractref=fields[0]
                        myContract.systemname=fields[1]
                        myContract.contractrenewtype=fields[2]
                        myContract.contractcost=fields[3]
                        myContract.contractstartingdate=fields[4]
                        myContract.contractendingdate=fields[5]
                        myContract.contractcomment=fields[6]
                        mystring=fields[7]
                        mystring=mystring[:-2]
                        myContract.contractyear=int(mystring)
                        myContract.save()
                        recImported+=1
            flash('Congratulations, {} Contract(s) records have been imported recently !!! '.format(recImported), 'message')


    except:
        flash('Sorry, check the inputs of the importation process !!! ', 'error')
        return redirect(url_for('menu'))

    return redirect(url_for('menu'))