Commit 1d5faa31 authored by ibuler's avatar ibuler

Delete Model: Role

parent b97b3496
This source diff could not be displayed because it is too large. You can view the blob instead.
[{"model": "users.role", "pk": 1, "fields": {"name": "Administrator", "date_added": "2016-08-20T17:03:42.631Z", "created_by": "System", "comment": "\u7ba1\u7406\u5458", "permissions": [16, 17, 18, 19, 20, 21, 10, 11, 12, 13, 14, 15, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 1, 2, 3, 4, 5, 6, 7, 8, 9]}}, {"model": "users.role", "pk": 2, "fields": {"name": "User", "date_added": "2016-08-20T17:03:42.671Z", "created_by": "System", "comment": "\u7528\u6237", "permissions": []}}, {"model": "users.role", "pk": 3, "fields": {"name": "Auditor", "date_added": "2016-08-20T17:03:42.683Z", "created_by": "System", "comment": "\u5ba1\u8ba1\u5458", "permissions": []}}, {"model": "users.usergroup", "pk": 1, "fields": {"name": "ALL", "comment": "Default usergroup for all user", "date_added": "2016-08-20T17:03:42.693Z", "created_by": "System"}}, {"model": "users.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$30000$xZUhPadgI8rs$n2rm5futcOv7Ww4b4BflN8K90Vk3u7ozfnOS7GQq0ns=", "last_login": null, "is_superuser": false, "first_name": "", "last_name": "", "is_staff": false, "is_active": true, "date_joined": "2016-08-20T17:03:42.752Z", "username": "admin", "name": "Administrator", "email": "admin@jumpserver.org", "avatar": "", "wechat": "", "phone": "", "enable_otp": false, "secret_key_otp": "", "role": 1, "private_key": "", "public_key": "", "comment": "Administrator is the super user of system", "date_expired": "2086-08-03T17:03:42.753Z", "created_by": "System", "user_permissions": [], "groups": [1]}}]
\ No newline at end of file
[{"model": "users.role", "pk": 1, "fields": {"name": "Administrator", "date_added": "2016-08-20T17:03:42.631Z", "created_by": "System", "comment": "\u7ba1\u7406\u5458", "permissions": [16, 17, 18, 19, 20, 21, 10, 11, 12, 13, 14, 15, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 1, 2, 3, 4, 5, 6, 7, 8, 9]}}, {"model": "users.role", "pk": 2, "fields": {"name": "User", "date_added": "2016-08-20T17:03:42.671Z", "created_by": "System", "comment": "\u7528\u6237", "permissions": []}}, {"model": "users.role", "pk": 3, "fields": {"name": "Auditor", "date_added": "2016-08-20T17:03:42.683Z", "created_by": "System", "comment": "\u5ba1\u8ba1\u5458", "permissions": []}}, {"model": "users.usergroup", "pk": 1, "fields": {"name": "ALL", "comment": "Default usergroup for all user", "date_added": "2016-08-20T17:03:42.693Z", "created_by": "System"}}, {"model": "users.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$30000$xZUhPadgI8rs$n2rm5futcOv7Ww4b4BflN8K90Vk3u7ozfnOS7GQq0ns=", "last_login": null, "is_superuser": false, "first_name": "", "last_name": "", "is_staff": false, "is_active": true, "date_joined": "2016-08-20T17:03:42.752Z", "username": "admin", "name": "Administrator", "email": "admin@jumpserver.org", "avatar": "", "wechat": "", "phone": "", "enable_otp": false, "secret_key_otp": "", "role": 1, "private_key": "", "public_key": "", "comment": "Administrator is the super user of system", "date_expired": "2086-08-03T17:03:42.753Z", "created_by": "System", "user_permissions": [], "groups": [1]}}][{"model": "users.usergroup", "pk": 1, "fields": {"name": "Default", "comment": "Default user group for all user", "date_added": "2016-08-24T08:24:34.436Z", "created_by": "System"}}, {"model": "users.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$30000$MC3vobX7pa0C$l9qIj4UwHqODnj1hMvVy9DjLxbBumZaioQWIFrWQR7c=", "last_login": null, "first_name": "", "last_name": "", "is_active": true, "date_joined": "2016-08-24T08:24:34.438Z", "username": "admin", "name": "Administrator", "email": "admin@jumpserver.org", "role": "Admin", "avatar": "", "wechat": "", "phone": "", "enable_otp": false, "secret_key_otp": "", "private_key": "", "public_key": "", "comment": "Administrator is the super user of system", "date_expired": "2086-08-07T08:24:34.438Z", "created_by": "System", "user_permissions": [], "groups": [1]}}]
\ No newline at end of file
[{"model": "users.usergroup", "pk": 1, "fields": {"name": "Default", "comment": "Default user group for all user", "date_added": "2016-08-24T08:24:34.436Z", "created_by": "System"}}, {"model": "users.user", "pk": 1, "fields": {"password": "pbkdf2_sha256$30000$MC3vobX7pa0C$l9qIj4UwHqODnj1hMvVy9DjLxbBumZaioQWIFrWQR7c=", "last_login": null, "first_name": "", "last_name": "", "is_active": true, "date_joined": "2016-08-24T08:24:34.438Z", "username": "admin", "name": "Administrator", "email": "admin@jumpserver.org", "role": "Admin", "avatar": "", "wechat": "", "phone": "", "enable_otp": false, "secret_key_otp": "", "private_key": "", "public_key": "", "comment": "Administrator is the super user of system", "date_expired": "2086-08-07T08:24:34.438Z", "created_by": "System", "user_permissions": [], "groups": [1]}}]
\ No newline at end of file
This diff is collapsed.
......@@ -31,7 +31,7 @@ urlpatterns = [
url(r'^users/', include('users.urls')),
url(r'^assets/', include('assets.urls')),
url(r'^terminal/', include('webterminal.urls')),
url(r'^api/(?P<version>.*)/(?P<module>.*)/(?P<api>.*)', view),
# url(r'^api/(?P<version>.*)/(?P<module>.*)/(?P<api>.*)', view),
# url(r'^admin/', admin.site.urls),
]
......
......@@ -2,7 +2,7 @@
{% if is_paginated %}
<div class="col-sm-4">
<div class="dataTables_info text-center" id="editable_info" role="status" aria-live="polite">
Showing {{ page_obj.start_index }} to {{ page_obj.end_index }} of {{ paginator.count }} entries
{{ page_obj.start_index }} - {{ page_obj.end_index }} of {{ paginator.count }}
</div>
</div>
<div class="col-sm-4">
......
# ~*~ coding: utf-8 ~*~
#
from rest_framework import viewsets
from rest_framework import generics
from rest_framework import mixins
from .serializers import UserSerializer
from .models import User, UserGroup, Role
from .models import User, UserGroup
class UserViewSet(viewsets.ModelViewSet):
class UserListApi(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetailApi(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
......@@ -3,8 +3,10 @@
from django.conf.urls import url, include
from .api import UserViewSet
from .api import UserListApi, UserDetailApi
urlpatterns = [
url(r'^v1/users/$', UserListApi.as_view()),
url(r'^v1/users/(?P<pk>[0-9]+)/$', UserDetailApi.as_view()),
]
......@@ -17,7 +17,6 @@ class UserAddForm(ModelForm):
help_texts = {
'username': '* required',
'email': '* required',
'groups': '* required'
}
widgets = {
......
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-20 16:21
# Generated by Django 1.10 on 2016-08-24 08:23
from __future__ import unicode_literals
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import users.models
......@@ -24,15 +23,14 @@ class Migration(migrations.Migration):
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('username', models.CharField(max_length=20, unique=True, verbose_name='\u7528\u6237\u540d')),
('name', models.CharField(help_text='* required', max_length=20, verbose_name='\u59d3\u540d')),
('email', models.EmailField(help_text='* required', max_length=30, unique=True, verbose_name='\u90ae\u4ef6')),
('name', models.CharField(blank=True, max_length=20, verbose_name='\u59d3\u540d')),
('email', models.EmailField(max_length=30, unique=True, verbose_name='\u90ae\u4ef6')),
('role', models.CharField(choices=[('Admin', '\u7ba1\u7406\u5458'), ('User', '\u7528\u6237')], default='User', max_length=10, verbose_name='\u89d2\u8272')),
('avatar', models.ImageField(upload_to='avatar', verbose_name='\u5934\u50cf')),
('wechat', models.CharField(blank=True, max_length=30, verbose_name='\u5fae\u4fe1')),
('phone', models.CharField(blank=True, max_length=20, verbose_name='\u624b\u673a\u53f7')),
......@@ -51,18 +49,6 @@ class Migration(migrations.Migration):
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Role',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=80, unique=True, verbose_name='name')),
('comment', models.CharField(blank=True, max_length=80)),
('permissions', models.ManyToManyField(blank=True, to='auth.Permission', verbose_name='permissions')),
],
options={
'db_table': 'role',
},
),
migrations.CreateModel(
name='UserGroup',
fields=[
......@@ -79,12 +65,7 @@ class Migration(migrations.Migration):
migrations.AddField(
model_name='user',
name='groups',
field=models.ManyToManyField(help_text='* required', to='users.UserGroup', verbose_name='\u7528\u6237\u7ec4'),
),
migrations.AddField(
model_name='user',
name='role',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='users.Role', verbose_name='\u89d2\u8272'),
field=models.ManyToManyField(to='users.UserGroup', verbose_name='\u7528\u6237\u7ec4'),
),
migrations.AddField(
model_name='user',
......
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-20 16:51
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='role',
name='created_by',
field=models.CharField(default='System', max_length=100),
preserve_default=False,
),
migrations.AddField(
model_name='role',
name='date_added',
field=models.DateTimeField(auto_now_add=True, default=django.utils.timezone.now),
preserve_default=False,
),
]
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-22 05:16
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20160821_0051'),
]
operations = [
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(max_length=30, unique=True, verbose_name='\u90ae\u4ef6'),
),
migrations.AlterField(
model_name='user',
name='groups',
field=models.ManyToManyField(to='users.UserGroup', verbose_name='\u7528\u6237\u7ec4'),
),
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(max_length=20, verbose_name='\u59d3\u540d'),
),
]
......@@ -10,43 +10,43 @@ from django.contrib.auth.models import AbstractUser, Permission
from django.db import OperationalError
class Role(models.Model):
name = models.CharField('name', max_length=80, unique=True)
permissions = models.ManyToManyField(
Permission,
verbose_name='permissions',
blank=True,
)
date_added = models.DateTimeField(auto_now_add=True)
created_by = models.CharField(max_length=100)
comment = models.CharField(max_length=80, blank=True)
def __unicode__(self):
return self.name
def delete(self, using=None, keep_parents=False):
if self.user_set.all().count() > 0:
raise OperationalError('Role %s has some member, should not be delete.' % self.name)
else:
return super(Role, self).delete(using=using, keep_parents=keep_parents)
class Meta:
db_table = 'role'
@classmethod
def initial(cls):
roles = {
'Administrator': {'permissions': Permission.objects.all(), 'comment': '管理员'},
'User': {'permissions': [], 'comment': '用户'},
'Auditor': {'permissions': Permission.objects.filter(content_type__app_label='audits'),
'comment': '审计员'},
}
for role_name, props in roles.items():
if not cls.objects.filter(name=role_name):
role = cls.objects.create(name=role_name, comment=props.get('comment', ''), created_by='System')
if props.get('permissions'):
role.permissions = props.get('permissions')
# class Role(models.Model):
# name = models.CharField('name', max_length=80, unique=True)
# permissions = models.ManyToManyField(
# Permission,
# verbose_name='permissions',
# blank=True,
# )
# date_added = models.DateTimeField(auto_now_add=True)
# created_by = models.CharField(max_length=100)
# comment = models.CharField(max_length=80, blank=True)
#
# def __unicode__(self):
# return self.name
#
# def delete(self, using=None, keep_parents=False):
# if self.user_set.all().count() > 0:
# raise OperationalError('Role %s has some member, should not be delete.' % self.name)
# else:
# return super(Role, self).delete(using=using, keep_parents=keep_parents)
#
# class Meta:
# db_table = 'role'
#
# @classmethod
# def initial(cls):
# roles = {
# 'Administrator': {'permissions': Permission.objects.all(), 'comment': '管理员'},
# 'User': {'permissions': [], 'comment': '用户'},
# 'Auditor': {'permissions': Permission.objects.filter(content_type__app_label='audits'),
# 'comment': '审计员'},
# }
# for role_name, props in roles.items():
# if not cls.objects.filter(name=role_name):
# role = cls.objects.create(name=role_name, comment=props.get('comment', ''), created_by='System')
# if props.get('permissions'):
# role.permissions = props.get('permissions')
class UserGroup(models.Model):
......@@ -91,20 +91,25 @@ def date_expired_default():
class User(AbstractUser):
ROLE_CHOICES = (
('Admin', '管理员'),
('User', '用户'),
)
username = models.CharField(max_length=20, unique=True, verbose_name='用户名')
name = models.CharField(max_length=20, blank=True, verbose_name='姓名')
email = models.EmailField(max_length=30, unique=True, verbose_name='邮件')
groups = models.ManyToManyField(UserGroup, verbose_name='用户组')
groups = models.ManyToManyField(UserGroup, blank=True, verbose_name='用户组')
role = models.CharField(choices=ROLE_CHOICES, default='User', max_length=10, blank=True, verbose_name='角色')
avatar = models.ImageField(upload_to="avatar", verbose_name='头像')
wechat = models.CharField(max_length=30, blank=True, verbose_name='微信')
phone = models.CharField(max_length=20, blank=True, verbose_name='手机号')
enable_otp = models.BooleanField(default=False, verbose_name='启用二次验证')
secret_key_otp = models.CharField(max_length=16, blank=True)
role = models.ForeignKey(Role, on_delete=models.SET('None'), verbose_name='角色')
private_key = models.CharField(max_length=5000, blank=True, verbose_name='ssh私钥') # ssh key max length 4096 bit
public_key = models.CharField(max_length=1000, blank=True, verbose_name='公钥')
comment = models.TextField(max_length=200, blank=True, verbose_name='描述')
date_expired = models.DateTimeField(default=date_expired_default, verbose_name='有效期')
date_expired = models.DateTimeField(default=date_expired_default, blank=True, null=True, verbose_name='有效期')
created_by = models.CharField(max_length=30, default='')
@property
......@@ -120,16 +125,43 @@ class User(AbstractUser):
def password_raw(self, raw_password):
self.set_password(raw_password)
@property
def is_expired(self):
if self.date_expired > timezone.now():
return False
else:
return True
@property
def is_superuser(self):
if self.role == 'Admin':
return True
else:
return False
@is_superuser.setter
def is_superuser(self, value):
if value is True:
self.role = 'Admin'
else:
self.role = 'User'
@property
def is_staff(self):
if self.is_authenticated and self.is_active and not self.is_expired:
return True
else:
return False
@is_staff.setter
def is_staff(self, value):
pass
def save(self, *args, **kwargs):
# If user not set name, it's default equal username
if not self.name:
self.name = self.username
super(User, self).save(*args, **kwargs)
# Set user default group 'All'
# Todo: It's have bug
......@@ -148,7 +180,7 @@ class User(AbstractUser):
email='admin@jumpserver.org',
name='Administrator',
password_raw='admin',
role=Role.objects.get(name='Administrator'),
role='Admin',
comment='Administrator is the super user of system',
created_by='System')
user.save()
......@@ -166,11 +198,11 @@ class User(AbstractUser):
email=forgery_py.internet.email_address(),
name=forgery_py.name.full_name(),
password=make_password(forgery_py.lorem_ipsum.word()),
role=choice(Role.objects.all()),
role=choice(dict(User.ROLE_CHOICES).keys()),
wechat=forgery_py.internet.user_name(True),
comment=forgery_py.lorem_ipsum.sentence(),
created_by=choice(cls.objects.all()).username,
)
)
try:
user.save()
except IntegrityError:
......@@ -181,12 +213,12 @@ class User(AbstractUser):
def init_all_models():
for model in (Role, UserGroup, User):
for model in (UserGroup, User):
if hasattr(model, 'initial'):
model.initial()
def generate_fake():
for model in (Role, UserGroup, User):
for model in (UserGroup, User):
if hasattr(model, 'generate_fake'):
model.generate_fake()
......@@ -3,13 +3,16 @@
from rest_framework import serializers
from .models import Role, User, UserGroup
from .models import User, UserGroup
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
exclude = ['first_name', 'last_name', 'is_staff']
exclude = [
'password', 'first_name', 'last_name', 'is_staff', 'secret_key_otp',
'private_key', 'public_key',
]
class UserGroupSerializer(serializers.ModelSerializer):
......@@ -18,7 +21,3 @@ class UserGroupSerializer(serializers.ModelSerializer):
fields = '__all__'
class RoleSerializer(serializers.ModelSerializer):
class Meta:
model = Role
fields = '__all__'
......@@ -31,8 +31,8 @@
{% csrf_token %}
<h3>账户</h3>
{% block username %} {% endblock %}
{{ form.name|bootstrap_horizontal }}
{{ form.email|bootstrap_horizontal }}
{{ form.name|bootstrap_horizontal }}
{{ form.groups|bootstrap_horizontal }}
<div class="hr-line-dashed"></div>
......
......@@ -92,7 +92,7 @@
{% endif %}
<tr>
<td>角色:</td>
<td><b>{{ user.role.name }}</b></td>
<td><b>{{ user.get_role_display }}</b></td>
</tr>
<tr>
<td>有效期:</td>
......
......@@ -30,7 +30,7 @@
</a>
</td>
<td class="text-center">{{ user.username }}</td>
<td class="text-center">{{ user.role.name }}</td>
<td class="text-center">{{ user.get_role_display }}</td>
<td class="text-center" title="{% for user_group in user.group.all %} {{ user_group.name }} {% endfor %}"> {{ user.groups.all|join_queryset_attr:"name" }} </td>
<th class="text-center">{{ user.name }}</th>
<td class="text-center">
......
......@@ -4,7 +4,7 @@
from random import choice
import forgery_py
from users.models import User, UserGroup, Role, init_all_models
from users.models import User, UserGroup, init_all_models
def gen_username():
......@@ -20,5 +20,5 @@ def gen_name():
def get_role():
role = choice(Role.objects.all())
role = choice(dict(User.ROLE_CHOICES).keys())
return role
\ No newline at end of file
......@@ -3,9 +3,9 @@
from django.utils import timezone
from django.shortcuts import reverse
from django.test import TestCase, Client, TransactionTestCase
from django.test import TestCase, TransactionTestCase
from django.db import IntegrityError
from users.models import User, UserGroup, Role, init_all_models
from users.models import User, UserGroup, init_all_models
from django.contrib.auth.models import Permission
from .base import gen_name, gen_username, gen_email, get_role
......@@ -22,8 +22,6 @@ class UserModelTest(TransactionTestCase):
def test_initial(self):
self.assertEqual(User.objects.all().count(), 2)
self.assertEqual(Role.objects.all().count(), 3)
self.assertEqual(UserGroup.objects.all().count(), 1)
@property
def role(self):
......@@ -32,7 +30,7 @@ class UserModelTest(TransactionTestCase):
# 创建一个姓名一致的用户, 应该创建成功
def test_user_name_duplicate(self):
user1 = User(name='test', username=gen_username(), password_raw=gen_username(),
email=gen_email(), role=self.role)
email=gen_email())
try:
user1.save()
user1.delete()
......@@ -59,7 +57,7 @@ class UserModelTest(TransactionTestCase):
user = User(name=gen_name(), username=gen_username(),
email=gen_email(), role=self.role, date_expired=date)
self.assertTrue(user.is_expired())
self.assertTrue(user.is_expired)
# 测试用户默认会输入All用户组
def test_user_with_default_group(self):
......@@ -80,26 +78,6 @@ class UserModelTest(TransactionTestCase):
def tearDown(self):
User.objects.all().delete()
UserGroup.objects.all().delete()
Role.objects.all().delete()
class RoleModelTestCase(TransactionTestCase):
def setUp(self):
Role.objects.all().delete()
Role.initial()
def test_role_initial(self):
self.assertEqual(Role.objects.all().count(), 3)
def test_create_new_role(self):
role = Role(name=gen_name(), comment=gen_name()*3)
role.save()
role.permissions = Permission.objects.all()
role.save()
self.assertEqual(Role.objects.count(), 4)
role = Role.objects.last()
self.assertEqual(role.permissions.all().count(), Permission.objects.all().count())
class UserGroupModelTestCase(TransactionTestCase):
......
......@@ -2,7 +2,7 @@
# -*- coding: utf-8 -*-
#
from users.models import User, UserGroup, Role, init_all_models
from users.models import User, UserGroup, init_all_models
from django.shortcuts import reverse
from django.test import TestCase, Client, TransactionTestCase
......@@ -45,7 +45,7 @@ class UserAddTests(TestCase):
'name': gen_name(),
'email': gen_email(),
'groups': [UserGroup.objects.first().id, ],
'role': get_role().id,
'role': get_role(),
'date_expired': '2086-08-06 19:12:22',
}
......
......@@ -11,7 +11,7 @@ from django.views.generic.detail import DetailView
from django.contrib.messages.views import SuccessMessageMixin
from django.conf import settings
from .models import User, UserGroup, Role
from .models import User, UserGroup
from .forms import UserAddForm, UserUpdateForm, UserGroupForm
......@@ -53,9 +53,10 @@ class UserAddView(SuccessMessageMixin, CreateView):
return context
def form_valid(self, form):
user = form.save()
user.created_by = self.request.user.username or 'Admin'
user = form.save(commit=False)
user.created_by = self.request.user.username or 'System'
user.save()
form.save_m2m()
return super(UserAddView, self).form_valid(form)
def get_success_message(self, cleaned_data):
......
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