I would like if you could guide me a bit, I am making an application of videos, the user registers, uploads videos, and sees them. The administrator accepts or rejects videos.
The video is sent to a stock agency.
My problem is the following, in my back-end with node and mongoDB, I have already created the login and registration service.
File Login.js
var express = require( 'express');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var Usuario = require('../models/usuario');
// Google
var SEED = require ('../config/config').SEED;
var CADUCIDAD_TOKEN = require('../config/config').CADUCIDAD_TOKEN;
const { OAuth2Client } = require('google-auth-library');
const GOOGLE_CLIENT_ID = require('../config/config').GOOGLE_CLIENT_ID;
// const GOOGLE_SECRET = require('../config/config').GOOGLE_SECRET;
var client = new OAuth2Client(GOOGLE_CLIENT_ID);
var app = express();
//Autenticacion de Google
async function verify(token) {
var ticket = await client.verifyIdToken({
idToken: token,
audience: GOOGLE_CLIENT_ID
});
var payload = ticket.getPayload();
return {
nombre: payload.name,
email: payload.email,
img: payload.picture,
google: true
}
}
app.post('/google', async (req, res) => {
var token = req.body.token;
var googleUser = await verify(token).catch(err => {
return res.status(403).json({
ok: false,
mensaje: 'Token de google inválido',
errors: { message: 'Token de google inválido' }
});
});
Usuario.findOne({ email: googleUser.email }, (err, usuario) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'El usuario no existe',
errors: err
});
}
if (usuario) {
if (!usuario.google) {
return res.status(400).json({
ok: false,
mensaje: 'Debe usar su autenticación con correo y contraseña'
});
}
else {
usuario.password = ':)';
// Expira en 4 horas (14400 ms)
var token = jwt.sign({ usuario: usuario }, SEED, { expiresIn: CADUCIDAD_TOKEN});
var fs = require('fs');
var dir = './uploads/videos/${usuario.id}';
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
return res.status(200).json({
ok: true,
id: usuario.id,
usuario: usuario,
token: token,
menu: obtenerMenu( usuario.rol)
});
}
} else {
// El usuario no existe, hay que crearlo
var nuevoUsuario = new Usuario({
nombre: googleUser.nombre,
email: googleUser.email,
password: ':)',
img: googleUser.img,
google: true
});
nuevoUsuario.save((err, usuarioGuardado) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: 'Error al crear usuario',
errors: err
});
}
// Expira en 4 horas (14400 ms)
var token = jwt.sign({ usuario: usuarioGuardado }, SEED, { expiresIn: CADUCIDAD_TOKEN});
return res.status(200).json({
ok: true,
id: usuarioGuardado.id,
usuario: usuarioGuardado,
token: token,
menu: obtenerMenu( usuarioGuardado.rol)
});
});
}
});
});
// Autenticacion Normal
app.post ('/', (req, res) => {
var body = req.body;
Usuario.findOne ( {email: body.email}, ( err, usuarioDB ) => {
if( err ){
return res.status(500).json ({
ok: false,
mensaje: 'Error al buscar usuarios',
errors: err
});
}
if ( !usuarioDB ){
return res.status(400).json ({
ok: false,
mensaje: 'Credenciales incorrectas',
errors: err
});
}
if ( !bcrypt.compareSync ( body.password, usuarioDB.password)){
return res.status(400).json ({
ok: false,
mensaje: 'Credenciales incorrectas',
errors: err
});
}
// Crear un token!!!
usuarioDB.password = ' :D ';
var token = jwt.sign( { usuario: usuarioDB }, SEED, { expiresIn: 28800 });
var fs = require('fs');
var dir = './uploads/videos/${usuarioDB._id}';
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
res.status(200).json ({
ok: true,
usuario: usuarioDB,
token: token,
id: usuarioDB._id,
menu: obtenerMenu( usuarioDB.rol)
});
});
});
function obtenerMenu ( ROLE ) {
var menu = [
{
titulo: 'Principal',
icono: 'mdi mdi-gauge',
submenu: [
{ titulo: ' Escritorio', icono: 'fa fa-desktop', url: '/escritorio'},
{ titulo: ' Soporte', icono: 'fa fa-support', url: '/soporte'},
{ titulo: ' Configuración', icono: 'fa fa-gear', url: '/edicion'},
{ titulo: 'Subir', url: '/subirvideo'}
]
},
{
titulo: 'Administración',
icono: 'mdi mdi-folder-lock-open',
submenu: [
// { titulo: 'Usuarios', url: '/usuarios'},
// { titulo: 'Videos', url: '/videos'},
// { titulo: 'Ventas', url: '/ventas'},
]
}
];
console.log( ROLE );
if ( ROLE === 'admin') {
menu[1].submenu.unshift(
{ titulo: 'Usuarios', url: '/usuarios'},
{ titulo: 'Videos', url: '/videos'},
{ titulo: 'Ventas', url: '/ventas'},
{ titulo: 'Subir', url: '/subirvideo'}
)
}
return menu;
}
module.exports = app;
I have the app connected to MongoDB in localhost: 3000, everything works fine, the user collection.
Now create a collection called videos:
This is the file:
/*jshint esversion: 6 */
var express = require( 'express');
var mdAutenticacion = require ('../middlewares/autenticacion');
var app = express();
var Video = require('../models/videos');
//OBTENER TODOS LOS VIDEOS
app.get('/', ( req, res, next ) => {
var desde = req.query.desde || 0;
desde = Number(desde);
Video.find({ })
.skip(desde)
.limit(5)
.exec( (err, videos ) => {
if( err ){
return res.status(500).json ({
ok: false,
mensaje: 'Error cargando videos',
errors: err
});
}
Video.countDocuments({}, (err, conteo) => {
res.status(200).json ({
ok: true,
videos: videos,
total: conteo
});
});
});
});
// ==========================================
// Obtener Videos por ID
// ==========================================
app.get('/:id', (req, res ) => {
var id = req.params.id;
Video.findById(id).populate('usuario','nombre img email').exec((err,video) => {
if (err) {
return res.status(500).json({
ok:false,
mensaje:'Error al buscar video',
errors: err
});
}
if (!video) {
return res.status(400).json({
ok:false,
mensaje:'El video con el id '+ id + ' no existe',
errors: { message:'No existe un video con ese ID'}});
}
res.status(200).json({
ok:true,
video:video
});
})
})
//Actualizar Video
app.put('/:id', [mdAutenticacion.verificaToken, mdAutenticacion.verificaAdmin_o_MismoUsuario], (req, res) => {
var id = req.params.id;
var body = req.body;
Video.findById( id, (err, video) => {
if( err ){
return res.status(500).json ({
ok: false,
mensaje: 'Error al buscar video',
errors: err
});
}
if( !video ){
return res.status(400).json ({
ok: false,
mensaje: 'El video con el id ' + id + ' no existe',
errors: {message: 'No existe un video con ese ID'}
});
}
video.titulo = body.titulo;
video.keywords = body.keywords;
video.categoria = body.titulo;
video.usuario = req.usuario._id;
video.save(( err, videoGuardado) => {
if( err ){
return res.status(400).json ({
ok: false,
mensaje: 'Error al actualizar video',
errors: err
});
}
res.status(200).json ({
ok: true,
video: videoGuardado
});
});
});
});
// CREAR NUEVO VIDEO
app.post('/', [mdAutenticacion.verificaToken, mdAutenticacion.verificaAdmin_o_MismoUsuario], (req, res) => {
var body = req.body;
var video = new Video({
titulo: body.titulo,
categoria: body.categoria,
keywords: body.keywords,
tipo: body.tipo,
usuario: req.usuario._id
});
video.save ((err, videoGuardado ) => {
if( err ){
return res.status(400).json ({
ok: false,
mensaje: 'Error al crear video',
errors: err
});
}
res.status(201).json ({
ok: true,
video: videoGuardado,
});
});
});
//Eliminar Video por ID
app.delete('/:id', [mdAutenticacion.verificaToken, mdAutenticacion.verificaAdmin], (req, res) => {
var id = req.params.id;
Video.findByIdAndRemove (id, ( err, videoBorrado ) => {
if( err ){
return res.status(500).json ({
ok: false,
mensaje: 'Error al borrar video',
errors: err
});
}
if( !videoBorrado ){
return res.status(400).json ({
ok: false,
mensaje: 'No existe video con ese id',
errors: {message: 'No existe video con ese id'}
});
}
res.status(200).json ({
ok: true,
video: videoBorrado
});
});
});
module.exports = app;
All right up there, when doing tests with postman, everything is fine, an object is created in mongodb with the Videos schema.
Now when I want my users to upload a video, I must link that video to the user, in the schema, I have a user and file. user links it well, but how can I upload the video and save it in its folder created at the time of login? And how is implemented in Angular? I already have a front-end in angular, but I'm still stuck with uploading the video, rescue the file, assign it to the user and rescue thumbnail.
This is the video model file:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var videosSchema = new Schema({
titulo: { type: String, required: [true, 'El título o descripción es necesario'] },
keywords: { type: String, required: [true, 'Los Keywords son necesarios']},
categoria: { type: String, required: [true, 'La categoria es necesaria']},
miniatura: { type: String, required: false },
archivo: { type: String },
usuario: { type: Schema.Types.ObjectId, ref: 'Usuario' }
}, { collection: 'videos' });
module.exports = mongoose.model('Videos', videosSchema);