actions.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import NP from 'number-precision'
  2. import API from '@/api'
  3. import { showError, Cookie } from '@/util/util.js'
  4. import { getNetwork } from '@/util/contract.js'
  5. import Eos from 'eosjs'
  6. export const actions = {
  7. setScatter: ({ commit }, scatter) => commit('setScatter', scatter),
  8. setEos: ({ commit }, eosjs) => commit('setEos', eosjs),
  9. setAccount: ({ commit }, account) => commit('setAccount', account),
  10. /**
  11. * 调起授权登录
  12. * @param {Object} store
  13. * @param {Object} params
  14. */
  15. async doScatterLogin ({ dispatch, commit, state }, h5Router) {
  16. if (!state.scatter) {
  17. showError('Please install the scatter', 'Scatter')
  18. } else {
  19. // 获取最快主网
  20. let networkConfig = await getNetwork()
  21. // 调用getIdentity方法获取用户名
  22. try {
  23. var identity = await state.scatter.getIdentity({
  24. accounts: [networkConfig]
  25. })
  26. } catch (error) {
  27. if (error.type !== 'identity_rejected') {
  28. showError(error.message)
  29. }
  30. return Promise.reject(error)
  31. }
  32. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  33. let lastAccounts = localStorage.getItem('accounts')
  34. if (lastAccounts && JSON.parse(lastAccounts).name !== accounts.name) {
  35. await actions.doScatterLogout(...arguments)
  36. h5Router.push({ path: '/login' })
  37. commit('setUserInfo', null)
  38. commit('initChatData')
  39. commit('initGroupData')
  40. commit('chatAppLogin', false)
  41. commit('toApp', true)
  42. }
  43. commit('setAccount', accounts)
  44. localStorage.setItem('accounts', JSON.stringify(accounts))
  45. // 如果当前登录的用户名和cookie中保存的account不一致
  46. // 则删除cookie中保存的account
  47. // 避免某些用户在移动端钱包中切换账号时跳过注销流程导致账号不一致的问题
  48. // if (Cookie.getCookie('account') !== accounts.name) {
  49. // Cookie.delCookie('account')
  50. // }
  51. // 设置全局EOS对象
  52. window.EOS = state.scatter.eos(networkConfig, Eos, {})
  53. // 调用scatter登录成功后获取用户EOS、GT
  54. // dispatch('getUserEOS')
  55. // dispatch('getUserGT')
  56. await dispatch('getAccount')
  57. // 每分钟刷新一次
  58. // this.limitTimer = setInterval(() => {
  59. // dispatch('getAccount')
  60. // }, 60000)
  61. return Promise.resolve(true)
  62. }
  63. },
  64. /**
  65. * 注销当前scatter账号
  66. * @param {Object} store
  67. * @param {Object} params
  68. */
  69. doScatterLogout ({ commit, state }, params) {
  70. Cookie.delCookie('user_id')
  71. Cookie.delCookie('token')
  72. localStorage.removeItem('user_id')
  73. localStorage.removeItem('token')
  74. localStorage.removeItem('accounts')
  75. commit('setUserId', null)
  76. commit('setToken', null)
  77. // sessionStorage.removeItem('vuex')
  78. commit('setAccount', '')
  79. return state.scatter && state.scatter.forgetIdentity && state.scatter.forgetIdentity()
  80. },
  81. /**
  82. * 更新用户EOS币数量
  83. * @param {Object} store
  84. * @param {Object} params
  85. */
  86. getUserEOS ({ dispatch, commit, state }, params) {
  87. return new Promise((resolve, reject) => {
  88. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  89. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  90. balanceNum = NP.times(balanceNum, 10000)
  91. commit('setBalance', balanceNum)
  92. commit('setEOSError', 0)
  93. resolve()
  94. }).catch(error => {
  95. // 失败重新尝试,最大尝试5次
  96. commit('setEOSError', state.eosErrorCount + 1)
  97. if (state.eosErrorCount <= 5) {
  98. setTimeout(() => {
  99. dispatch('getUserEOS')
  100. }, 1000 * state.eosErrorCount)
  101. }
  102. reject(error)
  103. })
  104. })
  105. },
  106. /**
  107. * 获取用户信息
  108. * @param {Object} store
  109. * @param {Object} params
  110. */
  111. getAccount ({ commit, state }, params) {
  112. return new Promise((resolve, reject) => {
  113. window.EOS.getAccount(state.account.name).then(data => {
  114. // 设置公钥
  115. const perms = JSON.parse(JSON.stringify(data.permissions))
  116. perms.forEach(v => {
  117. if (v.perm_name === 'active') {
  118. let publicKey = v.required_auth.keys[0].key
  119. commit('setPublicKey', publicKey)
  120. }
  121. })
  122. resolve(data)
  123. }).catch(error => {
  124. reject(error)
  125. })
  126. })
  127. },
  128. /**
  129. * 进行验证身份登录,生成业务登录态token
  130. * @param {Object} store
  131. * @param {Object} params
  132. */
  133. async doGameLogin ({ dispatch, commit, state }, params) {
  134. let userId = localStorage.getItem('user_id')
  135. let token = localStorage.getItem('token')
  136. if (userId && token) {
  137. commit('setUserId', userId)
  138. commit('setToken', token)
  139. return Promise.resolve({
  140. user_id: userId,
  141. token: token
  142. })
  143. } else {
  144. let rData = await API.user.getRandom({ account: state.account.name })
  145. let random = rData.data.data
  146. let pubkey = state.publicKey
  147. return new Promise((resolve, reject) => {
  148. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  149. let param = {
  150. account: state.account.name,
  151. sign,
  152. pubkey,
  153. data: random
  154. }
  155. API.user.eosLogin(param).then(({ data }) => {
  156. if (data.result === 1) {
  157. let userId = data.data.user_id
  158. let token = data.data.token
  159. localStorage.setItem('user_id', userId)
  160. localStorage.setItem('token', token)
  161. commit('setUserId', userId)
  162. commit('setToken', token)
  163. resolve(data)
  164. } else {
  165. reject(new Error(data.msg))
  166. }
  167. })
  168. }).catch(error => {
  169. reject(error)
  170. })
  171. })
  172. }
  173. },
  174. /**
  175. * 登录态过期,清除当前登录态相关数据,重新调起登录
  176. * @param {Object} store
  177. * @param {Object} params
  178. */
  179. async resetGameLogin ({ dispatch, commit, state }, params) {
  180. console.log('doContractLogin')
  181. localStorage.removeItem('user_id')
  182. localStorage.removeItem('token')
  183. await dispatch('doContractLogin')
  184. if (self !== top) {
  185. location.replace(location.href.replace('show=false', 'show=true'))
  186. } else {
  187. location.reload()
  188. }
  189. },
  190. /**
  191. * 合约登录, 生成业务登录态token
  192. * @param {Array} params
  193. */
  194. async doContractLogin ({ commit, state }, params) {
  195. let userId = localStorage.getItem('user_id')
  196. let token = localStorage.getItem('token')
  197. if (userId && token) {
  198. commit('setUserId', userId)
  199. commit('setToken', token)
  200. return Promise.resolve({
  201. user_id: userId,
  202. token: token
  203. })
  204. } else {
  205. try {
  206. // 合约登录
  207. let { data } = await API.user.getRandom2({ account: state.account.name })
  208. let random = data.data.random
  209. let accessToken = data.data.accessToken
  210. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  211. let trx = null
  212. if (self !== top) {
  213. trx = await window.postMessager.send({
  214. action: 'meechat:eosAction',
  215. data: {
  216. contract: 'meechatadmin',
  217. action: 'login',
  218. param: [state.account.name, random, identity]
  219. }
  220. })
  221. } else {
  222. let eos = window.EOS || state.scatter.eos
  223. let contract = await eos.contract('meechatadmin')
  224. trx = await contract.login(state.account.name, random, identity)
  225. }
  226. let param = {
  227. account: state.account.name,
  228. access_token: accessToken,
  229. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  230. group_id: state.group.groupId || null
  231. }
  232. let res = await API.user.eosLogin2(param)
  233. if (res.data.result === 1) {
  234. let userId = res.data.data.user_id
  235. let token = res.data.data.token
  236. localStorage.setItem('user_id', userId)
  237. localStorage.setItem('token', token)
  238. commit('setUserId', userId)
  239. commit('setToken', token)
  240. return Promise.resolve(res.data)
  241. }
  242. } catch (error) {
  243. return Promise.reject(error)
  244. }
  245. }
  246. },
  247. /**
  248. * @des 获取热门群组
  249. */
  250. getHotList ({ state }, params) {
  251. if (state.hotList.length > 0) return
  252. API.group.getHotList().then(({ data }) => {
  253. state.hotList = data.data
  254. })
  255. }
  256. }