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 🙏

© 2024 – Pkg Stats / Ryan Hefner

easy-auth-mail

v1.2.3

Published

Autentificación de usuarios utilizando correo electronico y la dependencia nodemailer

Downloads

17

Readme

Easy-auth-mail

Descripción

Al desarrollar una aplicación web que requiere el registro de usuarios es necesario implementar un método de autentificación para evitar que se utilicen correos electronicos falsos que ocupan espacio innecesario en la base de datos.

Para evitar que esto suceda podemos implementar una forma de autentificar que dichos correos son reales enviando un token o código que debe ser ingresado para completar el registro.

Instalación

Para instalar el paquete utiliza npm o pnpm

npm

npm i easy-auth-mail

pnpm

pnpm add easy-auth-mail

Uso/Ejemplos

Por seguridad, evita escribir tus credenciales de tu servicio de correo electronico directamente en el código. Utiliza variables de entorno con dotenv

1) Instala dotenv en tu proyecto

npm
npm install dotenv
pnpm
pnpm add dotenv

2) Crea un archivo llamado .env en la raíz de tu proyecto

3) En el archivo creado escribe las siguientas variables

MAIL_SENDER=<[email protected]>
PASS_SENDER=<yourpassword>

4) Carga las variables de entorno y declara las variables a utilizar en un archivo de configuración o en alguna parte de tu aplicación para utilizarlas posteriormente

import dotenv from 'dotenv'
dotenv.config()
const user = process.env.MAIL_SENDER
const pass = process.env.PASS_SENDER

5) Finalmente utiliza las funciones del proyecto

// TODO: Importa las funciones 
import { Router } from "express";
import { authenticateUser, authenticateToken, createMailOptions } from "easy-auth-mail/src/index.js";
import UserToken from 'easy-auth-mail/src/models/UserToken.js'
import dotenv from 'dotenv'
dotenv.config()
// carga las variables de entorno
const user = process.env.MAIL_SENDER
const pass = process.env.PASS_SENDER

// crea el transportador (te permitira conectarte con tu servicio de mail)
// indica que tipo de servicio quieres utiliza e ingresa las credenciales para utilizar tu correo. Este objeto puedes crearlo una vez y
// guardarlo en un archivo de configuración
const transport = createTransport({service: 'gmail', auth: {user: user, pass: pass}})

// ejemplo utilizando express
const api = Router()

api.post('/api/signup', async (req, res) => {
    // get credentials from body request
    const { mail, password } = req.body
    if (!mail || !password) return res.status(401).json({ status: 401, message: 'No mail or password received' })
    // create object userToken and generate token 
    const token = new UserToken({ user: { email: mail, password: password } })
    await token.generateToken()
    // create mailOptions
    const mailOptions = await createMailOptions({
        sender: config.user, user: { mail: token.email, token: token.token },
        content: { subject: `Authentication code from Test App` }
    })
    // finally, use authenticateUser to send mail
    await authenticateUser({ userToken: token, transport, config: { timeOutDuration: ((60 * 3) * 1000) }, mailOptions })
    // you can save a temporal session with user value in your db

    // response
    res.status(201).json({ status: 200, message: 'Mail send' })
})

api.post('/api/auth', (req, res) => {
    // get token from body request
    const { token } = req.body
    if (!token) return res.status(401).json({ status: 401, message: 'No token received' })

    // in case token was received - authenticate token
    const isAuthenticated = authenticateToken({ token })
    // if its true you can get from your db the temporal session and save in user table

    // response
    res.status(200).json({ status: isAuthenticated ? 200 : 401, message: isAuthenticated ? 'Authentication success' : 'Error. Invalid token or expired' })
})

Usando un callback al autenticar un token

api.post('/api/auth', (req, res) => {
    // get token from body request
    const { token } = req.body
    if (!token) return res.status(401).json({ status: 401, message: 'No token received' })

    // in case token was received - authenticate token and get token with callback
    const isAuthenticated = authenticateToken({ token, callback: (userToken) => {
        // do somenting like save credentials in your db
    } })

    // response
    res.status(200).json({ status: isAuthenticated ? 200 : 401, message: isAuthenticated ? 'Authentication success' : 'Error. Invalid token or expired' })
})

Para contribuir

Para contribuir visita el siguiente enlace donde se encuenta el repositorio. easy-auth-mail

License

MIT