예제 #1
0
def dt_login(request):
    redirect_to = request.REQUEST.get('next', '/')
    if request.method == 'POST':
        data = request.POST
        if "username" in data and "password" in data:
            username = data.get("username")
            password = data.get("password")

            if username and password:
                user = auth.authenticate(username=username, password=password)
                if user and user.is_active:
                    login(request, user)
                    if request.session.test_cookie_worked():
                        request.session.delete_test_cookie()
                    return HttpResponseRedirect(redirect_to)

    else:
        request.session.set_test_cookie()

    return render(
        'newtem/sign-in.html', request, {
            'action': urlresolvers.reverse('django_web.auth.views.dt_login'),
            'next': redirect_to,
            'login_errors': request.method == 'POST',
        })
 def response(self, request):
   data = dict(title=self.title, message=self.message, detail=self.detail, traceback=self.traceback)
   if not request.ajax:
     data['request'] = request
   response = render("popup_error.html", request, data)
   response.status_code = self.error_code
   return response
예제 #3
0
def credential(request, username):
    ''' user's credential , for ansible jobs '''
    user = User.objects.get(username = username)
    if (request.user != user):
        raise PopupException('Sorry, you have not right to see the cretential!')

    if request.method == 'POST':
        ssh_password = request.POST.get('ssh_password')
        ssh_key = request.POST.get('id_dsa_pub')
        profile = Profile.objects.get_or_create(user=request.user)[0]
        if ssh_password == '':
            profile.ssh_password=''
        else:
            profile.ssh_password =  AESencrypt("pass34",ssh_password)        
        profile.ssh_key = ssh_key
        profile.save()

    try:
        profile = Profile.objects.get(user=request.user)
    except:
        profile = None
    return render("account/credential.html", request, {
        'username':username,
        'profile':profile,
    })
예제 #4
0
def schedule(request, project_name):
    user = request.user
    project = Project.objects.get(name=project_name)
    if user.has_perm("execute_proj", project) == False:
        raise PopupException("Sorry, you have not right to execute the project!")
    jobs = Job.objects.filter(project=project).filter(status="pending").exclude(countdown=0)
    return render("ansible/schedule.html", request, {"project": project, "jobs": jobs, "request": request})
예제 #5
0
def view_project(request, project_name):
    if not project_name:
        raise Exception("project name required!")

    user = request.user
    project = Project.objects.get(name=project_name)
    if (User.objects.get(username='******').has_perm(
            'access_proj', project) == False):
        if (user.has_perm('access_proj', project) == False):
            raise PopupException(
                'Sorry, you have not right to access the project!')

    if not project:
        raise Exception("project not exits!")

    if request.method == 'POST':
        if (user.has_perm('config_proj', project) == False):
            raise PopupException(
                'Sorry, you have not right to config the project!')
        hostcontent = request.POST.get("hostcontent")
        savefilecontent(project_name, hostcontent)

    if project:
        templates = JobTemplate.objects.filter(project=project)
        hostcontent = getfilecontent(project_name)

        return render(
            "ansible/view_project.html", request, {
                'project': project,
                'templates': templates,
                'hostcontent': hostcontent,
                'request': request,
            })
    else:
        return HttpResponseRedirect(urlresolvers.reverse('list_projects'))
예제 #6
0
def view_project(request, project_name):
    if not project_name:
        raise Exception("project name required!")

    user = request.user
    project = Project.objects.get(name=project_name)
    if User.objects.get(username="******").has_perm("access_proj", project) == False:
        if user.has_perm("access_proj", project) == False:
            raise PopupException("Sorry, you have not right to access the project!")

    if not project:
        raise Exception("project not exits!")

    if request.method == "POST":
        if user.has_perm("config_proj", project) == False:
            raise PopupException("Sorry, you have not right to config the project!")
        hostcontent = request.POST.get("hostcontent")
        savefilecontent(project_name, hostcontent)

    if project:
        templates = JobTemplate.objects.filter(project=project)
        hostcontent = getfilecontent(project_name)

        return render(
            "ansible/view_project.html",
            request,
            {"project": project, "templates": templates, "hostcontent": hostcontent, "request": request},
        )
    else:
        return HttpResponseRedirect(urlresolvers.reverse("list_projects"))
예제 #7
0
def explore(request, project_name):
    user = request.user
    project = Project.objects.get(name=project_name)
    if User.objects.get(username="******").has_perm("config_proj", project) == False:
        if user.has_perm("config_proj", project) == False:
            raise PopupException("Sorry, you have not right to config the project!")
    return render("ansible/explore.html", request, {"request": request, "project": project})
예제 #8
0
def profile(request, username):
    ''' user's profile '''
    view_user = User.objects.get(username=username)
    profile = None
    if request.method == 'POST':
        cn_name = request.POST.get('cn')
        phonenum = request.POST.get('phone')
        profile = Profile.objects.get_or_create(user=request.user)[0]
        profile.cn_name = cn_name
        profile.phonenum = phonenum
        profile.save()
    try:
        profile = Profile.objects.get(user=request.user)
    except:
        profile = None
    if profile == None:
        try:
            profile = Profile.objects.get(user=view_user)
        except:
            pass
    return render(
        "account/profile.html", request, {
            'login_user': request.user,
            'username': username,
            'view_user': view_user,
            'profile': profile,
        })
예제 #9
0
def credential(request, username):
    ''' user's credential , for ansible jobs '''
    user = User.objects.get(username=username)
    if (request.user != user):
        raise PopupException(
            'Sorry, you have not right to see the cretential!')

    if request.method == 'POST':
        ssh_password = request.POST.get('ssh_password')
        ssh_key = request.POST.get('id_dsa_pub')
        profile = Profile.objects.get_or_create(user=request.user)[0]
        if ssh_password == '':
            profile.ssh_password = ''
        else:
            profile.ssh_password = AESencrypt("pass34", ssh_password)
        profile.ssh_key = ssh_key
        profile.save()

    try:
        profile = Profile.objects.get(user=request.user)
    except:
        profile = None
    return render("account/credential.html", request, {
        'username': username,
        'profile': profile,
    })
예제 #10
0
def view_file(request, project_name, path, type):
    if type.count('/') > 0:
        types = type.split('/')
        temp = '/'.join(types[1:])
        path = os.path.join(temp, path)
        type = types[0]
    project = Project.objects.get(name=project_name)
    if type == "inventory":
        path = os.path.join(get_project_dir(project_name), "inventories", path)
    if type == "playbook":
        path = os.path.join(get_project_dir(project_name), "playbooks", path)
    if type == "vars":
        path = os.path.join(get_project_dir(project_name), "vars", path)
    content = get_project_file_content(project_name, path)

    file_name = ntpath.basename(path)

    return render(
        "ansible/view_file.html", request, {
            'request': request,
            'path': path,
            'file_name': file_name,
            'content': content,
            'project': project,
        })
예제 #11
0
def profile(request, username):
    ''' user's profile '''
    view_user = User.objects.get(username = username)
    profile = None
    if request.method == 'POST':
        cn_name = request.POST.get('cn')
        phonenum = request.POST.get('phone')
        profile = Profile.objects.get_or_create(user=request.user)[0]
        profile.cn_name = cn_name
        profile.phonenum = phonenum
        profile.save()
    try:
        profile = Profile.objects.get(user=request.user)
    except:
        profile = None
    if profile == None:
        try:
            profile = Profile.objects.get(user=view_user)
        except:
            pass
    return render("account/profile.html", request, {
        'login_user':request.user,
        'username':username,
        'view_user':view_user,
        'profile':profile,
        })
예제 #12
0
def result(request, project_name, job_pk):
    project = Project.objects.get(name=project_name)
    job = Job.objects.get(pk=job_pk)
    color = re.compile("(.\[0\;\d+m)?(.*?)(.\[\dm)?")
    job.result_stdout = color.sub(r"\2", job.result_stdout)
    job.result_stderr = color.sub(r"\2", job.result_stderr)
    job.result_traceback = color.sub(r"\2", job.result_traceback)
    return render("ansible/result.html", request, {"request": request, "job": job})
예제 #13
0
def list_users(request):
    ''' list users '''
    users_json = json.dumps(list(User.objects.values_list('id', flat=True)))
    return render("account/list_users.html", request ,{
            'login_user':request.user,
            'users': User.objects.all(),
            'users_json': users_json,
            'request': request,
           })
예제 #14
0
def list_users(request):
    ''' list users '''
    users_json = json.dumps(list(User.objects.values_list('id', flat=True)))
    return render(
        "account/list_users.html", request, {
            'login_user': request.user,
            'users': User.objects.all(),
            'users_json': users_json,
            'request': request,
        })
 def response(self, request):
     data = dict(title=self.title,
                 message=self.message,
                 detail=self.detail,
                 traceback=self.traceback)
     if not request.ajax:
         data['request'] = request
     response = render("popup_error.html", request, data)
     response.status_code = self.error_code
     return response
예제 #16
0
def result(request, project_name, job_pk):
    project = Project.objects.get(name=project_name)
    job = Job.objects.get(pk=job_pk)
    color = re.compile('(.\[0\;\d+m)?(.*?)(.\[\dm)?')
    job.result_stdout = color.sub(r'\2', job.result_stdout)
    job.result_stderr = color.sub(r'\2', job.result_stderr)
    job.result_traceback = color.sub(r'\2', job.result_traceback)
    return render("ansible/result.html", request, {
        'request': request,
        'job': job
    })
예제 #17
0
def list_projects(request):
    #    user=request.user
    #    if  ( user.has_perm('ansible.access_ansible')==False ):
    #         raise PopupException('Sorry, you have not right to manage ansible !')
    projects = Project.objects.all()
    groups = []
    for project in projects:
        if project.group not in groups and project.group != None and project.group != "":
            groups.append(project.group)

    return render("ansible/list_projects.html", request, {"projects": projects, "groups": groups, "request": request})
예제 #18
0
def explore(request, project_name):
    user = request.user
    project = Project.objects.get(name=project_name)
    if (User.objects.get(username='******').has_perm(
            'config_proj', project) == False):
        if (user.has_perm('config_proj', project) == False):
            raise PopupException(
                'Sorry, you have not right to config the project!')
    return render("ansible/explore.html", request, {
        'request': request,
        'project': project
    })
예제 #19
0
def schedule(request, project_name):
    user = request.user
    project = Project.objects.get(name=project_name)
    if (user.has_perm('execute_proj', project) == False):
        raise PopupException(
            'Sorry, you have not right to execute the project!')
    jobs = Job.objects.filter(project=project).filter(
        status='pending').exclude(countdown=0)
    return render("ansible/schedule.html", request, {
        'project': project,
        'jobs': jobs,
        'request': request,
    })
예제 #20
0
def manage_project(request, project_id=""):
    user = request.user
    id = project_id
    project = Project.objects.get(pk=id)
    if (user.has_perm('manage_proj', project) == False):
        raise PopupException(
            'Sorry, you have not right to manage the project!')
    user_perms = get_users_with_perms(project, attach_perms=True)
    allusers = json.dumps(list(get_allusers()))
    page_errors = None
    if request.method == 'POST':
        for key in request.POST:
            value = request.POST[key]
        for key, value in request.POST.iteritems():
            m = re.match(r'.+_proj@', key)
            if m:
                keylist = re.split(r'@', key)
                keyperm = keylist[0]
                keyuser = User.objects.get(pk=keylist[1])
                if user_perms.has_key(keyuser):
                    if keyperm in user_perms[keyuser]:
                        user_perms[keyuser].remove(keyperm)
                    else:
                        assign_perm(keyperm, keyuser, project)
                else:
                    assign_perm(keyperm, keyuser, project)
        for key, value in user_perms.items():
            if value != []:
                for item in value:
                    remove_perm(item, key, project)
        return HttpResponseRedirect(urlresolvers.reverse('list_projects'))
    else:
        try:
            project = Project.objects.get(id=id)
        except Exception:
            raise Http404
    return render(
        "ansible/manage_project.html", request, {
            'action':
            urlresolvers.reverse('manage_project', kwargs={'project_id': id}),
            'project':
            project,
            'user_perms':
            user_perms,
            'allusers':
            allusers,
            'page_errors':
            page_errors,
            'request':
            request,
        })
예제 #21
0
def view_project_logs(request, project_name):
    if not project_name:
        raise Exception("project name required!")

    project = Project.objects.get(name=project_name)

    if not project:
        raise Exception("project not exits!")

    if project:
        jobs = Job.objects.filter(project=project)

        return render("ansible/view_project_logs.html", request, {"project": project, "jobs": jobs, "request": request})
    else:
        return HttpResponseRedirect(urlresolvers.reverse("list_projects"))
예제 #22
0
def list_projects(request):
    #    user=request.user
    #    if  ( user.has_perm('ansible.access_ansible')==False ):
    #         raise PopupException('Sorry, you have not right to manage ansible !')
    projects = Project.objects.all()
    groups = []
    for project in projects:
        if project.group not in groups and project.group != None and project.group != '':
            groups.append(project.group)

    return render("ansible/list_projects.html", request, {
        'projects': projects,
        'groups': groups,
        'request': request,
    })
예제 #23
0
def elfinder_view_file(request, project_name, path):
    tmppath = path
    if path[0] != "/":
        path = "/" + path
    project = Project.objects.get(name=project_name)
    workpath = get_project_dir(project_name)
    if workpath not in path:
        path = os.path.join(workpath, tmppath)
    content = get_project_file_content(project_name, path)
    file_name = ntpath.basename(path)
    return render(
        "ansible/view_file.html",
        request,
        {"request": request, "path": path, "file_name": file_name, "content": content, "project": project},
    )
예제 #24
0
def manage_project(request, project_id=""):
    user = request.user
    id = project_id
    project = Project.objects.get(pk=id)
    if user.has_perm("manage_proj", project) == False:
        raise PopupException("Sorry, you have not right to manage the project!")
    user_perms = get_users_with_perms(project, attach_perms=True)
    allusers = json.dumps(list(get_allusers()))
    page_errors = None
    if request.method == "POST":
        for key in request.POST:
            value = request.POST[key]
        for key, value in request.POST.iteritems():
            m = re.match(r".+_proj@", key)
            if m:
                keylist = re.split(r"@", key)
                keyperm = keylist[0]
                keyuser = User.objects.get(pk=keylist[1])
                if user_perms.has_key(keyuser):
                    if keyperm in user_perms[keyuser]:
                        user_perms[keyuser].remove(keyperm)
                    else:
                        assign_perm(keyperm, keyuser, project)
                else:
                    assign_perm(keyperm, keyuser, project)
        for key, value in user_perms.items():
            if value != []:
                for item in value:
                    remove_perm(item, key, project)
        return HttpResponseRedirect(urlresolvers.reverse("list_projects"))
    else:
        try:
            project = Project.objects.get(id=id)
        except Exception:
            raise Http404
    return render(
        "ansible/manage_project.html",
        request,
        {
            "action": urlresolvers.reverse("manage_project", kwargs={"project_id": id}),
            "project": project,
            "user_perms": user_perms,
            "allusers": allusers,
            "page_errors": page_errors,
            "request": request,
        },
    )
예제 #25
0
def elfinder_view_file(request, project_name, path):
    tmppath = path
    if path[0] != '/':
        path = '/' + path
    project = Project.objects.get(name=project_name)
    workpath = get_project_dir(project_name)
    if workpath not in path:
        path = os.path.join(workpath, tmppath)
    content = get_project_file_content(project_name, path)
    file_name = ntpath.basename(path)
    return render(
        "ansible/view_file.html", request, {
            'request': request,
            'path': path,
            'file_name': file_name,
            'content': content,
            'project': project,
        })
예제 #26
0
def edit_project(request, project_id=""):
    id = project_id
    user = request.user
    project = Project.objects.get(pk=id)
    if (user.has_perm('manage_proj', project) == False):
        raise PopupException(
            'Sorry, you have not right to manage the project!')
    page_errors = None
    if request.method == 'POST':
        name = request.POST.get("name")
        desc = request.POST.get("description")
        scmtype = request.POST.get("scmtype")
        scmurl = request.POST.get("scmurl")
        group = request.POST.get("group")
        if not name:
            raise Exception("project name required!")
    #   project = Project.objects.get(pk = id)
        if project:
            project.name = name
            project.description = desc
            project.created_by = request.user
            project.scmtype = scmtype
            project.scmurl = scmurl
            project.group = group
            project.save()
        else:
            raise Exception("Project is not existed!")
        return HttpResponseRedirect(urlresolvers.reverse('list_projects'))
    else:
        try:
            project = Project.objects.get(id=id)
        except Exception:
            raise Http404
    return render(
        "ansible/add_project.html", request, {
            'action':
            urlresolvers.reverse('edit_project', kwargs={'project_id': id}),
            'project':
            project,
            'page_errors':
            page_errors,
            'request':
            request,
        })
예제 #27
0
def deploykey(request, project_name):
    user = request.user
    project = Project.objects.get(name=project_name)
    if (user.has_perm('execute_proj', project) == False):
        raise PopupException(
            'Sorry, you have not right to execute the project!')

    result = []
    page_errors = None
    if request.method == 'POST':
        inventory = request.POST.get('inventory')
        hosts = request.POST.get('hosts')
        user = request.POST.get('user')
        password = request.POST.get('password')
        key = request.POST.get('sshkey')

        if inventory == '<--None-->':
            file_content = hosts
            if file_content.count(','):
                file_content = '\n'.join(file_content.split(','))
            elif file_content.count(';'):
                file_content = '\n'.join(file_content.split(';'))
            else:
                file_content = '\n'.join(file_content.split(' '))
            file_name = 'hosts'
            inventory = create_tmp_task_file(project_name, file_name,
                                             file_content)

        inventory = get_inventory_local_path(project_name, inventory)
        hostlist = get_hosts(inventory, hosts)
        result = get_sshkey_deploy(hostlist, user, password, key)
        results = {}
        for i in range(len(result)):
            results[i] = result[i]
        results = [results]
        return render_json(results)

    return render(
        "ansible/deploykey.html", request, {
            'project': project,
            'result': result,
            'page_errors': page_errors,
            'request': request,
        })
예제 #28
0
def view_project_logs(request, project_name):
    if not project_name:
        raise Exception("project name required!")

    project = Project.objects.get(name=project_name)

    if not project:
        raise Exception("project not exits!")

    if project:
        jobs = Job.objects.filter(project=project)

        return render("ansible/view_project_logs.html", request, {
            'project': project,
            'jobs': jobs,
            'request': request,
        })
    else:
        return HttpResponseRedirect(urlresolvers.reverse('list_projects'))
예제 #29
0
def edit_project(request, project_id=""):
    id = project_id
    user = request.user
    project = Project.objects.get(pk=id)
    if user.has_perm("manage_proj", project) == False:
        raise PopupException("Sorry, you have not right to manage the project!")
    page_errors = None
    if request.method == "POST":
        name = request.POST.get("name")
        desc = request.POST.get("description")
        scmtype = request.POST.get("scmtype")
        scmurl = request.POST.get("scmurl")
        group = request.POST.get("group")
        if not name:
            raise Exception("project name required!")
        #   project = Project.objects.get(pk = id)
        if project:
            project.name = name
            project.description = desc
            project.created_by = request.user
            project.scmtype = scmtype
            project.scmurl = scmurl
            project.group = group
            project.save()
        else:
            raise Exception("Project is not existed!")
        return HttpResponseRedirect(urlresolvers.reverse("list_projects"))
    else:
        try:
            project = Project.objects.get(id=id)
        except Exception:
            raise Http404
    return render(
        "ansible/add_project.html",
        request,
        {
            "action": urlresolvers.reverse("edit_project", kwargs={"project_id": id}),
            "project": project,
            "page_errors": page_errors,
            "request": request,
        },
    )
예제 #30
0
  def process_exception(self, request, exception):


    import traceback
    tb = traceback.format_exc()

    if isinstance(exception, PopupException):
        return exception.response(request)

    if isinstance(exception, StructuredException):
      if request.ajax:
        response = render_json(exception.response_data)
        response[MIDDLE_WARE_HEADER] = 'EXCEPTION'
        response.status_code = getattr(exception, 'error_code', 500)
        return response
      else:
        response = render("error.html", request,dict(error=exception.response_data.get("message")))
        response.status_code = getattr(exception, 'error_code', 500)
        return response

    return None
예제 #31
0
def deploykey(request, project_name):
    user = request.user
    project = Project.objects.get(name=project_name)
    if user.has_perm("execute_proj", project) == False:
        raise PopupException("Sorry, you have not right to execute the project!")

    result = []
    page_errors = None
    if request.method == "POST":
        inventory = request.POST.get("inventory")
        hosts = request.POST.get("hosts")
        user = request.POST.get("user")
        password = request.POST.get("password")
        key = request.POST.get("sshkey")

        if inventory == "<--None-->":
            file_content = hosts
            if file_content.count(","):
                file_content = "\n".join(file_content.split(","))
            elif file_content.count(";"):
                file_content = "\n".join(file_content.split(";"))
            else:
                file_content = "\n".join(file_content.split(" "))
            file_name = "hosts"
            inventory = create_tmp_task_file(project_name, file_name, file_content)

        inventory = get_inventory_local_path(project_name, inventory)
        hostlist = get_hosts(inventory, hosts)
        result = get_sshkey_deploy(hostlist, user, password, key)
        results = {}
        for i in range(len(result)):
            results[i] = result[i]
        results = [results]
        return render_json(results)

    return render(
        "ansible/deploykey.html",
        request,
        {"project": project, "result": result, "page_errors": page_errors, "request": request},
    )
예제 #32
0
def add_project(request):
    page_errors = None

    if request.method == 'POST':
        name = request.POST.get("name")
        desc = request.POST.get("description")
        scmtype = request.POST.get("scmtype")
        scmurl = request.POST.get("scmurl")
        group = request.POST.get("group")
        if not name:
            raise Exception("project name required!")

        try:
            project = Project(name=name)
            project.description = desc
            project.created_by = request.user
            project.scmtype = scmtype
            project.scmurl = scmurl
            project.group = group
            project.save()

            ensure_project_dir(project.name)
            user = request.user
            perms = get_perms(user, project)
            if perms == []:
                assign_perm('access_proj', user, project)
                assign_perm('config_proj', user, project)
                assign_perm('execute_proj', user, project)
                assign_perm('manage_proj', user, project)

        except Exception:
            raise Exception()
        return HttpResponseRedirect(urlresolvers.reverse('list_projects'))

    return render(
        "ansible/add_project.html", request, {
            'action': urlresolvers.reverse('add_project'),
            'page_errors': page_errors,
            'request': request,
        })
예제 #33
0
def view_file(request, project_name, path, type):
    if type.count("/") > 0:
        types = type.split("/")
        temp = "/".join(types[1:])
        path = os.path.join(temp, path)
        type = types[0]
    project = Project.objects.get(name=project_name)
    if type == "inventory":
        path = os.path.join(get_project_dir(project_name), "inventories", path)
    if type == "playbook":
        path = os.path.join(get_project_dir(project_name), "playbooks", path)
    if type == "vars":
        path = os.path.join(get_project_dir(project_name), "vars", path)
    content = get_project_file_content(project_name, path)

    file_name = ntpath.basename(path)

    return render(
        "ansible/view_file.html",
        request,
        {"request": request, "path": path, "file_name": file_name, "content": content, "project": project},
    )
예제 #34
0
def add_project(request):
    page_errors = None

    if request.method == "POST":
        name = request.POST.get("name")
        desc = request.POST.get("description")
        scmtype = request.POST.get("scmtype")
        scmurl = request.POST.get("scmurl")
        group = request.POST.get("group")
        if not name:
            raise Exception("project name required!")

        try:
            project = Project(name=name)
            project.description = desc
            project.created_by = request.user
            project.scmtype = scmtype
            project.scmurl = scmurl
            project.group = group
            project.save()

            ensure_project_dir(project.name)
            user = request.user
            perms = get_perms(user, project)
            if perms == []:
                assign_perm("access_proj", user, project)
                assign_perm("config_proj", user, project)
                assign_perm("execute_proj", user, project)
                assign_perm("manage_proj", user, project)

        except Exception:
            raise Exception()
        return HttpResponseRedirect(urlresolvers.reverse("list_projects"))

    return render(
        "ansible/add_project.html",
        request,
        {"action": urlresolvers.reverse("add_project"), "page_errors": page_errors, "request": request},
    )
예제 #35
0
    def process_exception(self, request, exception):

        import traceback
        tb = traceback.format_exc()

        if isinstance(exception, PopupException):
            return exception.response(request)

        if isinstance(exception, StructuredException):
            if request.ajax:
                response = render_json(exception.response_data)
                response[MIDDLE_WARE_HEADER] = 'EXCEPTION'
                response.status_code = getattr(exception, 'error_code', 500)
                return response
            else:
                response = render(
                    "error.html", request,
                    dict(error=exception.response_data.get("message")))
                response.status_code = getattr(exception, 'error_code', 500)
                return response

        return None
예제 #36
0
def dt_login(request):
  redirect_to = request.REQUEST.get('next', '/')
  if request.method == 'POST':
      data=request.POST
      if "username" in data and "password" in data:
          username=data.get("username")
          password=data.get("password")

          if username and password :
              user = auth.authenticate( username=username, password=password )
              if user and user.is_active:
                  login(request, user)
                  if request.session.test_cookie_worked():
                    request.session.delete_test_cookie()
                  return HttpResponseRedirect(redirect_to)

  else:
    request.session.set_test_cookie()

  return render('newtem/sign-in.html', request, {
        'action': urlresolvers.reverse('django_web.auth.views.dt_login'),
        'next': redirect_to,
        'login_errors': request.method == 'POST',
    })
예제 #37
0
def log_view(request):
    l = logging.getLogger()
    return render('logs.html', request, dict(log=["No logs found!"]))
예제 #38
0
def delete_user(request, username):
    ''' delete user '''
    return render("account/list_users.html", request, {})
예제 #39
0
def serve_404_error(request, *args, **kwargs):
    """Registered handler for 404. We just return a simple error"""
    return render("404.html", request, dict(uri=request.build_absolute_uri()))
예제 #40
0
def serve_500_error(request, *args, **kwargs):
    """Registered handler for 500. We use the debug view to make debugging easier."""
    exc_info = sys.exc_info()
    return render("500.html", request, {'traceback': traceback.extract_tb(exc_info[2])})
예제 #41
0
def execute_script(request, project_name):
    project = Project.objects.get(name=project_name)
    if request.method == 'POST':
        if (request.user.has_perm('execute_proj', project) == False):
            raise PopupException(
                'Soarry, you have not right to execute the project!')

        inventory = request.POST.get('inventory')
        script = request.POST.get('script')
        args = request.POST.get('args')
        hosts = request.POST.get('hosts')
        user = request.POST.get('user')
        use_sudo = request.POST.get('use_sudo')
        forks = request.POST.get('forks')
        limit = request.POST.get('limit')
        sudo_password = request.POST.get('sudo_password')
        sudo_user = request.POST.get('sudo_user')

        script_file_name = "%s.sh" % uuid.uuid1()
        script_content = script
        script_path = create_tmp_script_file(project_name, script_file_name,
                                             script_content)

        file_name = "%s.yml" % uuid.uuid1()
        file_content = "- hosts  : %s \n" % hosts
        # file_content += "  sudo   : yes\n"
        file_content += "  user   : %s \n" % user
        if sudo_user:
            file_content += "  sudo    : yes\n"
            file_content += "  sudo_user : %s \n" % sudo_user

        file_content += "  tasks  : \n"
        file_content += "      - name: execute script \n"
        file_content += "        action: script %s %s \n" % (script_path, args)

        file_path = create_tmp_task_file(project_name, file_name, file_content)

        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job = Job()
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job_today_id = job.get_id()
        job.name = '-'.join(['job', now, job_today_id])
        job.created_by = request.user

        job.project = project
        job.playbook = file_path
        job.inventory = get_inventory_local_path(project_name, inventory)
        if forks:
            job.forks = forks
        if limit:
            job.limit = limit
        job.use_sudo = use_sudo
        if sudo_user:
            job.sudo_user = sudo_user
        if sudo_password:
            job.sudo_password = sudo_password

        job.save()
        job_pk = job.pk

        job.start()

        return HttpResponseRedirect(
            urlresolvers.reverse('job_execute_result',
                                 kwargs={
                                     'project_name': project_name,
                                     'job_pk': job_pk
                                 }))

    return render("ansible/execute_script.html", request, {
        'request': request,
        'project': project
    })
예제 #42
0
def sync_ldap_users_groups(request):
    return render("account/list_users.html", request, {})
예제 #43
0
def serve_500_error(request, *args, **kwargs):
    """Registered handler for 500. We use the debug view to make debugging easier."""
    exc_info = sys.exc_info()
    return render("500.html", request,
                  {'traceback': traceback.extract_tb(exc_info[2])})
예제 #44
0
def delete_user(request, username):
    ''' delete user '''
    return render("account/list_users.html",request,{})
예제 #45
0
def execute_playbook(request, project_name, template_pk=None):

    project = Project.objects.get(name=project_name)
    template = JobTemplate()
    plist = list(project.package.values('version', 'date'))
    packagelist = []
    for item in plist:
        array = {}
        array['version'] = item['version']
        array['date'] = item['date'].strftime("%Y-%m-%d-%H:%M:%S")
        packagelist.append(array)
    package_json = json.dumps(packagelist)
    pmax = project.package.annotate().order_by('-date')[:1]

    if template_pk:
        template = JobTemplate.objects.get(pk=template_pk)

    if request.method == 'POST':

        if (request.user.has_perm('execute_proj', project) == False):
            raise PopupException(
                'Sorry, you have not right to execute the project!')

        save = request.POST.get('save')

        inventory = request.POST.get('inventory')
        var_files = request.POST.get('var_files')
        tasks = request.POST.get('tasks')
        hosts = request.POST.get('hosts')
        user = request.POST.get('user')
        use_sudo = request.POST.get('use_sudo')
        sudo_user = request.POST.get('sudo_user')
        forks = request.POST.get('forks')
        limit = request.POST.get('limit')
        extra_vars = request.POST.get('extra_vars')
        sudo_password = request.POST.get('sudo_password')
        package_version = request.POST.get('packageselect')
        email = request.POST.get('email')
        timer = request.POST.get('timer')
        #package_file = project_name + "_" + package_version + ".tar.gz"

        if inventory == '<--None-->':
            file_content = request.POST.get('hosts')
            if file_content.count(','):
                file_content = '\n'.join(file_content.split(','))
            elif file_content.count(';'):
                file_content = '\n'.join(file_content.split(';'))
            else:
                file_content = '\n'.join(file_content.split(' '))
            file_name = 'hosts'
            inventory = create_tmp_task_file(project_name, file_name,
                                             file_content)

        real_tasks = ""
        for t in tasks.splitlines():
            real_tasks = real_tasks + "     - include : " + get_playbook_local_path(
                project_name, t.strip()) + "\n"

        file_name = "%s.yml" % uuid.uuid1()
        file_content = "- hosts  : %s \n" % hosts
        #file_content += "  sudo   : yes\n"
        file_content += "  user   : %s \n" % user
        if sudo_user:
            file_content += "  sudo    : yes\n"
            file_content += "  sudo_user : %s \n" % sudo_user

        if package_version == "":
            if pmax:
                package_version = str(pmax[0].version)
        if package_version != "":
            package_file = project_name + "_" + package_version + ".tar.gz"
            file_content += "  vars   :\n"
            file_content += "        package : %s \n" % package_file

        if var_files is not None and var_files != "":
            real_var_files = ""
            for f in var_files.splitlines():
                real_var_files = real_var_files + "    - " + get_vars_local_path(
                    project_name, f.strip()) + "\n"
            file_content += "  vars_files:\n"
            file_content += real_var_files
        file_content += "  tasks  : \n"
        file_content += real_tasks

        file_path = create_tmp_task_file(project_name, file_name, file_content)

        countdown = 0
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        if timer:
            execute_date = datetime.datetime.strptime(timer,
                                                      "%d/%m/%Y %H:%M:%S")
            if execute_date > datetime.datetime.now():
                countdown = (execute_date - datetime.datetime.now()).seconds
        else:
            execute_date = datetime.datetime.now()

        job = Job()

        job_today_id = job.get_id()
        job.name = '-'.join(['job', now, job_today_id])
        job.created_by = request.user

        job.project = project
        job.playbook = file_path
        job.inventory = get_inventory_local_path(project_name, inventory)
        job.extra_vars = extra_vars
        if forks:
            job.forks = forks
        if limit:
            job.limit = limit
        job.use_sudo = use_sudo
        if sudo_user:
            job.sudo_user = sudo_user
        if sudo_password:
            job.sudo_password = sudo_password
        if email != "":
            job.email = email
        job.countdown = countdown
        job.execute_date = execute_date

        job.save()
        job_pk = job.pk

        job.start()

        return HttpResponseRedirect(
            urlresolvers.reverse('job_execute_result',
                                 kwargs={
                                     'project_name': project_name,
                                     'job_pk': job_pk
                                 }))

    return render(
        "ansible/execute_playbook.html", request, {
            'request': request,
            'project': project,
            'package_json': package_json,
            'template': template,
            'template_pk': template_pk,
        })
예제 #46
0
def execute_scp(request, project_name):
    project = Project.objects.get(name=project_name)
    if request.method == 'POST':
        if (request.user.has_perm('execute_proj', project) == False):
            raise PopupException(
                'Soarry, you have not right to execute the project!')

        inventory = request.POST.get('inventory')
        hosts = request.POST.get('hosts')
        user = request.POST.get('user')
        use_sudo = request.POST.get('use_sudo')
        forks = request.POST.get('forks')
        limit = request.POST.get('limit')
        sudo_password = request.POST.get('sudo_password')
        sudo_user = request.POST.get('sudo_user')
        owner = request.POST.get('owner')
        group = request.POST.get('group')
        mode = request.POST.get('mode')
        dest = request.POST.get('dest')
        file_obj = request.FILES.get('src', None)
        handle_uploaded_file(file_obj)

        script_file_name = "%s.sh" % uuid.uuid1()
        script_content = ""
        script_path = create_tmp_script_file(project_name, script_file_name,
                                             script_content)

        src_path = settings.TMP_FILE
        dest_path = dest
        file_name = "%s.yml" % uuid.uuid1()
        file_content = "- hosts  : %s \n" % hosts
        file_content += "  user   : %s \n" % user
        if sudo_user:
            file_content += "  sudo    : yes\n"
            file_content += "  sudo_user : %s \n" % sudo_user
        file_content += "  tasks  : \n"
        file_content += "      - name: execute script \n"
        file_content += "        action: copy src=%s dest=%s owner=%s group=%s mode=%d\n" % (
            src_path, dest_path, owner, group, int(mode))

        file_path = create_tmp_task_file(project_name, file_name, file_content)

        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job = Job()
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job_today_id = job.get_id()
        job.name = '-'.join(['job', now, job_today_id])
        job.created_by = request.user

        job.project = project
        job.playbook = file_path
        job.inventory = get_inventory_local_path(project_name, inventory)
        job.forks = forks
        if limit:
            job.limit = limit
        job.use_sudo = use_sudo
        if sudo_password:
            job.sudo_password = sudo_password
        if sudo_user:
            job.sudo_user = sudo_user

        job.save()
        job_pk = job.pk

        job.start()

        return HttpResponseRedirect(
            urlresolvers.reverse('job_execute_result',
                                 kwargs={
                                     'project_name': project_name,
                                     'job_pk': job_pk
                                 }))

    return render("ansible/execute_scp.html", request, {
        'request': request,
        'project': project
    })
예제 #47
0
def add_ldap_users(request):
    return render("account/list_users.html", request, {})
예제 #48
0
def sync_ldap_users_groups(request):
    return render("account/list_users.html", request, {})
예제 #49
0
def execute_playbook(request, project_name, template_pk=None):

    project = Project.objects.get(name=project_name)
    template = JobTemplate()
    plist = list(project.package.values("version", "date"))
    packagelist = []
    for item in plist:
        array = {}
        array["version"] = item["version"]
        array["date"] = item["date"].strftime("%Y-%m-%d-%H:%M:%S")
        packagelist.append(array)
    package_json = json.dumps(packagelist)
    pmax = project.package.annotate().order_by("-date")[:1]

    if template_pk:
        template = JobTemplate.objects.get(pk=template_pk)

    if request.method == "POST":

        if request.user.has_perm("execute_proj", project) == False:
            raise PopupException("Sorry, you have not right to execute the project!")

        save = request.POST.get("save")

        inventory = request.POST.get("inventory")
        var_files = request.POST.get("var_files")
        tasks = request.POST.get("tasks")
        hosts = request.POST.get("hosts")
        user = request.POST.get("user")
        use_sudo = request.POST.get("use_sudo")
        sudo_user = request.POST.get("sudo_user")
        forks = request.POST.get("forks")
        limit = request.POST.get("limit")
        extra_vars = request.POST.get("extra_vars")
        sudo_password = request.POST.get("sudo_password")
        package_version = request.POST.get("packageselect")
        email = request.POST.get("email")
        timer = request.POST.get("timer")
        # package_file = project_name + "_" + package_version + ".tar.gz"

        if inventory == "<--None-->":
            file_content = request.POST.get("hosts")
            if file_content.count(","):
                file_content = "\n".join(file_content.split(","))
            elif file_content.count(";"):
                file_content = "\n".join(file_content.split(";"))
            else:
                file_content = "\n".join(file_content.split(" "))
            file_name = "hosts"
            inventory = create_tmp_task_file(project_name, file_name, file_content)

        real_tasks = ""
        for t in tasks.splitlines():
            real_tasks = real_tasks + "     - include : " + get_playbook_local_path(project_name, t.strip()) + "\n"

        file_name = "%s.yml" % uuid.uuid1()
        file_content = "- hosts  : %s \n" % hosts
        # file_content += "  sudo   : yes\n"
        file_content += "  user   : %s \n" % user
        if sudo_user:
            file_content += "  sudo    : yes\n"
            file_content += "  sudo_user : %s \n" % sudo_user

        if package_version == "":
            if pmax:
                package_version = str(pmax[0].version)
        if package_version != "":
            package_file = project_name + "_" + package_version + ".tar.gz"
            file_content += "  vars   :\n"
            file_content += "        package : %s \n" % package_file

        if var_files is not None and var_files != "":
            real_var_files = ""
            for f in var_files.splitlines():
                real_var_files = real_var_files + "    - " + get_vars_local_path(project_name, f.strip()) + "\n"
            file_content += "  vars_files:\n"
            file_content += real_var_files
        file_content += "  tasks  : \n"
        file_content += real_tasks

        file_path = create_tmp_task_file(project_name, file_name, file_content)

        countdown = 0
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        if timer:
            execute_date = datetime.datetime.strptime(timer, "%d/%m/%Y %H:%M:%S")
            if execute_date > datetime.datetime.now():
                countdown = (execute_date - datetime.datetime.now()).seconds
        else:
            execute_date = datetime.datetime.now()

        job = Job()

        job_today_id = job.get_id()
        job.name = "-".join(["job", now, job_today_id])
        job.created_by = request.user

        job.project = project
        job.playbook = file_path
        job.inventory = get_inventory_local_path(project_name, inventory)
        job.extra_vars = extra_vars
        if forks:
            job.forks = forks
        if limit:
            job.limit = limit
        job.use_sudo = use_sudo
        if sudo_user:
            job.sudo_user = sudo_user
        if sudo_password:
            job.sudo_password = sudo_password
        if email != "":
            job.email = email
        job.countdown = countdown
        job.execute_date = execute_date

        job.save()
        job_pk = job.pk

        job.start()

        return HttpResponseRedirect(
            urlresolvers.reverse("job_execute_result", kwargs={"project_name": project_name, "job_pk": job_pk})
        )

    return render(
        "ansible/execute_playbook.html",
        request,
        {
            "request": request,
            "project": project,
            "package_json": package_json,
            "template": template,
            "template_pk": template_pk,
        },
    )
예제 #50
0
def execute_script(request, project_name):
    project = Project.objects.get(name=project_name)
    if request.method == "POST":
        if request.user.has_perm("execute_proj", project) == False:
            raise PopupException("Soarry, you have not right to execute the project!")

        inventory = request.POST.get("inventory")
        script = request.POST.get("script")
        args = request.POST.get("args")
        hosts = request.POST.get("hosts")
        user = request.POST.get("user")
        use_sudo = request.POST.get("use_sudo")
        forks = request.POST.get("forks")
        limit = request.POST.get("limit")
        sudo_password = request.POST.get("sudo_password")
        sudo_user = request.POST.get("sudo_user")

        script_file_name = "%s.sh" % uuid.uuid1()
        script_content = script
        script_path = create_tmp_script_file(project_name, script_file_name, script_content)

        file_name = "%s.yml" % uuid.uuid1()
        file_content = "- hosts  : %s \n" % hosts
        # file_content += "  sudo   : yes\n"
        file_content += "  user   : %s \n" % user
        if sudo_user:
            file_content += "  sudo    : yes\n"
            file_content += "  sudo_user : %s \n" % sudo_user

        file_content += "  tasks  : \n"
        file_content += "      - name: execute script \n"
        file_content += "        action: script %s %s \n" % (script_path, args)

        file_path = create_tmp_task_file(project_name, file_name, file_content)

        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job = Job()
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job_today_id = job.get_id()
        job.name = "-".join(["job", now, job_today_id])
        job.created_by = request.user

        job.project = project
        job.playbook = file_path
        job.inventory = get_inventory_local_path(project_name, inventory)
        if forks:
            job.forks = forks
        if limit:
            job.limit = limit
        job.use_sudo = use_sudo
        if sudo_user:
            job.sudo_user = sudo_user
        if sudo_password:
            job.sudo_password = sudo_password

        job.save()
        job_pk = job.pk

        job.start()

        return HttpResponseRedirect(
            urlresolvers.reverse("job_execute_result", kwargs={"project_name": project_name, "job_pk": job_pk})
        )

    return render("ansible/execute_script.html", request, {"request": request, "project": project})
예제 #51
0
def add_ldap_users(request):
    return render("account/list_users.html", request, {})
예제 #52
0
def log_view(request):
    l = logging.getLogger()
    return render('logs.html', request, dict(log=["No logs found!"]))
예제 #53
0
def serve_404_error(request, *args, **kwargs):
    """Registered handler for 404. We just return a simple error"""
    return render("404.html", request, dict(uri=request.build_absolute_uri()))
예제 #54
0
def execute_scp(request, project_name):
    project = Project.objects.get(name=project_name)
    if request.method == "POST":
        if request.user.has_perm("execute_proj", project) == False:
            raise PopupException("Soarry, you have not right to execute the project!")

        inventory = request.POST.get("inventory")
        hosts = request.POST.get("hosts")
        user = request.POST.get("user")
        use_sudo = request.POST.get("use_sudo")
        forks = request.POST.get("forks")
        limit = request.POST.get("limit")
        sudo_password = request.POST.get("sudo_password")
        sudo_user = request.POST.get("sudo_user")
        owner = request.POST.get("owner")
        group = request.POST.get("group")
        mode = request.POST.get("mode")
        dest = request.POST.get("dest")
        file_obj = request.FILES.get("src", None)
        handle_uploaded_file(file_obj)

        script_file_name = "%s.sh" % uuid.uuid1()
        script_content = ""
        script_path = create_tmp_script_file(project_name, script_file_name, script_content)

        src_path = settings.TMP_FILE
        dest_path = dest
        file_name = "%s.yml" % uuid.uuid1()
        file_content = "- hosts  : %s \n" % hosts
        file_content += "  user   : %s \n" % user
        if sudo_user:
            file_content += "  sudo    : yes\n"
            file_content += "  sudo_user : %s \n" % sudo_user
        file_content += "  tasks  : \n"
        file_content += "      - name: execute script \n"
        file_content += "        action: copy src=%s dest=%s owner=%s group=%s mode=%d\n" % (
            src_path,
            dest_path,
            owner,
            group,
            int(mode),
        )

        file_path = create_tmp_task_file(project_name, file_name, file_content)

        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job = Job()
        now = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time()))
        job_today_id = job.get_id()
        job.name = "-".join(["job", now, job_today_id])
        job.created_by = request.user

        job.project = project
        job.playbook = file_path
        job.inventory = get_inventory_local_path(project_name, inventory)
        job.forks = forks
        if limit:
            job.limit = limit
        job.use_sudo = use_sudo
        if sudo_password:
            job.sudo_password = sudo_password
        if sudo_user:
            job.sudo_user = sudo_user

        job.save()
        job_pk = job.pk

        job.start()

        return HttpResponseRedirect(
            urlresolvers.reverse("job_execute_result", kwargs={"project_name": project_name, "job_pk": job_pk})
        )

    return render("ansible/execute_scp.html", request, {"request": request, "project": project})