auth.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import Toast from "toasters";
  2. import io from "../io";
  3. // when Vuex needs to interact with socket.io
  4. export default {
  5. register(user) {
  6. return new Promise((resolve, reject) => {
  7. const { username, email, password, recaptchaToken } = user;
  8. io.getSocket(socket => {
  9. socket.emit(
  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. },
  46. login(user) {
  47. return new Promise((resolve, reject) => {
  48. const { email, password } = user;
  49. io.getSocket(socket => {
  50. socket.emit("users.login", email, password, res => {
  51. if (res.status === "success") {
  52. return lofig.get("cookie").then(cookie => {
  53. const date = new Date();
  54. date.setTime(
  55. new Date().getTime() +
  56. 2 * 365 * 24 * 60 * 60 * 1000
  57. );
  58. const secure = cookie.secure ? "secure=true; " : "";
  59. let domain = "";
  60. if (cookie.domain !== "localhost")
  61. domain = ` domain=${cookie.domain};`;
  62. document.cookie = `${cookie.SIDname}=${
  63. res.SID
  64. }; expires=${date.toGMTString()}; ${domain}${secure}path=/`;
  65. return resolve({ status: "success" });
  66. });
  67. }
  68. return reject(new Error(res.message));
  69. });
  70. });
  71. });
  72. },
  73. logout() {
  74. return new Promise((resolve, reject) => {
  75. io.getSocket(socket => {
  76. socket.emit("users.logout", res => {
  77. if (res.status === "success") {
  78. return lofig.get("cookie").then(cookie => {
  79. document.cookie = `${cookie.SIDname}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;`;
  80. return window.location.reload();
  81. });
  82. }
  83. new Toast({ content: res.message, timeout: 4000 });
  84. return reject(new Error(res.message));
  85. });
  86. });
  87. });
  88. }
  89. };