generated from Arquisoft/wiq_0
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c5621b0
commit 381f9f4
Showing
5 changed files
with
70 additions
and
41 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
const bcrypt = require('bcrypt'); | ||
const jwt = require('jsonwebtoken'); | ||
const User = require('./auth-model.js'); | ||
|
||
exports.loginController = async (req, res) => { | ||
try { | ||
const { username, password } = req.body; | ||
|
||
// Buscar el usuario por nombre en la base de datos | ||
const user = await User.findOne({ username }); | ||
|
||
// Verificar que el usuario exista y la contraseña sea correcta | ||
if (user && (await bcrypt.compare(password, user.password))) { | ||
// Generar un token JWT | ||
const token = jwt.sign({ userId: user._id }, 'your-secret-key', { | ||
expiresIn: '1h', | ||
}); | ||
|
||
// Responder con el token y la información del usuario | ||
res.json({ username, createdAt: user.createdAt }); | ||
} else { | ||
res.status(401).json({ error: 'Invalid credentials' }); | ||
} | ||
} catch (error) { | ||
res.status(500).json({ error: 'Internal Server Error' }); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,28 @@ | ||
const mongoose = require('mongoose'); | ||
|
||
const userSchema = new mongoose.Schema({ | ||
username: String, | ||
password: String, | ||
createdAt: Date, | ||
name: String, | ||
lastName: String, | ||
email: String, | ||
username: { | ||
type: String, | ||
required: true, | ||
}, | ||
password: { | ||
type: String, | ||
required: true, | ||
}, | ||
role: { | ||
type: String, | ||
enum: ['admin', 'user'], | ||
default: 'user', | ||
}, | ||
createdAt: { | ||
type: Date, | ||
default: Date.now, | ||
}, | ||
}); | ||
|
||
const User = mongoose.model('User', userSchema); | ||
|
||
module.exports = User | ||
module.exports = User; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
// authRouter.js | ||
const express = require('express'); | ||
const { loginController } = require('./auth-controller.js'); // Asegúrate de que esta ruta sea correcta | ||
|
||
const authRouter = express.Router(); | ||
|
||
// Define la ruta para el login y asocia el controlador | ||
authRouter.post('/login', loginController); | ||
|
||
module.exports = authRouter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,61 +1,37 @@ | ||
const express = require('express'); | ||
const mongoose = require('mongoose'); | ||
const bcrypt = require('bcrypt'); | ||
const jwt = require('jsonwebtoken'); | ||
const User = require('./auth-model') | ||
const authRouter = require('./auth-router.js'); | ||
|
||
const app = express(); | ||
const port = 8002; | ||
const port = 8002; | ||
|
||
// Middleware to parse JSON in request body | ||
app.use(express.json()); | ||
|
||
// Connect to MongoDB | ||
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/userdb'; | ||
mongoose.connect(mongoUri); | ||
mongoose.connect(mongoUri, { useNewUrlParser: true, useUnifiedTopology: true }); | ||
|
||
// Function to validate required fields in the request body | ||
function validateRequiredFields(req, requiredFields) { | ||
for (const field of requiredFields) { | ||
if (!(field in req.body)) { | ||
throw new Error(`Missing required field: ${field}`); | ||
} | ||
for (const field of requiredFields) { | ||
if (!(field in req.body)) { | ||
throw new Error(`Missing required field: ${field}`); | ||
} | ||
} | ||
} | ||
|
||
// Route for user login | ||
app.post('/login', async (req, res) => { | ||
try { | ||
// Check if required fields are present in the request body | ||
validateRequiredFields(req, ['username', 'password']); | ||
|
||
const { username, password } = req.body; | ||
|
||
// Find the user by username in the database | ||
const user = await User.findOne({ username }); | ||
|
||
// Check if the user exists and verify the password | ||
if (user && await bcrypt.compare(password, user.password)) { | ||
// Generate a JWT token | ||
const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' }); | ||
// Respond with the token and user information | ||
res.json({ token: token, username: username, createdAt: user.createdAt }); | ||
} else { | ||
res.status(401).json({ error: 'Invalid credentials' }); | ||
} | ||
} catch (error) { | ||
res.status(500).json({ error: 'Internal Server Error' }); | ||
} | ||
}); | ||
app.use('/', authRouter); | ||
|
||
// Start the server | ||
const server = app.listen(port, () => { | ||
console.log(`Auth Service listening at http://localhost:${port}`); | ||
}); | ||
|
||
server.on('close', () => { | ||
// Close the Mongoose connection | ||
mongoose.connection.close(); | ||
}); | ||
// Close the Mongoose connection | ||
mongoose.connection.close(); | ||
}); | ||
|
||
module.exports = server | ||
module.exports = server; |