Skip to content

Commit

Permalink
新增二次验证码有效时间
Browse files Browse the repository at this point in the history
  • Loading branch information
yo committed Oct 31, 2018
1 parent 5a2f075 commit 693fd8c
Show file tree
Hide file tree
Showing 15 changed files with 59 additions and 71 deletions.
3 changes: 0 additions & 3 deletions apps/authority/api/group.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ class GroupCreateAPI(WebTokenAuthentication, generics.CreateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Permission_PMNGROUP_CREATE'])
def create(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(GroupCreateAPI, self).create(request, *args, **kwargs)
return self.msg.format(
USER=request.user.full_name,
Expand All @@ -69,7 +68,6 @@ class GroupUpdateAPI(WebTokenAuthentication, generics.UpdateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Permission_PMNGROUP_UPDATE'])
def update(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(GroupUpdateAPI, self).update(request, *args, **kwargs)
pmngroup = self.get_object()
return self.msg.format(
Expand All @@ -90,7 +88,6 @@ class GroupDeleteAPI(WebTokenAuthentication, generics.DestroyAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Permission_PMNGROUP_DELETE'])
def delete(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
pmngroup = self.get_object()
response = super(GroupDeleteAPI, self).delete(request, *args, **kwargs)
return self.msg.format(
Expand Down
3 changes: 0 additions & 3 deletions apps/authority/api/jumper.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ class JumperCreateAPI(WebTokenAuthentication, generics.CreateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Jumper_JUMPER_CREATE'])
def create(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(JumperCreateAPI, self).create(request, *args, **kwargs)
return self.msg.format(
USER=request.user.full_name,
Expand All @@ -90,7 +89,6 @@ class JumperUpdateAPI(WebTokenAuthentication, generics.UpdateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Jumper_JUMPER_UPDATE'])
def update(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(JumperUpdateAPI, self).update(request, *args, **kwargs)
jumper = self.get_object()
return self.msg.format(
Expand All @@ -115,7 +113,6 @@ class JumperDeleteAPI(WebTokenAuthentication, generics.DestroyAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Jumper_JUMPER_DELETE'])
def delete(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
jumper = self.get_object()
try:
group = jumper.group
Expand Down
3 changes: 0 additions & 3 deletions apps/authority/api/key.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ class KeyCreateAPI(WebTokenAuthentication, generics.CreateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Key_KEY_CREATE'])
def create(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(KeyCreateAPI, self).create(request, *args, **kwargs)
return self.msg.format(
USER=request.user.full_name,
Expand All @@ -73,7 +72,6 @@ class KeyUpdateAPI(WebTokenAuthentication, generics.UpdateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Key_KEY_UPDATE'])
def update(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(KeyUpdateAPI, self).update(request, *args, **kwargs)
key = self.get_object()
return self.msg.format(
Expand All @@ -97,7 +95,6 @@ class KeyDeleteAPI(WebTokenAuthentication, generics.DestroyAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Key_KEY_DELETE'])
def delete(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
key = self.get_object()
try:
group = key.group
Expand Down
37 changes: 23 additions & 14 deletions apps/authority/api/user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# -*- coding:utf-8 -*-
# !/usr/bin/env python
# Time 17-10-25
# Author Yo
# Email [email protected]
import pyotp
import os
from qrcode import QRCode, constants
Expand All @@ -13,13 +17,13 @@
from deveops.utils import aes
from authority.permission import user as UserPermission
from timeline.decorator import decorator_api
from .. import models,serializers,filter
from .. import models, serializers, filter

__all__ = [
"UserLoginAPI", "UserInfoAPI", "UserListAPI",
"UserOpsListAPI", "UserUpdateAPI", "UserDeleteAPI",
"UserListByPageAPI", 'UserPagination', 'UserOpsListByPageAPI',
'UserQRCodeAPI', 'UserCreateAPI',
'UserQRCodeAPI', 'UserCreateAPI', 'UserExpireAPI'
]


Expand Down Expand Up @@ -96,18 +100,17 @@ class UserCreateAPI(WebTokenAuthentication, generics.CreateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['ExtendUser_USER_CREATE'])
def create(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(UserCreateAPI, self).create(request, *args, **kwargs)
return self.msg.format(
USER = request.user.full_name,
USERNAME = response.data['username'],
FULLNAME = response.data['full_name'],
USER=request.user.full_name,
USERNAME=response.data['username'],
FULLNAME=response.data['full_name'],
), response
else:
return '', self.qrcode_response


class UserUpdateAPI(WebTokenAuthentication,generics.UpdateAPIView):
class UserUpdateAPI(WebTokenAuthentication, generics.UpdateAPIView):
module = models.ExtendUser
serializer_class = serializers.UserSerializer
queryset = models.ExtendUser.objects.all()
Expand All @@ -117,7 +120,6 @@ class UserUpdateAPI(WebTokenAuthentication,generics.UpdateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['ExtendUser_USER_UPDATE'])
def update(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(UserUpdateAPI, self).update(request, *args, **kwargs)
user = self.get_object()
return self.msg.format(
Expand All @@ -139,7 +141,6 @@ class UserDeleteAPI(WebTokenAuthentication,generics.DestroyAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['ExtendUser_USER_DELETE'])
def delete(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
user = self.get_object()
response = super(UserDeleteAPI, self).delete(request, *args, **kwargs)
return self.msg.format(
Expand All @@ -152,14 +153,13 @@ def delete(self, request, *args, **kwargs):


def get_qrcode(user):
if not user.qrcode: # ''
if not user.qrcode:
user.qrcode = pyotp.random_base32()
user.save()
file_name = str(aes.encrypt(user.qrcode),encoding='utf-8')
file_name = str(aes.encrypt(user.qrcode), encoding='utf-8')
file = settings.QCODE_ROOT+'/'+file_name+'.png'
if not os.path.exists(file):
data = pyotp.totp.TOTP(user.qrcode).provisioning_uri(user.username, issuer_name="devEops")
print('data',data)
qr = QRCode(
version=1,
error_correction=constants.ERROR_CORRECT_L,
Expand All @@ -170,9 +170,9 @@ def get_qrcode(user):
qr.make(fit=True)
img = qr.make_image()
img.save(file)
return '/media/qrcode/'+ file_name +'.png'
return '/media/qrcode/' + file_name + '.png'
except Exception as e:
return '/media/qrcode/'+ file_name +'.png'
return '/media/qrcode/' + file_name + '.png'
else:
return '/media/qrcode/' + file_name + '.png'

Expand All @@ -198,3 +198,12 @@ def get(self, request, *args, **kwargs):
return '', Response({
'detail': settings.LANGUAGE.UserQRCodeAPIHaveQRCode
}, status=status.HTTP_406_NOT_ACCEPTABLE)


class UserExpireAPI(WebTokenAuthentication, APIView):
permission_classes = [IsAuthenticated, ]

def get(self, request, *args, **kwargs):
return Response({
'isexpire': request.user.is_expire
}, status=status.HTTP_200_OK)
12 changes: 8 additions & 4 deletions apps/authority/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
# Time 18-6-7
# Author Yo
# Email [email protected]
import django_filters
from manager import models
from django.contrib.auth.models import Permission,Group
from django.db.models import Q
import django_filters
from manager import models

__all__ = [
'UserFilter', 'GroupFilter', 'KeyFilter', 'JumperFilter'
Expand All @@ -18,6 +18,7 @@ class UserFilter(django_filters.FilterSet):
name = django_filters.CharFilter(method="name_filter")
username = django_filters.CharFilter(method="username_filter")
is_active = django_filters.CharFilter(method="is_active_filter")

class Meta:
model = models.ExtendUser
fields = ['phone', 'name', 'username', 'email', 'is_active']
Expand All @@ -42,6 +43,7 @@ def is_active_filter(queryset, first_name, value):
class GroupFilter(django_filters.FilterSet):
permission = django_filters.CharFilter(method="permission_filter")
name = django_filters.CharFilter(method="name_filter")

class Meta:
model = Group
fields = ['permission', 'name']
Expand All @@ -59,9 +61,10 @@ def name_filter(queryset, first_name, value):
class KeyFilter(django_filters.FilterSet):
name = django_filters.CharFilter(method="name_filter")
group_name = django_filters.CharFilter(method="group_name_filter")

class Meta:
model = models.Key
fields = ['name',]
fields = ['name', ]

@staticmethod
def name_filter(queryset, first_name, value):
Expand All @@ -76,6 +79,7 @@ def group_name_filter(queryset, first_name, value):
class JumperFilter(django_filters.FilterSet):
info = django_filters.CharFilter(method="info_filter")
group_name = django_filters.CharFilter(method="group_name_filter")

class Meta:
model = models.Jumper
fields = ['info', 'group_name']
Expand All @@ -87,4 +91,4 @@ def info_filter(queryset, first_name, value):
@staticmethod
def group_name_filter(queryset, first_name, value):
groups = models.Group.objects.filter(name__icontains=value)
return queryset.filter(group__in=groups)
return queryset.filter(group__in=groups)
30 changes: 7 additions & 23 deletions apps/authority/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class ExtendUser(AbstractUser):
full_name = models.CharField(max_length=11, default='未获取')
qrcode = models.CharField(max_length=16, default='')
have_qrcode = models.BooleanField(default=False)
expire = models.IntegerField(default=300)
expire = models.IntegerField(default=100)
groups = models.ManyToManyField(
Group,
verbose_name=_('groups'),
Expand Down Expand Up @@ -136,19 +136,6 @@ class Meta:
('yo_list_permission', u'罗列所有权限')
)

def __unicode__(self):
list = []
if self.is_superuser:
list.append(u'超级管理员')
elif self.groups.count() == 0:
list.append(u'无权限')
else:
for group in self.groups.all():
list.append(group.name)
return self.username + ' - ' + "|".join(list)

__str__ = __unicode__

def get_8531email(self):
return self.username + '@8531.cn'

Expand All @@ -158,14 +145,14 @@ def get_group_name(self):
elif self.groups.count() == 0:
return "无权限"
else:
list = []
gourp_list = []
groups = self.groups.all()
for group in groups:
list.append(group.name)
if len(list) == 0:
gourp_list.append(group.name)
if len(gourp_list) == 0:
return ''
else:
return "-".join(list)
return "-".join(gourp_list)

def check_qrcode(self, verifycode):
t = pyotp.TOTP(self.qrcode)
Expand All @@ -174,11 +161,11 @@ def check_qrcode(self, verifycode):

@property
def is_expire(self):
return connect.exists(self.username)
return not connect.exists(self.username)

@is_expire.setter
def is_expire(self, qrcode):
connect.set(self.username, qrcode, self.expire)
connect.set(self.username, qrcode, self.expire or 1)


class Jumper(models.Model):
Expand All @@ -201,9 +188,6 @@ class Meta:
('yo_delete_jumper', u'删除跳板机'),
)

def __unicode__(self):
return self.connect_ip + ' - ' + self.name

@property
def status(self):
return self._status
Expand Down
2 changes: 1 addition & 1 deletion apps/authority/serializers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from rest_framework import serializers
from django.contrib.auth.models import Permission
from authority.models import ExtendUser,Group,Key,Jumper
from authority.models import ExtendUser, Group, Key, Jumper
from deveops.utils.sshkey import ssh_keygen

__all__ = [
Expand Down
13 changes: 9 additions & 4 deletions apps/authority/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@
# Time 17-10-25
# Author Yo
# Email [email protected]
from __future__ import absolute_import, unicode_literals
from celery import Task,task
import socket, paramiko, os, stat, time
import socket
import paramiko
import os
import stat
import time
from django.conf import settings
from celery import Task, task


class JumperTask(Task):
def on_failure(self, exc, task_id, args, kwargs, einfo):
print('{0!r} failed: {1!r}'.format(task_id, exc))
Expand Down Expand Up @@ -70,4 +75,4 @@ def jumper_status_flush(obj):
return

obj._status = settings.STATUS_JUMPER_CAN_BE_USE
obj.save()
obj.save()
8 changes: 7 additions & 1 deletion apps/authority/urls/api_urls.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# from django.conf.urls import path
# -*- coding:utf-8 -*-
# !/usr/bin/env python
# Time 17-10-25
# Author Yo
# Email [email protected]
from django.urls import path
from ..api import user
from ..api import group
from ..api import permission
from ..api import key
from ..api import jumper

urlpatterns = [
# Resource login api
path(r'login/', user.UserLoginAPI.as_view()),
Expand All @@ -19,6 +24,7 @@
path(r'v1/user/<int:pk>/update/', user.UserUpdateAPI.as_view()),
path(r'v1/user/<int:pk>/delete/', user.UserDeleteAPI.as_view()),
path(r'v1/user/qrcode/', user.UserQRCodeAPI.as_view()),
path(r'v1/user/expire/', user.UserExpireAPI.as_view()),
#
# Resource group api
path(r'v1/group/', group.GroupListAPI.as_view()),
Expand Down
5 changes: 0 additions & 5 deletions apps/manager/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,6 @@ class Meta:
('yo_delete_group', u'删除应用组'),
('yo_group_sort_host', u'批量归类主机'))

def __unicode__(self):
return self.name

__str__ = __unicode__

@property
def status(self):
if self.jumper is None or self.key is None:
Expand Down
1 change: 0 additions & 1 deletion apps/ops/api/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ class OpsMetaCreateAPI(WebTokenAuthentication, generics.CreateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['META_META_CREATE'])
def create(self, request, *args, **kwargs):
if self.qrcode_check(request):
request.data.pop('qrcode')
response = super(OpsMetaCreateAPI, self).create(request, *args, **kwargs)
return self.msg.format(
USER=request.user.full_name,
Expand Down
1 change: 0 additions & 1 deletion apps/ops/api/mission.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ class OpsMissionCreateAPI(WebTokenAuthentication, generics.CreateAPIView):
@decorator_api(timeline_type=settings.TIMELINE_KEY_VALUE['Mission_MISSION_CREATE'])
def create(self, request, *args, **kwargs):
if 'qrcode' in request.data.keys() and self.request.user.check_qrcode(request.data.get('qrcode')):
request.data.pop('qrcode')
response = super(OpsMissionCreateAPI, self).create(request, *args, **kwargs)
return self.msg.format(
USER=request.user.full_name,
Expand Down
Loading

0 comments on commit 693fd8c

Please sign in to comment.