auth.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import Cookies from "js-cookie";
  2. import axios from "axios";
  3. import {message} from "antd";
  4. const TokenKey = "hello-blog-token";
  5. const Avatar = "Avatar";
  6. export function getAvatar() {
  7. return Cookies.get(Avatar);
  8. }
  9. export function setAvatar(url) {
  10. return Cookies.set(Avatar, url);
  11. }
  12. export function getToken() {
  13. return Cookies.get(TokenKey);
  14. }
  15. export function setToken(token) {
  16. return Cookies.set(TokenKey, token);
  17. }
  18. export function removeToken() {
  19. return Cookies.remove(TokenKey);
  20. }
  21. export function loginGithubHandel(e) {
  22. const {socialId, avatar, name, htmlUrl} = e.data;
  23. if (socialId) {
  24. axios({
  25. method: 'post',
  26. url: '/auth/user/v1/login',
  27. data: {
  28. socialId: socialId,
  29. avatar: avatar,
  30. name: name,
  31. htmlUrl: htmlUrl
  32. }
  33. }).then((res) => {
  34. if (res.success === 1) {
  35. setToken(res.model.token);
  36. setAvatar(res.model.avatar);
  37. message.success('登录成功');
  38. }
  39. });
  40. window.removeEventListener("message", loginGithubHandel, false);
  41. }
  42. }
  43. export function scrollAnimation(currentY, targetY) {
  44. // 计算需要移动的距离
  45. let needScrollTop = targetY - currentY;
  46. let _currentY = currentY;
  47. setTimeout(() => {
  48. // 一次调用滑动帧数,每次调用会不一样
  49. const dist = Math.ceil(needScrollTop / 10);
  50. _currentY += dist;
  51. window.scrollTo(_currentY, currentY);
  52. // 如果移动幅度小于十个像素,直接移动,否则递归调用,实现动画效果
  53. if (needScrollTop > 10 || needScrollTop < -10) {
  54. scrollAnimation(_currentY, targetY)
  55. } else {
  56. window.scrollTo(_currentY, targetY)
  57. }
  58. }, 1)
  59. }