LoginForm.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import {f} from "../helper.js";
  2. import {dEvent} from "../main.js";
  3. export default class LoginForm extends HTMLElement {
  4. constructor() {
  5. super();
  6. this.user = null;
  7. this.data = {
  8. login: "",
  9. password: "",
  10. }
  11. this.bindEvents();
  12. }
  13. connectedCallback() {
  14. if (!this.user) {
  15. this.render(this.getTemplateLogin())
  16. }
  17. }
  18. render(template) {
  19. this.innerHTML = template;
  20. this.attachModel();
  21. }
  22. getTemplateLogin() {
  23. return `
  24. <h3>Вход</h3>
  25. <div class="message"></div>
  26. <label>Логин: <input type="text" data-model="login"></label>
  27. <label>Пароль: <input type="text" data-model="password"></label>
  28. <button data-click="login">Войти</button>
  29. `
  30. }
  31. getTemplateOut() {
  32. return `
  33. <h3>Вы вошли как ${this.user.login}</h3>
  34. <div class="message"></div>
  35. <button data-click="logout">Выход</button>
  36. `
  37. }
  38. bindEvents() {
  39. console.log("BIND EVENT - " + this.constructor.name)
  40. document.addEventListener("user-login",(e) => {
  41. this.user = e.detail;
  42. this.render(this.getTemplateOut())
  43. })
  44. document.addEventListener("user-logout", (e)=>{
  45. this.render(this.getTemplateLogin())
  46. })
  47. }
  48. attachModel() {
  49. this.querySelectorAll("input")
  50. .forEach(el=>el.addEventListener("input",e =>this.inputText(e)))
  51. this.querySelector('button')
  52. .addEventListener('click', e => this.clickButton(e));
  53. }
  54. inputText(e) {
  55. if (this.data[e.target.dataset.model] !== undefined) {
  56. this.data[e.target.dataset.model] = e.target.value;
  57. console.log(this.data);
  58. }
  59. }
  60. clickButton(e) {
  61. this[e.target.dataset.click]();
  62. }
  63. async login() {
  64. if (!this.data.login || !this.data.password) return;
  65. let res = await f('login', 'post', null, this.data);
  66. console.log(res);
  67. localStorage.setItem("user", JSON.stringify(res));
  68. if (res.error) {
  69. this.querySelector('.message').innerHTML = 'Не правильный логин или пароль';
  70. this.querySelector('.message').innerHTML+=`<style>.message {background:crimson}</style>`
  71. return;
  72. }
  73. dEvent('user-login', {login: this.data.login, api_token: res.data.user_token, role: "admin"});
  74. }
  75. async logout() {
  76. console.log(this.user)
  77. let res = await f('logout', 'get', this.user.api_token, this.data);
  78. console.log(res)
  79. if (!res.message) {
  80. dEvent('user-logout');
  81. }
  82. }
  83. }