def post(self, request, *args, **kwargs): if request.data["type"] == "account": pic_captcha = request.data["pic_captcha"] key = request.data["key"] try: captcha = CaptchaStore.objects.get( challenge=pic_captcha.upper(), hashkey=key) captcha.delete() except CaptchaStore.DoesNotExist: raise ValidationError({"pic_captcha": ["验证码不正确"]}) user = authenticate(request, username=request.data["userName"], password=request.data["password"]) log_save(user=request.user.username, request=self.request, flag="登录", message=f'{request.user.username}登录成功', log_type="login") if user is not None: login(request, user) return JsonResponse({ "status": 'ok', "type": "account", "currentAuthority": "" }) else: raise ValidationError({"password": ["密码错误"]})
def create(self, request, *args, **kwargs): ret = super().create(request, args, kwargs) log_save( user=request.user.username, request=self.request, flag="新增", message= f'{self.serializer_class.Meta.model._meta.verbose_name}: {ret.data.__str__()}被新增', log_type=self.serializer_class.Meta.model._meta.model_name) return ret
def post(self, request, *args, **kwargs): if request.data["type"] == "account": pic_captcha = request.data["pic_captcha"] key = request.data["key"] try: captcha = CaptchaStore.objects.get( challenge=pic_captcha.upper(), hashkey=key) captcha.delete() except CaptchaStore.DoesNotExist: raise ValidationError({"pic_captcha": ["验证码不正确"]}) user = authenticate(request, username=request.data["userName"], password=request.data["password"]) log_save(user=request.user.username, request=self.request, flag="登录", message=f'{request.user.username}登录成功', log_type="login") if user is not None: login(request, user) return JsonResponse({ "status": 'ok', "type": "account", "currentAuthority": "" }) else: raise ValidationError({"password": ["密码错误"]}) else: # 邮箱登录 captcha = request.data["captcha"] email = request.data["email"] try: user = SysUser.objects.get(email=email) except SysUser.DoesNotExist: raise ValidationError({"email": ["邮箱不存在"]}) try: email_code = TyAdminEmailVerifyRecord.objects.get(code=captcha, email=email) if email_code.send_time + datetime.timedelta( minutes=6) < datetime.datetime.now(): email_code.delete() raise ValidationError({"captcha": ["邮箱验证码已过期"]}) else: email_code.delete() login(request, user) return JsonResponse({ "status": 'ok', "type": "account", "currentAuthority": "" }) except TyAdminEmailVerifyRecord.DoesNotExist: raise ValidationError({"captcha": ["邮箱验证码错误"]})
def change_password(self, request): data = request.data change_password = data["new_password"] change_re_password = data["re_password"] if change_password != change_re_password: raise ValidationError({"password": ["两次密码不可以不一致"]}) cur_user = SysUser.objects.get(pk=data["id"]) if cur_user is None: raise ValidationError({"username": ["用户名不存在"]}) password = make_password(change_re_password) cur_user.password = password cur_user.save() log_save(user=request.user.username, request=self.request, flag="修改", message=f'用户: {cur_user.username}密码被修改', log_type="user") serializer = self.get_serializer(cur_user) return BaseResponseData.success(data=serializer.data)
def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() data = deepcopy(request.data) del_dict = {} for key, value in request.data.items(): print(key) if isinstance(getattr(instance, key), ImageFieldFile) and isinstance(value, str): print(value) print(self.request.META['HTTP_HOST'] + settings.MEDIA_URL) pure_value = value.replace( "http://" + self.request.META['HTTP_HOST'] + settings.MEDIA_URL, "") print(pure_value) del_dict[key] = pure_value del data[key] elif isinstance(getattr(instance, key), FieldFile) and isinstance( value, str): print(value) print(self.request.META['HTTP_HOST'] + settings.MEDIA_URL) pure_value = value.replace( "http://" + self.request.META['HTTP_HOST'] + settings.MEDIA_URL, "") print(pure_value) del_dict[key] = pure_value del data[key] serializer = self.get_serializer(instance, data=data, partial=True) serializer.is_valid(raise_exception=True) for key, value in del_dict.items(): serializer.validated_data[key] = value self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = {} ret = Response(serializer.data) log_save( user=request.user.username, request=self.request, flag="更新", message= f'{self.serializer_class.Meta.model._meta.verbose_name}: {ret.data.__str__()}被更新', log_type=self.serializer_class.Meta.model._meta.model_name) return ret
def destroy(self, request, *args, **kwargs): # return Response({ # "演示模式" # },status=status.HTTP_403_FORBIDDEN) ids = kwargs["pk"].split(",") names = [] for one in self.serializer_class.Meta.model.objects.filter(id__in=ids): names.append(one.__str__()) self.serializer_class.Meta.model.objects.filter(pk__in=ids).delete() log_save( user=request.user.username, request=self.request, flag="删除", message= f'{self.serializer_class.Meta.model._meta.verbose_name}: {"".join(names)}被删除', log_type=self.serializer_class.Meta.model._meta.model_name) return Response({"code": 200})
def post(self, request, *args, **kwargs): user = authenticate(request, username=request.data["userName"], password=request.data["password"]) log_save(user=request.user.username, request=self.request, flag="登录", message=f'{request.user.username}登录成功', log_type="login") if user is not None: payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) expireTime = settings.JWT_AUTH["JWT_EXPIRATION_DELTA"] return BaseResponseData.success(data={ "token": token, "user": {"id": user.id, "name": user.username, "email": user.email, "avatar": "https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"}, "expireTime": expireTime.seconds, "userPermissions": user.get_all_permissions() }) else: raise ValidationError({"password": ["密码错误"]})
def create(self, request, *args, **kwargs): try: # data = deepcopy(request.data) # del_dict = {} self_serializer_class = self.get_serializer_class() serializer = self_serializer_class(data=request.data) serializer.is_valid(raise_exception=True) # for key, value in del_dict.items(): # serializer.validated_data[key] = value self.perform_create(serializer) headers = self.get_success_headers(serializer.data) # ret = Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) ret = BaseResponseData.success(data=serializer.data, headers=headers) log_save( user=request.user.username, request=self.request, flag="新增", message= f'{self.serializer_class.Meta.model._meta.verbose_name}: {ret.data.__str__()}被新增', log_type=self.serializer_class.Meta.model._meta.model_name) return ret except DjangoValidationError as e: raise ValidationError(e.error_dict)