t00-multiuser/server/controller/ApiController.ts

47 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-09-19 00:41:40 +01:00
import ApiLoginModel from "../models/api/ApiLoginModel";
import Config from "../objects/Config";
import UserService from "../services/UserService";
import Controller from "./Controller";
// for Git server lookup
let cachedVersion = "";
let cacheExpiry = 0;
export default class ApiController extends Controller {
public async Login_Post_AllowAnonymous(apiLoginModel: ApiLoginModel) {
this.res.header("access-control-allow-origin", "*");
if (typeof(apiLoginModel.username) !== "string" || typeof(apiLoginModel.password) !== "string") {
return this.badRequest();
}
const user = await UserService.AuthenticateUser(apiLoginModel.username, apiLoginModel.password);
if (user) {
return this.ok(user.APIKey);
}
return this.unauthorised("Username or Password incorrect");
}
public async Version_Post_AllowAnonymous() {
this.res.header("access-control-allow-origin", "*");
if (Date.now() < cacheExpiry) {
this.ok(cachedVersion);
} else {
const response = await fetch(`http://${Config.githost}/tgpholly/t00-multiuser/raw/branch/master/client/Terminal-00-Multiuser.user.js?${Date.now()}`);
if (response.status === 200) {
const content = await response.text();
if (content.includes("@version")) {
cachedVersion = content.split("@version")[1].split("\n")[0].trim().split(".").join("");
cacheExpiry = Date.now() + 30000;
return this.ok(cachedVersion);
} else {
return this.ok("0");
}
} else {
return this.ok("0");
}
}
}
}