Skip to content

Commit

Permalink
feat(login): add current user api,return login data when 401 (#1168)
Browse files Browse the repository at this point in the history
  • Loading branch information
nannan00 authored Aug 17, 2023
1 parent df94a53 commit 68f6f92
Show file tree
Hide file tree
Showing 11 changed files with 104 additions and 9 deletions.
15 changes: 15 additions & 0 deletions src/bk-user/bkuser/apis/web/basic/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from rest_framework import serializers


class CurrentUserRetrieveOutputSLZ(serializers.Serializer):
username = serializers.CharField(help_text="用户名")
17 changes: 17 additions & 0 deletions src/bk-user/bkuser/apis/web/basic/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from django.urls import path

from . import views

urlpatterns = [
path("current-user/", views.CurrentUserRetrieveApi.as_view(), name="basic.current_user.retrieve"),
]
31 changes: 31 additions & 0 deletions src/bk-user/bkuser/apis/web/basic/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-用户管理(Bk-User) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from drf_yasg.utils import swagger_auto_schema
from rest_framework import generics, status
from rest_framework.response import Response

from .serializers import CurrentUserRetrieveOutputSLZ


class CurrentUserRetrieveApi(generics.RetrieveAPIView):
@swagger_auto_schema(
operation_description="当前用户信息",
responses={status.HTTP_200_OK: CurrentUserRetrieveOutputSLZ()},
tags=["basic.current_user"],
)
def get(self, request, *args, **kwargs):
# FIXME: 待新版登录后重构,return更多信息
current_user = request.user
info = {
"username": current_user.username,
}

return Response(CurrentUserRetrieveOutputSLZ(instance=info).data)
7 changes: 6 additions & 1 deletion src/bk-user/bkuser/apis/web/tenant/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ def get_queryset(self):
return queryset

@swagger_auto_schema(
tags=["tenant"],
operation_description="租户列表",
query_serializer=TenantSearchInputSLZ(),
responses={status.HTTP_200_OK: TenantSearchOutputSLZ(many=True)},
Expand All @@ -72,6 +73,7 @@ def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)

@swagger_auto_schema(
tags=["tenant"],
operation_description="新建租户",
request_body=TenantCreateInputSLZ(),
responses={status.HTTP_201_CREATED: TenantCreateOutputSLZ()},
Expand Down Expand Up @@ -100,7 +102,7 @@ def post(self, request, *args, **kwargs):
]
tenant_id = TenantHandler.create_with_managers(tenant_info, managers)

return Response({"id": tenant_id})
return Response(TenantCreateOutputSLZ(instance={"id": tenant_id}).data)


class TenantRetrieveUpdateApi(ExcludePatchAPIViewMixin, generics.RetrieveUpdateAPIView):
Expand All @@ -116,13 +118,15 @@ def get_serializer_context(self):
}

@swagger_auto_schema(
tags=["tenant"],
operation_description="租户详情",
responses={status.HTTP_200_OK: TenantRetrieveOutputSLZ()},
)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)

@swagger_auto_schema(
tags=["tenant"],
operation_description="更新租户",
request_body=TenantUpdateInputSLZ(),
responses={status.HTTP_200_OK: ""},
Expand Down Expand Up @@ -161,6 +165,7 @@ def get_queryset(self):
return queryset

@swagger_auto_schema(
tags=["tenant"],
operation_description="租户下用户列表",
query_serializer=TenantUserSearchInputSLZ(),
responses={status.HTTP_200_OK: TenantUserSearchOutputSLZ(many=True)},
Expand Down
3 changes: 3 additions & 0 deletions src/bk-user/bkuser/apis/web/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@
from django.urls import include, path

urlpatterns = [
# 基础公共,比如当前登录的用户信息,一些常用常量枚举列表等等
path("basic/", include("bkuser.apis.web.basic.urls")),
# 租户
path("tenants/", include("bkuser.apis.web.tenant.urls")),
]
6 changes: 2 additions & 4 deletions src/bk-user/bkuser/biz/tenant.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
from bkuser.utils.uuid import generate_uuid


class DataSourceUserInfo(
BaseModel,
):
class DataSourceUserInfo(BaseModel):
"""数据源用户信息"""

username: str
Expand Down Expand Up @@ -134,7 +132,7 @@ def create_with_managers(tenant_info: TenantBaseInfo, managers: List[TenantManag
# 创建租户本身
tenant = Tenant.objects.create(**tenant_info.model_dump())

# TODO: 开发本地数据源时,重写(直接调用本地数据源Handler)
# FIXME: 开发本地数据源时,重写(直接调用本地数据源Handler)
# 创建本地数据源,名称则使用租户名称
data_source = DataSource.objects.create(
name=f"{tenant_info.name}-本地数据源",
Expand Down
21 changes: 19 additions & 2 deletions src/bk-user/bkuser/common/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from django.http.response import Http404, HttpResponseNotFound
from django.template.exceptions import TemplateDoesNotExist
from django.template.loader import get_template
from django.utils.translation import gettext_lazy as _
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.generic.base import TemplateView
from drf_yasg.utils import swagger_auto_schema
Expand Down Expand Up @@ -51,7 +52,17 @@ def one_line_error(error: ValidationError):
def _handle_exception(request, exc) -> APIError:
"""统一处理异常,并转换成 APIError"""
if isinstance(exc, (NotAuthenticated, AuthenticationFailed)):
return error_codes.UNAUTHENTICATED
# Q: 为什么需要f("")
# A: 如果直接 set_data , 那么 set_data 是影响 UNAUTHENTICATED 这个"全局变量"的,而 format 是返回 clone 后的对象
return error_codes.UNAUTHENTICATED.f("").set_data(
{
"login_url": settings.BK_LOGIN_URL,
"login_plain_url": settings.BK_LOGIN_PLAIN_URL,
"width": settings.BK_LOGIN_PLAIN_WINDOW_WIDTH,
"height": settings.BK_LOGIN_PLAIN_WINDOW_HEIGHT,
"callback_url_param_key": settings.BK_LOGIN_CALLBACK_URL_PARAM_KEY,
}
)

if isinstance(exc, PermissionDenied):
return error_codes.NO_PERMISSION.f(exc.detail)
Expand Down Expand Up @@ -155,17 +166,23 @@ def get(self, request, *args, **kwargs):
# Context
try:
context = {
# TITLE
"TITLE": _("用户管理 | 腾讯蓝鲸智云"),
# BK_DOMAIN
"BK_DOMAIN": settings.BK_DOMAIN,
# BK LOGIN
"BK_LOGIN_URL": settings.BK_LOGIN_URL.rstrip("/"),
"BK_LOGIN_CALLBACK_URL_PARAM_KEY": settings.BK_LOGIN_CALLBACK_URL_PARAM_KEY,
# BK USER
"BK_USER_URL": settings.BK_USER_URL.rstrip("/"),
"AJAX_BASE_URL": settings.AJAX_BASE_URL.rstrip("/"),
# 去除末尾的 /, 前端约定
"BK_STATIC_URL": settings.STATIC_URL.rstrip("/"),
# 去除开头的 . document.domain需要
"SESSION_COOKIE_DOMAIN": settings.SESSION_COOKIE_DOMAIN.lstrip("."),
# csrftoken name
# CSRF TOKEN COOKIE NAME
"CSRF_COOKIE_NAME": settings.CSRF_COOKIE_NAME,
# ESB
"BK_COMPONENT_API_URL": settings.BK_COMPONENT_API_URL.rstrip("/"),
}

Expand Down
9 changes: 8 additions & 1 deletion src/bk-user/bkuser/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@
BK_DOMAIN = env.str("BK_DOMAIN", default="")
# BK USER URL
BK_USER_URL = env.str("BK_USER_URL")
AJAX_BASE_URL = ""
AJAX_BASE_URL = env.str("AJAX_BASE_URL", SITE_URL)

# csrf
_BK_USER_URL_PARSE_URL = urlparse(BK_USER_URL)
Expand Down Expand Up @@ -185,6 +185,13 @@

# Login
BK_LOGIN_URL = env.str("BK_LOGIN_URL", default="/")
# 登录小窗相关
BK_LOGIN_PLAIN_URL = env.str("BK_LOGIN_PLAIN_URL", default=BK_LOGIN_URL.rstrip("/") + "/plain/")
BK_LOGIN_PLAIN_WINDOW_WIDTH = env.int("BK_LOGIN_PLAIN_WINDOW_WIDTH", default=415)
BK_LOGIN_PLAIN_WINDOW_HEIGHT = env.int("BK_LOGIN_PLAIN_WINDOW_HEIGHT", default=415)
# 登录回调地址参数Key
BK_LOGIN_CALLBACK_URL_PARAM_KEY = env.str("BK_LOGIN_CALLBACK_URL_PARAM_KEY", default="c_url")

# bk esb api url
BK_COMPONENT_API_URL = env.str("BK_COMPONENT_API_URL")

Expand Down
2 changes: 2 additions & 0 deletions src/bk-user/bkuser/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
from bkuser.common.views import VueTemplateView

urlpatterns = [
# 产品功能API
path("api/v1/web/", include("bkuser.apis.web.urls")),
# 用于监控相关的,比如ping/healthz/sentry/metrics/otel等等
path("", include("bkuser.monitoring.urls")),
]

Expand Down
2 changes: 1 addition & 1 deletion src/pages/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<link rel="icon" href="{{ BK_STATIC_URL }}/images/favicon.png" type="image/x-icon" />
<link rel="shortcut icon" href="{{ BK_STATIC_URL }}/images/favicon.png" type="image/x-icon" />
<meta charset="utf-8">
<title> index </title>
<title> {{ TITLE }} </title>
</head>
<body>
<div class="app"></div>
Expand Down

0 comments on commit 68f6f92

Please sign in to comment.