done with the connecting of coze

This commit is contained in:
Ebenezer
2026-03-30 18:30:09 +08:00
parent 8c0e327115
commit adde023647
619 changed files with 8987 additions and 46206 deletions

View File

@@ -4,6 +4,7 @@ import cors from 'cors';
import mysql from 'mysql2/promise';
import bcrypt from 'bcryptjs';
import argon2 from 'argon2';
import jwt from 'jsonwebtoken';
dotenv.config();
@@ -203,6 +204,77 @@ app.post('/api/login', async (req, res) => {
}
});
app.get('/api/coze/space-url', async (req, res) => {
try {
const rawUser = String(req.query.user || req.query.email || '').trim().toLowerCase();
if (!rawUser) {
res.status(400).json({ message: 'user is required' });
return;
}
const [userRows] = await pool.query(
'SELECT CAST(id AS CHAR) AS id, email, unique_name, name FROM `user` WHERE email = ? OR unique_name = ? OR LOWER(name) = ? LIMIT 1',
[rawUser, rawUser, rawUser]
);
const user = userRows[0];
if (!user) {
res.status(404).json({ message: 'User not found' });
return;
}
const [spaceRows] = await pool.query(
'SELECT CAST(s.id AS CHAR) AS id FROM `space` s INNER JOIN `space_user` su ON su.space_id = s.id WHERE su.user_id = ? AND (s.deleted_at IS NULL OR s.deleted_at = 0) ORDER BY su.role_type ASC, su.id DESC LIMIT 1',
[user.id]
);
const space = spaceRows[0];
if (!space) {
res.status(404).json({ message: 'No space found for user' });
return;
}
const url = `http://nw.sgcode.cn:18888/space/${space.id}/develop`;
res.json({ url, spaceId: space.id, user: user.email || user.unique_name || user.name });
} catch (error) {
console.error('Resolve Coze space URL failed:', error);
res.status(500).json({ message: 'Failed to resolve Coze space URL' });
}
});
// Coze SSO: issue short-lived JWT and redirect to Coze SSO exchange endpoint
app.get('/api/coze/sso-login', (req, res) => {
try {
const email = String(req.query.email || req.query.user || '').trim().toLowerCase();
if (!email) {
res.status(400).json({ message: 'email is required' });
return;
}
const secret = process.env.SSO_SHARED_SECRET;
const cozeHost = process.env.COZE_HOST || 'http://nw.sgcode.cn:18888';
if (!secret) {
res.status(500).json({ message: 'SSO is not configured on server (missing SSO_SHARED_SECRET)' });
return;
}
const token = jwt.sign(
{ email },
secret,
{ algorithm: 'HS256', expiresIn: 300 } // 5 minutes
);
const nextPath = encodeURIComponent('/space');
const redirectUrl = `${cozeHost.replace(/\/+$/, '')}/api/passport/web/sso/exchange/?token=${encodeURIComponent(
token
)}&next=${nextPath}`;
res.redirect(302, redirectUrl);
} catch (error) {
console.error('Coze SSO login failed:', error);
res.status(500).json({ message: 'Coze SSO login failed' });
}
});
ensureUsersTable()
.then(() => {
app.listen(port, () => {