Skip to content

Commit

Permalink
feature: 升级blueapps==3.3.1, tastypie==0.14.3, django==2.2.6
Browse files Browse the repository at this point in the history
  • Loading branch information
normal-wls committed Jan 27, 2021
1 parent 54b8e06 commit bfd1174
Show file tree
Hide file tree
Showing 116 changed files with 2,677 additions and 2,025 deletions.
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ exclude =
*/templates_module*,
*/bin/*,
local/*,
blueapps/*,
local_settings.py,
max-line-length = 120
max-complexity = 12
Expand Down
3 changes: 2 additions & 1 deletion blueapps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
specific language governing permissions and limitations under the License.
"""

VERSION = '2.5.1'
VERSION = "3.3.1"
__version__ = VERSION


Expand All @@ -20,6 +20,7 @@

def get_run_ver():
from django.conf import settings

try:
return settings.RUN_VER
except AttributeError:
Expand Down
27 changes: 4 additions & 23 deletions blueapps/account/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@

from django.conf import settings

from blueapps.account.conf import AUTH_USER_MODEL, ConfFixture
from blueapps.account.utils import load_backend
from blueapps.account.conf import ConfFixture, AUTH_USER_MODEL


def get_user_model():
Expand All @@ -24,28 +24,9 @@ def get_user_model():
return load_backend(ConfFixture.USER_MODEL)


def get_bk_login_ticket(request):
form_cls = 'AuthenticationForm'
context = [request.COOKIES, request.GET]

if request.is_rio():
form_cls = 'RioAuthenticationForm'
context.insert(0, request.META)

elif request.is_wechat():
form_cls = 'WeixinAuthenticationForm'

AuthenticationForm = load_backend("forms.{}".format(form_cls))

for form in (AuthenticationForm(c) for c in context):
if form.is_valid():
return form.cleaned_data

return {}


if AUTH_USER_MODEL == settings.AUTH_USER_MODEL:
from django.contrib import auth
from django.contrib import auth # pylint: disable=ungrouped-imports

auth.get_user_model = get_user_model

default_app_config = 'blueapps.account.apps.AccountConfig'
default_app_config = "blueapps.account.apps.AccountConfig" # pylint: disable=invalid-name
32 changes: 16 additions & 16 deletions blueapps/account/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,24 @@
class UserAdmin(admin.ModelAdmin):

fieldsets = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('nickname',)}),
(_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions')}),
(_('Important dates'), {'fields': ('last_login', 'date_joined')}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username',),
}),
(None, {"fields": ("username", "password")}),
(_("Personal info"), {"fields": ("nickname",)}),
(_("Permissions"), {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions",)},),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = ((None, {"classes": ("wide",), "fields": ("username",)}),)
add_form = UserCreationForm
filter_horizontal = ['groups']
list_display = ['username', 'nickname', 'is_active', 'is_staff',
'is_superuser', 'last_login']
search_fields = ['username']
list_filter = ['is_superuser', 'is_staff', 'is_active']
filter_horizontal = ["groups"]
list_display = [
"username",
"nickname",
"is_active",
"is_staff",
"is_superuser",
"last_login",
]
list_filter = ("is_superuser", "is_staff")
search_fields = ("username",)


admin.site.register(User, UserAdmin)
4 changes: 2 additions & 2 deletions blueapps/account/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@

class AccountConfig(AppConfig):

name = 'blueapps.account'
verbose_name = _('account')
name = "blueapps.account"
verbose_name = _("account")
8 changes: 4 additions & 4 deletions blueapps/account/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
from blueapps.account.conf import ConfFixture
from blueapps.account.utils import load_backend

if hasattr(ConfFixture, 'USER_BACKEND'):
if hasattr(ConfFixture, "USER_BACKEND"):
UserBackend = load_backend(ConfFixture.USER_BACKEND)

if hasattr(ConfFixture, 'WEIXIN_BACKEND'):
if hasattr(ConfFixture, "WEIXIN_BACKEND"):
WeixinBackend = load_backend(ConfFixture.WEIXIN_BACKEND)

if hasattr(ConfFixture, 'RIO_BACKEND'):
if hasattr(ConfFixture, "RIO_BACKEND"):
RioBackend = load_backend(ConfFixture.RIO_BACKEND)

if hasattr(ConfFixture, 'BK_JWT_BACKEND'):
if hasattr(ConfFixture, "BK_JWT_BACKEND"):
BkJwtBackend = load_backend(ConfFixture.BK_JWT_BACKEND)
77 changes: 33 additions & 44 deletions blueapps/account/components/bk_jwt/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,43 +15,41 @@

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.utils.translation import ugettext_lazy as _

from blueapps.account import get_user_model

bkoauth_jwt_client_exists = True
BKOAUTH_JWT_CLIENT_EXISTS = True
try:
from bkoauth.jwt_client import JWTClient
except ImportError:
bkoauth_jwt_client_exists = False
BKOAUTH_JWT_CLIENT_EXISTS = False

logger = logging.getLogger('component')
logger = logging.getLogger("component") # pylint: disable=invalid-name


class BkJwtBackend(ModelBackend):

def authenticate(self, request=None):
logger.debug(u"进入 BK_JWT 认证 Backend")

try:
verify_data = self.verify_bk_jwt_request(request)
except Exception as e:
logger.exception(u"[BK_JWT]校验异常: %s" % e)
except Exception as err: # pylint: disable=broad-except
logger.exception(u"[BK_JWT]校验异常: %s" % err)
return None

if not verify_data['result'] or not verify_data['data']:
logger.error(u"BK_JWT 验证失败: %s" % (
verify_data)
)
if not verify_data["result"] or not verify_data["data"]:
logger.error(u"BK_JWT 验证失败: %s" % verify_data)
return None

user_info = verify_data['data']['user']
user_info = verify_data["data"]["user"]
user_model = get_user_model()
try:
user, _ = user_model.objects.get_or_create(
username=user_info['bk_username'])
user.nickname = user_info['bk_username']
user, _ = user_model.objects.get_or_create(username=user_info["bk_username"])
user.nickname = user_info["bk_username"]
user.save()
except Exception as e:
logger.exception(u"自动创建 & 更新 User Model 失败: %s" % e)
except Exception as err: # pylint: disable=broad-except
logger.exception(u"自动创建 & 更新 User Model 失败: %s" % err)
return None

return user
Expand Down Expand Up @@ -82,51 +80,42 @@ def verify_bk_jwt_request(request):
}
}
"""
ret = {
'result': False,
'message': '',
'data': {}
}
ret = {"result": False, "message": "", "data": {}}
# 兼容bkoauth未支持jwt协议情况
if not bkoauth_jwt_client_exists:
ret['message'] = u'bkoauth暂不支持JWT协议'
if not BKOAUTH_JWT_CLIENT_EXISTS:
ret["message"] = _(u"bkoauth暂不支持JWT协议")
return ret

jwt = JWTClient(request)
if not jwt.is_valid:
ret['message'] = u"jwt_invalid: %s" % jwt.error_message
ret["message"] = _(u"jwt_invalid: %s") % jwt.error_message
return ret

# verify: user && app
app = jwt.get_app_model()
if not app['verified']:
ret['message'] = app.get('valid_error_message', u'APP鉴权失败')
ret['data']['app'] = app
if not app["verified"]:
ret["message"] = app.get("valid_error_message", _(u"APP鉴权失败"))
ret["data"]["app"] = app
return ret

if not app.get('bk_app_code'):
app['bk_app_code'] = app['app_code']
if not app.get("bk_app_code"):
app["bk_app_code"] = app["app_code"]

user = jwt.get_user_model()
# ESB默认需要校验用户信息
esb_white_list = True
if hasattr(settings, 'ESB_WHITE_LIST'):
esb_white_list = settings.ESB_WHITE_LIST
use_esb_white_list = getattr(settings, "USE_ESB_WHITE_LIST", True)

if not esb_white_list and not user['verified']:
ret['message'] = user.get('valid_error_message', u'用户鉴权失败')
ret['data']['user'] = user
if not use_esb_white_list and not user["verified"]:
ret["message"] = user.get("valid_error_message", _(u"用户鉴权失败且不支持ESB白名单"))
ret["data"]["user"] = user
return ret
if not user.get('bk_username'):
user['bk_username'] = user['username']
if not user.get("bk_username"):
user["bk_username"] = user["username"]

if not app['bk_app_code'] or not user['bk_username']:
ret['message'] = u'用户或来源为空'
if not app["bk_app_code"] or not user["bk_username"]:
ret["message"] = _(u"用户或来源为空")
return ret

ret['result'] = True
ret['data'] = {
"user": user,
"app": app
}
ret["result"] = True
ret["data"] = {"user": user, "app": app}
return ret
17 changes: 8 additions & 9 deletions blueapps/account/components/bk_jwt/middlewares.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from blueapps.account.conf import ConfFixture
from blueapps.account.handlers.response import ResponseHandler

logger = logging.getLogger('component')
logger = logging.getLogger("component")


class BkJwtLoginRequiredMiddleware(MiddlewareMixin):
Expand All @@ -31,21 +31,20 @@ def process_view(self, request, view, args, kwargs):
2. JWT签名正确
"""
# 框架前置中间件,已将识别的客户端信息填充进 request
if not hasattr(request, 'is_bk_jwt') or not request.is_bk_jwt():
if not hasattr(request, "is_bk_jwt") or not request.is_bk_jwt():
return None

logger.debug('当前请求是否经过JWT转发')
login_exempt = getattr(view, 'login_exempt', False)
logger.debug("当前请求是否经过JWT转发")
login_exempt = getattr(view, "login_exempt", False)

# 每次请求都需要做校验
if not (login_exempt or request.user.is_authenticated):
user = auth.authenticate(request=request)
if user:
# 登录成功,确认登陆正常后退出
if user and user.username != request.user.username:
auth.login(request, user)
if request.user.is_authenticated:
return None

if request.user.is_authenticated:
# 登录成功,确认登陆正常后退出
return None
handler = ResponseHandler(ConfFixture, settings)
return handler.build_bk_jwt_401_response(request)
return None
Expand Down
Loading

0 comments on commit bfd1174

Please sign in to comment.