Commit 4d96978b authored by ibuler's avatar ibuler

Merge branch 'master' into audits

parents a448fd02 81ec1219
......@@ -181,6 +181,12 @@ LOGGING = {
'formatter': 'main',
'filename': os.path.join(PROJECT_DIR, 'logs', 'jumpserver.log')
},
'ansible_logs': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'formatter': 'main',
'filename': os.path.join(PROJECT_DIR, 'logs', 'ansible.log')
},
},
'loggers': {
'django': {
......@@ -209,6 +215,10 @@ LOGGING = {
'jumpserver.users.view': {
'handlers': ['console', 'file'],
'level': LOG_LEVEL,
},
'ops.ansible_api': {
'handlers': ['console', 'ansible_logs'],
'level': LOG_LEVEL,
}
}
}
......
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
"""jumpserver URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
......@@ -27,11 +30,15 @@ urlpatterns = [
url(r'^perms/', include('perms.urls.views_urls', namespace='perms')),
url(r'^audits/', include('audits.urls.views_urls', namespace='audits')),
url(r'^terminal/', include('terminal.urls.views_urls', namespace='terminal')),
url('^ops/', include('ops.urls.view_urls', namespace='ops')),
url(r'^api/users/', include('users.urls.api_urls', namespace='api-users')),
url(r'^api/assets/', include('assets.urls.api_urls', namespace='api-assets')),
url(r'^api/perms/', include('perms.urls.api_urls', namespace='api-perms')),
url(r'^api/audits/', include('audits.urls.api_urls', namespace='api-audits')),
url(r'^api/terminal/', include('terminal.urls.api_urls', namespace='api-terminal')),
url(r'^api/ops/', include('ops.urls.api_urls', namespace='api-ops')),
]
......
This diff is collapsed.
# ~*~ coding: utf-8 ~*~
#
from views import *
\ No newline at end of file
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals, print_function
from rest_framework.exceptions import APIException
from django.utils.translation import ugettext as _
class ServiceUnavailable(APIException):
status_code = default_code = 503
default_detail = _('Service temporarily unavailable, try again later.')
class ServiceNotImplemented(APIException):
status_code = default_code = 501
default_detail = _('This service maybe implemented in the future, but now not implemented!')
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
from rest_framework import permissions
class AdminUserRequired(permissions.BasePermission):
"""
Custom permission to only allow admin user to access the resource.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Write permissions are only allowed to the admin role.
return request.user.is_staff
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
from ops.models import *
from rest_framework import serializers
class HostAliaSerializer(serializers.ModelSerializer):
class Meta:
model = HostAlia
class CmdAliaSerializer(serializers.ModelSerializer):
class Meta:
model = CmdAlia
class UserAliaSerializer(serializers.ModelSerializer):
class Meta:
model = UserAlia
class RunasAliaSerializer(serializers.ModelSerializer):
class Meta:
model = RunasAlia
class ExtraconfSerializer(serializers.ModelSerializer):
class Meta:
model = Extra_conf
class PrivilegeSerializer(serializers.ModelSerializer):
class Meta:
model = Privilege
class SudoSerializer(serializers.ModelSerializer):
class Meta:
model = Sudo
class CronTableSerializer(serializers.ModelSerializer):
class Meta:
model = CronTable
class TaskSerializer(serializers.ModelSerializer):
sub_tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Task
read_only_fields = ('record',)
class SubTaskSerializer(serializers.ModelSerializer):
class Meta:
model = SubTask
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
from rest_framework import viewsets
from serializers import *
from permissions import *
__all__ = ["HostAliaViewSet",
"CmdAliaViewSet",
"UserAliaViewSet",
"RunasAliaViewSet",
"ExtraconfViewSet",
"PrivilegeViewSet",
"SudoViewSet",
"CronTableViewSet",
"TaskViewSet",
"SubTaskViewSet",
]
class HostAliaViewSet(viewsets.ModelViewSet):
queryset = HostAlia.objects.all()
serializer_class = HostAliaSerializer
permission_classes = (AdminUserRequired,)
class CmdAliaViewSet(viewsets.ModelViewSet):
queryset = CmdAlia.objects.all()
serializer_class = CmdAliaSerializer
permission_classes = (AdminUserRequired,)
class UserAliaViewSet(viewsets.ModelViewSet):
queryset = UserAlia.objects.all()
serializer_class = UserAliaSerializer
permission_classes = (AdminUserRequired,)
class RunasAliaViewSet(viewsets.ModelViewSet):
queryset = RunasAlia.objects.all()
serializer_class = RunasAliaSerializer
permission_classes = (AdminUserRequired,)
class ExtraconfViewSet(viewsets.ModelViewSet):
queryset = Extra_conf.objects.all()
serializer_class = ExtraconfSerializer
permission_classes = (AdminUserRequired,)
class PrivilegeViewSet(viewsets.ModelViewSet):
queryset = Privilege.objects.all()
serializer_class = PrivilegeSerializer
permission_classes = (AdminUserRequired,)
class SudoViewSet(viewsets.ModelViewSet):
queryset = Sudo.objects.all()
serializer_class = SudoSerializer
permission_classes = (AdminUserRequired,)
class CronTableViewSet(viewsets.ModelViewSet):
queryset = CronTable.objects.all()
serializer_class = CronTableSerializer
permission_classes = (AdminUserRequired,)
class TaskViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all()
serializer_class = TaskSerializer
permission_classes = (AdminUserRequired,)
class SubTaskViewSet(viewsets.ModelViewSet):
queryset = SubTask.objects.all()
serializer_class = SubTaskSerializer
permission_classes = (AdminUserRequired,)
from __future__ import unicode_literals
from django.db import models
# Create your models here.
from ansible import *
from cron import *
from sudo import *
from utils import *
from task import *
This diff is collapsed.
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals, absolute_import
import logging
from django.db import models
from assets.models import Asset
from django.utils.translation import ugettext_lazy as _
logger = logging.getLogger(__name__)
__all__ = ["CronTable"]
class CronTable(models.Model):
name = models.CharField(max_length=128, blank=True, null=True, unique=True, verbose_name=_('Name'),
help_text=_("Description of a crontab entry"))
month = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Month'),
help_text=_("Month of the year the job should run ( 1-12, *, */2, etc )"))
weekday = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('WeekDay'),
help_text=_("Day of the week that the job should run"
" ( 0-6 for Sunday-Saturday, *, etc )"))
day = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Day'),
help_text=_("Day of the month the job should run ( 1-31, *, */2, etc )"))
hour = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Hour'),
help_text=_("Hour when the job should run ( 0-23, *, */2, etc )"))
minute = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('Minute'),
help_text=_("Minute when the job should run ( 0-59, *, */2, etc )"))
job = models.CharField(max_length=4096, blank=True, null=True, verbose_name=_('Job'),
help_text=_("The command to execute or, if env is set, the value of "
"environment variable. Required if state=present."))
user = models.CharField(max_length=128, blank=True, null=True, verbose_name=_('User'),
help_text=_("The specific user whose crontab should be modified."))
asset = models.ForeignKey(Asset, null=True, blank=True, related_name='crontables')
@property
def describe(self):
return "http://docs.ansible.com/ansible/cron_module.html"
@classmethod
def generate_fake(cls, count=20):
from random import seed, choice
import forgery_py
seed()
for i in range(count):
cron = cls(name=forgery_py.name.full_name(),
month=str(choice(range(1,13))),
weekday=str(choice(range(0,7))),
day=str(choice(range(1,32))),
hour=str(choice(range(0,24))),
minute=str(choice(range(0,60))),
job=forgery_py.lorem_ipsum.sentence(),
user=forgery_py.name.first_name(),
)
try:
cron.save()
logger.debug('Generate fake cron: %s' % cron.name)
except Exception as e:
print('Error: %s, continue...' % e.message)
continue
\ No newline at end of file
This diff is collapsed.
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals, absolute_import
import logging
from uuid import uuid4
from assets.models import Asset
from ops.models import TaskRecord
from ops.utils.ansible_api import ADHocRunner, Config
from django.db import models
from django.utils.translation import ugettext_lazy as _
__all__ = ["Task", "SubTask"]
logger = logging.getLogger(__name__)
class Task(models.Model):
record = models.OneToOneField(TaskRecord)
name = models.CharField(max_length=128, blank=True, verbose_name=_('Name'))
is_gather_facts = models.BooleanField(default=False,verbose_name=_('Is Gather Ansible Facts'))
assets = models.ManyToManyField(Asset, related_name='tasks')
def __unicode__(self):
return "%s" % self.name
@property
def ansible_assets(self):
return []
def run(self):
conf = Config()
gather_facts = "yes" if self.is_gather_facts else "no"
play_source = {
"name": "Ansible Play",
"hosts": "default",
"gather_facts": gather_facts,
"tasks": [
dict(action=dict(module='ping')),
]
}
hoc = ADHocRunner(conf, play_source, *self.ansible_assets)
uuid = "tasker-" + uuid4().hex
ext_code, result = hoc.run("test_task", uuid)
print(ext_code)
print(result)
class SubTask(models.Model):
task = models.ForeignKey(Task, related_name='sub_tasks', verbose_name=_('Ansible Task'))
module_name = models.CharField(max_length=128, verbose_name=_('Ansible Module Name'))
module_args = models.CharField(max_length=512, blank=True, verbose_name=_("Ansible Module Args"))
register = models.CharField(max_length=128, blank=True, verbose_name=_('Ansible Task Register'))
def __unicode__(self):
return "%s %s" % (self.module_name, self.module_args)
\ No newline at end of file
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
from ansible import *
from cron import *
from sudo import *
__all__ = ["generate_fake"]
def generate_fake():
for cls in (TaskRecord, AnsiblePlay, AnsibleTask, AnsibleHostResult, CronTable,
HostAlia, UserAlia, CmdAlia, RunasAlia, Privilege, Sudo):
cls.generate_fake()
\ No newline at end of file
from .tasks import longtime_add
import time
result = longtime_add.delay(1,2)
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
time.sleep(10)
print 'Task finished? ', result.ready()
print 'Task result: ', result.result
\ No newline at end of file
from __future__ import absolute_import
import time
from celery import shared_task
from common import celery_app
@shared_task
def longtime_add(x, y):
print 'long time task begins'
# sleep 5 seconds
time.sleep(5)
print 'long time task finished'
return x + y
@celery_app.task(name='hello-world')
def hello():
print('hello world!')
from taskers import *
\ No newline at end of file
from __future__ import absolute_import, unicode_literals
from celery import shared_task
from common import celery_app
from ops.utils.ansible_api import Config, ADHocRunner
@shared_task(name="get_asset_hardware_info")
def get_asset_hardware_info(task_name, task_uuid, *assets):
conf = Config()
play_source = {
"name": "Get host hardware information",
"hosts": "default",
"gather_facts": "no",
"tasks": [
dict(action=dict(module='setup'))
]
}
hoc = ADHocRunner(conf, play_source, *assets)
ext_code, result = hoc.run(task_name, task_uuid)
return ext_code, result
@shared_task(name="asset_test_ping_check")
def asset_test_ping_check(task_name, task_uuid, *assets):
conf = Config()
play_source = {
"name": "Test host connection use ping",
"hosts": "default",
"gather_facts": "no",
"tasks": [
dict(action=dict(module='ping'))
]
}
hoc = ADHocRunner(conf, play_source, *assets)
ext_code, result = hoc.run(task_name, task_uuid)
return ext_code, result
@shared_task(name="add_user_to_assert")
def add_user_to_asset():
pass
@celery_app.task(name='hello-world')
def hello():
print('hello world!')
# ~*~ coding: utf-8 ~*~
from __future__ import unicode_literals
from ops.tasks import _celery_tasks
from ops.models import TaskRecord
from uuid import uuid1
from celery.result import AsyncResult
__all__ = ["get_result",
"start_get_hardware_info",
"start_ping_test",
"get_hardware_info",
"get_ping_test"]
def get_result(task_id):
result = AsyncResult(task_id)
if result.ready():
return {"Completed": True, "data": result.get()}
else:
return {"Completed": False, "data": None}
def __get_result_by_tasker_id(tasker_uuid, deal_method):
tasker = TaskRecord.objects.get(uuid=tasker_uuid)
total = tasker.total_hosts
total_len = len(total)
host_results = []
# 存储数据
for play in tasker.plays.all():
for t in play.tasks.all():
task = {'name': t.name, 'uuid': t.uuid, 'percentage': 0, 'completed': {'success': {}, 'failed': {}}}
completed = []
count = 0
for h in t.host_results.all():
completed.append(h.name)
count += 1
if h.is_success:
result = getattr(h, deal_method)
if result.get('msg') is None:
task['completed']['success'][h.name] = result.get('data')
else:
task['completed']['failed'][h.name] = result.get('msg')
else:
task['completed']['failed'][h.name] = h.failed_msg
# 计算进度
task['percentage'] = float(count * 100 / total_len)
task['waited'] = list(set(total) - set(completed))
host_results.append(task)
return host_results
def start_get_hardware_info(*assets):
name = "Get host hardware information"
uuid = "tasker-" + uuid1().hex
_celery_tasks.get_asset_hardware_info.delay(name, uuid, *assets)
return uuid
def __get_hardware_info(tasker_uuid):
return __get_result_by_tasker_id(tasker_uuid, 'deal_setup')
def get_hardware_info(tasker_uuid):
"""
:param assets: 资产列表
:return: 返回数据结构样列
{u'data': [{u'completed': {
u'failed': {u'192.168.232.135': u'Authentication failure.'},
u'success': {u'192.168.1.119': {u'cpu': u'GenuineIntel Intel Xeon E312xx (Sandy Bridge) 6\u6838',
u'disk': {<device_name>: <device_detail_dict>},
u'env': {<env_name>: <env_value>},
u'interface': {<interface_name>: <interface_detail_dict>},
u'mem': 3951,
u'os': u'Ubuntu 16.04(xenial)',
u'sn': u'NA'}}},
u'name': u'',
u'percentage': 100.0,
u'uuid': u'87cfedfe-ba55-44ff-bc43-e7e73b869ca1',
u'waited': []}
],
u'msg': None}
"""
try:
return {"msg": None, "data": __get_hardware_info(tasker_uuid)}
except Exception as e:
return {"msg": "query data failed!, %s" % e.message, "data": None}
def start_ping_test(*assets):
name = "Test host connection"
uuid = "tasker-" + uuid1().hex
_celery_tasks.asset_test_ping_check.delay(name, uuid, *assets)
return uuid
def __get_ping_test(tasker_uuid):
return __get_result_by_tasker_id(tasker_uuid, 'deal_ping')
def get_ping_test(tasker_uuid):
"""
:param assets: 资产列表
:return: 返回数据结构样列
{u'data': [{u'completed': {
u'failed': {u'192.168.232.135': u'Authentication failure.'},
u'success': {u'192.168.1.119': {u'success': True}}},
u'name': u'',
u'percentage': 100.0,
u'uuid': u'3e6e0d3b-bee0-4383-b19e-bec6ba55d346',
u'waited': []}
],
u'msg': None}
"""
try:
return {"msg": None, "data": __get_ping_test(tasker_uuid)}
except Exception as e:
return {"msg": "query data failed!, %s" % e.message, "data": None}
{% extends 'base.html' %}
{% load i18n %}
{% load static %}
{% load bootstrap %}
{% block custom_head_css_js %}
<link href="{% static "css/plugins/select2/select2.min.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/select2/select2.full.min.js" %}"></script>
<link href="{% static "css/plugins/datepicker/datepicker3.css" %}" rel="stylesheet">
{% endblock %}
{% block content %}
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>{% block user_template_title %}{% trans 'Create user' %}{% endblock %}</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<form method="post" class="form-horizontal" action="" enctype="multipart/form-data">
{% csrf_token %}
<h3>{% trans 'Account' %}</h3>
{% block username %} {% endblock %}
{{ form.email|bootstrap_horizontal }}
{{ form.name|bootstrap_horizontal }}
{{ form.groups|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
{% block password %} {% endblock %}
<div class="hr-line-dashed"></div>
<h3>{% trans 'Security and Role' %}</h3>
{{ form.role|bootstrap_horizontal }}
<div class="form-group {% if form.date_expired.errors %} has-error {% endif %}" id="date_5">
<label for="{{ form.date_expired.id_for_label }}" class="col-sm-2 control-label">{{ form.date_expired.label }}</label>
<div class="col-sm-9">
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="{{ form.date_expired.id_for_label }}" name="{{ form.date_expired.html_name }}" type="text" class="form-control" value="{{ form.date_expired.value|date:'Y-m-d' }}">
</div>
<span class="help-block ">{{ form.date_expired.errors }}</span>
</div>
</div>
{# {{ form.date_expired|bootstrap_horizontal }}#}
<div class="form-group">
<label for="{{ form.enable_otp.id_for_label }}" class="col-sm-2 control-label">{% trans 'Enable OTP' %}</label>
<div class="col-sm-8">
{{ form.enable_otp }}
</div>
</div>
<div class="hr-line-dashed"></div>
<h3>{% trans 'Profile' %}</h3>
{{ form.phone|bootstrap_horizontal }}
{{ form.wechat|bootstrap_horizontal }}
{{ form.comment|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">{% trans 'Reset' %}</button>
<button id="submit_button" class="btn btn-primary" type="submit">{% trans 'Submit' %}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/plugins/datapicker/bootstrap-datepicker.js' %}"></script>
<script>
$(document).ready(function () {
$('.select2').select2();
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true
});
})
</script>
{% endblock %}
{% extends 'cron/_cron.html' %}
{% load i18n %}
{% load bootstrap %}
{% block user_template_title %}{% trans "Create user" %}{% endblock %}
{% block username %}
{{ form.username|bootstrap_horizontal }}
{% endblock %}
{% block password %}
<h3>{% trans 'Password' %}</h3>
<div class="form-group">
<label class="col-sm-2 control-label">{% trans 'Password' %}</label>
<div class="col-sm-8 controls" >
{% trans 'Reset link will be generated and sent to the user. ' %}
</div>
</div>
{% endblock %}
\ No newline at end of file
This diff is collapsed.
{% extends '_base_list.html' %}
{% load i18n static %}
{% block table_search %}
{% endblock %}
{% block table_container %}
<div class="uc pull-left m-l-5 m-r-5"><a href="{% url "users:user-create" %}" class="btn btn-sm btn-primary"> {% trans "Create cron" %} </a></div>
{#<div class="uc pull-left"><a href="javascript:void(0);" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#user_import_modal"> {% trans "Import user" %} </a></div>#}
<table class="table table-striped table-bordered table-hover " id="cron_list_table">
<thead>
<tr>
<th class="text-center">
{# <div><input id="" type="checkbox" class="ipt_check_all"><label></label></div>#}
<input id="" type="checkbox" class="ipt_check_all">
</th>
<th class="text-center">{% trans 'Name' %}</th>
<th class="text-center">{% trans 'Time(minute-hour-day-month-weekday)' %}</th>
<th class="text-center">{% trans 'Job' %}</th>
<th class="text-center">{% trans 'User' %}</th>
<th class="text-center">{% trans 'Action' %}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="actions" class="hide">
<div class="input-group">
<select class="form-control m-b" style="width: auto" id="slct_bulk_update">
<option value="delete">{% trans 'Delete selected' %}</option>
<option value="update">{% trans 'Update selected' %}</option>
<option value="deactive">{% trans 'Deactive selected' %}</option>
</select>
<div class="input-group-btn pull-left" style="padding-left: 5px;">
<button id='btn_bulk_update' style="height: 32px;" class="btn btn-sm btn-primary">
{% trans 'Submit' %}
</button>
</div>
</div>
</div>
{% include "users/_user_bulk_update_modal.html" %}
{#{% include "users/_user_import_modal.html" %}#}
{% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/jquery.form.min.js' %}"></script>
<script>
$(document).ready(function(){
var options = {
ele: $('#cron_list_table'),
columnDefs: [
{targets: 1, createdCell: function (td, cellData, rowData) {
var detail_btn = '<a href="{% url "ops:page-cron-detail" pk=99991937 %}">' + cellData + '</a>';
$(td).html(detail_btn.replace('99991937', rowData.id));
}},
{targets: 2, createdCell: function (td, cellData, rowData) {
var cron_time_tmp = "{0}-{1}-{2}-{3}-{4}";
var cron_time = cron_time_tmp.format(rowData.minute, rowData.hour, rowData.day, rowData.month, rowData.weekday);
var innerHtml = '<span>' + cron_time + '</span>';
$(td).html(innerHtml.replace('99991937', rowData.id));
}},
{targets: 5, createdCell: function (td, cellData, rowData) {
var job_btn = '<a href="{% url "users:user-update" pk=99991937 %}" class="btn btn-xs btn-primary m-l-xs">{% trans "Job" %}</a>'.replace('99991937', cellData);
var update_btn = '<a href="{% url "users:user-update" pk=99991937 %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace('99991937', cellData);
var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_user_delete" data-uid="99991937">{% trans "Delete" %}</a>'.replace('99991937', cellData);
if (rowData.id === 1 || rowData.username == "admin") {
$(td).html(update_btn)
} else {
$(td).html(job_btn + update_btn + del_btn)
}
}}],
ajax_url: '{% url "api-ops:crontable-list" %}',
columns: [{data: "id"}, {data: "name" }, {data: "month" }, {data: "job" }, {data: "user" }, {data: "id" }],
op_html: $('#actions').html()
};
var table = jumpserver.initDataTable(options);
$('.buttons-pdf').click(function () {
var users = [];
var rows = table.rows('.selected').data();
$.each(rows, function (index, obj) {
users.push(obj.id)
})
});
}).on('click', '#btn_bulk_update', function(){
var action = $('#slct_bulk_update').val();
var $data_table = $('#cron_list_table').DataTable();
var id_list = [];
var plain_id_list = [];
$data_table.rows({selected: true}).every(function(){
id_list.push({id: this.data().id});
plain_id_list.push(this.data().id);
});
if (id_list === []) {
return false;
}
var the_url = "{% url 'api-users:user-list' %}";
function doDeactive() {
var body = $.each(id_list, function(index, user_object) {
user_object['is_active'] = false;
});
APIUpdateAttr({url: the_url, method: 'PATCH', body: JSON.stringify(body)});
$data_table.ajax.reload();
jumpserver.checked = false;
}
function doDelete() {
swal({
title: "{% trans 'Are you sure?' %}",
text: "{% trans 'This will delete the selected users !!!' %}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{% trans 'Confirm' %}",
closeOnConfirm: false
}, function() {
var success = function() {
var msg = "{% trans 'User Deleted.' %}";
swal("{% trans 'User Delete' %}", msg, "success");
$('#cron_list_table').DataTable().ajax.reload();
};
var fail = function() {
var msg = "{% trans 'User Deleting failed.' %}";
swal("{% trans 'User Delete' %}", msg, "error");
};
var url_delete = the_url + '?id__in=' + JSON.stringify(plain_id_list);
APIUpdateAttr({url: url_delete, method: 'DELETE', success: success, error: fail});
jumpserver.checked = false;
});
}
function doUpdate() {
$('#user_bulk_update_modal').modal('show');
}
switch(action) {
case 'deactive':
doDeactive();
break;
case 'delete':
doDelete();
break;
case 'update':
doUpdate();
break;
default:
break;
}
}).on('click', '.btn_user_delete', function(){
var $this = $(this);
function doDelete() {
var uid = $this.data('uid');
var the_url = '{% url "api-users:user-detail" pk=99991937 %}'.replace('99991937', uid);
var body = {};
var success = function() {
var msg = "{% trans 'User Deleted.' %}";
swal("{% trans 'User Delete' %}", msg, "success");
$('#cron_list_table').DataTable().ajax.reload();
};
var fail = function() {
var msg = "{% trans 'User Deleting failed.' %}";
swal("{% trans 'User Delete' %}", msg, "error");
};
APIUpdateAttr({
url: the_url,
body: JSON.stringify(body),
method: 'DELETE',
success: success,
error: fail
});
}
swal({
title: "{% trans 'Are you sure?' %}",
text: "{% trans 'This will delete the selected user.' %}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{% trans 'Confirm' %}",
closeOnConfirm: false
}, function() {
doDelete();
});
}).on('click', '#btn_user_bulk_update', function(){
var json_data = $('#fm_user_bulk_update').serializeObject();
var body = {};
body.enable_otp = (json_data.enable_otp === 'on')? true: false;
if (json_data.role != '') {
body.role = json_data.role;
}
if (json_data.groups != undefined) {
body.groups = json_data.groups;
}
if (typeof body.groups === 'string') {
body.groups = [parseInt(body.groups)]
} else if(typeof body.groups === 'array') {
new_groups = body.groups.map(Number);
body.groups = new_groups;
}
var $data_table = $('#cron_list_table').DataTable()
var post_list = [];
$data_table.rows({selected: true}).every(function(){
var content = Object.assign({id: this.data().id}, body);
post_list.push(content);
});
if (post_list === []) {
return false
}
var the_url = "{% url 'api-users:user-list' %}";
var success = function() {
var msg = "{% trans 'The selected users has been updated successfully.' %}";
swal("{% trans 'User Updated' %}", msg, "success");
$('#cron_list_table').DataTable().ajax.reload();
jumpserver.checked = false;
};
APIUpdateAttr({url: the_url, method: 'PATCH', body: JSON.stringify(post_list), success: success});
$('#user_bulk_update_modal').modal('hide');
}).on('click', '#btn_user_import', function() {
var $form = $('#fm_user_import');
$form.find('.help-block').remove();
function success (data) {
if (data.success === false) {
var $help = $form.find('.help-block');
$('<span />', {class: 'help-block text-danger'}).html(data.msg).insertAfter($('#id_excel'));
} else {
$('#user_import_modal').modal('hide');
var $data_table = $('#cron_list_table').DataTable();
toastr.success("{% trans 'Import User Success.' %}");
$data_table.ajax.reload();
}
}
$form.ajaxSubmit({success: success});
})
</script>
{% endblock %}
{% extends 'cron/_cron.html' %}
{% load i18n %}
{% block user_template_title %}{% trans "Update user" %}{% endblock %}
{% block username %}
<div class="form-group">
<label for="{{ form.username.id_for_label }}" class="col-sm-2 control-label">{% trans 'Username' %}</label>
<div class="col-sm-9 controls" >
<input id="{{ form.username.id_for_label }}" name="{{ form.username.html_name }}" type="text" value="{{ user_object.username }}" readonly class="form-control">
</div>
</div>
{% endblock %}
{% block password %}
<h3>{% trans 'Password' %}</h3>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">{% trans 'Password' %}</label>
<div class="col-sm-9 controls" >
<input id="password" name="password" type="password" class="form-control">
</div>
</div>
{% endblock %}
{% extends 'base.html' %}
{% load i18n %}
{% load static %}
{% load bootstrap %}
{% block custom_head_css_js %}
<link href="{% static "css/plugins/select2/select2.min.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/select2/select2.full.min.js" %}"></script>
<link href="{% static "css/plugins/datepicker/datepicker3.css" %}" rel="stylesheet">
{% endblock %}
{% block content %}
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>{% block user_template_title %}{% trans 'Create user' %}{% endblock %}</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<form method="post" class="form-horizontal" action="" enctype="multipart/form-data">
{% csrf_token %}
<h3>{% trans 'Account' %}</h3>
{% block username %} {% endblock %}
{{ form.email|bootstrap_horizontal }}
{{ form.name|bootstrap_horizontal }}
{{ form.groups|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
{% block password %} {% endblock %}
<div class="hr-line-dashed"></div>
<h3>{% trans 'Security and Role' %}</h3>
{{ form.role|bootstrap_horizontal }}
<div class="form-group {% if form.date_expired.errors %} has-error {% endif %}" id="date_5">
<label for="{{ form.date_expired.id_for_label }}" class="col-sm-2 control-label">{{ form.date_expired.label }}</label>
<div class="col-sm-9">
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="{{ form.date_expired.id_for_label }}" name="{{ form.date_expired.html_name }}" type="text" class="form-control" value="{{ form.date_expired.value|date:'Y-m-d' }}">
</div>
<span class="help-block ">{{ form.date_expired.errors }}</span>
</div>
</div>
{# {{ form.date_expired|bootstrap_horizontal }}#}
<div class="form-group">
<label for="{{ form.enable_otp.id_for_label }}" class="col-sm-2 control-label">{% trans 'Enable OTP' %}</label>
<div class="col-sm-8">
{{ form.enable_otp }}
</div>
</div>
<div class="hr-line-dashed"></div>
<h3>{% trans 'Profile' %}</h3>
{{ form.phone|bootstrap_horizontal }}
{{ form.wechat|bootstrap_horizontal }}
{{ form.comment|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">{% trans 'Reset' %}</button>
<button id="submit_button" class="btn btn-primary" type="submit">{% trans 'Submit' %}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/plugins/datapicker/bootstrap-datepicker.js' %}"></script>
<script>
$(document).ready(function () {
$('.select2').select2();
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true
});
})
</script>
{% endblock %}
{% extends 'sudo/_sudo.html' %}
{% load i18n %}
{% load bootstrap %}
{% block user_template_title %}{% trans "Create user" %}{% endblock %}
{% block username %}
{{ form.username|bootstrap_horizontal }}
{% endblock %}
{% block password %}
<h3>{% trans 'Password' %}</h3>
<div class="form-group">
<label class="col-sm-2 control-label">{% trans 'Password' %}</label>
<div class="col-sm-8 controls" >
{% trans 'Reset link will be generated and sent to the user. ' %}
</div>
</div>
{% endblock %}
\ No newline at end of file
This diff is collapsed.
{% extends '_base_list.html' %}
{% load i18n static %}
{% block table_search %}
{% endblock %}
{% block table_container %}
<div class="uc pull-left m-l-5 m-r-5"><a href="{% url "users:user-create" %}" class="btn btn-sm btn-primary"> {% trans "Create sudo" %} </a></div>
{#<div class="uc pull-left"><a href="javascript:void(0);" class="btn btnbtn-sm btn-primary" data-toggle="modal" data-target="#user_import_modal"> {% trans "Import user" %} </a></div>#}
<table class="table table-striped table-bordered table-hover " id="sudo_list_table">
<thead>
<tr>
<th class="text-center">
<input id="" type="checkbox" class="ipt_check_all">
</th>
<th class="text-center">{% trans 'Name' %}</th>
<th class="text-center">{% trans 'Privileges' %}</th>
<th class="text-center">{% trans 'Extra Lines' %}</th>
<th class="text-center">{% trans 'Action' %}</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="actions" class="hide">
<div class="input-group">
<select class="form-control m-b" style="width: auto" id="slct_bulk_update">
<option value="delete">{% trans 'Delete selected' %}</option>
<option value="update">{% trans 'Update selected' %}</option>
<option value="deactive">{% trans 'Deactive selected' %}</option>
</select>
<div class="input-group-btn pull-left" style="padding-left: 5px;">
<button id='btn_bulk_update' style="height: 32px;" class="btn btn-sm btn-primary">
{% trans 'Submit' %}
</button>
</div>
</div>
</div>
{#{% include "users/_user_bulk_update_modal.html" %}#}
{#{% include "users/_user_import_modal.html" %}#}
{% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/jquery.form.min.js' %}"></script>
<script>
$(document).ready(function(){
var options = {
ele: $('#sudo_list_table'),
columnDefs: [
{targets: 1, createdCell: function (td, cellData, rowData) {
var detail_btn = '<a href="{% url "ops:page-sudo-detail" pk=99991937 %}">' + cellData + '</a>';
$(td).html(detail_btn.replace('99991937', rowData.id));
}},
{targets: 4, createdCell: function (td, cellData, rowData) {
var update_btn = '<a href="{% url "users:user-update" pk=99991937 %}" class="btn btn-xs btn-info m-l-xs">{% trans "Update" %}</a>'.replace('99991937', cellData);
var preview_btn = '<a href="{% url "users:user-update" pk=99991937 %}" class="btn btn-xs btn-info m-l-xs">{% trans "Preview" %}</a>'.replace('99991937', cellData);
var job_btn = '<a href="{% url "users:user-update" pk=99991937 %}" class="btn btn-xs btn-primary m-l-xs">{% trans "Job" %}</a>'.replace('99991937', cellData);
var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_user_delete" data-uid="99991937">{% trans "Delete" %}</a>'.replace('99991937', cellData);
if (rowData.id === 1 || rowData.username == "admin") {
$(td).html(update_btn)
} else {
$(td).html(preview_btn + job_btn + update_btn + del_btn)
}
}}],
ajax_url: '{% url "api-ops:sudo-list" %}',
columns: [{data: "id"}, {data: "name" }, {data: "privilege_items" }, {data: "extra_lines" }, {data: "id" }],
op_html: $('#actions').html()
};
var table = jumpserver.initDataTable(options);
$('.buttons-pdf').click(function () {
var users = [];
var rows = table.rows('.selected').data();
$.each(rows, function (index, obj) {
users.push(obj.id)
})
});
}).on('click', '#btn_bulk_update', function(){
var action = $('#slct_bulk_update').val();
var $data_table = $('#sudo_list_table').DataTable();
var id_list = [];
var plain_id_list = [];
$data_table.rows({selected: true}).every(function(){
id_list.push({id: this.data().id});
plain_id_list.push(this.data().id);
});
if (id_list === []) {
return false;
}
var the_url = "{% url 'api-users:user-list' %}";
function doDeactive() {
var body = $.each(id_list, function(index, user_object) {
user_object['is_active'] = false;
});
APIUpdateAttr({url: the_url, method: 'PATCH', body: JSON.stringify(body)});
$data_table.ajax.reload();
jumpserver.checked = false;
}
function doDelete() {
swal({
title: "{% trans 'Are you sure?' %}",
text: "{% trans 'This will delete the selected users !!!' %}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{% trans 'Confirm' %}",
closeOnConfirm: false
}, function() {
var success = function() {
var msg = "{% trans 'User Deleted.' %}";
swal("{% trans 'User Delete' %}", msg, "success");
$('#sudo_list_table').DataTable().ajax.reload();
};
var fail = function() {
var msg = "{% trans 'User Deleting failed.' %}";
swal("{% trans 'User Delete' %}", msg, "error");
};
var url_delete = the_url + '?id__in=' + JSON.stringify(plain_id_list);
APIUpdateAttr({url: url_delete, method: 'DELETE', success: success, error: fail});
jumpserver.checked = false;
});
}
function doUpdate() {
$('#user_bulk_update_modal').modal('show');
}
switch(action) {
case 'deactive':
doDeactive();
break;
case 'delete':
doDelete();
break;
case 'update':
doUpdate();
break;
default:
break;
}
}).on('click', '.btn_user_delete', function(){
var $this = $(this);
function doDelete() {
var uid = $this.data('uid');
var the_url = '{% url "api-users:user-detail" pk=99991937 %}'.replace('99991937', uid);
var body = {};
var success = function() {
var msg = "{% trans 'User Deleted.' %}";
swal("{% trans 'User Delete' %}", msg, "success");
$('#sudo_list_table').DataTable().ajax.reload();
};
var fail = function() {
var msg = "{% trans 'User Deleting failed.' %}";
swal("{% trans 'User Delete' %}", msg, "error");
};
APIUpdateAttr({
url: the_url,
body: JSON.stringify(body),
method: 'DELETE',
success: success,
error: fail
});
}
swal({
title: "{% trans 'Are you sure?' %}",
text: "{% trans 'This will delete the selected user.' %}",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "{% trans 'Confirm' %}",
closeOnConfirm: false
}, function() {
doDelete();
});
}).on('click', '#btn_user_bulk_update', function(){
var json_data = $('#fm_user_bulk_update').serializeObject();
var body = {};
body.enable_otp = (json_data.enable_otp === 'on')? true: false;
if (json_data.role != '') {
body.role = json_data.role;
}
if (json_data.groups != undefined) {
body.groups = json_data.groups;
}
if (typeof body.groups === 'string') {
body.groups = [parseInt(body.groups)]
} else if(typeof body.groups === 'array') {
new_groups = body.groups.map(Number);
body.groups = new_groups;
}
var $data_table = $('#sudo_list_table').DataTable()
var post_list = [];
$data_table.rows({selected: true}).every(function(){
var content = Object.assign({id: this.data().id}, body);
post_list.push(content);
});
if (post_list === []) {
return false
}
var the_url = "{% url 'api-users:user-list' %}";
var success = function() {
var msg = "{% trans 'The selected users has been updated successfully.' %}";
swal("{% trans 'User Updated' %}", msg, "success");
$('#sudo_list_table').DataTable().ajax.reload();
jumpserver.checked = false;
};
APIUpdateAttr({url: the_url, method: 'PATCH', body: JSON.stringify(post_list), success: success});
$('#user_bulk_update_modal').modal('hide');
}).on('click', '#btn_user_import', function() {
var $form = $('#fm_user_import');
$form.find('.help-block').remove();
function success (data) {
if (data.success === false) {
var $help = $form.find('.help-block');
$('<span />', {class: 'help-block text-danger'}).html(data.msg).insertAfter($('#id_excel'));
} else {
$('#user_import_modal').modal('hide');
var $data_table = $('#sudo_list_table').DataTable();
toastr.success("{% trans 'Import User Success.' %}");
$data_table.ajax.reload();
}
}
$form.ajaxSubmit({success: success});
})
</script>
{% endblock %}
{% extends 'sudo/_sudo.html' %}
{% load i18n %}
{% block user_template_title %}{% trans "Update user" %}{% endblock %}
{% block username %}
<div class="form-group">
<label for="{{ form.username.id_for_label }}" class="col-sm-2 control-label">{% trans 'Username' %}</label>
<div class="col-sm-9 controls" >
<input id="{{ form.username.id_for_label }}" name="{{ form.username.html_name }}" type="text" value="{{ user_object.username }}" readonly class="form-control">
</div>
</div>
{% endblock %}
{% block password %}
<h3>{% trans 'Password' %}</h3>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">{% trans 'Password' %}</label>
<div class="col-sm-9 controls" >
<input id="password" name="password" type="password" class="form-control">
</div>
</div>
{% endblock %}
{% extends 'base.html' %}
{% load i18n %}
{% load static %}
{% load bootstrap %}
{% block custom_head_css_js %}
<link href="{% static "css/plugins/select2/select2.min.css" %}" rel="stylesheet">
<script src="{% static "js/plugins/select2/select2.full.min.js" %}"></script>
<link href="{% static "css/plugins/datepicker/datepicker3.css" %}" rel="stylesheet">
{% endblock %}
{% block content %}
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-sm-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>{% block user_template_title %}{% trans 'Create user' %}{% endblock %}</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
<a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-wrench"></i>
</a>
<a class="close-link">
<i class="fa fa-times"></i>
</a>
</div>
</div>
<div class="ibox-content">
<form method="post" class="form-horizontal" action="" enctype="multipart/form-data">
{% csrf_token %}
<h3>{% trans 'Account' %}</h3>
{% block username %} {% endblock %}
{{ form.email|bootstrap_horizontal }}
{{ form.name|bootstrap_horizontal }}
{{ form.groups|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
{% block password %} {% endblock %}
<div class="hr-line-dashed"></div>
<h3>{% trans 'Security and Role' %}</h3>
{{ form.role|bootstrap_horizontal }}
<div class="form-group {% if form.date_expired.errors %} has-error {% endif %}" id="date_5">
<label for="{{ form.date_expired.id_for_label }}" class="col-sm-2 control-label">{{ form.date_expired.label }}</label>
<div class="col-sm-9">
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="{{ form.date_expired.id_for_label }}" name="{{ form.date_expired.html_name }}" type="text" class="form-control" value="{{ form.date_expired.value|date:'Y-m-d' }}">
</div>
<span class="help-block ">{{ form.date_expired.errors }}</span>
</div>
</div>
{# {{ form.date_expired|bootstrap_horizontal }}#}
<div class="form-group">
<label for="{{ form.enable_otp.id_for_label }}" class="col-sm-2 control-label">{% trans 'Enable OTP' %}</label>
<div class="col-sm-8">
{{ form.enable_otp }}
</div>
</div>
<div class="hr-line-dashed"></div>
<h3>{% trans 'Profile' %}</h3>
{{ form.phone|bootstrap_horizontal }}
{{ form.wechat|bootstrap_horizontal }}
{{ form.comment|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-white" type="reset">{% trans 'Reset' %}</button>
<button id="submit_button" class="btn btn-primary" type="submit">{% trans 'Submit' %}</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/plugins/datapicker/bootstrap-datepicker.js' %}"></script>
<script>
$(document).ready(function () {
$('.select2').select2();
$('.input-group.date').datepicker({
format: "yyyy-mm-dd",
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true
});
})
</script>
{% endblock %}
{% extends 'sudo/_sudo.html' %}
{% load i18n %}
{% load bootstrap %}
{% block user_template_title %}{% trans "Create user" %}{% endblock %}
{% block username %}
{{ form.username|bootstrap_horizontal }}
{% endblock %}
{% block password %}
<h3>{% trans 'Password' %}</h3>
<div class="form-group">
<label class="col-sm-2 control-label">{% trans 'Password' %}</label>
<div class="col-sm-8 controls" >
{% trans 'Reset link will be generated and sent to the user. ' %}
</div>
</div>
{% endblock %}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
{% extends 'sudo/_sudo.html' %}
{% load i18n %}
{% block user_template_title %}{% trans "Update user" %}{% endblock %}
{% block username %}
<div class="form-group">
<label for="{{ form.username.id_for_label }}" class="col-sm-2 control-label">{% trans 'Username' %}</label>
<div class="col-sm-9 controls" >
<input id="{{ form.username.id_for_label }}" name="{{ form.username.html_name }}" type="text" value="{{ user_object.username }}" readonly class="form-control">
</div>
</div>
{% endblock %}
{% block password %}
<h3>{% trans 'Password' %}</h3>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">{% trans 'Password' %}</label>
<div class="col-sm-9 controls" >
<input id="password" name="password" type="password" class="form-control">
</div>
</div>
{% endblock %}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
# ~*~ coding: utf-8 ~*~
#
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment