Skip to content

Commit

Permalink
agregado la encriptacion de la contraseña
Browse files Browse the repository at this point in the history
  • Loading branch information
Robotitusx committed Sep 5, 2024
1 parent 7aa144f commit 7cbbc76
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 20 deletions.
40 changes: 37 additions & 3 deletions backend/src/controllers/autenticacion.controllers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { Request, Response } from 'express';
import { User, getUserByUsername, getUsers } from '../models/users.models';

export const loginController = (req: Request, res: Response): void => {
import { User, createUserDB, getUserByUsername, getUsers } from '../models/users.models';
import { validateUser } from '../utils/validations/users.validations';
import db from '../database/connection';
import { equalsHash } from '../utils/validations/hashing';
/**
export const loginControllerV2 = (req: Request, res: Response): void => {
const { username, password } = req.body;
Expand All @@ -24,4 +27,35 @@ export const loginController = (req: Request, res: Response): void => {
} catch (error) {
res.status(500).send('Error en el inicio de sesión');
}
}*/

export async function loginController(req: Request, res: Response) {
const user = req.body;
let createdUser = createUserDB(user);

try {
let user = await db.getUser(createdUser);
res.status(200).json({user});
} catch (error) {
res.status(404).send("usuario no encontrado");
}


}

export function createController(req: Request, res: Response) {
const user = req.body;
let createdUser = createUserDB(user);

validateUser(req, res, async () => {
try {
await db.createAdmin(createdUser);
res.status(200).send('admin creado con exito');
} catch (err) {
res.status(400).send('Error al crear el admin, bad request');
}

});
}


41 changes: 41 additions & 0 deletions backend/src/database/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { readFileSync } from 'fs';
import Database from 'sqlite3';
import sqlite3 from 'sqlite3';
import { Incidencia } from '../models/incidencias.models';
import { User } from '../models/users.models';
import { encriptSHA256 } from '../utils/validations/hashing';

export interface DatabaseSQL{
getIncidencias():any;
Expand Down Expand Up @@ -216,6 +218,45 @@ class DatabaseWrapper {

});
}

async createAdmin(user:User): Promise<Error | void> {
return new Promise((resolve, reject) => {

this.db.run("INSERT INTO administrator(user, pass, nombre, apellido, url_perfil, fecha_creacion, Rol) VALUES(?,?,?,?,?,?,?)",[user.username, encriptSHA256(user.password), user.nombre, user.apellido, user.imagenDePerfil, user.fechaDeCreacion, user.role], (err:Error) => {
if (err) {
console.error("Error al insertar new admin", err);
reject(err);
}else{
console.log("Admin insertado con exito");
resolve();
}
});

});

}

async getUser(user: User): Promise<User | Error> {


return new Promise((resolve, reject) => {

this.db.get("SELECT * FROM administrator WHERE user=? AND pass=?",[user.username, encriptSHA256(user.password)],
(err:Error, row: User) =>{

if ((typeof row === 'undefined')) {
reject();
}
if(err){
reject(err);
}
else{
resolve(row);
}
});
});

}

close(){
this.db.close();
Expand Down
10 changes: 5 additions & 5 deletions backend/src/database/database.sql
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ CREATE TABLE IF NOT EXISTS incidencia (

CREATE TABLE IF NOT EXISTS administrator (
admin_id INTEGER PRIMARY KEY,
user TEXT,
user TEXT UNIQUE,
pass TEXT,
nombre TEXT,
apellido TEXT,
Expand Down Expand Up @@ -53,7 +53,7 @@ INSERT OR IGNORE INTO incidencia (incidencia_id, nombre, dni, email, tema, nivel

INSERT OR IGNORE INTO administrator (admin_id, user, pass, nombre, apellido, url_perfil, fecha_creacion, Rol)
VALUES
(1, 'admin01', 'pass123', 'Miguel Angel', 'Gabrielli', 'https://miweb.com/perfil/gmiguel', '2024-09-05', 'Admin'),
(2, 'admin02', 'adminpass', 'Ezequiel', 'Cañete', 'https://miweb.com/perfil/eca', '2024-09-04', 'Admin'),
(3, 'admin03', 'securepass', 'Ignacio', 'Tula', 'https://miweb.com/perfil/itula', '2024-09-03', 'Admin'),
(4, 'admin04', 'mypassword', 'German', 'Lucero', 'https://miweb.com/perfil/glucero', '2024-09-02', 'Admin');
(1, 'admin01', '03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4', 'Miguel Angel', 'Gabrielli', 'https://miweb.com/perfil/gmiguel', '2024-08-31T12:00:00Z', 'Admin'),
(2, 'admin02', '03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4', 'Ezequiel', 'Cañete', 'https://miweb.com/perfil/eca', '2024-08-31T12:00:00Z', 'Admin'),
(3, 'admin03', '03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4', 'Ignacio', 'Tula', 'https://miweb.com/perfil/itula', '2024-08-31T12:00:00Z', 'Admin'),
(4, 'admin04', '03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4', 'German', 'Lucero', 'https://miweb.com/perfil/glucero', '2024-08-31T12:00:00Z', 'Admin');
Binary file modified backend/src/database/mydatabase.sqlite
Binary file not shown.
18 changes: 13 additions & 5 deletions backend/src/models/users.models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@ export enum Role {
}

export interface User {
id: number;
id: number | null;
username: string;
password: string;
nombre: string;
apellido: string;
imagenDePerfil: string; // URL o ruta de la imagen de perfil
imagenDePerfil: string | null; // URL o ruta de la imagen de perfil
fechaDeCreacion: Date; // Fecha de creación, se genera automáticamente
role: Role; // Campo para el rol del usuario
role: Role | null; // Campo para el rol del usuario
}


const users: Array<User> = [
{
id: 1,
Expand Down Expand Up @@ -72,4 +71,13 @@ export const updateUser = (user: User): void => {
export const deleteUser = (id: number): void => {
const index = users.findIndex(u => u.id === id);
users.splice(index, 1);
};
};

export const createUserDB = (user: User): User => {

const UserCreated: User = {
...user,
};
UserCreated.fechaDeCreacion = new Date();
return UserCreated;
}
5 changes: 4 additions & 1 deletion backend/src/routes/autenticacion.routes.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Router, Request, Response } from 'express';
import { loginController } from '../controllers/autenticacion.controllers';
import { loginController, createController } from '../controllers/autenticacion.controllers';
import { validateUser } from '../utils/validations/users.validations';

// New Router instance
const router = Router();

// login routes
router.post('/login', loginController);
router.post('/create', createController);


export default router;
15 changes: 9 additions & 6 deletions backend/src/utils/validations/users.validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,14 @@ export const validateUser = (
next: NextFunction
): void => {
// Get data from request body
const { id, username, password } = req.body;
const { username, password, nombre, apellido } = req.body;

// Create an array to store errors
const errors: string[] = [];

// Validate data
if (!id) {
errors.push('ID is required');
}

if (!username) {
errors.push('Name is required');
errors.push('UserName is required');
}

if (!password) {
Expand All @@ -29,6 +25,13 @@ export const validateUser = (
}
}

if (!nombre) {
errors.push('name is required');
}

if (!apellido) {
errors.push('name is required');
}
// If there are errors
if (errors.length > 0) {
res.status(422).json({
Expand Down

0 comments on commit 7cbbc76

Please sign in to comment.