auth.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import {body, get} from "@/utils/https";
  2. // const _tokenQueue: {
  3. // pending: boolean;
  4. // list: {
  5. // resolve: (value: string) => void;
  6. // reject: (err: any) => void;
  7. // }[];
  8. // } = {
  9. // pending: false,
  10. // list: [],
  11. // };
  12. //
  13. // let _onTokenListener: {
  14. // cb: (token: string) => void;
  15. // }[] = [];
  16. //
  17. // const _resolveTokenQueue = function (res: any) {
  18. // _tokenQueue.pending = false;
  19. // uni.hideLoading();
  20. // if (res.errMsg) {
  21. // console.log(res);
  22. // uni.showModal({
  23. // title: "登录失败",
  24. // content: `${res.errMsg}`,
  25. // });
  26. // _tokenQueue.list.forEach((item) => {
  27. // item.reject(res);
  28. // });
  29. // } else {
  30. // uni.showToast({
  31. // icon: "success",
  32. // title: "登录成功",
  33. // });
  34. // setToken(res as string);
  35. // _onTokenListener.forEach((item) => {
  36. // item.cb(res as string);
  37. // });
  38. // _tokenQueue.list.forEach((item) => {
  39. // item.resolve(res as string);
  40. // });
  41. // }
  42. // _onTokenListener = [];
  43. // _tokenQueue.list = [];
  44. // };
  45. export function login(e: any): Promise<string> {
  46. return new Promise((resolve, reject) => {
  47. if (/deny|cancel/.test(e.errMsg)) {
  48. reject(e.errMsg);
  49. return;
  50. }
  51. if (!e.code) {
  52. uni.showModal({
  53. title: `${e.errMsg},请重试`,
  54. });
  55. reject(e);
  56. return;
  57. }
  58. // _tokenQueue.list.push({
  59. // resolve,
  60. // reject,
  61. // });
  62. // if (_tokenQueue.pending) {
  63. // return;
  64. // }
  65. // _tokenQueue.pending = true;
  66. uni.showLoading({
  67. title: "登录中",
  68. mask: true,
  69. });
  70. uni.login({
  71. success: (res) => {
  72. let data = {
  73. phoneCode: e.code,
  74. code: res.code,
  75. avatar: "",
  76. nickname: "",
  77. shortId: e.shortId
  78. }
  79. body(`/user/wxLogin`, data).then(async (res: any) => {
  80. let {satoken, userId} = res;
  81. if (satoken) {
  82. getApp<any>().globalData.user.id = userId
  83. // _resolveTokenQueue(satoken);
  84. setToken(satoken);
  85. await loadUserInfo();
  86. resolve(satoken)
  87. uni.hideLoading();
  88. } else {
  89. uni.showModal({
  90. title: `登录失败`,
  91. icon: 'none',
  92. duration: 2000
  93. });
  94. uni.hideLoading();
  95. // _resolveTokenQueue({
  96. // errMsg: `${JSON.stringify(res)}`,
  97. // });
  98. }
  99. }).catch(e => {
  100. uni.showModal({
  101. title: `${e}`,
  102. icon: 'none',
  103. duration: 2000
  104. });
  105. uni.hideLoading();
  106. })
  107. },
  108. fail: () => {
  109. uni.showModal({
  110. title: `登录失败`,
  111. icon: 'none',
  112. duration: 2000
  113. });
  114. uni.hideLoading();
  115. },
  116. });
  117. });
  118. }
  119. export function tryLogin() {
  120. return new Promise(((resolve, reject) => {
  121. let ftoken = fetchToken();
  122. // console.log("ftoken", ftoken)
  123. if (ftoken) {
  124. resolve(ftoken)
  125. return;
  126. }
  127. uni.showLoading()
  128. uni.login({
  129. success: (res) => {
  130. let data = {
  131. phoneCode: "",
  132. code: res.code,
  133. avatar: "",
  134. nickname: "",
  135. }
  136. body(`/user/wxLogin`, data).then(async (res: any) => {
  137. const {satoken, userId} = res;
  138. if (satoken) {
  139. getApp<any>().globalData.user.id = userId
  140. setToken(satoken);
  141. await loadUserInfo();
  142. resolve(satoken)
  143. } else {
  144. console.error("tryLogin")
  145. // _resolveTokenQueue({
  146. // errMsg: `${JSON.stringify(res)}`,
  147. // });
  148. }
  149. uni.hideLoading()
  150. }).catch(e => {
  151. reject(e)
  152. uni.hideLoading()
  153. })
  154. },
  155. fail: function () {
  156. reject('fail')
  157. uni.hideLoading()
  158. },
  159. });
  160. }))
  161. }
  162. export function checkLogin() {
  163. return new Promise((resolve, reject) => {
  164. let user = getApp<any>().globalData.user;
  165. if (!user || !user.id) {
  166. uni.showToast({
  167. icon: "none",
  168. title: "请先登录",
  169. });
  170. reject('未获取到用户登录信息');
  171. } else {
  172. resolve(user);
  173. }
  174. })
  175. }
  176. export async function loadUserInfo() {
  177. getApp<any>().globalData.manualLogout = false;
  178. get(`/user/me`).then((res: any) => {
  179. // getApp<any>().globalData.user = res;
  180. // getApp<any>().globalData.isLogin = true;
  181. getApp<any>().globalData = Object.assign({}, {...getApp<any>().globalData},{user:res,isLogin:true,manualLogout:false})
  182. uni.$emit('login', {isLogin: true})
  183. })
  184. }
  185. export function refresh(): Promise<string> {
  186. return new Promise((resolve, reject) => {
  187. uni.getStorage({key: "token"}).then((token) => {
  188. if (!token) {
  189. clearToken();
  190. reject({
  191. errMsg: "请登录",
  192. });
  193. uni.reLaunch({
  194. url: "/pages/map/index",
  195. });
  196. } else {
  197. getApp<any>().globalData.token = "";
  198. uni.removeStorageSync("token");
  199. get(`/user/refresh`).then((res: any) => {
  200. const {statusCode, data} = res;
  201. if (
  202. statusCode === 200 &&
  203. data &&
  204. data.msg === "OK" &&
  205. data.code === 200
  206. ) {
  207. resolve(data.data.access_token);
  208. } else {
  209. if (data.code === 21005) {
  210. uni.reLaunch({
  211. url: "/pages/map/index",
  212. });
  213. }
  214. reject({
  215. errMsg: `${JSON.stringify(res)}`,
  216. });
  217. }
  218. }).catch(() => {
  219. reject()
  220. })
  221. }
  222. });
  223. });
  224. }
  225. export function fetchToken() {
  226. let tk = uni.getStorageSync("token");
  227. // console.log(tk)
  228. if (tk.length > 16) {
  229. return tk;
  230. }
  231. return null;
  232. }
  233. export function setToken(token: string) {
  234. if (!token) {
  235. console.error("empty token")
  236. return;
  237. } else {
  238. console.log("set token", token)
  239. }
  240. getApp<any>().globalData = Object.assign({}, {...getApp<any>().globalData},{token,isLogin:true})
  241. uni.setStorageSync("token", token)
  242. }
  243. export function clearToken() {
  244. let device = uni.getWindowInfo();
  245. let initGlobalData = {
  246. token: "",
  247. user: {},
  248. isLogin: false,
  249. last: {},
  250. device: {
  251. windowWidth:device.windowWidth,
  252. windowHeight:device.windowHeight,
  253. screenTop: device.screenTop,
  254. windowTop: device.windowTop,
  255. },
  256. deviceId: null,
  257. manualLogout: false
  258. }
  259. uni.$emit('logout')
  260. uni.removeStorageSync("token")
  261. getApp<any>().globalData = Object.assign({}, initGlobalData)
  262. }