index.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import API from '@/api'
  2. import Eos from 'eosjs'
  3. import { Cookie } from '../../util/util'
  4. import { getNetwork } from '../../util/contract.js'
  5. var LoginPlugin = {}
  6. LoginPlugin.install = function (Vue, options) {
  7. // 获取用户公钥
  8. Vue.prototype.$getPubKey = function () {
  9. return new Promise((resolve, reject) => {
  10. let publicKey
  11. let account = this.$store.state.account
  12. if (account) {
  13. this.$store.state.eos.getAccount(account.name).then(data => {
  14. const perms = JSON.parse(JSON.stringify(data.permissions))
  15. perms.forEach(v => {
  16. if (v.perm_name === 'active') {
  17. publicKey = v.required_auth.keys[0].key
  18. }
  19. })
  20. resolve(publicKey)
  21. })
  22. }
  23. })
  24. }
  25. // 生成随机数
  26. Vue.prototype.$getRandom = function () {
  27. let account = this.$store.state.account
  28. return new Promise((resolve, reject) => {
  29. API.user.getRandom({
  30. account: account.name
  31. }).then(data => {
  32. resolve(data.data.data)
  33. })
  34. })
  35. }
  36. // 私钥签名登录
  37. Vue.prototype.$login = async function () {
  38. if (!this.$store.state.account.name) {
  39. let networkConfig = await getNetwork()
  40. try {
  41. let identity = await this.$store.state.scatter.getIdentity({ accounts: [networkConfig] })
  42. let accounts = identity.accounts.find(x => x.blockchain === 'eos')
  43. this.$store.dispatch('setAccount', accounts)
  44. this.$store.dispatch('setEos', this.$store.state.scatter.eos(networkConfig, Eos, {}))
  45. return Promise.resolve()
  46. } catch (error) {
  47. return Promise.reject(error)
  48. }
  49. }
  50. if (Cookie.getCookie('account') && Cookie.getCookie('token')) {
  51. return Promise.resolve()
  52. } else {
  53. try {
  54. let account = this.$store.state.account
  55. let [random, pubkey] = await Promise.all([this.$getRandom(), this.$getPubKey()])
  56. return new Promise((resolve, reject) => {
  57. this.$store.state.scatter.getArbitrarySignature(pubkey, random, this.$t('walletLogin')).then(sign => {
  58. let param = {
  59. account: account.name,
  60. sign,
  61. pubkey,
  62. data: random
  63. }
  64. API.user.login(param).then(({ data }) => {
  65. if (data.result === 1) {
  66. let account = data.data.account
  67. let token = data.data.token
  68. Cookie.setCookie('account', account)
  69. Cookie.setCookie('token', token)
  70. resolve(data)
  71. } else {
  72. reject(new Error(data.msg))
  73. }
  74. })
  75. }).catch(error => {
  76. reject(error)
  77. })
  78. })
  79. } catch (error) {
  80. Promise.reject(error)
  81. }
  82. }
  83. }
  84. Vue.prototype.$isLogin = function () {
  85. return Cookie.getCookie('account') && Cookie.getCookie('token')
  86. }
  87. }
  88. export default LoginPlugin