actions.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. * eos账号绑定
  66. * @param {*} param0
  67. */
  68. async doScatterBind ({ dispatch, commit, state }) {
  69. if (!state.scatter) {
  70. showError('Please install the scatter', 'Scatter')
  71. } else {
  72. // 获取最快主网
  73. let networkConfig = await getNetwork()
  74. // 调用getIdentity方法获取用户名
  75. try {
  76. var identity = await state.scatter.getIdentity({
  77. accounts: [networkConfig]
  78. })
  79. } catch (error) {
  80. if (error.type !== 'identity_rejected') {
  81. showError(error.message)
  82. }
  83. return Promise.reject(error)
  84. }
  85. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  86. window.EOS = state.scatter.eos(networkConfig, Eos, {})
  87. // 合约登录
  88. let { data } = await API.user.getRandom2({ account: accounts.name })
  89. let random = data.data.random
  90. let accessToken = data.data.accessToken
  91. let trx = null
  92. let eos = window.EOS || state.scatter.eos
  93. let contract = await eos.contract('meechatadmin')
  94. trx = await contract.login(accounts.name, random, { authorization: [`${accounts.name}@${accounts.authority}`] })
  95. let param = {
  96. account: accounts.name,
  97. access_token: accessToken,
  98. trx_id: trx.transaction_id || trx.transaction.transaction_id
  99. }
  100. return API.user.eosBind2(param)
  101. }
  102. },
  103. /**
  104. * 注销当前scatter账号
  105. * @param {Object} store
  106. * @param {Object} params
  107. */
  108. doScatterLogout ({ commit, state }, params) {
  109. Cookie.delCookie('user_id')
  110. Cookie.delCookie('token')
  111. localStorage.removeItem('user_id')
  112. localStorage.removeItem('token')
  113. localStorage.removeItem('accounts')
  114. commit('setUserId', null)
  115. commit('setToken', null)
  116. // sessionStorage.removeItem('vuex')
  117. commit('setAccount', '')
  118. return state.scatter && state.scatter.forgetIdentity && state.scatter.forgetIdentity()
  119. },
  120. /**
  121. * 更新用户EOS币数量
  122. * @param {Object} store
  123. * @param {Object} params
  124. */
  125. getUserEOS ({ dispatch, commit, state }, params) {
  126. return new Promise((resolve, reject) => {
  127. window.EOS.getCurrencyBalance('eosio.token', state.account.name, 'EOS').then(([ balance ]) => {
  128. let balanceNum = Number(balance.replace(/\sEOS/, '')).toFixed(4)
  129. balanceNum = NP.times(balanceNum, 10000)
  130. commit('setBalance', balanceNum)
  131. commit('setEOSError', 0)
  132. resolve()
  133. }).catch(error => {
  134. // 失败重新尝试,最大尝试5次
  135. commit('setEOSError', state.eosErrorCount + 1)
  136. if (state.eosErrorCount <= 5) {
  137. setTimeout(() => {
  138. dispatch('getUserEOS')
  139. }, 1000 * state.eosErrorCount)
  140. }
  141. reject(error)
  142. })
  143. })
  144. },
  145. /**
  146. * 获取用户信息
  147. * @param {Object} store
  148. * @param {Object} params
  149. */
  150. getAccount ({ commit, state }, params) {
  151. return new Promise((resolve, reject) => {
  152. window.EOS.getAccount(state.account.name).then(data => {
  153. // 设置公钥
  154. const perms = JSON.parse(JSON.stringify(data.permissions))
  155. perms.forEach(v => {
  156. if (v.perm_name === 'active') {
  157. let publicKey = v.required_auth.keys[0].key
  158. commit('setPublicKey', publicKey)
  159. }
  160. })
  161. resolve(data)
  162. }).catch(error => {
  163. reject(error)
  164. })
  165. })
  166. },
  167. /**
  168. * 进行验证身份登录,生成业务登录态token
  169. * @param {Object} store
  170. * @param {Object} params
  171. */
  172. async doGameLogin ({ dispatch, commit, state }, params) {
  173. let userId = localStorage.getItem('user_id')
  174. let token = localStorage.getItem('token')
  175. if (userId && token) {
  176. commit('setUserId', userId)
  177. commit('setToken', token)
  178. return Promise.resolve({
  179. user_id: userId,
  180. token: token
  181. })
  182. } else {
  183. let rData = await API.user.getRandom({ account: state.account.name })
  184. let random = rData.data.data
  185. let pubkey = state.publicKey
  186. return new Promise((resolve, reject) => {
  187. state.scatter.getArbitrarySignature(pubkey, random, 'Need Login').then(sign => {
  188. let param = {
  189. account: state.account.name,
  190. sign,
  191. pubkey,
  192. data: random
  193. }
  194. API.user.eosLogin(param).then(({ data }) => {
  195. if (data.result === 1) {
  196. let userId = data.data.user_id
  197. let token = data.data.token
  198. localStorage.setItem('user_id', userId)
  199. localStorage.setItem('token', token)
  200. commit('setUserId', userId)
  201. commit('setToken', token)
  202. resolve(data)
  203. } else {
  204. reject(new Error(data.msg))
  205. }
  206. })
  207. }).catch(error => {
  208. reject(error)
  209. })
  210. })
  211. }
  212. },
  213. /**
  214. * 登录态过期,清除当前登录态相关数据,重新调起登录
  215. * @param {Object} store
  216. * @param {Object} params
  217. */
  218. async resetGameLogin ({ dispatch, commit, state }, params) {
  219. localStorage.removeItem('user_id')
  220. localStorage.removeItem('token')
  221. await dispatch('doContractLogin')
  222. if (self !== top) {
  223. location.replace(location.href.replace('show=false', 'show=true'))
  224. } else {
  225. location.reload()
  226. }
  227. },
  228. /**
  229. * 合约登录, 生成业务登录态token
  230. * @param {Array} params
  231. */
  232. async doContractLogin ({ commit, state }, params) {
  233. let userId = localStorage.getItem('user_id')
  234. let token = localStorage.getItem('token')
  235. if (userId && token) {
  236. commit('setUserId', userId)
  237. commit('setToken', token)
  238. return Promise.resolve({
  239. user_id: userId,
  240. token: token
  241. })
  242. } else {
  243. try {
  244. // 合约登录
  245. let { data } = await API.user.getRandom2({ account: state.account.name })
  246. let random = data.data.random
  247. let accessToken = data.data.accessToken
  248. let identity = { authorization: [`${state.account.name}@${state.account.authority}`] }
  249. let trx = null
  250. if (self !== top) {
  251. trx = await window.postMessager.send({
  252. action: 'meechat:eosAction',
  253. data: {
  254. contract: 'meechatadmin',
  255. action: 'login',
  256. param: [state.account.name, random, identity]
  257. }
  258. })
  259. } else {
  260. let eos = window.EOS || state.scatter.eos
  261. let contract = await eos.contract('meechatadmin')
  262. trx = await contract.login(state.account.name, random, identity)
  263. }
  264. let param = {
  265. account: state.account.name,
  266. access_token: accessToken,
  267. trx_id: trx.transaction_id || trx.transaction.transaction_id,
  268. group_id: state.group.groupId || null
  269. }
  270. let res = await API.user.eosLogin2(param)
  271. if (res.data.result === 1) {
  272. let userId = res.data.data.user_id
  273. let token = res.data.data.token
  274. localStorage.setItem('user_id', userId)
  275. localStorage.setItem('token', token)
  276. commit('setUserId', userId)
  277. commit('setToken', token)
  278. return Promise.resolve(res.data)
  279. }
  280. } catch (error) {
  281. return Promise.reject(error)
  282. }
  283. }
  284. },
  285. /**
  286. * @des 获取热门群组
  287. */
  288. getHotList ({ state }, params) {
  289. if (state.hotList.length > 0) return
  290. API.group.getHotList().then(({ data }) => {
  291. state.hotList = data.data
  292. })
  293. }
  294. }