def to_arr(): """ 硬件下位机获取二维码 """ # return '<' lock_id = request.args.get('lock_id')[:2] code = tools.random_str(6) # 获取随机六位数字码 redis.set(lock_id, code, ex=60) data = { 'page': 'pages/lock/lock', 'scene': lock_id + '_' + code, # 此处踏坑不使用“=”分割,改用“_” 'width': '280' } conn = requests.post(url=config.API_QR_URL + get_token(), data=json.dumps(data), verify=False) qr_file_name = "static/images/qr/" + lock_id + ".png" with open(qr_file_name, 'wb') as f: # 保存二维码 f.write(conn.content) image_aspect(qr_file_name, 128, 128). \ change_aspect_rate(). \ past_background(). \ save_result(qr_file_name) if img_to_arr(qr_file_name): return '{' + img_to_arr(qr_file_name) + '}' else: return '<' # 直接返回空<,交给硬件下位机处理,让其再次请求
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({})
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 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 login(user: User, response_class=ORJSONResponse): [username, passwd] = map(user.dict().get, ['username', 'password']) try: db_user = db.user.find_one({'username': username}) assert db_user pwhash = db_user['password'] passwd_check = check_password_hash(pwhash, passwd) assert passwd_check token = tools.new_token(20) uid = str(db_user['_id']) redis.set(token, uid) return { 'ok': True, 'data': { 'token': token, 'username': username, 'id': uid } } except Exception as e: print(e) return {'ok': False, 'msg': '用户名或密码错误!'}
def send_email(): email = request.args.get('email') if email: strnum = list(string.ascii_letters) num = map(lambda x:str(x),range(10)) strnum.extend(num) captche = "".join(random.sample(strnum,6)) try: send_mail.delay('Python论坛邮箱验证码', [email], '您的验证码是:%s' % captche) redis.set(email, captche, 120) return restful.success('邮件发送成功!') except Exception as e: return restful.server_error(str(e)) # message = Message('后台邮箱验证码',body='你的验证码是:'+captche,recipients=[email]) # try: # mail.send(message) # redis.set(email,captche,120) # return restful.success('邮件发送成功!') # except Exception as e: # return restful.server_error(str(e)) # pass else: return restful.params_error('请输入邮箱地址!')
async def log_query(self, event): # TODO covert everything to json # here send_json redis.set(f"results-{event['uid']}", serialize({})) await self.send(json.dumps(event))
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({})