npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sistema-login-proprio

v1.0.0

Published

Sistema de login completo com API key para uso em outros projetos

Readme

Sistema de Login Multi-Tenant

Uma aplicação completa de autenticação e gestão de dados, isolada por tenant (site). Inclui frontend SPA (dashboard) e backend RESTful com JWT, refresh tokens, proteção contra brute-force, emails de reset e logs estruturados.

Tecnologias

  • Backend: Node.js, Express, Sequelize (SQLite)
  • Frontend: HTML5, CSS3 (Flexbox), JavaScript (Vanilla ES6)
  • Autenticação: JWT (jsonwebtoken), bcrypt, uuid
  • Segurança: express-rate-limit, express-validator, helmet, cors, xss-clean, hpp
  • Logs: winston (console + arquivo)
  • Emails: nodemailer (SMTP + fallback Ethereal)
  • Criptografia: AES-256-GCM (dados seguros via PBKDF2)

Estrutura do Projeto

.
├── config.js             # Configurações de criptografia (passphrase, salt, iterations, key version)
├── db.js                 # Instância Sequelize + definição de models
├── index.js              # Inicialização do Express + seed admin site + rotas
├── middleware/           # siteAuth, auth (JWT), bruteForce, security
├── models/               # User, Site, ApiKey, SecureData, LoginEvent, RefreshToken, PasswordReset
├── routes/               # auth.js, secureData.js, keys.js, protected.js
├── frontend/             # SPA static
│   ├── config.js         # define API_URL e SITE_API_KEY para o front
│   ├── dashboard.html    # SPA principal
│   ├── main.js           # lógica de autenticação, dashboard, perfil, API Keys
│   └── reset-password.js # página dedicada de reset
└── utils/logger.js       # logger Winston

Variáveis de Ambiente (.env)

SQLITE_STORAGE=database.sqlite
ADMIN_API_KEY=<uuid>
JWT_SECRET=<seu_segredo_jwt>
APP_ENCRYPTION_PASSPHRASE=<senha_criptografia>
APP_ENCRYPTION_SALT=<salt>
APP_ENCRYPTION_PBKDF2_ITERATIONS=100000
APP_ENCRYPTION_KEY_VERSION=1
PORT=5000
EMAIL_HOST=smtp.exemplo.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=seu_user
EMAIL_PASS=seu_pass
[email protected]
CORS_ORIGIN=http://localhost:5000

Instalação & Execução

  1. Clone e instale dependências:
    git clone <repo>
    cd sistema-login-proprio
    npm install
  2. Configure .env conforme acima.
  3. Inicie o servidor:
    npm run dev
  4. Abra no navegador:
    http://localhost:5000

Endpoints da API

Auth (/api/auth)

  • GET /has-user: verifica existência de usuário no tenant.
  • POST /register: { name, email, password } → cria usuário + API Key.
  • POST /login: { email, password } → retorna JSON { token, apiKey, name, email, message } + cookies HttpOnly.
  • GET /profile: headers Authorization: Bearer <token>, x-organization-key: retorna { id, name, email, siteId, createdAt }.
  • POST /refresh: renova tokens (cookies).
  • POST /logout: revoga refresh tokens.
  • POST /update-profile: { name, email } (1x) → atualiza nome/email.

Secure Data (/api/secure-data)

CRUD de dados criptografados (AES-GCM):

  • POST /: { name, data }.
  • GET /: lista dados.
  • GET /:id: lê.
  • DELETE /:id: remove.

API Keys (/api/keys)

  • GET /: lista chaves do usuário.
  • POST /: gera nova chave para integração externa.

Protected Example (/api/data)

  • GET /api/data: acesso via header x-api-key.

Como Funciona o Sistema

Fluxo de Registro e Login

  • Registro (POST /api/auth/register): recebe { name, email, password }, aplica bcrypt hash na senha e cria usuário + API Key de site.
  • Login (POST /api/auth/login): valida credenciais, gera JWT (1h) e Refresh Token (7d) em cookies HttpOnly; retorna JSON { token, apiKey, name, email, message }.

Fluxo de Dashboard e Perfil

  • Profile (GET /api/auth/profile): envia headers Authorization e x-organization-key; recebe { id, name, email, siteId, createdAt }.
  • Dashboard: exibe métricas (total de chaves, usuários, dados seguros) e histórico de API Keys.
  • Atualização de Perfil (POST /api/auth/update-profile): permite alterar nome/email apenas uma vez.

Criptografia & Secure Data

  • Endpoints /api/secure-data criptografam data via AES-256-GCM. Chave derivada por PBKDF2 (passphrase + salt, 100k iterações), inclui tag para autenticação.
  • O DB armazena ciphertext, nonce e versão da chave para futuras rotações.

Geração de API Keys (SaaS)

  • Botão “Get API Key” no dashboard abre modal (#api-key-modal) em dashboard.html.
  • Front envia POST /api/keys com body { email, project, site } e headers Authorization + x-organization-key.
  • Backend retorna { key: <uuid> }. Essa chave pode ser usada em outros projetos via header x-api-key, dispensando cookies.

Frontend SPA

  • Autenticação: login, registro, reset senha (forms centralizados).
  • Dashboard: visão geral (contagens de API Keys, usuários, dados seguros), histórico de chaves, gerenciamento de perfil, logout.
  • Perfil: visualiza e edita nome/email uma única vez.
  • API Key Modal: gerador de novas chaves.
  • Páginas: dashboard.html, reset-password.html.
  • Configuração: edite frontend/config.js:
    const API_URL = 'http://localhost:5000';
    const SITE_API_KEY = '<ADMIN_API_KEY ou ORG_API_KEY>';
  • Chamada HTTP: utiliza fetch com headers Authorization e x-organization-key.

Contribuição

Contribuições são bem-vindas! Abra issues ou envie PRs.


2025 Sistema de Login Multi-Tenant