Niansuh commited on
Commit
7e335b9
1 Parent(s): e31fd5b

Update routes/user.js

Browse files
Files changed (1) hide show
  1. routes/user.js +9 -10
routes/user.js CHANGED
@@ -1,25 +1,24 @@
1
  const express = require('express');
2
  const router = express.Router();
3
- const ApiKey = require('../models/ApiKey');
4
 
5
  router.get('/', (req, res) => {
6
  if (req.session.user) {
7
- res.render('user.html');
 
 
 
8
  } else {
9
- res.status(403).send('Unauthorized');
10
  }
11
  });
12
 
13
  router.post('/generate-api-key', (req, res) => {
14
- const apiKey = generateApiKey();
15
- ApiKey.create(req.session.user.id, apiKey, (err) => {
16
  if (err) return res.status(500).send('Failed to generate API key');
17
- res.send(`API Key: ${apiKey}`);
18
  });
19
  });
20
 
21
- function generateApiKey() {
22
- return 'api_' + Math.random().toString(36).substr(2, 16);
23
- }
24
-
25
  module.exports = router;
 
1
  const express = require('express');
2
  const router = express.Router();
3
+ const db = require('../database');
4
 
5
  router.get('/', (req, res) => {
6
  if (req.session.user) {
7
+ db.query(`SELECT api_key, credits FROM users WHERE id = ?`, [req.session.user.id], (err, results) => {
8
+ if (err || results.length === 0) return res.status(500).send('Error loading user data');
9
+ res.render('user', { apiKey: results[0].api_key, credits: results[0].credits });
10
+ });
11
  } else {
12
+ res.redirect('/auth/login');
13
  }
14
  });
15
 
16
  router.post('/generate-api-key', (req, res) => {
17
+ const apiKey = 'api_' + Math.random().toString(36).substr(2, 16);
18
+ db.query(`UPDATE users SET api_key = ? WHERE id = ?`, [apiKey, req.session.user.id], (err) => {
19
  if (err) return res.status(500).send('Failed to generate API key');
20
+ res.redirect('/user');
21
  });
22
  });
23
 
 
 
 
 
24
  module.exports = router;