Commit 4d71c2d1 authored by ibuler's avatar ibuler

修改token获取,拆分认证文件和权限文件

parent d9642216
...@@ -12,5 +12,5 @@ ...@@ -12,5 +12,5 @@
from users.utils import AdminUserRequiredMixin from users.utils import AdminUserRequiredMixin
from users.backends import IsSuperUserOrTerminalUser, IsSuperUser from users.permissions import IsSuperUserOrTerminalUser, IsSuperUser
from users.models import User, UserGroup from users.models import User, UserGroup
...@@ -14,9 +14,9 @@ router.register(r'v1/admin-user', api.AdminUserViewSet, 'admin-user') ...@@ -14,9 +14,9 @@ router.register(r'v1/admin-user', api.AdminUserViewSet, 'admin-user')
router.register(r'v1/system-user', api.SystemUserViewSet, 'system-user') router.register(r'v1/system-user', api.SystemUserViewSet, 'system-user')
urlpatterns = [ urlpatterns = [
url(r'^v1/assets_bulk/$', api.AssetListUpdateApi.as_view(), name='asset-bulk-update'), url(r'^v1/assets_bulk$', api.AssetListUpdateApi.as_view(), name='asset-bulk-update'),
# url(r'^v1/idc/(?P<pk>[0-9]+)/assets/$', api.IDCAssetsApi.as_view(), name='api-idc-assets'), # url(r'^v1/idc/(?P<pk>[0-9]+)/assets/$', api.IDCAssetsApi.as_view(), name='api-idc-assets'),
url(r'^v1/system-user/auth/', api.SystemUserAuthApi.as_view(), name='system-user-auth'), url(r'^v1/system-user/auth', api.SystemUserAuthApi.as_view(), name='system-user-auth'),
] ]
urlpatterns += router.urls urlpatterns += router.urls
......
...@@ -4,5 +4,5 @@ ...@@ -4,5 +4,5 @@
from users.utils import AdminUserRequiredMixin from users.utils import AdminUserRequiredMixin
from users.models import User from users.models import User
from assets.models import Asset, SystemUser from assets.models import Asset, SystemUser
from users.backends import IsSuperUserOrTerminalUser from users.permissions import IsSuperUserOrTerminalUser
from terminal.models import Terminal from terminal.models import Terminal
...@@ -263,11 +263,11 @@ REST_FRAMEWORK = { ...@@ -263,11 +263,11 @@ REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions, # Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users. # or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': ( 'DEFAULT_PERMISSION_CLASSES': (
'users.backends.IsValidUser', 'users.permissions.IsValidUser',
), ),
'DEFAULT_AUTHENTICATION_CLASSES': ( 'DEFAULT_AUTHENTICATION_CLASSES': (
'users.backends.TerminalAuthentication', 'users.authentication.TerminalAuthentication',
'users.backends.AccessTokenAuthentication', 'users.authentication.AccessTokenAuthentication',
'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.SessionAuthentication',
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
from rest_framework.views import APIView, Response from rest_framework.views import APIView, Response
from rest_framework.generics import ListAPIView, get_object_or_404 from rest_framework.generics import ListAPIView, get_object_or_404
from rest_framework import viewsets from rest_framework import viewsets
from users.backends import IsValidUser, IsSuperUser from users.permissions import IsValidUser, IsSuperUser
from common.utils import get_object_or_none from common.utils import get_object_or_none
from .utils import get_user_granted_assets, get_user_granted_asset_groups, get_user_asset_permissions, \ from .utils import get_user_granted_assets, get_user_granted_asset_groups, get_user_asset_permissions, \
get_user_group_asset_permissions, get_user_group_granted_assets, get_user_group_granted_asset_groups get_user_group_asset_permissions, get_user_group_granted_assets, get_user_group_granted_asset_groups
......
...@@ -11,7 +11,8 @@ from rest_framework.permissions import AllowAny ...@@ -11,7 +11,8 @@ from rest_framework.permissions import AllowAny
from common.utils import signer, get_object_or_none from common.utils import signer, get_object_or_none
from .models import Terminal, TerminalHeatbeat from .models import Terminal, TerminalHeatbeat
from .serializers import TerminalSerializer, TerminalHeatbeatSerializer from .serializers import TerminalSerializer, TerminalHeatbeatSerializer
from .hands import IsSuperUserOrTerminalUser from .hands import IsSuperUserOrTerminalUser, User
class TerminalViewSet(viewsets.ModelViewSet): class TerminalViewSet(viewsets.ModelViewSet):
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
from users.backends import IsSuperUserOrTerminalUser from users.models import User
from users.permissions import IsSuperUserOrTerminalUser
from audits.models import ProxyLog from audits.models import ProxyLog
...@@ -13,10 +13,10 @@ from django_filters.rest_framework import DjangoFilterBackend ...@@ -13,10 +13,10 @@ from django_filters.rest_framework import DjangoFilterBackend
from common.mixins import IDInFilterMixin from common.mixins import IDInFilterMixin
from common.utils import get_logger from common.utils import get_logger
from .utils import check_user_valid, token_gen from .utils import check_user_valid, get_or_refresh_token
from .models import User, UserGroup from .models import User, UserGroup
from .hands import write_login_log_async from .hands import write_login_log_async
from .backends import IsSuperUser, IsTerminalUser, IsValidUser, IsSuperUserOrTerminalUser from .permissions import IsSuperUser, IsTerminalUser, IsValidUser, IsSuperUserOrTerminalUser
from . import serializers from . import serializers
...@@ -87,19 +87,11 @@ class UserGroupUpdateUserApi(generics.RetrieveUpdateAPIView): ...@@ -87,19 +87,11 @@ class UserGroupUpdateUserApi(generics.RetrieveUpdateAPIView):
class UserToken(APIView): class UserToken(APIView):
permission_classes = (IsValidUser,) permission_classes = (IsValidUser,)
expiration = settings.CONFIG.TOKEN_EXPIRATION or 3600
def get(self, request): def get(self, request):
if not request.user: if not request.user:
return Response({'error': 'unauthorized'}) return Response({'error': 'unauthorized'})
token = get_token(request)
remote_addr = request.META.get('REMOTE_ADDR', '')
remote_addr = base64.b16encode(remote_addr).replace('=', '')
token = cache.get('%s_%s' % (request.user.id, remote_addr))
if not token:
token = token_gen(request.user)
cache.set(token, request.user.id, self.expiration)
cache.set('%s_%s' % (request.user.id, remote_addr), token, self.expiration)
return Response({'token': token}) return Response({'token': token})
......
...@@ -11,6 +11,7 @@ from rest_framework.compat import is_authenticated ...@@ -11,6 +11,7 @@ from rest_framework.compat import is_authenticated
from common.utils import signer, get_object_or_none from common.utils import signer, get_object_or_none
from .hands import Terminal from .hands import Terminal
from .utils import get_or_refresh_token
from .models import User from .models import User
...@@ -83,45 +84,5 @@ class AccessTokenAuthentication(authentication.BaseAuthentication): ...@@ -83,45 +84,5 @@ class AccessTokenAuthentication(authentication.BaseAuthentication):
if not user: if not user:
return None return None
get_or_refresh_token(request, user)
remote_addr = request.META.get('REMOTE_ADDR', '')
remote_addr = base64.b16encode(remote_addr).replace('=', '')
cache.set(token, user_id, self.expiration)
cache.set('%s_%s' % (user.id, remote_addr), token, self.expiration)
return user, None return user, None
class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission):
"""Allows access to valid user, is active and not expired"""
def has_permission(self, request, view):
return super(IsValidUser, self).has_permission(request, view) \
and request.user.is_valid
class IsTerminalUser(IsValidUser, permissions.BasePermission):
"""Allows access only to app user """
def has_permission(self, request, view):
return super(IsTerminalUser, self).has_permission(request, view) \
and isinstance(request.user, Terminal)
class IsSuperUser(IsValidUser, permissions.BasePermission):
"""Allows access only to superuser"""
def has_permission(self, request, view):
return super(IsSuperUser, self).has_permission(request, view) \
and request.user.is_superuser
class IsSuperUserOrTerminalUser(IsValidUser, permissions.BasePermission):
"""Allows access between superuser and app user"""
def has_permission(self, request, view):
return super(IsSuperUserOrTerminalUser, self).has_permission(request, view) \
and (request.user.is_superuser or request.user.is_terminal)
if __name__ == '__main__':
pass
...@@ -12,5 +12,6 @@ ...@@ -12,5 +12,6 @@
from terminal.models import Terminal from terminal.models import Terminal
from audits.tasks import write_login_log_async from audits.tasks import write_login_log_async
from users.models import User
# from perms.models import AssetPermission # from perms.models import AssetPermission
# from perms.utils import get_user_granted_assets, get_user_granted_asset_groups # from perms.utils import get_user_granted_assets, get_user_granted_asset_groups
...@@ -67,6 +67,7 @@ class User(AbstractUser): ...@@ -67,6 +67,7 @@ class User(AbstractUser):
ROLE_CHOICES = ( ROLE_CHOICES = (
('Admin', _('Administrator')), ('Admin', _('Administrator')),
('User', _('User')), ('User', _('User')),
('APP', _('Application'))
) )
username = models.CharField(max_length=20, unique=True, verbose_name=_('Username')) username = models.CharField(max_length=20, unique=True, verbose_name=_('Username'))
......
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import base64
from django.core.cache import cache
from django.conf import settings
from django.utils.translation import ugettext as _
from rest_framework import authentication, exceptions, permissions
from rest_framework.compat import is_authenticated
from common.utils import signer, get_object_or_none
from .hands import Terminal
from .models import User
class IsValidUser(permissions.IsAuthenticated, permissions.BasePermission):
"""Allows access to valid user, is active and not expired"""
def has_permission(self, request, view):
return super(IsValidUser, self).has_permission(request, view) \
and request.user.is_valid
class IsTerminalUser(IsValidUser, permissions.BasePermission):
"""Allows access only to app user """
def has_permission(self, request, view):
return super(IsTerminalUser, self).has_permission(request, view) \
and isinstance(request.user, Terminal)
class IsSuperUser(IsValidUser, permissions.BasePermission):
"""Allows access only to superuser"""
def has_permission(self, request, view):
return super(IsSuperUser, self).has_permission(request, view) \
and request.user.is_superuser
class IsSuperUserOrTerminalUser(IsValidUser, permissions.BasePermission):
"""Allows access between superuser and app user"""
def has_permission(self, request, view):
return super(IsSuperUserOrTerminalUser, self).has_permission(request, view) \
and (request.user.is_superuser or request.user.is_terminal)
if __name__ == '__main__':
pass
...@@ -16,14 +16,14 @@ router.register(r'v1/user-groups', api.UserGroupViewSet, 'user-group') ...@@ -16,14 +16,14 @@ router.register(r'v1/user-groups', api.UserGroupViewSet, 'user-group')
urlpatterns = [ urlpatterns = [
url(r'^v1/users/token/$', api.UserToken.as_view(), name='user-token'), url(r'^v1/token$', api.UserToken.as_view(), name='user-token'),
url(r'^v1/users/profile/$', api.UserProfile.as_view(), name='user-profile'), url(r'^v1/profile$', api.UserProfile.as_view(), name='user-profile'),
url(r'^v1/users/(?P<pk>\d+)/reset-password/$', api.UserResetPasswordApi.as_view(), name='user-reset-password'), url(r'^v1/users/(?P<pk>\d+)/reset-password$', api.UserResetPasswordApi.as_view(), name='user-reset-password'),
url(r'^v1/users/(?P<pk>\d+)/reset-pk/$', api.UserResetPKApi.as_view(), name='user-reset-pk'), url(r'^v1/users/(?P<pk>\d+)/reset-pk$', api.UserResetPKApi.as_view(), name='user-reset-pk'),
url(r'^v1/users/(?P<pk>\d+)/update-pk/$', api.UserUpdatePKApi.as_view(), name='user-update-pk'), url(r'^v1/users/(?P<pk>\d+)/update-pk$', api.UserUpdatePKApi.as_view(), name='user-update-pk'),
url(r'^v1/users/(?P<pk>\d+)/groups/$', url(r'^v1/users/(?P<pk>\d+)/groups$',
api.UserUpdateGroupApi.as_view(), name='user-update-group'), api.UserUpdateGroupApi.as_view(), name='user-update-group'),
url(r'^v1/user-groups/(?P<pk>\d+)/users/$', url(r'^v1/user-groups/(?P<pk>\d+)/users$',
api.UserGroupUpdateUserApi.as_view(), name='user-group-update-user'), api.UserGroupUpdateUserApi.as_view(), name='user-group-update-user'),
] ]
......
# ~*~ coding: utf-8 ~*~ # ~*~ coding: utf-8 ~*~
# #
from __future__ import unicode_literals from __future__ import unicode_literals
import base64
import logging import logging
import os import os
import re import re
...@@ -10,6 +11,7 @@ from django.conf import settings ...@@ -10,6 +11,7 @@ from django.conf import settings
from django.contrib.auth.mixins import UserPassesTestMixin from django.contrib.auth.mixins import UserPassesTestMixin
from django.urls import reverse_lazy from django.urls import reverse_lazy
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.core.cache import cache
from paramiko.rsakey import RSAKey from paramiko.rsakey import RSAKey
...@@ -195,6 +197,13 @@ def check_user_valid(**kwargs): ...@@ -195,6 +197,13 @@ def check_user_valid(**kwargs):
return None return None
def token_gen(*args, **kwargs): def get_or_refresh_token(request, user):
expiration = settings.CONFIG.TOKEN_EXPIRATION or 3600
remote_addr = request.META.get('REMOTE_ADDR', '')
remote_addr = base64.b16encode(remote_addr).replace('=', '')
token = cache.get('%s_%s' % (user.id, remote_addr))
if not token:
token = uuid.uuid4().get_hex()
cache.set(token, request.user.id, expiration)
cache.set('%s_%s' % (request.user.id, remote_addr), token, expiration)
return uuid.uuid4().get_hex() return uuid.uuid4().get_hex()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment