control audio remoto
This commit is contained in:
60
src/app.js
60
src/app.js
@@ -13,10 +13,11 @@ const googleClient = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
|
|||||||
|
|
||||||
//importando rutas
|
//importando rutas
|
||||||
const rutasGlobales = require('./rutas/rutasGlobales');
|
const rutasGlobales = require('./rutas/rutasGlobales');
|
||||||
|
const rutas_auth = require('./rutas/rutas_auth');
|
||||||
|
|
||||||
//configuraciones
|
//configuraciones
|
||||||
var puertoApp=2000;
|
var puertoApp=2000;
|
||||||
app.set('port',process.env.PORT||puertoApp);
|
app.set('port', process.env.PORT || puertoApp);
|
||||||
app.set('view engine','ejs');
|
app.set('view engine','ejs');
|
||||||
app.set('views',path.join(__dirname, 'views'));
|
app.set('views',path.join(__dirname, 'views'));
|
||||||
//app.set('vistas',path.join(__dirname, 'vistas'));
|
//app.set('vistas',path.join(__dirname, 'vistas'));
|
||||||
@@ -26,13 +27,13 @@ app.use(cors({
|
|||||||
origin: '*' // En producción, deberías restringirlo a tu dominio de frontend
|
origin: '*' // En producción, deberías restringirlo a tu dominio de frontend
|
||||||
}));
|
}));
|
||||||
app.use(morgan('dev'));
|
app.use(morgan('dev'));
|
||||||
app.use(myConecction(mysql,{
|
app.use(myConecction(mysql, {
|
||||||
//host:'192.168.10.50',
|
//host:'192.168.10.50',
|
||||||
host:'192.168.10.149',
|
host:'192.168.10.149',
|
||||||
user:'admin',
|
user:'admin',
|
||||||
password:'Dx.1706%',
|
password:'Dx.1706%',
|
||||||
port:3306,
|
port:3306,
|
||||||
database:'AUDIO_CTRL'
|
database:'AUDIO_CTRL',
|
||||||
},'single'));
|
},'single'));
|
||||||
//cuando reciba dato desde req body
|
//cuando reciba dato desde req body
|
||||||
app.use(express.urlencoded({extended:false}));
|
app.use(express.urlencoded({extended:false}));
|
||||||
@@ -40,6 +41,7 @@ app.use(express.json()); // Middleware para parsear JSON
|
|||||||
|
|
||||||
//rutas
|
//rutas
|
||||||
app.use('/', rutasGlobales);
|
app.use('/', rutasGlobales);
|
||||||
|
app.use('/api/auth', rutas_auth); // Es mejor agrupar las rutas de autenticación
|
||||||
//prueba de json directa
|
//prueba de json directa
|
||||||
app.get('/pruebaJson',function(req,res){
|
app.get('/pruebaJson',function(req,res){
|
||||||
res.json([
|
res.json([
|
||||||
@@ -60,58 +62,6 @@ app.get('/cmd', (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- NUEVA RUTA DE AUTENTICACIÓN CON GOOGLE ---
|
|
||||||
app.post('/api/auth/google', (req, res) => {
|
|
||||||
const { token } = req.body;
|
|
||||||
|
|
||||||
if (!token) {
|
|
||||||
return res.status(400).json({ message: 'No se proporcionó el token de Google.' });
|
|
||||||
}
|
|
||||||
|
|
||||||
req.getConnection(async (err, conn) => {
|
|
||||||
if (err) {
|
|
||||||
console.error("Error de conexión a la BD:", err);
|
|
||||||
return res.status(500).json({ message: "Error de conexión a la base de datos" });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. Verificar el token de Google
|
|
||||||
const ticket = await googleClient.verifyIdToken({
|
|
||||||
idToken: token,
|
|
||||||
audience: process.env.GOOGLE_CLIENT_ID,
|
|
||||||
});
|
|
||||||
const { sub: googleId, email, name, picture } = ticket.getPayload();
|
|
||||||
|
|
||||||
// 2. Buscar o crear el usuario en la base de datos
|
|
||||||
conn.query('SELECT * FROM users WHERE email = ?', [email], (err, rows) => {
|
|
||||||
if (err) throw err;
|
|
||||||
|
|
||||||
let user = rows[0];
|
|
||||||
if (!user) {
|
|
||||||
// Crear nuevo usuario
|
|
||||||
const newUser = { google_id: googleId, email, name, picture_url: picture };
|
|
||||||
conn.query('INSERT INTO users SET ?', newUser, (err, result) => {
|
|
||||||
if (err) throw err;
|
|
||||||
user = { id: result.insertId, ...newUser };
|
|
||||||
generateTokenAndRespond(user, res);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// Usuario existente
|
|
||||||
generateTokenAndRespond(user, res);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error en la autenticación con Google:', error);
|
|
||||||
res.status(401).json({ message: 'Token de Google inválido o expirado.' });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
function generateTokenAndRespond(user, res) {
|
|
||||||
// 3. Crear nuestro propio token (JWT) para la sesión
|
|
||||||
const appToken = jwt.sign({ userId: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: '7d' });
|
|
||||||
res.status(200).json({ message: 'Autenticación exitosa', token: appToken, user });
|
|
||||||
}
|
|
||||||
|
|
||||||
//archivos staticos
|
//archivos staticos
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
app.use(express.static(path.join(__dirname, 'public')));
|
||||||
|
|||||||
67
src/controladores/controlador_auth.js
Normal file
67
src/controladores/controlador_auth.js
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
const controlador_auth = {};
|
||||||
|
const { OAuth2Client } = require('google-auth-library'); // Cliente de Google
|
||||||
|
const jwt = require('jsonwebtoken'); // JSON Web Token
|
||||||
|
|
||||||
|
const googleClient = new OAuth2Client(process.env.GOOGLE_CLIENT_ID);
|
||||||
|
|
||||||
|
function generateTokenAndRespond(user, res) {
|
||||||
|
// Crear nuestro propio token (JWT) para la sesión
|
||||||
|
const appToken = jwt.sign({ userId: user.id, email: user.email }, process.env.JWT_SECRET, { expiresIn: '7d' });
|
||||||
|
res.status(200).json({ message: 'Autenticación exitosa', token: appToken, user });
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- NUEVA RUTA DE AUTENTICACIÓN CON GOOGLE ---
|
||||||
|
controlador_auth.authenticateWithGoogle = (req, res) => {
|
||||||
|
const { token } = req.body;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
return res.status(400).json({ message: 'No se proporcionó el token de Google.' });
|
||||||
|
}
|
||||||
|
|
||||||
|
req.getConnection(async (err, conn) => {
|
||||||
|
if (err) {
|
||||||
|
console.error("Error de conexión a la BD:", err);
|
||||||
|
return res.status(500).json({ message: "Error de conexión a la base de datos" });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. Verificar token de Google
|
||||||
|
const ticket = await googleClient.verifyIdToken({
|
||||||
|
idToken: token,
|
||||||
|
audience: process.env.GOOGLE_CLIENT_ID,
|
||||||
|
});
|
||||||
|
const { sub: googleId, email, name, picture } = ticket.getPayload();
|
||||||
|
|
||||||
|
// 2. Buscar usuario por email
|
||||||
|
conn.query('SELECT * FROM users WHERE email = ?', [email], (err, rows) => {
|
||||||
|
if (err) {
|
||||||
|
console.error("Error en consulta SQL:", err);
|
||||||
|
return res.status(500).json({ message: "Error en la base de datos" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = rows[0];
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
// Crear nuevo usuario
|
||||||
|
const newUser = { google_id: googleId, email, name, picture_url: picture };
|
||||||
|
conn.query('INSERT INTO users SET ?', newUser, (err, result) => {
|
||||||
|
if (err) {
|
||||||
|
console.error("Error al crear usuario:", err);
|
||||||
|
return res.status(500).json({ message: "Error al registrar usuario" });
|
||||||
|
}
|
||||||
|
const createdUser = { id: result.insertId, ...newUser };
|
||||||
|
generateTokenAndRespond(createdUser, res);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Usuario existente
|
||||||
|
generateTokenAndRespond(user, res);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error en autenticación con Google:', error.message);
|
||||||
|
return res.status(401).json({ message: 'Token de Google inválido o expirado.' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = controlador_auth;
|
||||||
@@ -118,7 +118,8 @@ $(document).ready(function() {
|
|||||||
youtubePlaylist.forEach((video, index) => {
|
youtubePlaylist.forEach((video, index) => {
|
||||||
$playlistEl.append(`<li><a href="#" data-video-id="${video.video_id}" data-index="${index}">${video.title || video.video_id}</a></li>`);
|
$playlistEl.append(`<li><a href="#" data-video-id="${video.video_id}" data-index="${index}">${video.title || video.video_id}</a></li>`);
|
||||||
});
|
});
|
||||||
$playlistEl.find('a').on('click', function(e) {
|
// Usar delegación de eventos para los elementos de la playlist
|
||||||
|
$playlistEl.off('click', 'a').on('click', 'a', function(e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
playVideo($(this).data('index'));
|
playVideo($(this).data('index'));
|
||||||
});
|
});
|
||||||
@@ -128,28 +129,30 @@ $(document).ready(function() {
|
|||||||
if (youtubePlaylist.length > 0 && index >= 0 && index < youtubePlaylist.length) {
|
if (youtubePlaylist.length > 0 && index >= 0 && index < youtubePlaylist.length) {
|
||||||
currentVideoIndex = index;
|
currentVideoIndex = index;
|
||||||
youtubePlayer.loadVideoById(youtubePlaylist[currentVideoIndex].video_id);
|
youtubePlayer.loadVideoById(youtubePlaylist[currentVideoIndex].video_id);
|
||||||
youtubePlayer.playVideo();
|
// No es necesario llamar a playVideo() aquí, onPlayerReady o el evento de click lo harán.
|
||||||
$('#yt-play-pause i').text('pause'); // Cambiar icono a pausa
|
// El estado del icono se actualizará en onPlayerStateChange.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function playNextVideo() {
|
function playNextVideo() {
|
||||||
|
if (youtubePlaylist.length === 0) return;
|
||||||
currentVideoIndex = (currentVideoIndex + 1) % youtubePlaylist.length;
|
currentVideoIndex = (currentVideoIndex + 1) % youtubePlaylist.length;
|
||||||
playVideo(currentVideoIndex);
|
playVideo(currentVideoIndex);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Eventos para los controles del reproductor de YouTube
|
// Eventos para los controles del reproductor de YouTube
|
||||||
$('#yt-play-pause').on('click', function() {
|
$('#yt-play-pause').on('click', function() {
|
||||||
|
const $icon = $(this).find('i');
|
||||||
if (youtubePlayer.getPlayerState() == YT.PlayerState.PLAYING || youtubePlayer.getPlayerState() == YT.PlayerState.BUFFERING) {
|
if (youtubePlayer.getPlayerState() == YT.PlayerState.PLAYING || youtubePlayer.getPlayerState() == YT.PlayerState.BUFFERING) {
|
||||||
youtubePlayer.pauseVideo();
|
youtubePlayer.pauseVideo();
|
||||||
$(this).find('i').text('play_arrow');
|
$icon.text('play_arrow');
|
||||||
} else {
|
} else {
|
||||||
if (youtubePlaylist.length > 0 && youtubePlayer.getPlayerState() == YT.PlayerState.UNSTARTED) {
|
if (youtubePlaylist.length > 0 && youtubePlayer.getPlayerState() == YT.PlayerState.UNSTARTED) {
|
||||||
playVideo(currentVideoIndex); // Si no ha empezado, empieza el video actual
|
playVideo(currentVideoIndex); // Si no ha empezado, empieza el video actual
|
||||||
} else {
|
} else {
|
||||||
youtubePlayer.playVideo();
|
youtubePlayer.playVideo();
|
||||||
}
|
}
|
||||||
$(this).find('i').text('pause');
|
$icon.text('pause');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
8
src/rutas/rutas_auth.js
Normal file
8
src/rutas/rutas_auth.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const rutas_auth = express.Router();
|
||||||
|
|
||||||
|
const controlador_auth = require('../controladores/controlador_auth');
|
||||||
|
//ver listar items /formulario/:varNomCampoDb, controlador clase.funcion
|
||||||
|
rutas_auth.post('/google', controlador_auth.authenticateWithGoogle); // Cambiado a POST y nombre más descriptivo
|
||||||
|
|
||||||
|
module.exports = rutas_auth;
|
||||||
Reference in New Issue
Block a user