db-permission.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // 参考文档:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/permission.html
  2. const app = getApp()
  3. const sliderWidth = 96
  4. Page({
  5. onShareAppMessage() {
  6. return {
  7. title: '权限管理',
  8. path: 'packageCloud/pages/database/db-permission/db-permission'
  9. }
  10. },
  11. data: {
  12. theme: 'light',
  13. openid: '',
  14. permissions: ['仅创建者可写,所有人可读', '仅创建者可读写', '仅管理端可写,所有人可读', '仅管理端可读写'],
  15. currentPermissionIndex: 0,
  16. tabs: [
  17. ['我的个性签名', '阿白的个性签名'],
  18. ['我的邮箱', '阿绿的邮箱'],
  19. [],
  20. [],
  21. ],
  22. activeTabIndex: 0,
  23. sliderOffset: 0,
  24. sliderLeft: 0,
  25. querying: false,
  26. updating: false,
  27. hasMyWhatsUp: false,
  28. myWhatsUp: '',
  29. adminWhatsUp: '',
  30. myEmail: '',
  31. adminEmail: '',
  32. hasProduct: false,
  33. product: {},
  34. serverData: '',
  35. },
  36. onLoad() {
  37. this.setData({
  38. theme: wx.getSystemInfoSync().theme || 'light'
  39. })
  40. if (wx.onThemeChange) {
  41. wx.onThemeChange(({theme}) => {
  42. this.setData({theme})
  43. })
  44. }
  45. if (app.globalData.openid) {
  46. this.setData({
  47. openid: app.globalData.openid
  48. })
  49. } else {
  50. wx.showLoading({
  51. title: '正在初始化...'
  52. })
  53. app.getUserOpenIdViaCloud()
  54. .then(openid => {
  55. this.setData({
  56. openid
  57. })
  58. wx.hideLoading()
  59. return openid
  60. }).catch(err => {
  61. console.error(err)
  62. wx.hideLoading()
  63. wx.showModal({
  64. content: '初始化失败,请检查网络',
  65. showCancel: false
  66. })
  67. })
  68. }
  69. const {
  70. myWhatsUp, adminWhatsUp, myEmail, adminEmail
  71. } = app.globalData
  72. this.setData({
  73. hasMyWhatsUp: !!myWhatsUp,
  74. myWhatsUp: myWhatsUp || '',
  75. adminWhatsUp: adminWhatsUp || '',
  76. myEmail: myEmail || '',
  77. adminEmail: adminEmail || '',
  78. })
  79. this.initTabs()
  80. },
  81. initTabs() {
  82. const currentPermissionIndex = this.data.currentPermissionIndex
  83. const tabLength = this.data.tabs[currentPermissionIndex].length
  84. const that = this
  85. wx.getSystemInfo({
  86. success(res) {
  87. that.setData({
  88. sliderLeft: (res.windowWidth / tabLength - sliderWidth) / 2,
  89. sliderOffset: (res.windowWidth / tabLength) * that.data.activeTabIndex
  90. })
  91. }
  92. })
  93. },
  94. onTabClick(e) {
  95. this.setData({
  96. sliderOffset: e.currentTarget.offsetLeft,
  97. activeTabIndex: Number(e.currentTarget.id)
  98. })
  99. },
  100. onPermissionChange(e) {
  101. const oldIndex = this.data.currentPermissionIndex
  102. const newIndex = Number(e.detail.value)
  103. if (oldIndex !== newIndex) {
  104. this.setData({
  105. currentPermissionIndex: Number(newIndex),
  106. activeTabIndex: 0
  107. })
  108. this.initTabs()
  109. }
  110. },
  111. bindInput(e) {
  112. const {name} = e.currentTarget.dataset
  113. this.setData({
  114. [name]: e.detail.value
  115. })
  116. },
  117. showErrorModal(name, err) {
  118. let errMsg = `${name}失败`
  119. if (err.toString().indexOf('permission denied') >= 0) {
  120. errMsg += ':无权限操作'
  121. }
  122. wx.showModal({
  123. content: errMsg,
  124. showCancel: false
  125. })
  126. },
  127. // 根据 openid 获取第一条数据
  128. queryOneByOpenId(collection, openid, options = {
  129. showLoading: false,
  130. showError: false,
  131. success: null,
  132. fail: null
  133. }) {
  134. const {
  135. showLoading, showError, success: successCallback, fail: failCallback
  136. } = options
  137. if (showLoading) {
  138. this.setData({
  139. querying: true
  140. })
  141. }
  142. const db = wx.cloud.database()
  143. const _openid = openid || this.data.openid
  144. db.collection(collection).where({
  145. _openid
  146. }).get({
  147. success: res => {
  148. console.log('[数据库] [查询记录] 成功: ', res)
  149. const resFirstData = res.data[0] || {}
  150. // 返回的不是要查询用户的记录,是由于没有读权限,视为查询失败
  151. if (resFirstData._openid && resFirstData._openid !== _openid) {
  152. const err = new Error('database permission denied')
  153. if (showError) this.showErrorModal('获取', err)
  154. if (failCallback) failCallback.call(this, err)
  155. } else if (successCallback) {
  156. successCallback.call(this, res.data[0])
  157. }
  158. },
  159. fail: err => {
  160. if (showError) this.showErrorModal('获取', err)
  161. console.error('[数据库] [查询记录] 失败:', err)
  162. if (failCallback) failCallback.call(this, err)
  163. },
  164. complete: () => {
  165. if (showLoading) {
  166. this.setData({
  167. querying: false
  168. })
  169. }
  170. }
  171. })
  172. },
  173. // 根据 openid 更新数据
  174. updateOneByOpenId(collection, openid, data, options = {
  175. showLoading: false,
  176. showError: false,
  177. success: null,
  178. fail: null
  179. }) {
  180. const {
  181. showLoading, showError, success: successCallback, fail: failCallback
  182. } = options
  183. if (showLoading) {
  184. this.setData({
  185. updating: true
  186. })
  187. }
  188. const db = wx.cloud.database()
  189. // 限制每人仅存一条记录,先查询是否已存在记录
  190. this.queryOneByOpenId(collection, openid || '', {
  191. success: dbData => {
  192. if (dbData) { // 已有数据,进行更新操作
  193. db.collection(collection).doc(dbData._id).update({
  194. data,
  195. success: res => {
  196. console.log('[数据库] [更新记录] 成功: ', res)
  197. if (successCallback) successCallback.call(this, res.stats)
  198. },
  199. fail: err => {
  200. if (showError) this.showErrorModal('设置', err)
  201. console.error('[数据库] [更新记录] 失败:', err)
  202. if (failCallback) failCallback.call(this, err)
  203. },
  204. complete: () => {
  205. if (showLoading) {
  206. this.setData({
  207. updating: false
  208. })
  209. }
  210. }
  211. })
  212. } else if (!openid || openid === this.data.openid) { // 还没有插入过数据且要操作的是自己的数据,进行新增操作
  213. db.collection(collection).add({
  214. data,
  215. success: res => {
  216. console.log('[数据库] [新增记录] 成功:', res)
  217. if (successCallback) successCallback.call(this, {_id: res._id})
  218. },
  219. fail: err => {
  220. if (showError) this.showErrorModal('设置', err)
  221. console.error('[数据库] [新增记录] 失败:', err)
  222. if (failCallback) failCallback.call(this, err)
  223. },
  224. complete: () => {
  225. if (showLoading) {
  226. this.setData({
  227. updating: false
  228. })
  229. }
  230. }
  231. })
  232. } else {
  233. const err = new Error('database permission denied')
  234. if (showError) this.showErrorModal('设置', err)
  235. if (failCallback) failCallback.call(this, err)
  236. if (showLoading) {
  237. this.setData({
  238. updating: false
  239. })
  240. }
  241. }
  242. },
  243. fail: err => {
  244. if (showError) this.showErrorModal('设置', err)
  245. if (failCallback) failCallback.call(this, err)
  246. if (showLoading) {
  247. this.setData({
  248. updating: false
  249. })
  250. }
  251. }
  252. })
  253. },
  254. // perm1:仅创建者可写,所有人可读
  255. queryMyWhatsUp() {
  256. this.queryOneByOpenId('perm1', '', {
  257. showLoading: true,
  258. showError: true,
  259. success: data => {
  260. const content = (data && data.whatsUp) || ''
  261. wx.showModal({
  262. title: '获取成功',
  263. content: content ? `个性签名为:${content}` : '个性签名为空',
  264. showCancel: false
  265. })
  266. }
  267. })
  268. },
  269. updateMyWhatsUp() {
  270. const data = {
  271. whatsUp: this.data.myWhatsUp
  272. }
  273. this.updateOneByOpenId('perm1', '', data, {
  274. showLoading: true,
  275. showError: true,
  276. success: () => {
  277. app.globalData.myWhatsUp = this.data.myWhatsUp
  278. this.setData({
  279. hasMyWhatsUp: true
  280. })
  281. wx.showModal({
  282. content: '设置成功',
  283. showCancel: false
  284. })
  285. }
  286. })
  287. },
  288. queryAdminWhatsUp() {
  289. this.queryOneByOpenId('perm1', 'kiki', {
  290. showLoading: true,
  291. showError: true,
  292. success: data => {
  293. const content = (data && data.whatsUp) || ''
  294. wx.showModal({
  295. title: '获取成功',
  296. content: content ? `个性签名为:${content}` : '个性签名为空',
  297. showCancel: false
  298. })
  299. }
  300. })
  301. },
  302. updateAdminWhatsUp() {
  303. const data = {
  304. whatsUp: this.data.adminWhatsUp
  305. }
  306. this.updateOneByOpenId('perm1', 'kiki', data, {
  307. showLoading: true,
  308. showError: true,
  309. success: res => {
  310. if (res.updated === 0) {
  311. wx.showModal({
  312. content: '设置失败:无权限操作',
  313. showCancel: false
  314. })
  315. } else {
  316. app.globalData.adminWhatsUp = this.data.adminWhatsUp
  317. wx.showModal({
  318. content: '设置成功',
  319. showCancel: false
  320. })
  321. }
  322. }
  323. })
  324. },
  325. // perm2:仅创建者可读写
  326. queryMyEmail() {
  327. this.queryOneByOpenId('perm2', '', {
  328. showLoading: true,
  329. showError: true,
  330. success: data => {
  331. const content = (data && data.email) || ''
  332. wx.showModal({
  333. title: '获取成功',
  334. content: content ? `邮箱为:${content}` : '邮箱为空',
  335. showCancel: false
  336. })
  337. }
  338. })
  339. },
  340. updateMyEmail() {
  341. const data = {
  342. email: this.data.myEmail
  343. }
  344. this.updateOneByOpenId('perm2', '', data, {
  345. showLoading: true,
  346. showError: true,
  347. success: () => {
  348. app.globalData.myEmail = this.data.myEmail
  349. wx.showModal({
  350. content: '设置成功',
  351. showCancel: false
  352. })
  353. }
  354. })
  355. },
  356. queryAdminEmail() {
  357. this.queryOneByOpenId('perm2', 'popo', {
  358. showLoading: true,
  359. showError: true,
  360. success: data => {
  361. const content = (data && data.email) || ''
  362. wx.showModal({
  363. title: '获取成功',
  364. content: content ? `邮箱为:${content}` : '邮箱为空',
  365. showCancel: false
  366. })
  367. }
  368. })
  369. },
  370. updateAdminEmail() {
  371. const data = {
  372. email: this.data.adminEmail
  373. }
  374. this.updateOneByOpenId('perm2', 'popo', data, {
  375. showLoading: true,
  376. showError: true,
  377. success: () => {
  378. app.globalData.adminEmail = this.data.adminEmail
  379. wx.showModal({
  380. content: '设置成功',
  381. showCancel: false
  382. })
  383. }
  384. })
  385. },
  386. // perm3:仅管理端可写,所有人可读
  387. queryProduct() {
  388. this.queryOneByOpenId('perm3', 'admin', {
  389. showLoading: true,
  390. showError: true,
  391. success: data => {
  392. const price = (data && data.price) || null
  393. wx.showModal({
  394. title: '获取成功',
  395. content: price !== null ? `商品价格为:${price}` : '商品价格暂未设置',
  396. showCancel: false
  397. })
  398. }
  399. })
  400. },
  401. updateProductPrice() {
  402. const data = {
  403. price: parseInt(this.data.product.price, 10)
  404. }
  405. this.updateOneByOpenId('perm3', 'admin', data, {
  406. showLoading: true,
  407. showError: true,
  408. success: () => {
  409. wx.showModal({
  410. content: '设置成功',
  411. showCancel: false
  412. })
  413. }
  414. })
  415. },
  416. // perm4:仅管理端可读写
  417. queryServerData() {
  418. this.queryOneByOpenId('perm4', 'server', {
  419. showLoading: true,
  420. showError: true,
  421. success: data => {
  422. const content = (data && data.serverData) || ''
  423. wx.showModal({
  424. title: '获取成功',
  425. content: content ? `后台流水数据为:${content}` : '后台流水数据为空',
  426. showCancel: false
  427. })
  428. }
  429. })
  430. },
  431. updateServerData() {
  432. const data = {
  433. data: this.data.serverData
  434. }
  435. this.updateOneByOpenId('perm4', 'server', data, {
  436. showLoading: true,
  437. showError: true,
  438. success: () => {
  439. wx.showModal({
  440. content: '设置成功',
  441. showCancel: false
  442. })
  443. }
  444. })
  445. },
  446. })