Implement JWT authentication and user token management
This commit is contained in:
@@ -1,4 +1,7 @@
|
||||
import { register, activateUser, login, logout } from '../services/authService.js';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import UserToken from '../models/UserToken.js';
|
||||
import User from '../models/User.js'; // ggf. Pfad anpassen
|
||||
|
||||
const registerUser = async (req, res, next) => {
|
||||
try {
|
||||
@@ -20,24 +23,26 @@ const activate = async (req, res, next) => {
|
||||
}
|
||||
};
|
||||
|
||||
const loginUser = async (req, res, next) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
const result = await login(email, password);
|
||||
res.status(200).json(result);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
const loginUser = async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
const user = await User.findOne({ where: { username } });
|
||||
if (!user || !(await user.validatePassword(password))) {
|
||||
return res.status(401).json({ message: 'Ungültige Anmeldedaten' });
|
||||
}
|
||||
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
|
||||
await UserToken.create({
|
||||
userId: user.id,
|
||||
token,
|
||||
expiresAt: new Date(Date.now() + 3600 * 1000),
|
||||
});
|
||||
res.json({ token });
|
||||
};
|
||||
|
||||
const logoutUser = async(req, res) => {
|
||||
const { userid: userId, authtoken: authToken } = req.headers;
|
||||
try {
|
||||
logout(userId, authToken);
|
||||
} catch (error) {
|
||||
res.status(401).json({ msg: 'not found' });
|
||||
}
|
||||
res.status(200).json({ msg: 'loggedout' });
|
||||
}
|
||||
const logoutUser = async (req, res) => {
|
||||
const token = req.headers['authorization']?.split(' ')[1];
|
||||
if (!token) return res.status(400).json({ message: 'Token fehlt' });
|
||||
await UserToken.destroy({ where: { token } });
|
||||
res.json({ message: 'Logout erfolgreich' });
|
||||
};
|
||||
|
||||
export { registerUser, activate, loginUser, logoutUser };
|
||||
|
||||
Reference in New Issue
Block a user