Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 🎸 修复了celery启动的问题和slug问题 #891

Merged
merged 1 commit into from
May 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions api/v1/schema/child_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from ninja import ModelSchema
from arkid.core.models import User

class ChildManagerListOut(ModelSchema):

class Config:
model = User
model_fields = ["id","username", "avatar"]
53 changes: 35 additions & 18 deletions api/v1/views/child_manager.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,47 @@
from arkid.core.api import api

from api.v1.schema.child_manager import *
from arkid.core.models import User
from arkid.core.api import api, operation
from ninja.pagination import paginate
from typing import Union, Literal, List
from arkid.core.pagenation import CustomPagination
from arkid.core.translation import gettext_default as _
from arkid.core.constants import NORMAL_USER, TENANT_ADMIN, PLATFORM_ADMIN


@api.get("/tenant/{tenant_id}/child_managers/", tags=["子管理员"],auth=None)
@api.get("/tenant/{tenant_id}/child_managers/", response=List[ChildManagerListOut], tags=["子管理员"],auth=None)
@operation(roles=[TENANT_ADMIN, PLATFORM_ADMIN])
@paginate(CustomPagination)
def get_child_managers(request, tenant_id: str):
""" 子管理员列表,TODO
"""
return []

@api.get("/tenant/{tenant_id}/child_managers/{id}/", tags=["子管理员"],auth=None)
from arkid.core.perm.permission_data import PermissionData
tenant = request.tenant
users = User.valid_objects.filter(tenant=tenant)
permissiondata = PermissionData()
child_mans = permissiondata.get_child_mans(users, tenant)
return child_mans

@api.get("/tenant/{tenant_id}/child_managers/{id}/", response=ChildManagerListOut, tags=["子管理员"],auth=None)
@operation(roles=[TENANT_ADMIN, PLATFORM_ADMIN, NORMAL_USER])
def get_child_manager(request, tenant_id: str, id: str):
""" 获取子管理员,TODO
"""
return {}

@api.post("/tenant/{tenant_id}/child_managers/", tags=["子管理员"],auth=None)
def create_child_manager(request, tenant_id: str):
""" 创建子管理员,TODO
"""
return {}

@api.put("/tenant/{tenant_id}/child_managers/{id}/", tags=["子管理员"],auth=None)
def update_child_manager(request, tenant_id: str, id: str):
""" 编辑子管理员,TODO
"""
return {}
tenant = request.tenant
user = User.valid_objects.filter(tenant=tenant, id=id).first()
return user

# @api.post("/tenant/{tenant_id}/child_managers/", tags=["子管理员"],auth=None)
# def create_child_manager(request, tenant_id: str):
# """ 创建子管理员,TODO
# """
# return {}

# @api.put("/tenant/{tenant_id}/child_managers/{id}/", tags=["子管理员"],auth=None)
# def update_child_manager(request, tenant_id: str, id: str):
# """ 编辑子管理员,TODO
# """
# return {}

@api.delete("/tenant/{tenant_id}/child_managers/{id}/", tags=["子管理员"],auth=None)
def delete_child_manager(request, tenant_id: str, id: str):
Expand Down
12 changes: 11 additions & 1 deletion api/v1/views/permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,16 @@ def get_permission_str(request, tenant_id: str, app_id: str = None):
return permissiondata.get_permission_str(user, tenant_id, app_id)


@api.get("/app/permission_result", tags=['权限'], response=PermissionStrSchemaOut, auth=None)
def get_arkstore_permission_str(request):
'''
获取应用权限字符串
'''
from arkid.core.perm.permission_data import PermissionData
permissiondata = PermissionData()
return permissiondata.id_token_to_permission_str(request)


@api.get("/tenant/{tenant_id}/permission/{permission_id}/user/{user_id}/add_permission", tags=['权限'], auth=None)
@operation(roles=[TENANT_ADMIN, PLATFORM_ADMIN])
def user_add_permission(request, tenant_id: str, permission_id: str, user_id: str):
Expand Down Expand Up @@ -206,4 +216,4 @@ def permission_set_close(request, tenant_id: str, permission_id: str):
permission.save()
return {'error': ErrorCode.OK.value}
else:
return {'error': ErrorCode.PERMISSION_EXISTS_ERROR.value}
return {'error': ErrorCode.PERMISSION_EXISTS_ERROR.value}
2 changes: 1 addition & 1 deletion arkid/core/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def ready(self):
try:
from arkid.core.models import Tenant, User
tenant, _ = Tenant.objects.get_or_create(
# slug='',
slug='',
name="platform tenant",
)
user, _ = User.objects.get_or_create(
Expand Down
18 changes: 18 additions & 0 deletions arkid/core/migrations/0007_alter_tenant_slug.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.2.13 on 2022-05-31 10:36

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0006_merge_20220526_1647'),
]

operations = [
migrations.AlterField(
model_name='tenant',
name='slug',
field=models.SlugField(default='', unique=True, verbose_name='slug'),
),
]
4 changes: 2 additions & 2 deletions arkid/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class Meta(object):
verbose_name_plural = _("tenant", "租户")

name = models.CharField(verbose_name=_('name', '名字'), max_length=128)
slug = models.SlugField(verbose_name=_('slug', '短链接标识'), blank=True, null=True, default='' ,unique=True)
slug = models.SlugField(verbose_name=_('slug', '短链接标识'), default='', unique=True)
icon = models.URLField(verbose_name=_('icon', '图标'), blank=True, null=True)

token_duration_minutes = models.IntegerField(
Expand Down Expand Up @@ -63,7 +63,7 @@ def is_platform_tenant(self):
'''
是否是平台租户
'''
tenant = Tenant.valid_objects.order_by('id').first()
tenant = Tenant.valid_objects.order_by('created').first()
if tenant.id == self.id:
return True
else:
Expand Down
132 changes: 130 additions & 2 deletions arkid/core/perm/permission_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import collections
import requests
import uuid
import jwt
import re
from oauth2_provider.models import Application

Expand Down Expand Up @@ -70,6 +71,7 @@ def get_platfrom_tenant(self):
获取平台租户
'''
tenant, _ = Tenant.objects.get_or_create(
slug='',
name="platform tenant",
)
return tenant
Expand Down Expand Up @@ -109,7 +111,7 @@ def add_system_permission_to_user(self, tenant_id, user_id, permission_id):
tenant = Tenant.valid_objects.filter(id=tenant_id).first()
user = User.valid_objects.filter(id=user_id).first()
permission = SystemPermission.valid_objects.filter(id=permission_id).first()
if tenant and user:
if tenant:
self.update_arkid_single_user_permission(tenant, user, permission, 1)
else:
print('不存在租户或者用户无法更新')
Expand Down Expand Up @@ -1168,6 +1170,41 @@ def check_app_entry_permission(self, request, type, kwargs):

return True

def id_token_reverse(self, id_token):
'''
id token转换
'''
try:
payload = jwt.decode(id_token, options={"verify_signature": False})
return payload
except Exception:
raise Exception("unable to parse id_token")

def id_token_to_permission_str(self, request):
id_token = request.META.get('HTTP_ID_TOKEN', '')
payload = self.id_token_reverse(id_token)
client_id = payload.get('aud', None)
user_id = payload.get('sub_id', '')
tenant_id = payload.get('tenant_id', '')

apps = App.valid_objects.filter(
type__in=['OIDC-Platform'],
tenant_id=tenant_id,
)
app_temp = None
for app in apps:
data = app.config.config
app_client_id = data.get('client_id', '')
if app_client_id == client_id:
app_temp = app
break
user = User.valid_objects.filter(id=user_id).first()
if user and app_temp and tenant_id:
self.get_permission_str(user, tenant_id, app_temp.id)
else:
print('不存在用户或者应用或者租户')
return {'result': ''}

def permission_check_by_sortid(self, permission, user, app, tenant_id):
'''
根据权限检查用户身份
Expand Down Expand Up @@ -1220,4 +1257,95 @@ def get_open_appids(self):
app_id = permission.app_id
if app_id not in app_ids:
app_ids.append(app_id)
return app_ids
return app_ids

def get_default_system_permission(self):
'''
获取默认的系统权限
'''
systempermission = SystemPermission.valid_objects.filter(
name='normal-user',
category='group',
).first()
if systempermission:
describe = systempermission.describe
sort_ids = describe.get('sort_ids', [])
return sort_ids
else:
return []

def get_user_system_permission_arr(self, auth_users, tenant):
'''
获取用户的系统权限
'''
# 取得当前用户权限数据
userpermissionresults = UserPermissionResult.valid_objects.filter(
user__in=auth_users,
tenant=tenant,
app=None,
)
compress = Compress()
list_user = []
for userpermissionresult in userpermissionresults:
temp_user = userpermissionresult.user
if userpermissionresult:
permission_result = compress.decrypt(userpermissionresult.result)
permission_result_arr = list(permission_result)
temp_user.arr = permission_result_arr
else:
temp_user.arr = []
list_user.append(temp_user)
return list_user

def get_child_mans(self, auth_users, tenant):
'''
获取子管理员
'''
sort_ids = self.get_default_system_permission()
list_user = self.get_user_system_permission_arr(auth_users, tenant)
exclude_id = []
for item_user in list_user:
user_arr = item_user.arr
for index, user_arr_item in enumerate(user_arr):
if index not in sort_ids and user_arr_item == 1:
exclude_id.append(item_user.id)
break
auth_users = auth_users.exclude(id__in=exclude_id)
# 区分出那些人是管理员
systempermission = SystemPermission.valid_objects.filter(tenant=tenant, code=tenant.admin_perm_code, is_system=True).first()
# 管理权限在arkidpermission表里
system_userpermissionresults = UserPermissionResult.valid_objects.filter(
user__in=auth_users,
tenant=tenant,
app=None,
)
system_userpermissionresults_dict = {}
for system_userpermissionresult in system_userpermissionresults:
system_userpermissionresults_dict[system_userpermissionresult.user.id.hex] = system_userpermissionresult
ids = []
compress = Compress()
for auth_user in auth_users:
# 权限鉴定
if auth_user.is_superuser:
auth_user.is_tenant_admin = True
else:
if auth_user.id.hex in system_userpermissionresults_dict:
system_userpermissionresults_obj = system_userpermissionresults_dict.get(auth_user.id.hex)
auth_user_permission_result = compress.decrypt(system_userpermissionresults_obj.result)

auth_user_permission_result_arr = list(auth_user_permission_result)
check_result = int(auth_user_permission_result_arr[systempermission.sort_id])

if check_result == 1:
auth_user.is_tenant_admin = True
else:
ids.append(auth_user.id)
auth_user.is_tenant_admin = False
else:
ids.append(auth_user.id)
auth_user.is_tenant_admin = False

if ids:
return User.valid_objects.filter(id__in=ids)
else:
return []
29 changes: 14 additions & 15 deletions arkid/core/tasks/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import os

from celery import Celery
from celery import Celery, bootsteps
from click import Option

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'arkid.settings')
Expand All @@ -15,22 +16,20 @@
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
app.user_options['worker'].add(Option(('--is-init-permission',), is_flag=False, help='init permission option.'))

class MyBootstep(bootsteps.Step):

from arkid.core.tasks import tasks
def __init__(self, parent, is_init_permission=False, **options):
super().__init__(parent, **options)
if is_init_permission:
from arkid.core.tasks.tasks import update_system_permission
update_system_permission.delay()

app.steps['worker'].add(MyBootstep)

# class ReadyCelery(object):
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

# def __init__(self):
# print('你被执行了')
# from arkid.core.models import Tenant
# from arkid.core.event import Event, dispatch_event, APP_START
# tenant, _ = Tenant.objects.get_or_create(
# slug='',
# name="platform tenant",
# )
# dispatch_event(Event(tag=APP_START, tenant=tenant))

# ReadyCelery()
from arkid.core.tasks import tasks
20 changes: 10 additions & 10 deletions arkid/core/tasks/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,16 +285,16 @@ def check_extensions_expired(self, *args, **kwargs):
pass


class ReadyCelery(object):
# class ReadyCelery(object):

def __init__(self, *args, **kwargs):
pass
# def __init__(self, *args, **kwargs):
# pass

@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(ReadyCelery, "_instance"):
ReadyCelery._instance = ReadyCelery(*args, **kwargs)
update_system_permission.delay()
return ReadyCelery._instance
# @classmethod
# def instance(cls, *args, **kwargs):
# if not hasattr(ReadyCelery, "_instance"):
# ReadyCelery._instance = ReadyCelery(*args, **kwargs)
# update_system_permission.delay()
# return ReadyCelery._instance

ReadyCelery.instance()
# ReadyCelery.instance()
2 changes: 1 addition & 1 deletion extension_root/com_longgui_oauth2_server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import uuid

package='com.longgui.auth.oauth2_server'
package='com.longgui.auth.oauth2server'

OIDCConfigSchema = create_extension_schema('OIDCConfigSchema',package, base_schema=OIDCConfigSchema)
Oauth2ConfigSchema = create_extension_schema('Oauth2ConfigSchema',package, base_schema=Oauth2ConfigSchema)
Expand Down