Skip to content

Commit 90e8e7a

Browse files
committed
There! Use it!
1 parent f97a382 commit 90e8e7a

File tree

6 files changed

+2107
-0
lines changed

6 files changed

+2107
-0
lines changed

.env

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
DB_HOST = "localhost"
2+
DB_USERNAME = "root"
3+
DB_PASSWORD = ""
4+
DB_NAME = "node_api"
5+
DB_PORT = 3306
6+
HTTP_PORT = 9002

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
/node_modules

app.js

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
// DotEnv Config
2+
require('dotenv').config(); // Load Configuration
3+
4+
// WebServer Library untuk handle incoming client, etc.
5+
const cors = require('cors');
6+
const express = require('express');
7+
const validator = require('express-validator');
8+
const jwt = require('jsonwebtoken');
9+
const app = express();
10+
app.use(cors()); // Menggunakan CORS agar api dapat dipakai oleh siapa saja (tanpa perlu origin server)
11+
app.use(express.json()); // Untuk mengurai JSON
12+
app.use(express.urlencoded({ extended: true })); // Untuk mengurai URL-encoded
13+
14+
// Password Encryption
15+
const bcrypt = require('bcrypt');
16+
const saltRounds = 10; // Number of rounds for salting, similar to cost factor in PHP
17+
async function hashPassword(password) {
18+
const hashedPassword = await bcrypt.hash(password, saltRounds);
19+
return hashedPassword;
20+
}
21+
async function verifyPassword(password, hashedPassword) {
22+
const isMatch = await bcrypt.compare(password, hashedPassword);
23+
return isMatch;
24+
}
25+
26+
// Validasi input
27+
function validatorResult(req, res, next) {
28+
const validation = validator.validationResult(req);
29+
if (!validation.isEmpty()) {
30+
res.status(200).json({
31+
code : 'error',
32+
msg : validation.errors[0].msg
33+
});
34+
return true;
35+
}else{
36+
return false;
37+
}
38+
}
39+
40+
// Koneksi mysql
41+
const mysql = require('mysql2');
42+
const pooldb = mysql.createPool({
43+
host: process.env.DB_HOST,
44+
user: process.env.DB_USERNAME,
45+
password: process.env.DB_PASSWORD,
46+
database: process.env.DB_NAME,
47+
port: process.env.DB_PORT,
48+
multipleStatements: true
49+
});
50+
51+
// Middleware Token Auth
52+
const authenticateToken = (req, res, next) => {
53+
const authHeader = req.headers['authorization'];
54+
const token = authHeader && authHeader.split(' ')[1]; // Bearer <token>
55+
56+
if (token == null) return res.sendStatus(401); // No token present
57+
58+
jwt.verify(token, 'SECRET_KEY', (err, user) => {
59+
if (err) return res.sendStatus(403); // Invalid token
60+
61+
req.user = user;
62+
next();
63+
});
64+
};
65+
66+
// REST API Stateless
67+
app.post('/login', [
68+
validator.body('username').not().isEmpty().withMessage('Masukan username').trim().escape(),
69+
validator.body('password').not().isEmpty().withMessage('Masukan password').trim().escape()
70+
], (req, res) => { if ( validatorResult(req, res) ){ return; }
71+
72+
let {username, password} = req.body;
73+
74+
let sqlsyn = ` SELECT * FROM user WHERE username=?; `;
75+
pooldb.query(sqlsyn, [username], async (err, result) => {
76+
if (err){
77+
console.log(err);
78+
} else {
79+
if (result[0]){
80+
let userData = result[0];
81+
hashedPassword = userData.password;
82+
83+
verifyPassword(password, hashedPassword).then((isMatch) => {
84+
if (isMatch) {
85+
const token = jwt.sign({ username }, 'SECRET_KEY', { expiresIn: '1h' });
86+
res.json({
87+
code : "ok",
88+
msg : "Berhasil Masuk!",
89+
data : {
90+
userData,
91+
token
92+
}
93+
});
94+
} else {
95+
res.json({
96+
code : "error",
97+
msg : "Password salah!"
98+
});
99+
}
100+
});
101+
}else{
102+
res.json({
103+
code : "error",
104+
msg : "User tidak ditemukan"
105+
});
106+
}
107+
}
108+
});
109+
});
110+
111+
app.get('/check/:username', authenticateToken, (req, res) => { if ( validatorResult(req, res) ){ return; }
112+
113+
let {username} = req.params;
114+
115+
let sqlsyn = ` SELECT * FROM user WHERE username=?; `;
116+
pooldb.query(sqlsyn, [username], async (err, result) => {
117+
if (err){
118+
console.log(err);
119+
} else {
120+
if (result[0]){
121+
let userData = result[0];
122+
res.json({
123+
code : "ok",
124+
msg : "User ditemukan!",
125+
data : {userData}
126+
});
127+
}else{
128+
res.json({
129+
code : "error",
130+
msg : "User tidak ditemukan!"
131+
});
132+
}
133+
}
134+
});
135+
});
136+
137+
app.get('/*', (req, res) => {
138+
res.json({
139+
code : "error",
140+
msg : "API Invalid"
141+
})
142+
});
143+
144+
app.listen(process.env.HTTP_PORT, () => {
145+
console.log(`Server dengan port ${process.env.HTTP_PORT} berjalan...`);
146+
});
147+

module-tools.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/*
2+
Module untuk penanganan generate random number dan lainnya di masa mendatang
3+
Daftar Function :
4+
numberGen( jumlahDigit ); return angka
5+
*/
6+
7+
let tools = {};
8+
9+
// Number Gen (Hanya jarak 2-Sekian)
10+
tools.numberGen = function (antara=6){
11+
let digit = '';
12+
for (let index = 1; index < antara; index++) {
13+
digit += '0';
14+
}
15+
return Math.floor( parseInt('1' + digit) + ( Math.random() * parseInt('9' + digit) ) );
16+
}
17+
18+
module.exports = tools;

0 commit comments

Comments
 (0)