优化代码

publicsignpoll
youngS 3 years ago
parent 34971b792a
commit f30aafb5d9
  1. 3
      fir_client/src/components/FirDownload.vue
  2. 2
      fir_client/src/components/FirHeader.vue
  3. 3
      fir_client/src/components/FirLogin.vue
  4. 4
      fir_client/src/components/ShortDownload.vue
  5. 3
      fir_client/src/components/apps/FirAppInfosbaseinfo.vue
  6. 16
      fir_client/src/components/apps/FirApps.vue
  7. 7
      fir_client/src/components/index/FirIndexBody.vue
  8. 2
      fir_client/src/components/user/FirSuperSignBase.vue
  9. 5
      fir_client/src/components/user/FirUserOrders.vue
  10. 4
      fir_client/src/components/user/FirUserProfileCertification.vue
  11. 5
      fir_client/src/components/user/FirUserProfileInfo.vue
  12. 7
      fir_client/src/components/user/FirUserStorage.vue
  13. 2
      fir_ser/admin/views/login.py
  14. 10
      fir_ser/admin/views/order.py
  15. 12
      fir_ser/admin/views/user.py
  16. 23
      fir_ser/api/migrations/0024_auto_20211108_1755.py
  17. 3
      fir_ser/api/models.py
  18. 9
      fir_ser/api/utils/baseutils.py
  19. 36
      fir_ser/api/utils/storage/caches.py
  20. 25
      fir_ser/api/utils/utils.py
  21. 24
      fir_ser/api/views/login.py
  22. 3
      fir_ser/api/views/order.py
  23. 6
      fir_ser/fir_ser/settings.py

@ -56,7 +56,8 @@
placeholder="验证码" prefix-icon="el-icon-mobile"/> placeholder="验证码" prefix-icon="el-icon-mobile"/>
</el-col> </el-col>
<el-col :span="12"> <el-col :span="12">
<el-button plain style="margin:0 4px;border-radius:4px;cursor:pointer;height: 40px;width: 100%" type="info" <el-button plain style="margin:0 4px;border-radius:4px;cursor:pointer;height: 40px;width: 100%"
type="info"
@click="getphonecode"> @click="getphonecode">
获取验证码 获取验证码
</el-button> </el-button>

@ -91,7 +91,7 @@ export default {
this.$message.success('复制剪切板成功'); this.$message.success('复制剪切板成功');
}, },
maketoken() { maketoken() {
this.$confirm('确认重新生成新的密钥么?', '警告', { this.$confirm('该操作将导致老秘钥失效,确认重新生成新的密钥么?', '警告', {
type: 'warning' type: 'warning'
}) })
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars

@ -86,7 +86,8 @@
<el-image :src="wx_login_qr_url" style="width: 176px;height: 166px"/> <el-image :src="wx_login_qr_url" style="width: 176px;height: 166px"/>
</div> </div>
<el-button slot="reference" <el-button slot="reference"
size="small" style="color: #1fc939;border: 1px solid rgba(31,201,57,.5); width: 110px" @click="wxLogin">微信 size="small" style="color: #1fc939;border: 1px solid rgba(31,201,57,.5); width: 110px"
@click="wxLogin">微信
</el-button> </el-button>
</el-popover> </el-popover>

@ -44,7 +44,7 @@
<div class="content-row"> <div class="content-row">
<div v-if="captcha.captcha_image" class="report_captcha"> <div v-if="captcha.captcha_image" class="report_captcha">
<input v-model="report_info.authcode" maxlength="6" placeholder="请输入图片验证码" type="text"/> <input v-model="report_info.authcode" maxlength="6" placeholder="请输入图片验证码" type="text"/>
<img :src="captcha.captcha_image" @click="get_auth_code" alt="验证码"/> <img :src="captcha.captcha_image" alt="验证码" @click="get_auth_code"/>
</div> </div>
<div class="report_phone"> <div class="report_phone">
@ -119,7 +119,7 @@
<span id="qrcode" class="qrcode"></span> <span id="qrcode" class="qrcode"></span>
</div> </div>
<p v-if="currentappinfo.issupersign" class="scan-tips wrapper icon-warp">超级签</p> <p v-if="currentappinfo.issupersign" class="scan-tips wrapper icon-warp">超级签</p>
<p v-else class="scan-tips wrapper icon-warp">{{mcurrentappinfo.release_type|getiOStype}}</p> <p v-else class="scan-tips wrapper icon-warp">{{ mcurrentappinfo.release_type|getiOStype }}</p>
<h1 class="name wrapper"> <h1 class="name wrapper">
<span class="icon-warp" style="margin-left:0"> <span class="icon-warp" style="margin-left:0">
<i v-if="currentappinfo.type === 0 && agent !== ''" <i v-if="currentappinfo.type === 0 && agent !== ''"

@ -44,7 +44,8 @@
<el-form-item> <el-form-item>
<el-row> <el-row>
<el-col :span="15"> <el-col :span="15">
<el-button plain size="medium" style="width: 160px;height: 50px;font-size: large;float: right" type="primary" <el-button plain size="medium" style="width: 160px;height: 50px;font-size: large;float: right"
type="primary"
@click="saveappinfo('save')">保存信息 @click="saveappinfo('save')">保存信息
</el-button> </el-button>
</el-col> </el-col>

@ -28,7 +28,8 @@
<div class="package-actions"> <div class="package-actions">
<el-radio v-model="default_price_radio" :label="packages.name" border> <el-radio v-model="default_price_radio" :label="packages.name" border>
<span>此套餐</span> <span>此套餐</span>
<span v-if="default_price_radio === packages.name" :style="{background:`url(${pay_image.selected}) right bottom/100% no-repeat`}" <span v-if="default_price_radio === packages.name"
:style="{background:`url(${pay_image.selected}) right bottom/100% no-repeat`}"
class="pay-current"/> class="pay-current"/>
</el-radio> </el-radio>
@ -46,7 +47,8 @@
class="pay-icon alipay"/> class="pay-icon alipay"/>
<span v-if="pay.type === 'WX'" :style="{backgroundImage:`url(${pay_image.wx})`}" <span v-if="pay.type === 'WX'" :style="{backgroundImage:`url(${pay_image.wx})`}"
class="pay-icon"/> class="pay-icon"/>
<span v-if="default_pay_radio === pay.name" :style="{background:`url(${pay_image.selected}) right bottom/100% no-repeat` }" <span v-if="default_pay_radio === pay.name"
:style="{background:`url(${pay_image.selected}) right bottom/100% no-repeat` }"
class="pay-current"/> class="pay-current"/>
</span> </span>
</el-radio> </el-radio>
@ -301,12 +303,16 @@
<span v-if="currentfile&& currentfile.uid" slot="footer" class="dialog-footer"> <span v-if="currentfile&& currentfile.uid" slot="footer" class="dialog-footer">
<span v-if="uploadflag === true"> <span v-if="uploadflag === true">
{{ uploadprocess[uploadprocessList[multiFileList.indexOf(currentfile)]].speed }}/s {{ uploadprocess[uploadprocessList[multiFileList.indexOf(currentfile)]].speed }}/s
<el-progress :percentage="uploadprocess[uploadprocessList[multiFileList.indexOf(currentfile)]].process" :stroke-width="26" <el-progress
:text-inside="true"/> :percentage="uploadprocess[uploadprocessList[multiFileList.indexOf(currentfile)]].process"
:stroke-width="26"
:text-inside="true"/>
</span> </span>
<el-button v-else plain <el-button v-else plain
type="primary" type="primary"
@click="uploadcloud(analyseappinfo,currentfile,false,getappsFun)">{{ analyseappinfo.is_new|get_upload_text }}</el-button> @click="uploadcloud(analyseappinfo,currentfile,false,getappsFun)">{{
analyseappinfo.is_new|get_upload_text
}}</el-button>
</span> </span>
</el-dialog> </el-dialog>

@ -45,9 +45,10 @@
<el-main class="contactUs-container"> <el-main class="contactUs-container">
<div class="content">您身边的应用托管分发专家</div> <div class="content">您身边的应用托管分发专家</div>
<div class="content">7x24小时提供出色的不间断服务</div> <div class="content">7x24小时提供出色的不间断服务</div>
<el-button onmouseenter="this.style.backgroundColor='transparent'; this.style.borderColor='#ffffff'; this.style.color='#ffffff';" <el-button
onmouseleave="this.style.borderColor='#ffffff'; this.style.backgroundColor='#ffffff'; this.style.color='#3f3f3f';" onmouseenter="this.style.backgroundColor='transparent'; this.style.borderColor='#ffffff'; this.style.color='#ffffff';"
@click="$router.push({name:'FirContact'})" onmouseleave="this.style.borderColor='#ffffff'; this.style.backgroundColor='#ffffff'; this.style.color='#3f3f3f';"
@click="$router.push({name:'FirContact'})"
>联系我们 >联系我们
</el-button> </el-button>
<div class="contactUs-contactWay"> <div class="contactUs-contactWay">

@ -593,7 +593,7 @@
align="center" align="center"
label="设备名称" label="设备名称"
prop="product" prop="product"
width="200"> width="160">
</el-table-column> </el-table-column>
<el-table-column <el-table-column

@ -132,6 +132,7 @@
style="width: 100%"> style="width: 100%">
<el-table-column <el-table-column
align="center"
fixed fixed
label="系统订单ID" label="系统订单ID"
prop="order_number"> prop="order_number">
@ -172,6 +173,7 @@
<el-table-column <el-table-column
:formatter="format_actual_amount" :formatter="format_actual_amount"
align="center"
label="实付金额" label="实付金额"
prop="actual_amount" prop="actual_amount"
width="100"> width="100">
@ -179,12 +181,14 @@
<el-table-column <el-table-column
align="center"
label="购买数量" label="购买数量"
prop="actual_download_times" prop="actual_download_times"
width="120"> width="120">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
label="赠送数量" label="赠送数量"
prop="actual_download_gift_times" prop="actual_download_gift_times"
width="90"> width="90">
@ -207,6 +211,7 @@
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
fixed="right" fixed="right"
label="查看详细" label="查看详细"
width="145"> width="145">

@ -130,7 +130,9 @@
placeholder="请输入您收到的验证码" prefix-icon="el-icon-mobile"/> placeholder="请输入您收到的验证码" prefix-icon="el-icon-mobile"/>
</el-col> </el-col>
<el-col :span="6"> <el-col :span="6">
<el-button plain style="border-radius:4px;cursor:pointer;height: 40px;background-color: #ecf5ff;color: #dd6161" type="info" <el-button plain
style="border-radius:4px;cursor:pointer;height: 40px;background-color: #ecf5ff;color: #dd6161"
type="info"
@click="getsmsemailcode('sms',form.mobile)"> @click="getsmsemailcode('sms',form.mobile)">
获取验证码 获取验证码
</el-button> </el-button>

@ -247,8 +247,9 @@
</el-row> </el-row>
</el-form-item> </el-form-item>
<div v-if="userinfo && userinfo.login_type && userinfo.login_type.third && JSON.stringify(userinfo.login_type.third).indexOf('true')!==-1" <div
class="other-way"> v-if="userinfo && userinfo.login_type && userinfo.login_type.third && JSON.stringify(userinfo.login_type.third).indexOf('true')!==-1"
class="other-way">
<hr> <hr>
<span class="info">绑定第三方账户</span> <span class="info">绑定第三方账户</span>
<el-row v-if="userinfo.login_type.third && userinfo.login_type.third.wxp" :gutter="20"> <el-row v-if="userinfo.login_type.third && userinfo.login_type.third.wxp" :gutter="20">

@ -175,21 +175,25 @@
style="width: 100%"> style="width: 100%">
<el-table-column <el-table-column
align="center"
fixed fixed
label="存储名称" label="存储名称"
prop="name" prop="name"
width="180"> width="180">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
label="存储类型" label="存储类型"
prop="storage_type_display" prop="storage_type_display"
width="100"> width="100">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
label="下载域名" label="下载域名"
prop="domain_name"> prop="domain_name">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
label="bucket_name" label="bucket_name"
prop="bucket_name" prop="bucket_name"
width="130"> width="130">
@ -197,15 +201,18 @@
<el-table-column <el-table-column
:formatter="formatter" :formatter="formatter"
align="center"
label="修改时间" label="修改时间"
prop="updated_time" prop="updated_time"
width="170"> width="170">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
label="备注" label="备注"
prop="description"> prop="description">
</el-table-column> </el-table-column>
<el-table-column <el-table-column
align="center"
fixed="right" fixed="right"
label="操作" label="操作"
width="120"> width="120">

@ -41,7 +41,7 @@ class LoginView(APIView):
if user.is_active: if user.is_active:
if user.role == 3: if user.role == 3:
login_auth_failed("del", username) login_auth_failed("del", username)
key, user_info = set_user_token(user) key, user_info = set_user_token(user, request)
response.data = { response.data = {
"username": user_info.username, "username": user_info.username,
"token": key "token": key

@ -15,8 +15,7 @@ from api.utils.auth import AdminTokenAuthentication
from api.utils.baseutils import get_dict_from_filter_fields from api.utils.baseutils import get_dict_from_filter_fields
from api.utils.response import BaseResponse from api.utils.response import BaseResponse
from api.utils.serializer import AdminOrdersSerializer from api.utils.serializer import AdminOrdersSerializer
from api.utils.storage.caches import update_order_info from api.utils.storage.caches import update_order_info, admin_change_user_download_times
from api.utils.utils import get_order_num
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -95,12 +94,7 @@ class OrderInfoView(APIView):
obj = UserInfo.objects.filter(pk=pk).first() obj = UserInfo.objects.filter(pk=pk).first()
if obj: if obj:
if amount > 0: if amount > 0:
order_number = get_order_num() if admin_change_user_download_times(obj, amount):
order_obj = Order.objects.create(payment_type=2, order_number=order_number, payment_number=order_number,
user_id=obj, status=1, order_type=1, actual_amount=0,
actual_download_times=amount, payment_name='后台管理员充值',
actual_download_gift_times=0)
if update_order_info(obj.pk, order_obj.order_number, order_obj.order_number, order_obj.payment_type):
return Response(res.dict) return Response(res.dict)
else: else:
res.code = 1005 res.code = 1005

@ -15,6 +15,8 @@ from api.utils.auth import AdminTokenAuthentication
from api.utils.baseutils import get_dict_from_filter_fields from api.utils.baseutils import get_dict_from_filter_fields
from api.utils.response import BaseResponse from api.utils.response import BaseResponse
from api.utils.serializer import AdminUserInfoSerializer, AdminUserCertificationSerializer, AdminThirdWxSerializer from api.utils.serializer import AdminUserInfoSerializer, AdminUserCertificationSerializer, AdminThirdWxSerializer
from api.utils.storage.caches import auth_user_download_times_gift
from fir_ser.settings import AUTH_USER_GIVE_DOWNLOAD_TIMES
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -65,7 +67,12 @@ class UserInfoView(APIView):
users_serializer.save() users_serializer.save()
certification = data.get("certification", None) certification = data.get("certification", None)
if certification and certification != -1: if certification and certification != -1:
UserCertificationInfo.objects.filter(user_id=user_obj).update(status=data["certification"]) user_cert_obj = UserCertificationInfo.objects.filter(user_id=user_obj).first()
if user_cert_obj:
status = user_cert_obj.status
UserCertificationInfo.objects.filter(user_id=user_obj).update(status=data["certification"])
if status != 1 and UserCertificationInfo.objects.filter(user_id=user_obj).first().status == 1:
auth_user_download_times_gift(user_obj, AUTH_USER_GIVE_DOWNLOAD_TIMES)
res.data = users_serializer.data res.data = users_serializer.data
return Response(res.dict) return Response(res.dict)
res.code = 1004 res.code = 1004
@ -101,9 +108,12 @@ class UserCertificationInfoView(APIView):
obj = UserCertificationInfo.objects.filter(id=pk).first() obj = UserCertificationInfo.objects.filter(id=pk).first()
if obj: if obj:
data['pk'] = pk data['pk'] = pk
status = obj.status
users_serializer = AdminUserCertificationSerializer(obj, data=data, partial=True) users_serializer = AdminUserCertificationSerializer(obj, data=data, partial=True)
if users_serializer.is_valid(): if users_serializer.is_valid():
users_serializer.save() users_serializer.save()
if status != 1 and users_serializer.data.get('status') == 1:
auth_user_download_times_gift(obj.user_id, AUTH_USER_GIVE_DOWNLOAD_TIMES)
res.data = users_serializer.data res.data = users_serializer.data
return Response(res.dict) return Response(res.dict)
res.code = 1004 res.code = 1004

@ -0,0 +1,23 @@
# Generated by Django 3.2.3 on 2021-11-08 17:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0023_remove_appudid_binary_file'),
]
operations = [
migrations.AddField(
model_name='token',
name='remote_addr',
field=models.GenericIPAddressField(blank=True, null=True, verbose_name='远程IP地址'),
),
migrations.AlterField(
model_name='order',
name='order_type',
field=models.SmallIntegerField(choices=[(0, '用户下单'), (1, '后台充值'), (2, '系统赠送')], default=0, verbose_name='订单类型'),
),
]

@ -92,6 +92,7 @@ class Token(models.Model):
UserInfo, related_name='auth_token', UserInfo, related_name='auth_token',
on_delete=models.CASCADE, verbose_name="关联用户" on_delete=models.CASCADE, verbose_name="关联用户"
) )
remote_addr = models.GenericIPAddressField(verbose_name="远程IP地址",null=True,blank=True)
created = models.DateTimeField(verbose_name="创建时间", auto_now_add=True) created = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
def __str__(self): def __str__(self):
@ -389,7 +390,7 @@ class Order(models.Model):
actual_download_gift_times = models.BigIntegerField(verbose_name="实际赠送的数量", default=0) actual_download_gift_times = models.BigIntegerField(verbose_name="实际赠送的数量", default=0)
status_choices = ((0, '交易成功'), (1, '待支付'), (2, '订单已创建'), (3, '退费申请中'), (4, '已退费'), (5, '主动取消'), (6, '超时取消')) status_choices = ((0, '交易成功'), (1, '待支付'), (2, '订单已创建'), (3, '退费申请中'), (4, '已退费'), (5, '主动取消'), (6, '超时取消'))
status = models.SmallIntegerField(choices=status_choices, verbose_name="状态") status = models.SmallIntegerField(choices=status_choices, verbose_name="状态")
order_type_choices = ((0, '用户下单'), (1, '后台充值'),) order_type_choices = ((0, '用户下单'), (1, '后台充值'), (2, '系统赠送'))
order_type = models.SmallIntegerField(choices=order_type_choices, default=0, verbose_name="订单类型") order_type = models.SmallIntegerField(choices=order_type_choices, default=0, verbose_name="订单类型")
pay_time = models.DateTimeField(blank=True, null=True, verbose_name="付款时间") pay_time = models.DateTimeField(blank=True, null=True, verbose_name="付款时间")
cancel_time = models.DateTimeField(blank=True, null=True, verbose_name="订单取消时间") cancel_time = models.DateTimeField(blank=True, null=True, verbose_name="订单取消时间")

@ -12,6 +12,7 @@ import os
import re import re
import time import time
import uuid import uuid
import random
from Crypto import Random from Crypto import Random
from Crypto.Cipher import AES from Crypto.Cipher import AES
@ -291,3 +292,11 @@ def format_get_uri(domain, short, data):
if uri: if uri:
uri = '?' + uri[1:] uri = '?' + uri[1:]
return f'{domain}/{short}{uri}' return f'{domain}/{short}{uri}'
def get_order_num(order_type=1):
now = datetime.datetime.now()
date_str = "{0}{1}{2}{3}{4}{5}{6}".format(order_type, now.year, now.month, now.day, now.hour, now.minute,
now.second)
return date_str + str(random.randint(1000, 9999)) + str(random.randint(1000, 9999)) + str(
random.randint(1000, 9999))

@ -14,7 +14,7 @@ from django.utils import timezone
from api.models import Apps, UserInfo, AppReleaseInfo, AppUDID, APPToDeveloper, APPSuperSignUsedInfo, \ from api.models import Apps, UserInfo, AppReleaseInfo, AppUDID, APPToDeveloper, APPSuperSignUsedInfo, \
UserCertificationInfo, Order UserCertificationInfo, Order
from api.utils.baseutils import check_app_password from api.utils.baseutils import check_app_password, get_order_num
from api.utils.modelutils import get_app_d_count_by_app_id, get_app_domain_name, get_user_domain_name from api.utils.modelutils import get_app_d_count_by_app_id, get_app_domain_name, get_user_domain_name
from api.utils.storage.storage import Storage, LocalStorage from api.utils.storage.storage import Storage, LocalStorage
from fir_ser.settings import CACHE_KEY_TEMPLATE, SERVER_DOMAIN, SYNC_CACHE_TO_DATABASE, DEFAULT_MOBILEPROVISION, \ from fir_ser.settings import CACHE_KEY_TEMPLATE, SERVER_DOMAIN, SYNC_CACHE_TO_DATABASE, DEFAULT_MOBILEPROVISION, \
@ -430,7 +430,7 @@ def update_order_status(out_trade_no, status):
order_obj.save(update_fields=['status']) order_obj.save(update_fields=['status'])
def update_order_info(user_id, out_trade_no, payment_number, payment_type): def update_order_info(user_id, out_trade_no, payment_number, payment_type, description=None):
with cache.lock("%s_%s" % ('user_order_', out_trade_no), timeout=10, blocking_timeout=6): with cache.lock("%s_%s" % ('user_order_', out_trade_no), timeout=10, blocking_timeout=6):
try: try:
user_obj = UserInfo.objects.filter(pk=user_id).first() user_obj = UserInfo.objects.filter(pk=user_id).first()
@ -446,7 +446,10 @@ def update_order_info(user_id, out_trade_no, payment_number, payment_type):
if not timezone.is_naive(now): if not timezone.is_naive(now):
now = timezone.make_naive(now, timezone.utc) now = timezone.make_naive(now, timezone.utc)
order_obj.pay_time = now order_obj.pay_time = now
order_obj.description = "充值成功,充值下载次数 %s ,现共可用次数 %s" % ( default_description = "充值成功,充值下载次数 %s ,现共可用次数 %s"
if description:
default_description = description
order_obj.description = default_description % (
download_times, user_obj.download_times + download_times) download_times, user_obj.download_times + download_times)
order_obj.save( order_obj.save(
update_fields=["status", "payment_type", "payment_number", "pay_time", update_fields=["status", "payment_type", "payment_number", "pay_time",
@ -523,3 +526,30 @@ class MigrateStorageState(CacheBaseState):
class CleanSignDataState(CacheBaseState): class CleanSignDataState(CacheBaseState):
... ...
def add_download_times_free_base(user_obj, amount, payment_name, description, order_type=1):
order_number = get_order_num()
order_obj = Order.objects.create(payment_type=2, order_number=order_number, payment_number=order_number,
user_id=user_obj, status=1, order_type=order_type, actual_amount=0,
actual_download_times=amount, payment_name=payment_name,
actual_download_gift_times=0)
if update_order_info(user_obj.pk, order_obj.order_number, order_obj.order_number, order_obj.payment_type,
description):
return True
return False
def new_user_download_times_gift(user_obj, amount=200):
description = '新用户赠送下载次数 %s ,现共可用次数 %s'
return add_download_times_free_base(user_obj, amount, '系统', description, 2)
def admin_change_user_download_times(user_obj, amount=200):
description = '后台管理员充值下载次数 %s ,现共可用次数 %s'
return add_download_times_free_base(user_obj, amount, '后台管理员充值', description)
def auth_user_download_times_gift(user_obj, amount=200):
description = '实名认证赠送充值下载次数 %s ,现共可用次数 %s'
return add_download_times_free_base(user_obj, amount, '系统', description, 2)

@ -17,6 +17,7 @@ from api.models import APPSuperSignUsedInfo, APPToDeveloper, \
UDIDsyncDeveloper, UserInfo, AppReleaseInfo, AppScreenShot, Token, DeveloperDevicesID, UserAdDisplayInfo UDIDsyncDeveloper, UserInfo, AppReleaseInfo, AppScreenShot, Token, DeveloperDevicesID, UserAdDisplayInfo
from api.utils.TokenManager import generate_numeric_token_of_length, generate_alphanumeric_token_of_length, make_token, \ from api.utils.TokenManager import generate_numeric_token_of_length, generate_alphanumeric_token_of_length, make_token, \
verify_token verify_token
from api.utils.baseutils import get_real_ip_address
from api.utils.modelutils import get_app_d_count_by_app_id from api.utils.modelutils import get_app_d_count_by_app_id
from api.utils.sendmsg.sendmsg import SendMessage from api.utils.sendmsg.sendmsg import SendMessage
from api.utils.storage.caches import consume_user_download_times from api.utils.storage.caches import consume_user_download_times
@ -289,14 +290,6 @@ def clean_storage_data(user_obj, storage_obj=None):
return True return True
def get_order_num(order_type=1):
now = datetime.datetime.now()
date_str = "{0}{1}{2}{3}{4}{5}{6}".format(order_type, now.year, now.month, now.day, now.hour, now.minute,
now.second)
return date_str + str(random.randint(1000, 9999)) + str(random.randint(1000, 9999)) + str(
random.randint(1000, 9999))
def get_choices_dict(choices): def get_choices_dict(choices):
result = [] result = []
choices_org_list = list(choices) choices_org_list = list(choices)
@ -313,11 +306,23 @@ def get_choices_name_from_key(choices, key):
return '' return ''
def set_user_token(user_obj): def set_user_token(user_obj, request):
key = binascii.hexlify(os.urandom(32)).decode() key = binascii.hexlify(os.urandom(32)).decode()
now = datetime.datetime.now() now = datetime.datetime.now()
user_info = UserInfo.objects.get(pk=user_obj.pk) user_info = UserInfo.objects.get(pk=user_obj.pk)
auth_key = "_".join([CACHE_KEY_TEMPLATE.get('user_auth_token_key'), key]) auth_key = "_".join([CACHE_KEY_TEMPLATE.get('user_auth_token_key'), key])
cache.set(auth_key, {'uid': user_info.uid, 'username': user_info.username}, 3600 * 24 * 7) cache.set(auth_key, {'uid': user_info.uid, 'username': user_info.username}, 3600 * 24 * 7)
Token.objects.create(user=user_obj, **{"access_token": key, "created": now}) Token.objects.create(user=user_obj,
**{"access_token": key, "created": now, "remote_addr": get_real_ip_address(request)})
return key, user_info return key, user_info
def clean_user_token_and_cache(user_obj, white_token_list=None):
if white_token_list is None:
white_token_list = []
for token_obj in Token.objects.filter(user=user_obj):
if token_obj.access_token in white_token_list:
continue
auth_key = "_".join([CACHE_KEY_TEMPLATE.get('user_auth_token_key'), token_obj.access_token])
cache.delete(auth_key)
token_obj.delete()

@ -13,12 +13,13 @@ from api.utils.modelutils import get_min_default_domain_cname_obj, add_remote_in
from api.utils.mp.wechat import make_wx_login_qrcode, show_qrcode_url from api.utils.mp.wechat import make_wx_login_qrcode, show_qrcode_url
from api.utils.response import BaseResponse from api.utils.response import BaseResponse
from api.utils.serializer import UserInfoSerializer, CertificationSerializer, UserCertificationSerializer from api.utils.serializer import UserInfoSerializer, CertificationSerializer, UserCertificationSerializer
from api.utils.storage.caches import login_auth_failed, set_wx_ticket_login_info_cache, get_wx_ticket_login_info_cache from api.utils.storage.caches import login_auth_failed, set_wx_ticket_login_info_cache, get_wx_ticket_login_info_cache, \
new_user_download_times_gift
from api.utils.throttle import VisitRegister1Throttle, VisitRegister2Throttle, GetAuthC1Throttle, GetAuthC2Throttle from api.utils.throttle import VisitRegister1Throttle, VisitRegister2Throttle, GetAuthC1Throttle, GetAuthC2Throttle
from api.utils.utils import get_captcha, valid_captcha, \ from api.utils.utils import get_captcha, valid_captcha, \
get_sender_sms_token, is_valid_sender_code, get_sender_email_token, get_random_username, \ get_sender_sms_token, is_valid_sender_code, get_sender_email_token, get_random_username, \
check_username_exists, set_user_token check_username_exists, set_user_token, clean_user_token_and_cache
from fir_ser.settings import REGISTER, LOGIN, CHANGER, REPORT from fir_ser.settings import REGISTER, LOGIN, CHANGER, REPORT, NEW_USER_GIVE_DOWNLOAD_TIMES
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -36,9 +37,7 @@ def reset_user_pwd(user, sure_password, old_password=''):
user.set_password(sure_password) user.set_password(sure_password)
user.save(update_fields=["password"]) user.save(update_fields=["password"])
logger.info(f"user:{user} change password success,old {old_password} new {sure_password}") logger.info(f"user:{user} change password success,old {old_password} new {sure_password}")
for token_obj in Token.objects.filter(user=user): clean_user_token_and_cache(user)
cache.delete(token_obj.access_token)
token_obj.delete()
def get_authenticate(target, password, act, allow_type): def get_authenticate(target, password, act, allow_type):
@ -328,7 +327,7 @@ class LoginView(APIView):
if user.is_active: if user.is_active:
login_auth_failed("del", username) login_auth_failed("del", username)
# update the token # update the token
key, user_info = set_user_token(user) key, user_info = set_user_token(user, request)
serializer = UserInfoSerializer(user_info, ) serializer = UserInfoSerializer(user_info, )
data = serializer.data data = serializer.data
response.msg = "验证成功!" response.msg = "验证成功!"
@ -438,6 +437,10 @@ class RegistView(APIView):
response.msg = "注册异常" response.msg = "注册异常"
response.code = 1000 response.code = 1000
if user_obj: if user_obj:
try:
new_user_download_times_gift(user_obj, NEW_USER_GIVE_DOWNLOAD_TIMES)
except Exception as e:
logger.error(f"用户{user_obj}赠送下载次数失败{e}")
response.msg = "注册成功" response.msg = "注册成功"
response.code = 1000 response.code = 1000
else: else:
@ -524,10 +527,7 @@ class UserInfoView(APIView):
logger.info(f"user:{request.user} change password success,old {old_password} new {sure_password}") logger.info(f"user:{request.user} change password success,old {old_password} new {sure_password}")
auth_token = request.auth auth_token = request.auth
for token_obj in Token.objects.filter(user=user): clean_user_token_and_cache(user, [auth_token])
if token_obj.access_token != auth_token:
cache.delete(token_obj.access_token)
token_obj.delete()
return Response(res.dict) return Response(res.dict)
else: else:
@ -844,7 +844,7 @@ class WeChatLoginCheckView(APIView):
else: else:
user = UserInfo.objects.filter(pk=wx_ticket_data['pk']).first() user = UserInfo.objects.filter(pk=wx_ticket_data['pk']).first()
if user.is_active: if user.is_active:
key, user_info = set_user_token(user) key, user_info = set_user_token(user, request)
serializer = UserInfoSerializer(user_info) serializer = UserInfoSerializer(user_info)
data = serializer.data data = serializer.data
ret.msg = "验证成功!" ret.msg = "验证成功!"

@ -12,11 +12,12 @@ from rest_framework.views import APIView
from api.models import Price, Order from api.models import Price, Order
from api.utils.auth import ExpiringTokenAuthentication from api.utils.auth import ExpiringTokenAuthentication
from api.utils.baseutils import get_order_num
from api.utils.pay.util import get_pay_obj_form_name, get_enable_pay_choices, get_payment_type from api.utils.pay.util import get_pay_obj_form_name, get_enable_pay_choices, get_payment_type
from api.utils.response import BaseResponse from api.utils.response import BaseResponse
from api.utils.serializer import PriceSerializer, OrdersSerializer from api.utils.serializer import PriceSerializer, OrdersSerializer
from api.utils.storage.caches import update_order_status from api.utils.storage.caches import update_order_status
from api.utils.utils import get_order_num, get_choices_dict from api.utils.utils import get_choices_dict
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)

@ -219,8 +219,10 @@ CACHE_KEY_TEMPLATE = {
DATA_DOWNLOAD_KEY = "d_token" DATA_DOWNLOAD_KEY = "d_token"
FILE_UPLOAD_TMP_KEY = ".tmp" FILE_UPLOAD_TMP_KEY = ".tmp"
USER_FREE_DOWNLOAD_TIMES = 20 USER_FREE_DOWNLOAD_TIMES = 5
AUTH_USER_FREE_DOWNLOAD_TIMES = 60 AUTH_USER_FREE_DOWNLOAD_TIMES = 10
NEW_USER_GIVE_DOWNLOAD_TIMES = 100
AUTH_USER_GIVE_DOWNLOAD_TIMES = 200
SYNC_CACHE_TO_DATABASE = { SYNC_CACHE_TO_DATABASE = {
'download_times': 10, # 下载次数同步时间 'download_times': 10, # 下载次数同步时间

Loading…
Cancel
Save