-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
112 lines (100 loc) · 2.76 KB
/
server.js
File metadata and controls
112 lines (100 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const express = require('express');
const bodyParser = require('body-parser');
const swaggerUi = require('swagger-ui-express');
const swaggerJsdoc = require('swagger-jsdoc');
const path = require('path');
const app = express();
const PORT = 3000;
// Middleware untuk parsing JSON
app.use(bodyParser.json());
// Simpan API keys di sini (untuk demo saja, sebaiknya simpan di tempat yang lebih aman)
const API_KEYS = ['123456', 'abcdef'];
// Middleware untuk memeriksa API key
const checkApiKey = (req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (API_KEYS.includes(apiKey)) {
next();
} else {
res.status(403).json({ error: 'Forbidden - Invalid API Key' });
}
};
// Konfigurasi Swagger
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'HardiDev-APIs',
version: '1.0.0 BETA',
description: 'Free API for everyone.',
contact: {
name: 'Developer',
email: 'developer@example.com',
},
license: {
name: 'Apache 2.0',
url: 'https://www.apache.org/licenses/LICENSE-2.0.html',
},
},
servers: [
{
url: 'http://localhost:3000',
},
],
},
apis: ['./server.js'], // File dengan anotasi Swagger
};
const specs = swaggerJsdoc(options);
// Custom CSS untuk menyembunyikan elemen-elemen Swagger
const customCss = `
.swagger-ui .topbar {
display: none !important;
}
`;
// Serve favicon
app.get('/api.ico', (req, res) => {
res.sendFile(path.join(__dirname, 'api.ico'));
});
// Menggunakan Swagger UI dengan custom shortcut icon
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs, {
customCss,
customSiteTitle: 'HardiDev-APIs',
customfavIcon: '/api.ico'
}));
// Sajikan file statis dari folder 'public'
app.use(express.static(path.join(__dirname, 'public')));
/**
* @swagger
* /protected:
* get:
* summary: Get protected data
* security:
* - apiKeyAuth: []
* responses:
* 200:
* description: Successful response
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
* example: This is protected data
* 403:
* description: Forbidden - Invalid API Key
* content:
* application/json:
* schema:
* type: object
* properties:
* error:
* type: string
* example: Forbidden - Invalid API Key
*/
app.get('/protected', checkApiKey, (req, res) => {
res.json({ message: 'This is protected data' });
});
// Menjalankan server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});