Eco-It uses JSON Web Tokens (JWT) for stateless authentication. When a user logs in successfully, the server signs and returns a token that must be attached to every subsequent request that accesses a protected resource. There are no sessions stored on the server for REST API calls — the token itself carries all necessary identity and role information.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/vanegasjoseignacio2-cyber/Eco-It/llms.txt
Use this file to discover all available pages before exploring further.
How Authentication Works
The server signs tokens with theJWT_SECRET environment variable using the default HS256 algorithm. Every token has a 12-hour expiry. Once a token expires the client must obtain a new one by logging in again — there is no refresh token endpoint.
Tokens are signed server-side and cannot be tampered with. Any modification to the token payload invalidates the signature, causing the
verificarToken middleware to reject the request with a 401 error.JWT Payload
After successful login, the decoded token payload contains the following claims:The MongoDB
_id of the authenticated user. Used by middleware to look up the full, up-to-date user record from the database on every request.The user’s role. One of
user, admin, or superadmin. Controls access to role-restricted endpoints.Indicates whether the user has completed their profile setup. Some frontend flows gate certain actions on this flag.
Obtaining a Token
There are two ways to obtain a JWT.Google OAuth
Redirect the user to the Google OAuth callback URL handled by Passport.js. After Google authenticates the user and redirects back, the server issues a JWT in the same way as email/password login. The OAuth flow is initiated via
/api/auth/google and completes at the configured callback route.Sending the Token
Once you have a token, include it in theAuthorization header of every request to a protected endpoint using the Bearer scheme:
cURL example — authenticated request
401 response:
401 – Token required
401 – User not found
401 – Token expired
401 – Token invalid
How verificarToken Works
Every protected route applies the verificarToken middleware before its handler runs. The middleware performs the following steps in order:
Extract the token
Reads the
Authorization request header and extracts the token from Bearer <token>. If the header is absent or does not start with Bearer, the middleware immediately returns 401 { message: "Token requerido" }.Verify the signature
Calls
jwt.verify(token, process.env.JWT_SECRET) to validate the signature and check expiry. A TokenExpiredError returns 401 { message: "Token expirado, inicia sesion nuevamente" }; a JsonWebTokenError (tampered or malformed token) returns 401 { message: "Token invalido" }.Fetch the live user record
Uses the
id from the decoded payload to query MongoDB for the current user document (password field excluded). If no matching user is found, the middleware returns 401 { message: "Usuario no encontrado" }. This ensures that any changes made to the user’s account since the token was issued — such as role updates or bans — are reflected immediately without waiting for the token to expire.Check ban status
If the user’s
status is 'banned' and the current time is before banHasta, the middleware returns 403 with the ban details. If the ban period has already passed, it is automatically lifted (status set to 'active', banHasta and banReason cleared) and the request proceeds normally.Role-Based Access Control
AfterverificarToken populates req.usuario, additional role-guard middleware can be chained to restrict endpoints by role.
| Middleware | Allowed roles | Rejection response |
|---|---|---|
soloAdmin | admin, superadmin | 403 { message: "Acesso denegado: se requiere rol admin o superadmin" } |
soloSuperadmin | superadmin only | 403 { message: "Acceso denegado: se requiere rol superadmin" } |
soloUser | user only | 403 { message: "Acesso denegado: se requiere rol user" } |
Express route example
Ban Handling
If a user account has been banned by an administrator, theverificarToken middleware returns a 403 response with structured ban metadata so the client can display an informative message:
403 – Account banned
Always
true when this error is returned. Used by the frontend to distinguish a ban from other 403 errors.Human-readable reason provided by the administrator who issued the ban.
The UTC datetime at which the ban expires. After this point, the next authenticated request will automatically lift the ban and allow normal access.
Token Refresh
Frontend Integration
The Eco-It frontend uses afetchAPI helper defined in frontend/src/services/api.js that automatically reads the token from localStorage and injects it into every outgoing request:
frontend/src/services/api.js
fetchAPI with the endpoint path relative to /api:
Fetching the authenticated user's profile
When the API returns a
401 status code, fetchAPI dispatches an auth-expired DOM event on window. The application’s top-level auth listener catches this event and triggers an automatic logout, clearing the stored token and redirecting the user to the login page — no manual handling required at the component level. Pass { skipAuthError: true } in the options object to suppress this behaviour for endpoints where a 401 is an expected, non-critical response (e.g. silently checking authentication state on page load).