UNPKG

@nerdlat/auth

Version:

Authentication library similar to Clerk for React and Express applications

85 lines (84 loc) 3.05 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.resetPassword = exports.logout = exports.signup = exports.login = exports.getMe = exports.authAPI = void 0; exports.configureAuth = configureAuth; class AuthAPI { constructor(config = {}) { this.baseUrl = config.baseUrl || ''; this.apiPath = config.apiPath || '/api/auth'; } getUrl(endpoint) { return `${this.baseUrl}${this.apiPath}${endpoint}`; } async getMe() { const res = await fetch(this.getUrl('/me'), { credentials: 'include' // Importante para cookies }); if (!res.ok) throw new Error('Not authenticated'); return res.json(); } async login(email, password) { const res = await fetch(this.getUrl('/login'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ email, password }), }); if (!res.ok) { const error = await res.text(); throw new Error(error || 'Invalid credentials'); } return res.json(); } async signup(email, password) { const res = await fetch(this.getUrl('/signup'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ email, password }), }); if (!res.ok) { const error = await res.text(); throw new Error(error || 'Error creating user'); } return res.json(); } async logout() { const res = await fetch(this.getUrl('/logout'), { method: 'POST', credentials: 'include' }); if (!res.ok) throw new Error('Failed to logout'); } async resetPassword(email, newPassword) { const res = await fetch(this.getUrl('/reset-password'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ email, newPassword }), }); if (!res.ok) { const error = await res.text(); throw new Error(error || 'Failed to reset password'); } } } // Instancia por defecto exports.authAPI = new AuthAPI(); // Funciones de conveniencia que usan la instancia por defecto const getMe = () => exports.authAPI.getMe(); exports.getMe = getMe; const login = (email, password) => exports.authAPI.login(email, password); exports.login = login; const signup = (email, password) => exports.authAPI.signup(email, password); exports.signup = signup; const logout = () => exports.authAPI.logout(); exports.logout = logout; const resetPassword = (email, newPassword) => exports.authAPI.resetPassword(email, newPassword); exports.resetPassword = resetPassword; // Función para configurar la API function configureAuth(config) { Object.assign(exports.authAPI, new AuthAPI(config)); }