¿Todo esto no sobra si usamos el atributo encrypt en el modelo ?
https://sailsjs.com/documentation/concepts/models-and-orm/attributes#encryption-at-rest
Introducción
Qué aprenderás sobre API con Sails.js
Presentando el proyecto
Comenzando con Sails
Introducción a Sails.js
Estructura de archivos
Preparación del ambiente de desarrollo
Setup de Espacio de Trabajo
Generando rutas REST con blueprint
Instalación de MongoDB
Conexión a Mongo
Instalar MySQL y usarlo con Sails (a través de WaterLine)
CRUD
Entendiendo operaciones CRUD
Crear modelo de rodada
Crear app de Ionic
Obtener todas las Rodadas: preparando la aplicación para mostrar datos
Obtener todas las Rodadas: mostrando los datos
Crear Rodada: recibiendo parámetros desde la URL
Crear Rodada: enviando información desde el formulario
Actualizar Rodada
Eliminar Rodadas
Autenticación y Usuarios
Obtener Rodada
Crear Modelo y Controller de Usuarios
Implementar validación de modelo
Nueva versión de la librería Joi
Crear Usuario
Cifrado de contraseña
Implementación de Login
Sistemas Externos
Uso de JSON Web Token
Policies: verificar si usuario está loggeado
Agregar usuario a Ride
Preparando la App para implementar el Login y Sign up
Implementando Login
Implementando Sign up
Agregar puntos de Rodada
Obtener API Keys para Clima y Distancias
Integración Google Geocoding: definiendo la lógica
Integración Google Geocoding: probando la funcionalidad
Integración Weather API
Desplegar clima, distancia y tiempo en cada punto de Rodada
Cierre
Cierre
You don't have access to this class
Keep learning! Join and start boosting your career
Secure storage of passwords is a vital practice for maintaining the integrity and security of web applications. One of the most common challenges is storing passwords in such a way that they are inaccessible if someone unauthorized gains access to the database. Here's how you can use the Bcrypt library to securely encrypt passwords.
Bcrypt is a widely used library for encrypting passwords. The main advantage is that it converts a text string, such as "Password123", into a 32-character encrypted string with no direct relation to the original text. This means that even if someone can access the encrypted data, they will not be able to reverse the process or use it to authenticate users.
The following guide shows how you can encrypt your users' passwords using Bcrypt. We recommend you to follow these steps in your code:
// Import the Bcrypt libraryconst bcrypt = require('bcrypt');
// Set the 'salt' level, or encryption complexityconst saltRounds = 10;
// Store a password securelyasync function storePassword(password) { try { // Generate a hash for the password const hashedPassword = await bcrypt.hash(password, saltRounds); // We save the hash to the database instead of the password in cleartext // Database.saveUser({ password: hashedPassword }); } catch (error) { console.error('Error encrypting password:', error); } }}
// Example of usingstorePassword('Password123');
The term 'salt' refers to an additional value that is added to the encryption process to increase security. The idea is to avoid dictionary-based attacks and Rainbow tables, which compare previously encrypted hash outputs. By varying the 'salt', we make it more difficult for two of the same passwords to generate the same hash.
const saltRounds = 10;
, this line determines the level of security applied to the hash. The higher the number, the more robust the resulting hash will be, but also the more processing and time it will require.During development, it is common to face situations where the system has configuration or implementation errors. Here is a common error and how to fix it:
// Storage solution// Instead of creating a separate field, directly update the database field with the generated hash:function updateUserWithHash(hashPassword) { // Assuming the original database field is named 'password' database.updateUser({ password: hashPassword });}
Proper implementation and understanding of these concepts will not only ensure that your application protects user credentials from unauthorized access, but will also give you peace of mind that you are following industry best practices. Keep learning and exploring ways to improve the security of your applications!
Contributions 4
Questions 0
¿Todo esto no sobra si usamos el atributo encrypt en el modelo ?
https://sailsjs.com/documentation/concepts/models-and-orm/attributes#encryption-at-rest
Sails tiene algo parecido a las señales de Django que permite implementar acciones antes o después de que se guarde un usuario. Es decir, podríamos guardar la contraseña en texto plano y sails automáticamente se encarga de hashearla en el momento justo antes de guardarla en la base de datos. Dejo aquí el enlace a la documentación https://sailsjs.com/documentation/concepts/models-and-orm/lifecycle-callbacks#example
Yo recomendaría crear un helper:
const bcrypt = require('bcrypt');
module.exports = {
friendlyName: 'Generate password',
description: 'Generate password',
inputs: {
password: {
type: 'string',
required: true
}
},
exits: {},
fn: async function (inputs, exits) {
const hash = bcrypt.hashSync(inputs.password, 10);
return exits.success(hash);
}
};
Y en tu controller:
module.exports = async function signup (req, res) {
const email = req.param('email');
const pass = req.param('password');
// No olvides tus validaciones...
const hash = await sails.helpers.generatePassword(pass);
var user = await User.create({
email: email, password: hash
}).fetch();
return res.status(201).send("OK");
};
✌
Want to see more contributions, questions and answers from the community?