index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. let Parse = getApp().Parse;
  2. let company = getApp().globalData.company
  3. const request = require("../../utils/request");
  4. const qiniuUploader = require("../../utils/qiniuUploader");
  5. //获取应用实例
  6. const app = getApp()
  7. const real = require('../../utils/real')
  8. var timer
  9. /**
  10. * @class NovaAppAuth
  11. * @memberof module:components
  12. * @tutorial userauth
  13. * @desc 通用登录组件
  14. * # 登录组件相关数据表
  15. * - _User
  16. */
  17. Page({
  18. data: {
  19. phoneModal: false, //短信验证码登录弹窗
  20. logo: "https://file-cloud.fmode.cn/MldI5PBNt7/20210928/g0k1jb034826.png",
  21. name: "未来商城",
  22. desc: "江西脑控科技有限公司是国内领先的IT技术企业。专注于互联网+服务,面向政府提供区块链、大数据、物联网、人工智能解决方案",
  23. wxModel: false,
  24. avatarUrl: '',
  25. avatar: '',
  26. nickname: '',
  27. check: false,
  28. mobile: '', //手机号
  29. verilyCode: '', //验证码
  30. s: 0, //获取验证码倒计时 秒/s
  31. countDown: false
  32. },
  33. onLoad: async function (options) {
  34. let Company = new Parse.Query('Company')
  35. Company.equalTo("objectId", company)
  36. let currentCompany = await Company.first()
  37. if (currentCompany && currentCompany.id) {
  38. this.setData({
  39. logo: currentCompany.get('logo'),
  40. name: currentCompany.get('name'),
  41. desc: currentCompany.get('desc')
  42. })
  43. }
  44. this.getUptoken()
  45. this.getAgreement() //用户协议
  46. },
  47. async getUptoken() {
  48. let res = await Parse.Cloud.run('qiniu_uptoken', {
  49. company: company
  50. })
  51. this.setData({
  52. uptokenURL: res.uptoken,
  53. domain: res.domain,
  54. uploadURL: res.zoneUrl
  55. })
  56. },
  57. async getAgreement() {
  58. let query = new Parse.Query('ContractAgreement')
  59. query.equalTo('type', 'wxapp')
  60. query.equalTo('company', company)
  61. query.select('title', 'content')
  62. let res = await query.first()
  63. if (res?.id) {
  64. this.setData({
  65. agreement: res.toJSON()
  66. })
  67. }
  68. },
  69. /* 是否同意授权协议 */
  70. getAgreementAuth() {
  71. if (!this.data.check && this.data.agreement) {
  72. wx.showModal({
  73. title: '提示',
  74. content: `请您仔细阅读并充分理解相关条款,点击同意即代表已阅读并同意《${this.data.agreement.title || '用户隐私协议'}》`,
  75. showCancel: true,
  76. cancelText: '取消',
  77. cancelColor: '#000000',
  78. confirmText: '同意',
  79. confirmColor: '#3CC51F',
  80. success: (result) => {
  81. if (result.confirm) {
  82. this.setData({
  83. check: true,
  84. })
  85. // this.getUserProfile()
  86. }
  87. },
  88. fail: () => { },
  89. complete: () => { }
  90. });
  91. return
  92. }
  93. // this.getUserProfile()
  94. return true
  95. },
  96. /* 判断是否绑定手机号 */
  97. async getUserProfile() {
  98. if (!Parse.User.current()?.id) {
  99. await getApp().checkAuth(true)
  100. }
  101. let currentUser = Parse.User.current()
  102. /* 如果手机号存在,已注册过判断是否上传过头像昵称信息 */
  103. if (currentUser?.get('mobile')) {
  104. wx.setStorageSync("userLogin", currentUser.id);
  105. if (currentUser.get('nickname') == '微信用户' || currentUser.get('nickname') == '' || !currentUser.get('nickname')) {
  106. this.setData({
  107. wxModel: true
  108. })
  109. return
  110. }
  111. this.backLoad()
  112. return
  113. }
  114. return true
  115. },
  116. /* 短信验证码登录弹窗 */
  117. async showDialogBtn() {
  118. let auth = this.getAgreementAuth()
  119. if (!auth) return
  120. let userProfile = await this.getUserProfile()
  121. if (!userProfile) return
  122. this.setData({
  123. phoneModal: true
  124. })
  125. },
  126. async getPhoneNumber(e) {
  127. let auth = this.getAgreementAuth()
  128. if (!auth) return
  129. let userProfile = await this.getUserProfile()
  130. if (!userProfile) return
  131. let {
  132. code
  133. } = e.detail
  134. console.log(code);
  135. let phoneNumber = await request.getPhone(code)
  136. if(phoneNumber) this.authMobileUser(phoneNumber)
  137. },
  138. //合并User与绑定手机号逻辑
  139. async authMobileUser(mobile) {
  140. let currentUser = Parse.User.current()
  141. let queryMobUser = new Parse.Query('_User')
  142. queryMobUser.equalTo('mobile', mobile)
  143. queryMobUser.equalTo('company', company)
  144. queryMobUser.notEqualTo('type', 'admin')
  145. queryMobUser.notEqualTo('isDeleted', true)
  146. // queryMobUser.exists(`wxapp.${getApp().globalData.appid}`)
  147. let resMobUser = await queryMobUser.first()
  148. if (resMobUser?.id) {
  149. //请求User合并API,获取token重新登录,再更新昵称头像信息等
  150. let token = await this.getUpdateUserToken(currentUser.id, resMobUser.id)
  151. console.log(token);
  152. if (token) {
  153. Parse.User.become(token).then(async user => {
  154. // let user = Parse.User.current();
  155. wx.setStorageSync("userLogin", user.id);
  156. if (!user.get('avatar') || user.get('nickname') == '微信用户' || !user.get('nickname')) {
  157. this.setData({
  158. phoneModal: false,
  159. wxModel: true
  160. })
  161. return
  162. }
  163. this.backLoad()
  164. return
  165. })
  166. .catch(err => {
  167. console.log('登录失败:', err);
  168. wx.setStorageSync("sessionToken", null);
  169. wx.showModal({
  170. title: '提示',
  171. content: '登录信息过期,请退出重新进入小程序',
  172. showCancel: false,
  173. cancelText: '取消',
  174. cancelColor: '#000000',
  175. confirmText: '确定',
  176. confirmColor: '#3CC51F',
  177. success: (result) => {
  178. if (result.confirm) {
  179. wx.exitMiniProgram()
  180. }
  181. },
  182. });
  183. return
  184. })
  185. return
  186. }
  187. return
  188. }
  189. currentUser.set('mobile', mobile)
  190. await currentUser.save()
  191. if (!currentUser.get('avatar') || currentUser.get('nickname') == '微信用户' || !currentUser.get('nickname')) {
  192. this.setData({
  193. phoneModal: false,
  194. wxModel: true
  195. })
  196. return
  197. }
  198. this.backLoad()
  199. return
  200. },
  201. async getUpdateUserToken(oldUser, newUserId) {
  202. return new Promise((resolve, reject) => {
  203. wx.login({
  204. success: function (res) {
  205. let parms = {
  206. oldUserId: oldUser,
  207. newUserId: newUserId,
  208. appId: getApp().globalData.appid,
  209. code: res.code,
  210. companyId: company,
  211. appType: getApp().globalData.appType || ''
  212. }
  213. if (res.code) {
  214. let url = 'https://server.fmode.cn/api/wxapp/combine/user'
  215. wx.request({
  216. url: url,
  217. data: parms,
  218. header: { 'content-type': 'application/json' },
  219. method: 'POST',
  220. async success(res) {
  221. console.log(res);
  222. let data = res.data
  223. if (data.code == 200) {
  224. wx.setStorageSync("sessionToken", data.data.token);
  225. resolve(data.data.token)
  226. } else {
  227. console.log(data?.mess);
  228. wx.showModal({
  229. title: '提示',
  230. content: data?.mess,
  231. showCancel: false,
  232. cancelText: '取消',
  233. cancelColor: '#000000',
  234. confirmText: '确定',
  235. confirmColor: '#3CC51F',
  236. success: (result) => {
  237. if (result.confirm) {
  238. }
  239. },
  240. fail: () => { },
  241. complete: () => { }
  242. });
  243. resolve()
  244. }
  245. },
  246. });
  247. }
  248. },
  249. fail: function (err) {
  250. wx.showModal({
  251. title: '提示',
  252. content: '登录超时,请稍后重试',
  253. showCancel: false,
  254. cancelText: '取消',
  255. cancelColor: '#000000',
  256. confirmText: '确定',
  257. confirmColor: '#3CC51F',
  258. success: (result) => {
  259. if (result.confirm) {
  260. }
  261. },
  262. fail: () => { },
  263. complete: () => { }
  264. });
  265. console.warn('小程序wx.login失败');
  266. resolve()
  267. }
  268. });
  269. })
  270. },
  271. //获取验证码
  272. async getPhoneCode() {
  273. let { mobile, s, countDown } = this.data
  274. if (!real.isPoneAvailable(mobile)) {
  275. wx.showToast({
  276. title: '手机号格式有误',
  277. icon: 'error',
  278. duration: 1500,
  279. mask: false,
  280. });
  281. return
  282. }
  283. if(countDown || s > 0) return
  284. this.setData({
  285. countDown:true
  286. })
  287. let parsm = {
  288. company: company,
  289. mobile: mobile
  290. }
  291. let code = await this.getRequest(parsm, 'message')
  292. if(code?.code == 1){
  293. this.setData({
  294. s:60
  295. })
  296. this.decrementTime()
  297. }else{
  298. wx.showToast({
  299. title: '验证码获取失败',
  300. icon: 'error',
  301. image: '',
  302. duration: 1500,
  303. mask: false,
  304. });
  305. this.setData({
  306. countDown:false
  307. })
  308. }
  309. },
  310. //接口请求
  311. getRequest(parsm, apig) {
  312. return new Promise((resolve, rej) => {
  313. let url = 'https://server.fmode.cn/api/apig/'
  314. wx.request({
  315. url: url + apig,
  316. data: parsm,
  317. header: { 'content-type': 'application/json' },
  318. method: 'POST',
  319. dataType: 'json',
  320. responseType: 'text',
  321. success: (result) => {
  322. console.log(result);
  323. resolve(result.data)
  324. },
  325. fail: () => {
  326. resolve(false)
  327. },
  328. complete: () => { }
  329. });
  330. })
  331. },
  332. // 倒计时
  333. decrementTime(){
  334. timer = setTimeout(() => {
  335. let { s } = this.data
  336. if(s == 0){
  337. this.setData({ countDown:false })
  338. timer && clearTimeout(timer)
  339. return
  340. }
  341. s--
  342. this.setData({
  343. s:s
  344. })
  345. this.decrementTime()
  346. }, 1000);
  347. },
  348. //验证码绑定手机号登录
  349. async completePhone() {
  350. let { mobile, verilyCode } = this.data
  351. if(!real.isPoneAvailable(mobile) || !verilyCode.toString().trim()){
  352. wx.showToast({
  353. title: '手机号或验证码不正确',
  354. icon: 'none',
  355. image: '',
  356. duration: 1500,
  357. mask: false,
  358. });
  359. return
  360. }
  361. let parsm = {
  362. mobile: mobile,
  363. code:verilyCode
  364. }
  365. let isVerify = await this.getRequest(parsm, 'verifyCode')
  366. console.log(isVerify);
  367. if(isVerify.code == 200){
  368. this.authMobileUser(mobile.toString())
  369. }else{
  370. wx.showToast({
  371. title:isVerify?.msg || '验证码错误',
  372. icon: 'none',
  373. image: '',
  374. duration: 1500,
  375. mask: false,
  376. });
  377. return
  378. }
  379. },
  380. //关闭手机号授权弹窗
  381. hideModal: function () {
  382. this.setData({
  383. phoneModal: false
  384. })
  385. },
  386. backLoad() {
  387. let pages = getCurrentPages();
  388. let beforePage = pages[pages.length - 2];
  389. let options = {
  390. isInit: true
  391. }
  392. beforePage?.onLoad(options)
  393. wx.navigateBack({
  394. delta: 1,
  395. })
  396. },
  397. goBack: function () {
  398. wx.navigateBack({
  399. delta: 1,
  400. })
  401. },
  402. //手动获取微信头像
  403. onChooseAvatar(e) {
  404. console.log(e);
  405. let {
  406. avatarUrl
  407. } = e.detail
  408. console.log(avatarUrl);
  409. this.setData({
  410. avatarUrl
  411. })
  412. },
  413. //获取昵称
  414. onChangeName(e) {
  415. console.log('1111');
  416. console.log(e);
  417. },
  418. //确定头像昵称
  419. async onComplete() {
  420. let {
  421. nickname,
  422. avatarUrl
  423. } = this.data
  424. // console.log(nickname, avatarUrl);
  425. if (!nickname || !avatarUrl) {
  426. wx.showToast({
  427. title: '请填写完整信息',
  428. icon: 'none',
  429. image: '',
  430. duration: 1500,
  431. mask: false,
  432. });
  433. return
  434. }
  435. //关键注释: https://up-z2.qiniup.com 合法域名必须配置
  436. try {
  437. let avatar = await this.updataAvatar(avatarUrl)
  438. let user = Parse.User.current()
  439. user.set("avatar", avatar)
  440. user.set("nickname", nickname)
  441. user.save().then(res => {
  442. this.onClose()
  443. this.backLoad()
  444. })
  445. } catch (err) {
  446. console.warn('https://up-z2.qiniup.com 合法域名必须配置');
  447. console.log(err);
  448. this.onClose()
  449. this.backLoad()
  450. }
  451. },
  452. //关闭头像昵称填写弹窗
  453. onClose() {
  454. this.setData({
  455. wxModel: false
  456. })
  457. },
  458. //上传头像
  459. updataAvatar(url) {
  460. let that = this;
  461. return new Promise((resolve, rejcet) => {
  462. qiniuUploader.upload(
  463. url,
  464. async (res) => {
  465. let img = res.imageURL;
  466. resolve(img)
  467. },
  468. (error) => {
  469. console.log("error: " + error);
  470. resolve(false)
  471. }, {
  472. region: "SCN",
  473. uploadURL: that.data.uploadURL,
  474. domain: that.data.domain,
  475. uptoken: that.data.uptokenURL,
  476. }
  477. );
  478. })
  479. },
  480. //选择勾选用户协议
  481. onCheckAgreement() {
  482. this.setData({
  483. check: !this.data.check
  484. })
  485. },
  486. //附件下载
  487. openFile() {
  488. let {
  489. agreement
  490. } = this.data
  491. let url = agreement.content,
  492. name = agreement.title
  493. const _this = this;
  494. let rep = this.getFileType(url)
  495. console.log(url, name);
  496. wx.showLoading({
  497. title: '加载中',
  498. })
  499. wx.downloadFile({
  500. url: url, //要预览的PDF的地址
  501. filePath: wx.env.USER_DATA_PATH + `/${name}.${rep}`,
  502. success: function (res) {
  503. console.log(res);
  504. if (res.statusCode === 200) { //成功
  505. var Path = res.filePath //返回的文件临时地址,用于后面打开本地预览所用
  506. console.log(Path)
  507. wx.openDocument({
  508. filePath: Path, //要打开的文件路径
  509. showMenu: true,
  510. success: function (res) {
  511. wx.hideLoading()
  512. console.log(res, '打开PDF成功');
  513. },
  514. fail: function (res) {
  515. console.log(res)
  516. wx.hideLoading()
  517. }
  518. })
  519. }
  520. },
  521. fail: function (res) {
  522. wx.hideLoading()
  523. console.log(res); //失败
  524. },
  525. })
  526. },
  527. //解析文件类型
  528. getFileType(url) {
  529. let pdfReg = /^.+(\.pdf)$/
  530. let txtReg = /^.+(\.txt)$/
  531. let wordReg = /^.+(\.doc|\.docx)$/
  532. let excelReg = /^.+(\.xls|\.xlsx)$/
  533. let jpgPng = /^.+(\.png)$/
  534. let jpgJpg = /^.+(\.jpg)$/
  535. let jpgJpeg = /^.+(\.jpeg)$/
  536. if (pdfReg.test(url)) {
  537. return 'pdf'
  538. }
  539. if (txtReg.test(url)) {
  540. return 'txt'
  541. }
  542. if (wordReg.test(url)) {
  543. return 'docx'
  544. }
  545. if (excelReg.test(url)) {
  546. return 'xls'
  547. }
  548. if (jpgPng.test(url)) {
  549. return 'png'
  550. }
  551. if (jpgJpg.test(url)) {
  552. return 'jpg'
  553. }
  554. if (jpgJpeg.test(url)) {
  555. return 'jpeg'
  556. }
  557. },
  558. onShow: function () {
  559. let userLogin = wx.getStorageSync('userLogin');
  560. if (userLogin != '') {
  561. wx.navigateBack();
  562. };
  563. },
  564. onReady: function () {
  565. },
  566. })