ShopifyController.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. import re
  2. from datetime import datetime
  3. import concurrent.futures
  4. import pytz
  5. import requests
  6. from django.db.models import Q, F
  7. from django.views import View
  8. from Crypto.Cipher import AES
  9. from Crypto.Util.Padding import pad
  10. from django.contrib.auth.hashers import check_password, make_password
  11. import concurrent.futures
  12. from Controller.CheckUserData import DataValid
  13. from Model.models import Device_User, CountryModel, LanguageModel, CountryLanguageModel
  14. from Object.RedisObject import RedisObject
  15. from Object.ResponseObject import ResponseObject
  16. import base64
  17. import hmac
  18. import hashlib
  19. import os
  20. import json
  21. from Ansjer.config import SHOPIFY_CONFIG, CONFIG_INFO, CONFIG_EUR, CONFIG_US
  22. from Service.CommonService import CommonService
  23. class ShopifyMultipass:
  24. @staticmethod
  25. def generate_multipass_token(secret, customer_data):
  26. """
  27. 使用指定的密钥对加密并签名JSON数据,返回Base64编码的Multipass令牌
  28. """
  29. # 第一步:将客户数据转换为JSON格式
  30. json_data = json.dumps(customer_data)
  31. # 第二步:生成加密密钥和签名密钥
  32. hash_digest = hashlib.sha256(secret.encode()).digest()
  33. encryption_key = hash_digest[:16] # 128位加密密钥
  34. signature_key = hash_digest[16:32] # 128位签名密钥
  35. # 第三步:加密JSON数据
  36. iv = os.urandom(16) # 随机初始化向量
  37. cipher = AES.new(encryption_key, AES.MODE_CBC, iv)
  38. ciphertext = cipher.encrypt(pad(json_data.encode(), AES.block_size))
  39. # 第四步:签名加密数据
  40. data_to_sign = iv + ciphertext
  41. signature = hmac.new(signature_key, data_to_sign, hashlib.sha256).digest()
  42. # 第五步:Base64编码
  43. multipass_token = base64.urlsafe_b64encode(iv + ciphertext + signature).decode()
  44. return multipass_token
  45. @staticmethod
  46. def search_customer_by_email(store_name, access_token, email):
  47. # 设置请求URL
  48. url = f"https://{store_name}.myshopify.com/admin/api/2024-10/customers/search.json"
  49. params = {
  50. "query": f"email:{email}"
  51. }
  52. # 设置请求头
  53. headers = {
  54. "X-Shopify-Access-Token": access_token,
  55. }
  56. # 发送GET请求
  57. response = requests.get(url, headers=headers, params=params)
  58. # 返回响应的JSON数据
  59. return response.json()
  60. class ShopifyView(View):
  61. def get(self, request, *args, **kwargs):
  62. request.encoding = 'utf-8'
  63. operation = kwargs.get('operation')
  64. request_dict = request.GET
  65. return self.validation(request, request_dict, operation)
  66. def post(self, request, *args, **kwargs):
  67. request.encoding = 'utf-8'
  68. operation = kwargs.get('operation')
  69. request_dict = request.POST
  70. return self.validation(request, request_dict, operation)
  71. def validation(self, request, request_dict, operation):
  72. language = request_dict.get('language', 'cn')
  73. response = ResponseObject(language, "pc")
  74. if operation == 'shopifyLogin':
  75. return self.shopify_login(request_dict, response)
  76. elif operation == 'shopifyRegister':
  77. return self.shopify_register(request_dict, response)
  78. # 查询FAPP注册账号情况
  79. elif operation == 'searchCustomer':
  80. return self.search_customer(request_dict, response)
  81. # 官网检测账号接口
  82. elif operation == 'searchAccount':
  83. return self.search_account(request_dict, response)
  84. elif operation == 'getCountryDomainList':
  85. return self.get_country_domain_list(request_dict, response)
  86. # 忘记密码
  87. elif operation == 'shopifyChangePassword':
  88. return self.shopify_change_password(request_dict, response)
  89. elif operation == 'verifyAuthcode':
  90. return self.verify_authcode(request_dict, response)
  91. else:
  92. return response.json(414)
  93. @staticmethod
  94. def shopify_login(request_dict, response):
  95. email = request_dict.get("email", None)
  96. password = request_dict.get("password", None)
  97. account_iso2 = request_dict.get("accountCountry", None)
  98. shopify_country = request_dict.get("shopifyCountry", "")
  99. if not all([email, password, account_iso2]):
  100. return response.json(444)
  101. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  102. if not user_qs.exists():
  103. return response.json(104)
  104. users = user_qs.values(
  105. 'role__rid', 'role__roleName', 'userID', 'NickName',
  106. 'username', 'userEmail', 'phone', 'password', 'userIconPath'
  107. )[0]
  108. if not check_password(password, users['password']):
  109. return response.json(111)
  110. # 获取当前时间并格式化时间戳
  111. now = datetime.now(pytz.timezone('America/New_York'))
  112. timestamp = now.strftime('%Y-%m-%dT%H:%M:%S%z')
  113. timestamp = timestamp[:-2] + ':' + timestamp[-2:]
  114. customer_data = {
  115. "email": email,
  116. "created_at": timestamp,
  117. }
  118. # 根据条件选择配置键
  119. if shopify_country:
  120. secret_key = f"{shopify_country}_multipass_secret"
  121. store_name_key = f"{shopify_country}_store_name"
  122. elif account_iso2 == "jp":
  123. secret_key = "jp_multipass_secret"
  124. store_name_key = "jp_store_name"
  125. elif account_iso2 == "de":
  126. secret_key = "de_multipass_secret"
  127. store_name_key = "de_store_name"
  128. elif account_iso2 == "uk":
  129. secret_key = "uk_multipass_secret"
  130. store_name_key = "uk_store_name"
  131. elif CONFIG_INFO == CONFIG_EUR:
  132. secret_key = "eu_multipass_secret"
  133. store_name_key = "eu_store_name"
  134. elif CONFIG_INFO == CONFIG_US:
  135. secret_key = "us_multipass_secret"
  136. multipass_secret = SHOPIFY_CONFIG[secret_key]
  137. token = ShopifyMultipass.generate_multipass_token(multipass_secret, customer_data)
  138. redirect_url = f"https://www.zositech.com/account/login/multipass/{token}"
  139. return response.json(0, redirect_url)
  140. else:
  141. return response.json(444)
  142. # 获取配置并生成重定向URL
  143. multipass_secret = SHOPIFY_CONFIG[secret_key]
  144. store_name = SHOPIFY_CONFIG[store_name_key]
  145. token = ShopifyMultipass.generate_multipass_token(multipass_secret, customer_data)
  146. redirect_url = f"https://{store_name}.zositech.com/account/login/multipass/{token}"
  147. return response.json(0, redirect_url)
  148. @staticmethod
  149. def shopify_register(request_dict, response):
  150. email = request_dict.get("email", None)
  151. password = request_dict.get("password", None)
  152. authcode = request_dict.get("authCode", None)
  153. if not all([email, password, authcode]):
  154. return response.json(444)
  155. data_valid = DataValid()
  156. if data_valid.email_validate(email) is not True:
  157. return response.json(105)
  158. re_flag = data_valid.password_validate(password)
  159. has_upper = bool(re.search(r"[A-Z]", password)) # 大写字母
  160. has_lower = bool(re.search(r"[a-z]", password)) # 小写字母
  161. has_digit = bool(re.search(r"[0-9]", password)) # 数字
  162. has_special = bool(re.search(r"[!@#$%^&*()_+\-=\[\]{}|;:'\",.<>?/]", password)) # 特殊字符
  163. # 至少包含任意两类字符
  164. categories = sum([has_upper, has_lower, has_digit, has_special])
  165. if re_flag is not True and categories > 2:
  166. return response.json(109)
  167. reds = RedisObject()
  168. identifyingCode = reds.get_data(key=email + '_identifyingCode')
  169. # 判断验证码是否过期
  170. if identifyingCode is False:
  171. return response.json(120)
  172. # 验证码是否正确
  173. if authcode != identifyingCode:
  174. return response.json(121)
  175. # 注册
  176. if Device_User.objects.filter(Q(username=email) | Q(userEmail=email)).exists():
  177. return response.json(103)
  178. # 创建用户
  179. password = make_password(password)
  180. new_userID = CommonService.getUserID(μs=False, setOTAID=True)
  181. user_data = {
  182. "username": email,
  183. "NickName": email,
  184. "userEmail": email,
  185. "password": password,
  186. "userID": new_userID,
  187. "is_active": True,
  188. "user_isValid": True,
  189. }
  190. Device_User.objects.create(**user_data)
  191. reds.del_data(key=email + '_identifyingCode')
  192. return response.json(0)
  193. def search_account(self, request_dict, response):
  194. email = request_dict.get("email")
  195. if not email:
  196. return response.json(444)
  197. store_configs = [
  198. ("us", SHOPIFY_CONFIG["us_store_name"], SHOPIFY_CONFIG["us_token"]),
  199. ("eu", SHOPIFY_CONFIG["eu_store_name"], SHOPIFY_CONFIG["eu_token"]),
  200. ("de", SHOPIFY_CONFIG["de_store_name"], SHOPIFY_CONFIG["de_token"]),
  201. ("uk", SHOPIFY_CONFIG["uk_store_name"], SHOPIFY_CONFIG["uk_token"]),
  202. ("jp", SHOPIFY_CONFIG["jp_store_name"], SHOPIFY_CONFIG["jp_token"]),
  203. ]
  204. def search_customer(store_name, token):
  205. return ShopifyMultipass.search_customer_by_email(store_name, token, email)
  206. try:
  207. shopify_results = {}
  208. with concurrent.futures.ThreadPoolExecutor() as executor:
  209. future_to_country = {executor.submit(search_customer, store_name, token): country for
  210. country, store_name, token in store_configs}
  211. for future in concurrent.futures.as_completed(future_to_country):
  212. country = future_to_country[future]
  213. shopify_results[country] = future.result()
  214. shopify_country = next((country for country, result in shopify_results.items() if result["customers"]), "")
  215. account_country = self.call_search_customer(email)
  216. servers_continent = "us" if account_country["us"] else "eu" if account_country["eu"] else ""
  217. if servers_continent:
  218. account_region_list = []
  219. if account_country.get("us"):
  220. account_region_list.append({
  221. "url": "https://www.dvema.com/shopify/shopifyLogin",
  222. "accountCountry": account_country["us"].lower(),
  223. "shopifyCountry": shopify_country
  224. })
  225. if account_country.get("eu"):
  226. account_region_list.append({
  227. "url": "https://api.zositeche.com/shopify/shopifyLogin",
  228. "accountCountry": account_country["eu"].lower(),
  229. "shopifyCountry": shopify_country
  230. })
  231. return response.json(0, {"accountStatus": 3, "accountRegionList": account_region_list})
  232. elif shopify_country:
  233. if shopify_country == "eu":
  234. url = "https://eu.zositech.com/account/login"
  235. elif shopify_country == "jp":
  236. url = "https://www.zosi.jp/account/login"
  237. elif shopify_country == "de":
  238. url = "https://www.zositech.de/account/login"
  239. elif shopify_country == "uk":
  240. url = "https://www.zositech.co.uk/account/login"
  241. else:
  242. url = "https://www.zositech.com/account/login"
  243. return response.json(0, {"accountStatus": 2, "url": url})
  244. else:
  245. url = "注册链接"
  246. return response.json(0, {"accountStatus": 1, "url": url})
  247. except Exception as e:
  248. print(e)
  249. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  250. @staticmethod
  251. def call_search_customer(email):
  252. urls = {
  253. "us": "https://www.dvema.com/shopify/searchCustomer",
  254. "eu": "https://api.zositeche.com/shopify/searchCustomer"
  255. }
  256. params = {"email": email} # Use the provided email parameter
  257. customer_region = {}
  258. def fetch_customer(region, url):
  259. try:
  260. response = requests.get(url=url, params=params)
  261. response.raise_for_status() # Raise an error for bad responses
  262. customer_country = response.json()["data"]
  263. if customer_country == "":
  264. return region, None
  265. return region, customer_country
  266. except requests.RequestException:
  267. return region, None
  268. with concurrent.futures.ThreadPoolExecutor() as executor:
  269. future_to_region = {executor.submit(fetch_customer, region, url): region for region, url in urls.items()}
  270. for future in concurrent.futures.as_completed(future_to_region):
  271. region, customer_country = future.result()
  272. customer_region[region] = customer_country
  273. return customer_region
  274. @staticmethod
  275. def search_customer(request_dict, response):
  276. email = request_dict.get("email")
  277. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  278. if not user_qs.exists():
  279. return response.json(104)
  280. user_region_id = user_qs.values_list('region_country', flat=True).first()
  281. country_code = CountryModel.objects.filter(id=user_region_id).values_list("country_code", flat=True).first()
  282. return response.json(0, country_code)
  283. @staticmethod
  284. def get_country_domain_list(request_dict, response):
  285. lang = request_dict.get('lang', 'en')
  286. time_stamp = request_dict.get('time_stamp', None)
  287. time_stamp_token = request_dict.get('time_stamp_token', None)
  288. if not all([time_stamp, time_stamp_token]):
  289. return response.json(444)
  290. try:
  291. # 时间戳token校验
  292. if not CommonService.check_time_stamp_token(time_stamp_token, time_stamp):
  293. return response.json(13)
  294. lang_qs = LanguageModel.objects.filter(lang=lang)
  295. language = lang_qs[0]
  296. country_qs = CountryLanguageModel.objects.filter(language_id=language.id)
  297. country_qs = country_qs.annotate(api=F('country__region__zosi_api'))
  298. country_qs = country_qs.values('country_id', 'country_name', 'api').order_by('country_id')
  299. country_list = []
  300. for country in country_qs:
  301. country['api'] = country['api'] + 'shopify/shopifyRegister'
  302. country_list.append(country)
  303. return response.json(0, country_list)
  304. except Exception as e:
  305. print(e)
  306. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  307. @staticmethod
  308. def shopify_change_password(request_dict, response):
  309. email = request_dict.get("email", None)
  310. password = request_dict.get("password", None)
  311. authcode = request_dict.get("authCode", None)
  312. if not all([email, password, authcode]):
  313. return response.json(444)
  314. try:
  315. reds = RedisObject()
  316. identifyingCode = reds.get_data(key=email + '_forgetPwdResetCode')
  317. # 判断验证码是否过期
  318. if identifyingCode is False:
  319. return response.json(120)
  320. # 验证码是否正确
  321. if authcode != identifyingCode:
  322. return response.json(121)
  323. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  324. if not user_qs.exists():
  325. return response.json(174)
  326. password = make_password(password)
  327. user_qs.update(password=password)
  328. reds.del_data(key=email + '_forgetPwdResetCode')
  329. return response.json(0)
  330. except Exception as e:
  331. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  332. @staticmethod
  333. def verify_authcode(request_dict, response):
  334. """
  335. 在修改密码的时候改变验证码
  336. """
  337. email = request_dict.get("email", None)
  338. authcode = request_dict.get("authCode", None)
  339. code_type = request_dict.get("codeType", None)
  340. if not all([email, authcode, code_type]):
  341. return response.json(444)
  342. try:
  343. code_type = int(code_type)
  344. if code_type == 1:
  345. reds_key = "_identifyingCode"
  346. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  347. if user_qs.exists():
  348. return response.json(174)
  349. elif code_type == 2:
  350. reds_key = "_forgetPwdResetCode"
  351. user_qs = Device_User.objects.filter(Q(username=email) | Q(userEmail=email))
  352. if not user_qs.exists():
  353. return response.json(173)
  354. else:
  355. return response.json(444)
  356. reds = RedisObject()
  357. identifyingCode = reds.get_data(key=email + reds_key)
  358. if identifyingCode is False:
  359. return response.json(120)
  360. # 验证码是否正确
  361. if authcode != identifyingCode:
  362. return response.json(121)
  363. return response.json(0)
  364. except Exception as e:
  365. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))