async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) if self.ip is not None: log_servers = deserialize(redis.get('log_servers')) log_servers.discard(self.ip) redis.set('log_servers', serialize(log_servers))
def post(self, request): data = request.data if data: if 'token' not in data: return JsonResponse({'error': 'no token'}, status=HTTP_400_BAD_REQUEST) if 'email' not in data: return JsonResponse({'error': 'no email'}, status=HTTP_400_BAD_REQUEST) email = data['email'] user = User.objects.filter(email=email).first() if not user: return JsonResponse({'error': 'no user'}, status=HTTP_404_NOT_FOUND) key = f'VERIFY:{email}' token = redis.get(key) if not token: return JsonResponse({'error': 'no token'}, status=HTTP_404_NOT_FOUND) if token != data.get('token'): return JsonResponse({'error': 'incorrect'}, status=HTTP_400_BAD_REQUEST) user.email_verified = True user.save() del redis[key] else: if not request.user.is_authenticated: return JsonResponse({}, status=HTTP_401_UNAUTHORIZED) key = f'VERIFY:{request.user.email}' token = id_generator(size=128) redis.set(key, token, 180) # 3분 html = loader.render_to_string( 'email_verify_template.html', { 'token': token, 'email': request.user.email, 'verify_url': verify_url }) send_mail('[FreeChart] 이메일 인증 링크', '', from_email=EMAIL_HOST_SENDER, recipient_list=[request.user.email], html_message=html) return JsonResponse({})
def validate_captche(self, field): captche = field.data try: redis_captche = redis.get(self.email.data) except Exception as e: raise ValidationError(str(e)) if not redis_captche or redis_captche.decode( 'utf-8').lower() != captche.lower(): raise ValidationError('验证码输入不正确!')
async def receive(self, text_data): # print(text_data) data = json.loads(text_data) if data['type'] == 'server_info': ip = data['ip'] self.ip = ip log_servers = deserialize(redis.get('log_servers')) if not log_servers.isdisjoint([ip]): return await self.disconnect(1000) log_servers.add(ip) redis.set('log_servers', serialize(log_servers)) elif data['type'] == 'log_result': # print('at log server consumer log_result') cached_results = deserialize(redis.get(f"results-{data['uid']}")) cached_results[data['ip']] = data['result'] redis.set(f"results-{data['uid']}", serialize(cached_results), ex=r_uid_ex) await self.channel_layer.group_send('log_clients', data)
def open_lock(): """ 测试阶段 开锁接口 :return: """ open_id = request.args.get('open_id') # 用户标示 lock_id = request.args.get('lock_id') # 门锁ID,例AB code_c = request.args.get('code_c') # 门上动态码 reason = request.args.get('reason') # 开门缘由 # with app.app_context(): user = UserModel.query.filter_by(openID=open_id).first() if user: if user.has_permission(UserPermission.USER): # 检查当前用户权限 locks = user.locks lock = LocksModel.query.filter_by(lock_id=lock_id).first() if user.is_developer() or user.is_super_admin( ) or lock in locks: # 检查当前用户是否拥有当前锁的权限 检查是否为超级管理员,开发者 code_s = redis.get(lock_id) # 服务器动态码 if code_s is not None: # 防止异常处理,判断redis里面是否有内容<服务器只要不炸,这个条件都会成立> code_s = code_s.decode('utf-8') if code_s == code_c: # 判断门锁动态码是否与当前服务器上一致 lock.status = LockStatus.OPEN db.session.commit() # 记录开锁记录 log = LogsModel( # BUG已经修复 username=user.nameU, lock_id=lock_id, remark=lock.remark, reason=reason) user.logs.append(log) db.session.commit() return restful.success("开锁成功", data={'msg': '本次开锁已被记录'}) else: return restful.params_error("当前动态码已失效") else: return restful.server_error( "未提供锁ID,导致内部服务器Redis错误") # 日了狗,竟然会执行.. else: return restful.success("开锁失败,权限不足") else: return restful.params_error('无权限开锁') else: return restful.params_error('无该用户信息')
def get_token(): """ 获取token :return: json """ # grant_type = client_credential & appid = APPID & secret = APPSECRET token = redis.get('token') if token is not None: return token.decode('utf-8') else: conn = requests.get(url=Config.API_TOKEN_URL, params={ 'grant_type': 'client_credential', 'appid': Config.APP_ID, 'secret': Config.SESSION_KEY }, verify=False) json_ = json.dumps(conn.json()) token = json.loads(json_)['access_token'] redis.set('token', token, ex=240) # return token
def post(self, request): data = request.data # if request.POST: # data = request.POST # else: # data = json.loads(request.body.decode("utf-8")) if 'email' not in data: return JsonResponse({'error': 'no email'}, status=HTTP_400_BAD_REQUEST) email = data.get('email') if not User.objects.filter(email=email).exists(): return JsonResponse({'error': 'no user'}, status=HTTP_404_NOT_FOUND) key = f'RESET:{email}' tmp_key = f'TMP:{email}' if 'token' in data: token = redis.get(key) tmp_password = redis.get(tmp_key) if not token: return JsonResponse({'error': 'no token'}, status=HTTP_404_NOT_FOUND) if token != data.get('token'): return JsonResponse({'error': 'incorrect'}, status=HTTP_400_BAD_REQUEST) user = User.objects.filter(email=email).first() user.set_password(tmp_password) user.save() del redis[key] del redis[tmp_key] return HttpResponseRedirect(redirect_to=f'http://{HOST_NAME}/') else: token = id_generator(size=128) tmp_password = id_generator(size=12) redis.set(key, token, 180) # 3분 redis.set(tmp_key, tmp_password, 180) payload = '{"email": %s, "token": %s}' % (email, token) html = loader.render_to_string( 'tmp_password_template.html', { 'reset_url': reset_url, 'password': tmp_password, 'email': email, 'token': token }) send_mail('[FreeChart] 비밀번호 재설정 링크', '', from_email=EMAIL_HOST_SENDER, recipient_list=[email], html_message=html) return JsonResponse({})
def log_servers_count(request): return JsonResponse({ 'count': len(deserialize(redis.get('log_servers'))) })
def log_servers(request): context = { 'log_servers': deserialize(redis.get('log_servers')) } return render(request, 'logsearch/log_servers.html', context)
def results_cached(request, uid): results = redis.get(f"results-{uid}") if results is None: return JsonResponse({}) return JsonResponse(deserialize(results))