Skip to content

Commit

Permalink
feat(bklogin): call bk-user api, not access shared db (#1376)
Browse files Browse the repository at this point in the history
  • Loading branch information
nannan00 authored Nov 13, 2023
1 parent e681104 commit 9c840bd
Show file tree
Hide file tree
Showing 57 changed files with 1,403 additions and 854 deletions.
15 changes: 9 additions & 6 deletions .github/workflows/bk-user.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,21 @@ jobs:
run: |
ln -s $(pwd)/src/idp-plugins/idp_plugins $(pwd)/src/bk-login/bklogin
ln -s $(pwd)/src/idp-plugins/idp_plugins $(pwd)/src/bk-user/bkuser
- name: Format with black
- name: Format & Lint with ruff
run: |
pip install black==23.7.0 click==8.1.6
black src/bk-user --config=src/bk-user/pyproject.toml
- name: Lint with ruff
run: |
pip install ruff==0.0.277
pip install ruff==0.1.4
ruff format src/bk-user --config=src/bk-user/pyproject.toml
ruff src/bk-user --config=src/bk-user/pyproject.toml
ruff format src/bk-login --config=src/bk-login/pyproject.toml
ruff src/bk-login --config=src/bk-login/pyproject.toml
ruff format src/idp-plugins --config=src/idp-plugins/pyproject.toml
ruff src/idp-plugins --config=src/idp-plugins/pyproject.toml
- name: Lint with mypy
run: |
pip install mypy==1.6.1 types-requests==2.31.0.2 types-setuptools==57.4.18 types-dataclasses==0.1.7 types-redis==3.5.18 types-PyMySQL==1.1.0.1 types-six==0.1.9 types-toml==0.1.5 types-pytz==2023.3.0.0 types-urllib3==1.26.25.14
mypy src/bk-user --config-file=src/bk-user/pyproject.toml
mypy src/bk-login --config-file=src/bk-login/pyproject.toml
mypy src/idp-plugins --config-file=src/idp-plugins/pyproject.toml
test:
strategy:
fail-fast: false
Expand Down
22 changes: 11 additions & 11 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ repos:
entry: bash -c "if [[ -d pre_commit_hooks ]]; then pre_commit_hooks/ip.sh $@; fi"
- repo: local
hooks:
- id: black
name: black
- id: format
name: ruff-formatter
language: python
types: [python]
entry: black --config=src/bk-user/pyproject.toml
entry: ruff format --config=src/bk-user/pyproject.toml --force-exclude
files: src/bk-user/
- id: ruff
name: ruff
Expand All @@ -74,11 +74,11 @@ repos:
entry: bash -c "cd src/bk-user && lint-imports"
- repo: local
hooks:
- id: black
name: black
- id: format
name: ruff-formatter
language: python
types: [python]
entry: black --config=src/bk-login/pyproject.toml
entry: ruff format --config=src/bk-login/pyproject.toml --force-exclude
files: src/bk-login/
- id: ruff
name: ruff
Expand All @@ -99,18 +99,18 @@ repos:
entry: bash -c "cd src/bk-login && lint-imports"
- repo: local
hooks:
- id: black
name: black
- id: format
name: ruff-formatter
language: python
types: [python]
entry: black --config=src/idp-plugins/pyproject.toml
files: src/idp-plugins/
entry: ruff format --config=src/bk-plugins/pyproject.toml --force-exclude
files: src/bk-plugins/
- id: ruff
name: ruff
language: python
types: [python]
entry: ruff --config=src/idp-plugins/pyproject.toml --force-exclude --fix
files: src/bk-login/
files: src/idp-plugins/
- id: mypy
name: mypy
language: python
Expand Down
13 changes: 5 additions & 8 deletions src/bk-login/bklogin/authentication/api_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@
specific language governing permissions and limitations under the License.
"""
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.views.generic import View

from bklogin.bkuser.models import TenantUser
from bklogin.common.error_codes import error_codes
from bklogin.common.response import APISuccessResponse
from bklogin.component.bk_user import api as bk_user_api

from .manager import BkTokenManager

Expand All @@ -38,16 +37,14 @@ def get(self, request, *args, **kwargs):
if not ok:
raise error_codes.VALIDATION_ERROR.f(msg)

user = TenantUser.objects.filter(id=username).first()
if not user:
raise error_codes.OBJECT_NOT_FOUND.f(_("用户({})查询不到").format(username))
user = bk_user_api.get_tenant_user(username)

return APISuccessResponse(
{
"bk_username": username,
"bk_username": user.id,
"tenant_id": user.tenant_id,
"full_name": user.data_source_user.full_name,
"source_username": user.data_source_user.username,
"full_name": user.full_name,
"source_username": user.username,
"language": user.language,
"time_zone": user.time_zone,
}
Expand Down
2 changes: 1 addition & 1 deletion src/bk-login/bklogin/authentication/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@

SIGN_IN_TENANT_ID_SESSION_KEY = "sign_in_tenant_id"

ALLOWED_SIGN_IN_TENANT_USER_IDS_SESSION_KEY = "allowed_sign_in_tenant_user_ids"
ALLOWED_SIGN_IN_TENANT_USERS_SESSION_KEY = "allowed_sign_in_tenant_users"
17 changes: 8 additions & 9 deletions src/bk-login/bklogin/authentication/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
from blue_krill.encrypt.handler import EncryptHandler
from django.conf import settings
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.translation import gettext_lazy as _

from .models import BkToken
Expand All @@ -33,9 +32,9 @@ class BkTokenProcessor:
生成并加密Token & 解密Token
"""

def __init__(self, encrypt_secret_key: bytes):
# Token加密密钥
self.encrypt_secret_key = encrypt_secret_key
def __init__(self):
# 加密器,默认读取django settings里配置的加密密钥和加密类
self.crypter = EncryptHandler()

@staticmethod
def _salt(length: int = 8) -> str:
Expand All @@ -49,15 +48,15 @@ def generate(self, username: str, expires_at: int) -> str:
plain_token = "%s|%s|%s" % (expires_at, username, self._salt())

# 加密
return EncryptHandler(secret_key=self.encrypt_secret_key).encrypt(plain_token)
return self.crypter.encrypt(plain_token)

def parse(self, bk_token: str) -> Tuple[str, int]:
"""
token解析
:return: username, expires_at
"""
try:
plain_bk_token = EncryptHandler(secret_key=self.encrypt_secret_key).decrypt(bk_token)
plain_bk_token = self.crypter.decrypt(bk_token)
except Exception:
logger.exception("参数 bk_token [%s] 解析失败", bk_token)
plain_bk_token = ""
Expand All @@ -84,7 +83,7 @@ def parse(self, bk_token: str) -> Tuple[str, int]:
class BkTokenManager:
def __init__(self):
# Token加密密钥
self.bk_token_processor = BkTokenProcessor(encrypt_secret_key=force_bytes(settings.ENCRYPT_SECRET_KEY))
self.bk_token_processor = BkTokenProcessor()
# Token 过期间隔
self.cookie_age = settings.BK_TOKEN_COOKIE_AGE
# Token 无操作失效间隔
Expand Down Expand Up @@ -114,7 +113,7 @@ def get_bk_token(self, username: str) -> Tuple[str, datetime.datetime]:
bk_token = self.bk_token_processor.generate(username, expires_at)
# DB记录
try:
BkToken.objects.create(token=bk_token, inactive_expire_time=inactive_expires_at)
BkToken.objects.create(token=bk_token, inactive_expires_at=inactive_expires_at)
except Exception: # noqa: PERF203
logger.exception("Login ticket failed to be saved during ticket generation")
# 循环结束前将bk_token置空后重新生成
Expand Down Expand Up @@ -167,6 +166,6 @@ def is_bk_token_valid(self, bk_token: str) -> Tuple[bool, str, str]:
try:
BkToken.objects.filter(token=bk_token).update(inactive_expires_at=now + self.inactive_age)
except Exception:
logger.exception("update inactive_expire_time fail")
logger.exception("update inactive_expires_at fail")

return True, username, ""
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 3.2.21 on 2023-09-27 02:34
# Generated by Django 3.2.21 on 2023-11-09 11:26

from django.db import migrations, models

Expand All @@ -15,9 +15,14 @@ class Migration(migrations.Migration):
name='BkToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('token', models.CharField(db_index=True, max_length=255, unique=True, verbose_name='登录票据')),
('is_logout', models.BooleanField(default=False, verbose_name='票据是否已经执行过退出登录操作')),
('inactive_expires_at', models.IntegerField(default=0, verbose_name='无操作失效时间戳')),
],
options={
'abstract': False,
},
),
]
4 changes: 3 additions & 1 deletion src/bk-login/bklogin/authentication/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
"""
from django.db import models

from bklogin.common.models import TimestampedModel

class BkToken(models.Model):

class BkToken(TimestampedModel):
"""
登录票据
"""
Expand Down
4 changes: 3 additions & 1 deletion src/bk-login/bklogin/authentication/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
urlpatterns = [
# 登录入口
path("", views.LoginView.as_view()),
# 登录小窗入口
path("plain/", views.LoginView.as_view()),
# 前端页面(选择登录的用户)
path("pages/users", TemplateView.as_view(template_name="index.html")),
path("page/users/", TemplateView.as_view(template_name="index.html")),
# ------------------------------------------ 租户 & 登录方式选择 ------------------------------------------
# 租户配置
path("tenant-global-settings/", views.TenantGlobalSettingRetrieveApi.as_view()),
Expand Down
Loading

0 comments on commit 9c840bd

Please sign in to comment.