footprint/backend/src/routes/auth.js

79 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const express = require('express');
const router = express.Router();
const passport = require('../config/passport');
const jwt = require('jsonwebtoken');
// Google OAuth
router.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get(
'/google/callback',
passport.authenticate('google', { failureRedirect: `${process.env.FRONTEND_URL}/login` }),
(req, res) => {
const token = jwt.sign(
{
id: req.user.id,
username: req.user.username,
user_type: req.user.user_type,
},
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// 重定向到前端并在URL中带上token
res.redirect(`${process.env.FRONTEND_URL}/?token=${token}`);
}
);
// GitHub OAuth
router.get('/github', passport.authenticate('github', { scope: ['user:email'] }));
router.get(
'/github/callback',
passport.authenticate('github', { failureRedirect: `${process.env.FRONTEND_URL}/login` }),
(req, res) => {
const token = jwt.sign(
{
id: req.user.id,
username: req.user.username,
user_type: req.user.user_type,
},
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// 重定向到前端并在URL中带上token
res.redirect(`${process.env.FRONTEND_URL}/?token=${token}`);
}
);
// 登出
router.post('/logout', (req, res) => {
req.logout((err) => {
if (err) {
return res.status(500).json({ error: 'Failed to logout' });
}
res.json({ message: 'Logged out successfully' });
});
});
// 检查认证状态
router.get('/status', (req, res) => {
if (req.isAuthenticated()) {
res.json({
authenticated: true,
user: {
id: req.user.id,
username: req.user.username,
email: req.user.email,
avatar_url: req.user.avatar_url,
user_type: req.user.user_type,
},
});
} else {
res.json({ authenticated: false });
}
});
module.exports = router;