Skip to content
Merged
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
17 changes: 17 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@
"cordova-plugin-system": {},
"com.foxdebug.acode.rk.exec.proot": {},
"com.foxdebug.acode.rk.exec.terminal": {},
"com.foxdebug.acode.rk.customtabs": {}
"com.foxdebug.acode.rk.customtabs": {},
"com.foxdebug.acode.rk.auth": {}
},
"platforms": [
"android"
Expand All @@ -64,6 +65,7 @@
"@types/url-parse": "^1.4.11",
"autoprefixer": "^10.4.21",
"babel-loader": "^10.0.0",
"com.foxdebug.acode.rk.auth": "file:src/plugins/auth",
"com.foxdebug.acode.rk.customtabs": "file:src/plugins/custom-tabs",
"com.foxdebug.acode.rk.exec.proot": "file:src/plugins/proot",
"com.foxdebug.acode.rk.exec.terminal": "file:src/plugins/terminal",
Expand Down
220 changes: 69 additions & 151 deletions src/lib/auth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import fsOperation from "fileSystem";
import toast from "components/toast";
import { addIntentHandler } from "handlers/intent";
import constants from "./constants";

const loginEvents = {
listeners: new Set(),
Expand All @@ -18,70 +16,16 @@ const loginEvents = {
},
};

async function checkTokenFileExists() {
return await fsOperation(`${DATA_STORAGE}.acode_token`).exists();
}

async function saveToken(token) {
try {
if (await checkTokenFileExists()) {
await fsOperation(`${DATA_STORAGE}.acode_token`).writeFile(token);
} else {
await fsOperation(DATA_STORAGE).createFile(".acode_token", token);
}
return true;
} catch (error) {
console.error("Failed to save token", error);
return false;
}
}

async function getToken() {
try {
if (await checkTokenFileExists()) {
const token = await fsOperation(`${DATA_STORAGE}.acode_token`).readFile(
"utf8",
);
return token;
}
return null;
} catch (error) {
console.error("Failed to get token", error);
return null;
}
}

async function deleteToken() {
try {
if (await checkTokenFileExists()) {
await fsOperation(`${DATA_STORAGE}.acode_token`).delete();
return true;
}
return false;
} catch (error) {
console.error("Failed to delete token", error);
return false;
}
}

class AuthService {
constructor() {
addIntentHandler(this.onIntentReceiver.bind(this));
}

openLoginUrl() {
try {
system.openInBrowser("https://acode.app/login?redirect=app");
} catch (error) {
console.error("Failed while opening login page.", error);
}
}

async onIntentReceiver(event) {
try {
if (event?.module === "user" && event?.action === "login") {
if (event?.value) {
saveToken(event.value);
this._exec("saveToken", [event.value]);
toast("Logged in successfully");

setTimeout(() => {
Expand All @@ -96,10 +40,32 @@ class AuthService {
}
}

/**
* Helper to wrap cordova.exec in a Promise
*/
_exec(action, args = []) {
return new Promise((resolve, reject) => {
cordova.exec(resolve, reject, "Authenticator", action, args);
});
}

async openLoginUrl() {
const url = "https://acode.app/login?redirect=app";

try {
await new Promise((resolve, reject) => {
CustomTabs.open(url, { showTitle: true }, resolve, reject);
});
} catch (error) {
console.error("CustomTabs failed, opening system browser.", error);
system.openInBrowser(url);
}
}

async logout() {
try {
const result = await deleteToken();
return result;
await this._exec("logout");
return true;
} catch (error) {
console.error("Failed to logout.", error);
return false;
Expand All @@ -108,69 +74,20 @@ class AuthService {

async isLoggedIn() {
try {
const token = await getToken();
if (!token) return false;

return new Promise((resolve, reject) => {
cordova.plugin.http.sendRequest(
`${constants.API_BASE}/login`,
{
method: "GET",
headers: {
"x-auth-token": token,
},
},
(response) => {
resolve(true);
},
async (error) => {
if (error.status === 401) {
await deleteToken();
resolve(false);
} else {
console.error("Failed to check login status.", error);
resolve(false);
}
},
);
});
// Native checks EncryptedPrefs and validates with API internally
await this._exec("isLoggedIn");
return true;
} catch (error) {
console.error("Failed to check login status.", error);
console.error(error);
// error is typically the status code (0 if no token, 401 if invalid)
return false;
}
}

async getUserInfo() {
try {
const token = await getToken();
if (!token) return null;

return new Promise((resolve, reject) => {
cordova.plugin.http.sendRequest(
`${constants.API_BASE}/login`,
{
method: "GET",
headers: {
"x-auth-token": token,
},
},
async (response) => {
if (response.status === 200) {
resolve(JSON.parse(response.data));
}
resolve(null);
},
async (error) => {
if (error.status === 401) {
await deleteToken();
resolve(null);
} else {
console.error("Failed to fetch user data.", error);
resolve(null);
}
},
);
});
const data = await this._exec("getUserInfo");
return typeof data === "string" ? JSON.parse(data) : data;
} catch (error) {
console.error("Failed to fetch user data.", error);
return null;
Expand All @@ -187,42 +104,7 @@ class AuthService {
}

if (userData.name) {
const nameParts = userData.name.split(" ");
let initials = "";

if (nameParts.length >= 2) {
initials = `${nameParts[0][0]}${nameParts[1][0]}`.toUpperCase();
} else {
initials = nameParts[0][0].toUpperCase();
}

// Create a data URL for text-based avatar
const canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
const ctx = canvas.getContext("2d");

// Set background
// Array of colors to choose from
const colors = [
"#2196F3",
"#9C27B0",
"#E91E63",
"#009688",
"#4CAF50",
"#FF9800",
];
ctx.fillStyle = colors[Math.floor(Math.random() * colors.length)];
ctx.fillRect(0, 0, 100, 100);

// Add text
ctx.fillStyle = "#ffffff";
ctx.font = "bold 40px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(initials, 50, 50);

return canvas.toDataURL();
return this._generateInitialsAvatar(userData.name);
}

return null;
Expand All @@ -231,6 +113,42 @@ class AuthService {
return null;
}
}

_generateInitialsAvatar(name) {
const nameParts = name.split(" ");
const initials =
nameParts.length >= 2
? `${nameParts[0][0]}${nameParts[1][0]}`.toUpperCase()
: nameParts[0][0].toUpperCase();

const canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
const ctx = canvas.getContext("2d");

const colors = [
"#2196F3",
"#9C27B0",
"#E91E63",
"#009688",
"#4CAF50",
"#FF9800",
];
ctx.fillStyle =
colors[
name.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0) %
colors.length
];
ctx.fillRect(0, 0, 100, 100);

ctx.fillStyle = "#ffffff";
ctx.font = "bold 40px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(initials, 50, 50);

return canvas.toDataURL();
}
}

export default new AuthService();
Expand Down
17 changes: 17 additions & 0 deletions src/plugins/auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "com.foxdebug.acode.rk.auth",
"version": "1.0.0",
"description": "Authentication plugin",
"cordova": {
"id": "com.foxdebug.acode.rk.auth",
"platforms": [
"android"
]
},
"keywords": [
"ecosystem:cordova",
"cordova-android"
],
"author": "@RohitKushvaha01",
"license": "MIT"
}
20 changes: 20 additions & 0 deletions src/plugins/auth/plugin.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="com.foxdebug.acode.rk.auth" version="1.0.0">
<name>Authentication</name>


<platform name="android">
<config-file parent="/*" target="res/xml/config.xml">
<feature name="Authenticator">
<param name="android-package" value="com.foxdebug.acode.rk.auth.Authenticator" />
</feature>
</config-file>

<framework src="androidx.security:security-crypto:1.1.0" />

<source-file src="src/android/Authenticator.java" target-dir="src/com/foxdebug/acode/rk/auth" />
<source-file src="src/android/EncryptedPreferenceManager.java" target-dir="src/com/foxdebug/acode/rk/auth" />


</platform>
</plugin>
Loading