Commit 7412bdcb authored by ibuler's avatar ibuler

[Update] 完成基本框架

parent d6ec92d8
...@@ -13,7 +13,7 @@ from django.core.cache import cache ...@@ -13,7 +13,7 @@ from django.core.cache import cache
from ..const import ASSET_ADMIN_CONN_CACHE_KEY from ..const import ASSET_ADMIN_CONN_CACHE_KEY
from .user import AdminUser, SystemUser from .user import AdminUser, SystemUser
from orgs.mixins import OrgModelMixin, OrgQuerySet, OrgManager from orgs.mixins import OrgModelMixin,OrgManager
__all__ = ['Asset'] __all__ = ['Asset']
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -37,7 +37,7 @@ def default_node(): ...@@ -37,7 +37,7 @@ def default_node():
return None return None
class AssetQuerySet(OrgQuerySet): class AssetQuerySet(models.QuerySet):
def active(self): def active(self):
return self.filter(is_active=True) return self.filter(is_active=True)
......
...@@ -120,7 +120,7 @@ class AdminUserRequiredMixin(UserPassesTestMixin): ...@@ -120,7 +120,7 @@ class AdminUserRequiredMixin(UserPassesTestMixin):
def test_func(self): def test_func(self):
if not self.request.user.is_authenticated: if not self.request.user.is_authenticated:
return False return False
elif not self.request.user.is_superuser: elif not self.request.user:
self.raise_exception = True self.raise_exception = True
return False return False
return True return True
...@@ -10,9 +10,10 @@ from django.shortcuts import redirect ...@@ -10,9 +10,10 @@ from django.shortcuts import redirect
from users.models import User from users.models import User
from assets.models import Asset from assets.models import Asset
from terminal.models import Session from terminal.models import Session
from orgs.mixins import OrgViewGenericMixin
class IndexView(LoginRequiredMixin, TemplateView): class IndexView(LoginRequiredMixin, OrgViewGenericMixin, TemplateView):
template_name = 'index.html' template_name = 'index.html'
session_week = None session_week = None
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
from .utils import get_org_from_request from .utils import get_org_from_request, set_current_org
class OrgMiddleware: class OrgMiddleware:
...@@ -11,5 +11,6 @@ class OrgMiddleware: ...@@ -11,5 +11,6 @@ class OrgMiddleware:
def __call__(self, request): def __call__(self, request):
org = get_org_from_request(request) org = get_org_from_request(request)
request.current_org = org request.current_org = org
set_current_org(org)
response = self.get_response(request) response = self.get_response(request)
return response return response
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
from django.db import models from django.db import models
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from common.utils import get_logger from common.utils import get_logger
from .utils import get_current_org, get_model_by_db_table from .utils import get_current_org, get_model_by_db_table
...@@ -8,24 +10,27 @@ from .utils import get_current_org, get_model_by_db_table ...@@ -8,24 +10,27 @@ from .utils import get_current_org, get_model_by_db_table
logger = get_logger(__file__) logger = get_logger(__file__)
class OrgQuerySet(models.QuerySet): __all__ = ['OrgManager', 'OrgViewGenericMixin', 'OrgModelMixin']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
class OrgManager(OrgQuerySet.as_manager().__class__): class OrgManager(models.Manager):
def get_queryset(self): def get_queryset(self):
current_org = get_current_org() current_org = get_current_org()
user_model = get_user_model()
kwargs = {} kwargs = {}
print("Get queryset ")
print(self.model)
print(current_org)
if not current_org: if not current_org:
kwargs['id'] = None kwargs['id'] = None
elif current_org.is_real: elif issubclass(self.model, user_model):
kwargs['orgs'] = current_org
elif current_org.is_real():
kwargs['org'] = current_org kwargs['org'] = current_org
elif current_org.is_default(): elif current_org.is_default():
kwargs['org'] = None kwargs['org'] = None
print("GET QUWRYSET ")
print(kwargs) print(kwargs)
return super().get_queryset().filter(**kwargs) return super().get_queryset().filter(**kwargs)
...@@ -55,11 +60,25 @@ class OrgModelMixin(models.Model): ...@@ -55,11 +60,25 @@ class OrgModelMixin(models.Model):
def save(self, force_insert=False, force_update=False, using=None, def save(self, force_insert=False, force_update=False, using=None,
update_fields=None): update_fields=None):
user_model = get_user_model()
current_org = get_current_org() current_org = get_current_org()
if current_org and not current_org.is_real(): if current_org and not current_org.is_real():
self.org = current_org self.org = current_org
return super().save(force_insert=force_insert, force_update=force_update, instance = super().save(
using=using, update_fields=update_fields) force_insert=force_insert, force_update=force_update,
using=using, update_fields=update_fields
)
if isinstance(instance, user_model):
instance.orgs.add(current_org)
return instance
class Meta: class Meta:
abstract = True abstract = True
class OrgViewGenericMixin:
def dispatch(self, request, *args, **kwargs):
current_org = get_current_org()
if not current_org:
return redirect('orgs:switch-a-org')
return super().dispatch(request, *args, **kwargs)
...@@ -63,7 +63,7 @@ class Organization(models.Model): ...@@ -63,7 +63,7 @@ class Organization(models.Model):
pass pass
def is_real(self): def is_real(self):
return len(str(self.id)) == 32 return len(str(self.id)) == 36
@classmethod @classmethod
def get_user_admin_orgs(cls, user): def get_user_admin_orgs(cls, user):
......
...@@ -8,6 +8,6 @@ app_name = 'orgs' ...@@ -8,6 +8,6 @@ app_name = 'orgs'
urlpatterns = [ urlpatterns = [
url(r'^(?P<pk>.*)/switch/$', views.SwitchOrgView.as_view(), name='org-switch') url(r'^(?P<pk>.*)/switch/$', views.SwitchOrgView.as_view(), name='org-switch'),
url(r'^switch-a-org/$', views.SwitchToAOrgView.as_view(), name='switch-a-org')
] ]
from django.shortcuts import redirect from django.shortcuts import redirect, reverse
from django.http import HttpResponseForbidden
from django.views.generic import DetailView from django.views.generic import DetailView, View
from .models import Organization from .models import Organization
...@@ -14,3 +15,16 @@ class SwitchOrgView(DetailView): ...@@ -14,3 +15,16 @@ class SwitchOrgView(DetailView):
self.object = Organization.get_instance(pk) self.object = Organization.get_instance(pk)
request.session['oid'] = self.object.id.__str__() request.session['oid'] = self.object.id.__str__()
return redirect('index') return redirect('index')
class SwitchToAOrgView(View):
def get(self, request, *args, **kwargs):
admin_orgs = Organization.get_user_admin_orgs(request.user)
if not admin_orgs:
return HttpResponseForbidden()
default_org = Organization.default()
if default_org in admin_orgs:
redirect_org = default_org
else:
redirect_org = admin_orgs[0]
return redirect(reverse('orgs:org-switch', kwargs={'pk': redirect_org.id}))
{% load i18n %} {% load i18n %}
{% if ADMIN_ORGS %} {% if ADMIN_ORGS and ADMIN_ORGS|length > 1 %}
<li id="org"> <li id="org">
<a class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <a class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<i class="fa fa-star" style="width: 14px"></i> <span class="nav-label">{{ CURRENT_ORG.name }}</span> <i class="fa fa-star" style="width: 14px"></i> <span class="nav-label">{{ CURRENT_ORG.name }}</span>
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
</a> </a>
<ul class="dropdown-menu"> <ul class="dropdown-menu">
{% for org in ADMIN_ORGS %} {% for org in ADMIN_ORGS %}
{% if org.is_default %} {% if org.id != CURRENT_ORG.id %}
<li><a class="org-dropdown" href="{% url 'orgs:org-switch' pk=org.id %}" data-id="{{ org.id }}">{{ org.name }}</a></li> <li><a class="org-dropdown" href="{% url 'orgs:org-switch' pk=org.id %}" data-id="{{ org.id }}">{{ org.name }}</a></li>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
...@@ -17,8 +17,8 @@ ...@@ -17,8 +17,8 @@
{% endif %} {% endif %}
<li id="index"> <li id="index">
<a href="{% url 'index' %}"> <a href="{% url 'index' %}">
<i class="fa fa-dashboard" style="width: 14px"></i> <span class="nav-label">{% trans 'Dashboard' %}</span><span <i class="fa fa-dashboard" style="width: 14px"></i> <span class="nav-label">{% trans 'Dashboard' %}</span>
class="label label-info pull-right"></span> <span class="label label-info pull-right"></span>
</a> </a>
</li> </li>
<li id="users"> <li id="users">
...@@ -97,3 +97,10 @@ ...@@ -97,3 +97,10 @@
<i class="fa fa-gears"></i> <span class="nav-label">{% trans 'Settings' %}</span><span class="label label-info pull-right"></span> <i class="fa fa-gears"></i> <span class="nav-label">{% trans 'Settings' %}</span><span class="label label-info pull-right"></span>
</a> </a>
</li> </li>
<script>
$(document).ready(function () {
var current_org = '{{ CURRENT_ORG.name }}';
console.log(current_org);
})
</script>
\ No newline at end of file
...@@ -20,6 +20,7 @@ from .permissions import IsSuperUser, IsValidUser, IsCurrentUserOrReadOnly, \ ...@@ -20,6 +20,7 @@ from .permissions import IsSuperUser, IsValidUser, IsCurrentUserOrReadOnly, \
IsSuperUserOrAppUser IsSuperUserOrAppUser
from .utils import check_user_valid, generate_token, get_login_ip, \ from .utils import check_user_valid, generate_token, get_login_ip, \
check_otp_code, set_user_login_failed_count_to_cache, is_block_login check_otp_code, set_user_login_failed_count_to_cache, is_block_login
from orgs.utils import get_current_org
from common.mixins import IDInFilterMixin from common.mixins import IDInFilterMixin
from common.utils import get_logger from common.utils import get_logger
...@@ -33,6 +34,15 @@ class UserViewSet(IDInFilterMixin, BulkModelViewSet): ...@@ -33,6 +34,15 @@ class UserViewSet(IDInFilterMixin, BulkModelViewSet):
permission_classes = (IsSuperUser,) permission_classes = (IsSuperUser,)
filter_fields = ('username', 'email', 'name', 'id') filter_fields = ('username', 'email', 'name', 'id')
def get_queryset(self):
queryset = super().get_queryset()
current_org = get_current_org()
if current_org.is_real():
queryset = queryset.filter(orgs=current_org)
elif current_org.is_default():
queryset = queryset.filter(orgs=None)
return queryset
def get_permissions(self): def get_permissions(self):
if self.action == "retrieve": if self.action == "retrieve":
self.permission_classes = (IsSuperUserOrAppUser,) self.permission_classes = (IsSuperUserOrAppUser,)
......
...@@ -6,7 +6,7 @@ from collections import OrderedDict ...@@ -6,7 +6,7 @@ from collections import OrderedDict
from django.conf import settings from django.conf import settings
from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser, UserManager
from django.core import signing from django.core import signing
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
...@@ -15,6 +15,7 @@ from django.shortcuts import reverse ...@@ -15,6 +15,7 @@ from django.shortcuts import reverse
from common.utils import get_signer, date_expired_default from common.utils import get_signer, date_expired_default
from common.models import Setting from common.models import Setting
from orgs.utils import get_current_org
__all__ = ['User'] __all__ = ['User']
...@@ -186,6 +187,18 @@ class User(AbstractUser): ...@@ -186,6 +187,18 @@ class User(AbstractUser):
else: else:
self.role = 'User' self.role = 'User'
@property
def admin_orgs(self):
from orgs.models import Organization
return Organization.get_user_admin_orgs(self)
@property
def is_org_admin(self):
if self.is_superuser or self.admin_orgs:
return True
else:
return False
@property @property
def is_app(self): def is_app(self):
return self.role == 'App' return self.role == 'App'
...@@ -207,8 +220,11 @@ class User(AbstractUser): ...@@ -207,8 +220,11 @@ class User(AbstractUser):
if self.username == 'admin': if self.username == 'admin':
self.role = 'Admin' self.role = 'Admin'
self.is_active = True self.is_active = True
instance = super().save(*args, **kwargs)
super().save(*args, **kwargs) current_org = get_current_org()
if current_org and current_org.is_real():
instance.orgs.add(current_org)
return instance
@property @property
def private_token(self): def private_token(self):
......
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