2021-11-20 08:04:28 +01:00
|
|
|
const db = require("../modules/db");
|
|
|
|
|
|
|
|
function session_decode(session) {
|
|
|
|
let decode;
|
|
|
|
try {
|
|
|
|
decode = JSON.parse(Buffer.from(session, 'base64').toString('ascii'));
|
|
|
|
} catch (e) {
|
|
|
|
decode = {'user_id': 0, 'session_token': 'xxx'};
|
|
|
|
}
|
|
|
|
return decode;
|
|
|
|
}
|
|
|
|
|
|
|
|
function session_converter(session) {
|
|
|
|
let data = session_decode(session);
|
|
|
|
const conn = db.connect();
|
|
|
|
let key = new Promise(function (res, rej) {
|
|
|
|
conn.query(
|
|
|
|
"SELECT * FROM users WHERE id = ?",
|
|
|
|
[data.user_id],
|
|
|
|
function (error, response, fields) {
|
|
|
|
if (error) {
|
|
|
|
rej(error);
|
|
|
|
} else {
|
|
|
|
try {
|
|
|
|
let session_data = JSON.parse(response[0].session);
|
|
|
|
let filtered_session = session_data.filter( x => x.session == data.session_token);
|
|
|
|
if (filtered_session.length > 0 && response[0].verify == '1') {
|
|
|
|
res(response[0].token);
|
|
|
|
} else {
|
|
|
|
res(null);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
res(null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
return key;
|
|
|
|
}
|
|
|
|
|
2021-11-21 03:13:51 +01:00
|
|
|
function session_remove(key, session_token) {
|
|
|
|
let data = session_decode(session_token);
|
|
|
|
const conn = db.connect();
|
|
|
|
let status = new Promise(function (res, rej) {
|
|
|
|
conn.query(
|
|
|
|
"SELECT * FROM users WHERE token = ?",
|
|
|
|
[key],
|
|
|
|
async function (error, response, fields) {
|
|
|
|
if (error) {
|
|
|
|
rej(error);
|
|
|
|
} else {
|
|
|
|
let session_data = JSON.parse(response[0].session);
|
|
|
|
session_data = session_data.filter( x => {
|
|
|
|
if (x.session != data.session_token) {
|
|
|
|
return x;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
conn.query(
|
|
|
|
'UPDATE users SET ? WHERE token = ?', [{session: JSON.stringify(session_data)}, key],
|
|
|
|
function (err, result) {
|
|
|
|
if (err) {
|
|
|
|
rej(error)
|
|
|
|
} else {
|
|
|
|
console.log('sukses');
|
|
|
|
res(true)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
return status;
|
|
|
|
}
|
|
|
|
|
2021-11-20 08:04:28 +01:00
|
|
|
function auth_checker(key) {
|
|
|
|
const conn = db.connect();
|
|
|
|
let status = new Promise(function (res, rej) {
|
|
|
|
conn.query(
|
|
|
|
"SELECT * FROM users WHERE token = ?",
|
|
|
|
[key],
|
|
|
|
async function (error, response, fields) {
|
|
|
|
if (error) {
|
|
|
|
rej(error);
|
|
|
|
} else {
|
2021-11-21 01:40:43 +01:00
|
|
|
if (response[0]) {
|
2021-11-20 08:04:28 +01:00
|
|
|
res(true);
|
|
|
|
} else {
|
|
|
|
res(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
return status;
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
session_decode,
|
|
|
|
session_converter,
|
2021-11-21 03:13:51 +01:00
|
|
|
session_remove,
|
2021-11-20 08:04:28 +01:00
|
|
|
auth_checker
|
|
|
|
};
|