Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[30] fixed cors issue, header issue and removed code documentation #31

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions App/src/apis.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
const BASE_URL = "http://localhost:8000/";

export const postLogs = (params) => {
fetch(`${BASE_URL}/log`, {
fetch(`${BASE_URL}log`, {
method: "post",
data: JSON.stringify(params),
body: JSON.stringify(params),
headers: {
"Content-Type": "application/json",
},
}).catch((error) => {
console.log("error: ", error);
});
};

export const postEvent = (params) => {
fetch(`${BASE_URL}/event`, {
fetch(`${BASE_URL}event`, {
method: "post",
data: JSON.stringify(params),
body: JSON.stringify(params),
headers: {
"Content-Type": "application/json",
},
}).catch((error) => {
console.log("error: ", error);
});
Expand Down
77 changes: 33 additions & 44 deletions App/src/codeGremlin.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,42 @@
//to naina the unplugged
async function nainaAB() {
return new Promise((resolve, reject) => {
let isNainaFound = false;

function nainaAB() {
let isNainaFound = false;
const ad = document.createElement("div");
ad.className = "adsbox";
ad.style.width = "1px";
ad.style.height = "1px";
ad.style.position = "absolute";
ad.style.top = "-1000px";
document.body.appendChild(ad);

// Test using a dummy ad element
const ad = document.createElement("div");
ad.className = "adsbox"; // Class name commonly blocked by ad unpluggeds
ad.style.width = "1px";
ad.style.height = "1px";
ad.style.position = "absolute";
ad.style.top = "-1000px";
document.body.appendChild(ad);
setTimeout(() => {
if (ad.offsetParent === null || ad.offsetHeight === 0 || ad.offsetWidth === 0) {
isNainaFound = true;
}
document.body.removeChild(ad);

// Allow some time for the ad unplugged to block the element
setTimeout(() => {
if (
ad.offsetParent === null ||
ad.offsetHeight === 0 ||
ad.offsetWidth === 0
) {
isNainaFound = true;
}
document.body.removeChild(ad);
const testScript = document.createElement("script");
testScript.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";

// Test using an external ad script
const testScript = document.createElement("script");
testScript.src =
"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"; // Common ad script
testScript.onerror = () => {
// If the script fails to load, an ad unplugged is likely active
isNainaFound = true;
finalizeNaina();
};
testScript.onerror = () => {
isNainaFound = true;
resolve(isNainaFound);
};

// If the script loads successfully, no unplugged is found
testScript.onload = finalizeNaina;
testScript.onload = () => {
if (navigator.brave) {
navigator.brave.isBrave().then((isB) => {
reject(isNainaFound || isB);
});
} else {
resolve(isNainaFound);
}
};

document.head.appendChild(testScript);
}, 100);
// Brave browser Naina
function finalizeNaina() {
if (navigator.brave) {
navigator.brave.isBrave().then((isBrave) => {
return isNainaFound || isBrave;
});
} else {
return isNainaFound;
}
}
document.head.appendChild(testScript);
}, 100);
});
}

export default nainaAB;
34 changes: 8 additions & 26 deletions App/src/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,23 @@ import { postLogs, postEvent } from "./apis.js";
import nainaAB from "./codeGremlin.js";
import { ALY_TOOLS_ENDPOINTS } from "./constants.js";

let isABDhadakne = false;
(function () {
isABDhadakne = nainaAB();
})();

/**
* @param {Object} {message, sorurce}
* @returns {void}
* @description will do the api call if the page is breaking
*/
export const wizarddryHelper = ({ message, source }) => {
try {
//will do the api call if the page is breaking
const uuid = localStorage.getItem("dryId");
let params = {
uuid,
logs: [message],
log: String(message),
source: "F",
origin: source,
title: "dummy",
status: "PENDING"
};
postLogs(params);
} catch (error) {
console.log("error: ", error);
}
};

/**
* @param {Object} url
* @returns {boolean}
* @description this will check if the url is an tom api
*/
const isTomAPI = (url) => {
return ALY_TOOLS_ENDPOINTS.some((tom) => {
if (url.includes(tom)) {
Expand All @@ -42,27 +28,23 @@ const isTomAPI = (url) => {
});
};

/**
* @param {array, boolean} [url, options], isError
* @returns {void}
* @description will do the api call for specific api calls
*/
export const magicBeansHelper = (args = [], isError = false) => {
export const magicBeansHelper = async (args = [], isError = false) => {
try {
if (isTomAPI(args[0])) {
let isUnplugged = false;
if (isError) {
isUnplugged = isABDhadakne;
}
isUnplugged = await nainaAB();
};
const uuid = localStorage.getItem("dryId");
let browser = navigator.userAgentData?.brand?.[0]?.brand;
let browser = navigator.userAgentData?.brands?.[0]?.brand;
let params = {
uuid,
url: args[0],
source: "F",
payload: args[1],
ab_active: isUnplugged,
user_agent: browser,
result: isError ? "FAILED" : "SUCCESS"
};
postEvent(params);
}
Expand Down
3 changes: 1 addition & 2 deletions App/src/magicBeans.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
//This file is used to read events
import { magicBeansHelper } from "./helper.js";

(function () {
Expand All @@ -20,7 +19,7 @@ import { magicBeansHelper } from "./helper.js";
this.addEventListener("error", () => magicBeansHelper([url, method], true));
this.addEventListener("load", () => {
if (this.status === 0) {
magicBeansHelper([url, method], true); // Status 0 indicates a possible blocked request
magicBeansHelper([url, method], true);
} else {
magicBeansHelper([url, method], false);
}
Expand Down
23 changes: 17 additions & 6 deletions service/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,17 @@

from event_listener.event_listner import APIEventMiddleware
from utils.location import get_location
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8000", "http://localhost:5173", "http://localhost:8000/log"], # Allows all origins
allow_credentials=True, # Allows cookies and credentials
allow_methods=["*"], # Allows all HTTP methods
allow_headers=["*"], # Allows all headers
)

@app.get("/ping")
def read_ping():
Expand Down Expand Up @@ -72,24 +80,26 @@ async def log_event(log_request: LogRequest,request :Request, response: Response

insert_query = """
INSERT INTO error_logs (
uuid, log, title, source, country, city, region
) VALUES (%s, %s, %s, %s,%s,%s,%s);
uuid, log, title, source, country, city, region, origin, status
) VALUES (%s, %s, %s, %s,%s,%s,%s, %s, %s);
"""

# Convert the log list to a , separated string
log_request.logs = ",".join(log_request.logs)
log_request.log = ",".join(log_request.log)

try :
userLoc = get_location(request)
print(userLoc)
execute_query(insert_query, (
log_request.uuid,
log_request.logs,
log_request.log,
log_request.title,
log_request.source,
userLoc.get("country"),
userLoc.get("city"),
userLoc.get("region")
userLoc.get("region"),
log_request.origin,
log_request.status
))
return success_response(response, "log received", 201)
except Exception as e:
Expand Down Expand Up @@ -126,6 +136,7 @@ async def log_backend_event(event):

@app.middleware("http")
async def handle_http_exceptions(request: Request, call_next):
response={"status_code": 200}
try:
response = await call_next(request)
if response.status_code >= 400:
Expand All @@ -135,7 +146,7 @@ async def handle_http_exceptions(request: Request, call_next):
await event_middleware.process_exception(request, e)
return JSONResponse(
content={"error": "Internal Server Error"},
status_code=response.status_code,
status_code=response["status_code"],
)

if __name__ == "__main__":
Expand Down
7 changes: 7 additions & 0 deletions service/migrations/create_table.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ BEGIN
END IF;
END $$;

DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'result_enum') THEN
CREATE TYPE result_enum AS ENUM ('SUCCESS', 'FAILED');
END IF;
END $$;

DO $$
BEGIN
IF NOT EXISTS (
Expand Down