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(login): add current user api,return login data when 401 #1168

Merged
merged 3 commits into from
Aug 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
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 CurrentUserRetrieveSchema(serializers.Serializer):
nannan00 marked this conversation as resolved.
Show resolved Hide resolved
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 CurrentUserRetrieveSchema


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

return Response(info)
5 changes: 5 additions & 0 deletions 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 @@ -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")),
]
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后的对象
nannan00 marked this conversation as resolved.
Show resolved Hide resolved
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" />
nannan00 marked this conversation as resolved.
Show resolved Hide resolved
<meta charset="utf-8">
<title> index </title>
<title> {{ TITLE }} </title>
</head>
<body>
<div class="app"></div>
Expand Down
Loading