| 1 | /** |
| 2 | * MAPS Connect - Autenticación y sesión |
| 3 | */ |
| 4 | |
| 5 | const Auth = { |
| 6 | TOKEN_KEY: 'token', |
| 7 | USER_KEY: 'user', |
| 8 | |
| 9 | saveSession(token, user) { |
| 10 | localStorage.setItem(this.TOKEN_KEY, token); |
| 11 | localStorage.setItem(this.USER_KEY, JSON.stringify(user)); |
| 12 | }, |
| 13 | |
| 14 | getToken() { |
| 15 | return localStorage.getItem(this.TOKEN_KEY); |
| 16 | }, |
| 17 | |
| 18 | getUser() { |
| 19 | const user = localStorage.getItem(this.USER_KEY); |
| 20 | return user ? JSON.parse(user) : null; |
| 21 | }, |
| 22 | |
| 23 | isAuthenticated() { |
| 24 | return !!this.getToken(); |
| 25 | }, |
| 26 | |
| 27 | logout() { |
| 28 | localStorage.removeItem(this.TOKEN_KEY); |
| 29 | localStorage.removeItem(this.USER_KEY); |
| 30 | window.location.href = Auth.resolvePath('index.html'); |
| 31 | }, |
| 32 | |
| 33 | /** Redirige a login si no hay sesión. Usar en páginas protegidas. */ |
| 34 | requireAuth() { |
| 35 | if (!this.isAuthenticated()) { |
| 36 | window.location.href = this.resolvePath('login.html'); |
| 37 | return false; |
| 38 | } |
| 39 | return true; |
| 40 | }, |
| 41 | |
| 42 | /** Redirige al dashboard si ya hay sesión. Usar en login/registro. */ |
| 43 | redirectIfAuthenticated() { |
| 44 | if (this.isAuthenticated()) { |
| 45 | window.location.href = this.resolvePath('pages/inicio.html'); |
| 46 | } |
| 47 | }, |
| 48 | |
| 49 | resolvePath(relativePath) { |
| 50 | const inPages = window.location.pathname.includes('/pages/'); |
| 51 | if (inPages && !relativePath.startsWith('../') && !relativePath.startsWith('pages/')) { |
| 52 | return '../' + relativePath; |
| 53 | } |
| 54 | if (!inPages && relativePath.startsWith('pages/')) { |
| 55 | return relativePath; |
| 56 | } |
| 57 | return relativePath; |
| 58 | } |
| 59 | }; |