104 lines
2.9 KiB
JavaScript
104 lines
2.9 KiB
JavaScript
const usersDb = require('../../shared/usersDb');
|
||
const makeLinks = require('../../shared/hateoas');
|
||
|
||
exports.login = (req, res) => {
|
||
const { username, password, email } = req.body;
|
||
const user = usersDb.findUser(username, email, password);
|
||
if (user) {
|
||
res.json({
|
||
data: {
|
||
user: {
|
||
id: user.id,
|
||
username: user.username,
|
||
email: user.email,
|
||
firstName: user.firstName,
|
||
lastName: user.lastName
|
||
},
|
||
token: 'token-' + user.id,
|
||
message: 'Login successful'
|
||
},
|
||
_links: makeLinks('/api/auth', {
|
||
self: '/login',
|
||
profile: '/profile/',
|
||
logout: '/logout'
|
||
}),
|
||
_meta: {}
|
||
});
|
||
} else {
|
||
res.status(401).json({ error: 'Invalid credentials' });
|
||
}
|
||
};
|
||
|
||
exports.register = (req, res) => {
|
||
const { username, password, email, firstName, lastName } = req.body;
|
||
if (usersDb.exists(username, email)) {
|
||
return res.status(409).json({ error: 'User already exists' });
|
||
}
|
||
const newUser = usersDb.addUser({ username, password, email, firstName, lastName });
|
||
res.json({
|
||
data: {
|
||
user: {
|
||
id: newUser.id,
|
||
username,
|
||
email,
|
||
firstName,
|
||
lastName
|
||
},
|
||
token: 'token-' + newUser.id,
|
||
message: 'Register successful'
|
||
},
|
||
_links: makeLinks('/api/auth', {
|
||
self: '/register',
|
||
login: '/login',
|
||
profile: '/profile/'
|
||
}),
|
||
_meta: {}
|
||
});
|
||
};
|
||
|
||
exports.profile = (req, res) => {
|
||
const auth = req.headers.authorization;
|
||
if (!auth || !auth.startsWith('Bearer ')) {
|
||
return res.status(401).json({ error: 'No token provided' });
|
||
}
|
||
const token = auth.replace('Bearer ', '');
|
||
const id = parseInt(token.replace('token-', ''));
|
||
const user = usersDb.findById(id);
|
||
if (!user) {
|
||
return res.status(401).json({ error: 'Invalid token' });
|
||
}
|
||
res.json({
|
||
data: {
|
||
id: user.id,
|
||
username: user.username,
|
||
email: user.email,
|
||
firstName: user.firstName,
|
||
lastName: user.lastName
|
||
},
|
||
_links: makeLinks('/api/auth', {
|
||
self: '/profile/',
|
||
logout: '/logout'
|
||
}),
|
||
_meta: {}
|
||
});
|
||
};
|
||
|
||
exports.logout = (req, res) => {
|
||
res.json({
|
||
message: 'Logout successful',
|
||
_links: makeLinks('/api/auth', {
|
||
self: '/logout',
|
||
login: '/login'
|
||
}),
|
||
_meta: {}
|
||
});
|
||
};
|
||
|
||
exports.updateProfile = (req, res) => {
|
||
const userId = req.user?.id || req.body.id; // 这里假设有用户认证中间件,否则用body.id
|
||
if (!userId) return res.status(401).json({ error: 'Unauthorized' });
|
||
const { firstName, lastName, bio, location, website } = req.body;
|
||
const updated = require('../../shared/usersDb').updateUser(userId, { firstName, lastName, bio, location, website });
|
||
if (!updated) return res.status(404).json({ error: 'User not found' });
|
||
res.json({ success: true, user: updated });
|
||
};
|