auth.js 895 B

1234567891011121314151617181920212223242526272829303132333435
  1. import { login } from '../api/user'
  2. import { FETCH_AND_FORMAT_USER_INFO } from './util'
  3. // 检查是否登录
  4. export function isLoggedIn() {
  5. const token = wx.getStorageSync('token')
  6. const expires = wx.getStorageSync('expires_in')
  7. return token && expires && expires > Date.now()
  8. }
  9. // 调用登录
  10. export async function doLogin({ code, phone, nickname, avatar }) {
  11. wx.showLoading({
  12. title: '登录中...',
  13. mask: true
  14. });
  15. try {
  16. const res = await login({
  17. code,
  18. phone,
  19. nickname,
  20. avatar
  21. })
  22. wx.setStorageSync('token', res.data.token_type + ' ' + res.data.access_token)
  23. wx.setStorageSync('expires_in', Date.now() + ((res.data.expires_in - 10) * 1000))
  24. FETCH_AND_FORMAT_USER_INFO()
  25. } catch (error) {
  26. wx.showToast({
  27. title: '登录失败',
  28. icon: 'none',
  29. duration: 2000
  30. });
  31. } finally{
  32. wx.hideLoading();
  33. }
  34. }