auth.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* eslint-disable import/no-cycle */
  2. import Toast from "toasters";
  3. import ws from "@/ws";
  4. // when Vuex needs to interact with websockets
  5. export default {
  6. register(user) {
  7. return new Promise((resolve, reject) => {
  8. const { username, email, password, recaptchaToken } = user;
  9. ws.socket.dispatch(
  10. "users.register",
  11. username,
  12. email,
  13. password,
  14. recaptchaToken,
  15. res => {
  16. if (res.status === "success") {
  17. if (res.SID) {
  18. return lofig.get("cookie").then(cookie => {
  19. const date = new Date();
  20. date.setTime(
  21. new Date().getTime() +
  22. 2 * 365 * 24 * 60 * 60 * 1000
  23. );
  24. const secure = cookie.secure
  25. ? "secure=true; "
  26. : "";
  27. document.cookie = `SID=${
  28. res.SID
  29. }; expires=${date.toGMTString()}; domain=${
  30. cookie.domain
  31. }; ${secure}path=/`;
  32. return resolve({
  33. status: "success",
  34. message: "Account registered!"
  35. });
  36. });
  37. }
  38. return reject(new Error("You must login"));
  39. }
  40. return reject(new Error(res.message));
  41. }
  42. );
  43. });
  44. },
  45. login(user) {
  46. return new Promise((resolve, reject) => {
  47. const { email, password } = user;
  48. ws.socket.dispatch("users.login", email, password, res => {
  49. if (res.status === "success") {
  50. return lofig.get("cookie").then(cookie => {
  51. const date = new Date();
  52. date.setTime(
  53. new Date().getTime() + 2 * 365 * 24 * 60 * 60 * 1000
  54. );
  55. const secure = cookie.secure ? "secure=true; " : "";
  56. let domain = "";
  57. if (cookie.domain !== "localhost")
  58. domain = ` domain=${cookie.domain};`;
  59. document.cookie = `${cookie.SIDname}=${
  60. res.data.SID
  61. }; expires=${date.toGMTString()}; ${domain}${secure}path=/`;
  62. return resolve({ status: "success" });
  63. });
  64. }
  65. return reject(new Error(res.message));
  66. });
  67. });
  68. },
  69. logout() {
  70. return new Promise((resolve, reject) => {
  71. ws.socket.dispatch("users.logout", res => {
  72. if (res.status === "success") {
  73. return lofig.get("cookie").then(cookie => {
  74. document.cookie = `${cookie.SIDname}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
  75. return window.location.reload();
  76. });
  77. }
  78. new Toast(res.message);
  79. return reject(new Error(res.message));
  80. });
  81. });
  82. }
  83. };