try {
const hashedPassword = await bcrypt.hash(password, 10); // 비밀번호 해싱
await db.execute(
'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
[username, email, hashedPassword]
);
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
console.error('Register Error:', error);
if (error.code === 'ER_DUP_ENTRY') {
res.status(400).json({ error: 'Email already registered' });
} else {
res.status(500).json({ error: 'Failed to register user' });
}
}try {
const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
if (rows.length === 0) {
return res.status(404).json({ error: 'User not found' });
}
const user = rows[0];
const isPasswordValid = await bcrypt.compare(password, user.password); // 비밀번호 검증
if (!isPasswordValid) {
return res.status(401).json({ error: 'Invalid password' });
}
// 세션에 사용자 정보 저장
req.session.user = {
id: user.id,
username: user.username,
email: user.email,
};
res.json({ message: 'Login successful', user: req.session.user });
} catch (error) {
console.error('Login Error:', error);
res.status(500).json({ error: 'Failed to login' });
}res.json(req.session.user); const hallo = completion.choices[0].message.content; // 응답을 hallo 변수에 저장
console.log(hallo); // 응답을 콘솔에 출력
return hallo; // hallo 값을 반환
} catch (error) {
console.error("Error with OpenAI API:", error.response ? error.response.data : error.message);
throw new Error('Failed to get response from OpenAI API');
} let user;
if (rows.length === 0) {
// 사용자가 없으면 데이터베이스에 삽입
const [result] = await db.execute(
'INSERT INTO users (username, email, provider, provider_id, profile_picture) VALUES (?, ?, ?, ?, ?)',
[
profile.displayName,
profile.emails[0]?.value,
'google',
profile.id,
profile.photos[0]?.value,
]
);
// 삽입된 사용자 정보
user = {
id: result.insertId,
username: profile.displayName,
email: profile.emails[0]?.value,
};
} else {
// 기존 사용자 정보 로드
user = rows[0];
}
// 세션에 사용자 정보 저장
return done(null, user);
} catch (err) {
console.error('Google Auth Error:', err);
return done(err, null);
}
}
) let user;
if (rows.length === 0) {
// 사용자 정보를 DB에 저장
const [result] = await db.execute(
'INSERT INTO users (username, provider, provider_id, profile_picture) VALUES (?, ?, ?, ?)',
[
profile.displayName || profile.username,
'kakao',
profile.id,
profile._json.properties?.profile_image,
]
);
user = {
id: result.insertId,
username: profile.displayName || profile.username,
};
} else {
// 기존 사용자 정보 로드
user = rows[0];
}
return done(null, user); // 세션에 저장할 사용자 정보 반환
} catch (err) {
console.error('Kakao Auth Error:', err);
return done(err, null);
}
}
) let user;
if (rows.length === 0) {
// 사용자 정보를 DB에 저장
const [result] = await db.execute(
'INSERT INTO users (username, email, provider, provider_id, profile_picture) VALUES (?, ?, ?, ?, ?)',
[
profile.displayName,
profile.emails[0]?.value,
'naver',
profile.id,
profile._json.profile_image,
]
);
user = {
id: result.insertId,
username: profile.displayName,
email: profile.emails[0]?.value,
};
} else {
// 기존 사용자 정보 로드
user = rows[0];
}
return done(null, user); // 세션에 저장할 사용자 정보 반환
} catch (err) {
console.error('Naver Auth Error:', err);
return done(err, null);
}
}
)// 정적 파일 경로 설정
const frontendPath = path.join(__dirname, '../frontend');
app.use(express.static(frontendPath));
// 기본 경로에서 index.html 제공
app.get('/', (req, res) => {
res.sendFile(path.join(frontendPath, 'index.html'));
});
// OpenAI POST 요청 처리
app.post('/hallo', async (req, res) => {
const userMessage = req.body.message;
try {
const hallo = await getChatCompletion(userMessage);
res.json({ response: hallo });
} catch (error) {
res.status(500).json({ error: 'Error occurred while fetching the response.' });
}
});
// 로그인 라우트 (Google, Kakao, Naver 등 추가)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});