upd
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import authMiddleware from "../middlewares/auth";
|
||||
import create from "../services/apps/create";
|
||||
|
||||
const appsController = new Elysia({ prefix: "/apps" })
|
||||
.use(authMiddleware)
|
||||
.post("/", async ({ auth, body }) => await create(auth, body), {
|
||||
body: t.Object({
|
||||
apps: t.Array(t.String()),
|
||||
serverId: t.String(),
|
||||
companyId: t.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export default appsController;
|
||||
@@ -0,0 +1,32 @@
|
||||
import { Elysia, t } from "elysia";
|
||||
import login from "../services/auth/login";
|
||||
import authMiddleware from "../middlewares/auth";
|
||||
import logout from "../services/auth/logout";
|
||||
|
||||
const authController = new Elysia({ prefix: "/auth" })
|
||||
.post("/login", async ({ body }) => await login(body), {
|
||||
body: t.Object({
|
||||
email: t.String({ minLength: 1 }),
|
||||
password: t.String({ minLength: 1 }),
|
||||
}),
|
||||
})
|
||||
// .post("/register", async ({}) => {}, {
|
||||
// body: t.Object({
|
||||
// username: t.String({ minLength: 1 }),
|
||||
// password: t.String({ minLength: 1 }),
|
||||
// }),
|
||||
// })
|
||||
.use(authMiddleware)
|
||||
.get(
|
||||
"/logout",
|
||||
async ({ headers }) => {
|
||||
const token = headers["authorization"].split(" ")[1];
|
||||
|
||||
return await logout(token);
|
||||
},
|
||||
{
|
||||
headers: t.Object({ authorization: t.String() }),
|
||||
}
|
||||
);
|
||||
|
||||
export default authController;
|
||||
@@ -0,0 +1,6 @@
|
||||
// import Elysia from "elysia";
|
||||
// import authMiddleware from "../middlewares/auth";
|
||||
|
||||
// export const clientsController = new Elysia({ prefix: "/clients" })
|
||||
// .use(authMiddleware)
|
||||
// .get("/", async ({auth:{companyId}}) => {}, {});
|
||||
@@ -0,0 +1,18 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import getServers from "../services/servers/get";
|
||||
import authMiddleware from "../middlewares/auth";
|
||||
import createServer from "../services/servers/create";
|
||||
|
||||
const serversController = new Elysia({ prefix: "/servers" })
|
||||
.use(authMiddleware)
|
||||
.get("/", async ({ auth, query }) => await getServers(auth, query))
|
||||
.post("/", async ({ auth, body }) => await createServer(auth, body), {
|
||||
body: t.Object({
|
||||
hostname: t.String(),
|
||||
name: t.String(),
|
||||
location: t.String(),
|
||||
companyId: t.String(),
|
||||
}),
|
||||
});
|
||||
|
||||
export default serversController;
|
||||
@@ -0,0 +1,62 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import authMiddleware from "../middlewares/auth";
|
||||
import createSession from "../services/sessions/create";
|
||||
import getSessions from "../services/sessions/get";
|
||||
import updateSession from "../services/sessions/update";
|
||||
|
||||
const sessionsController = new Elysia({ prefix: "/sessions" })
|
||||
.use(authMiddleware)
|
||||
.get(
|
||||
"/",
|
||||
async ({ auth, query }) => {
|
||||
return await getSessions(auth, query);
|
||||
},
|
||||
{
|
||||
query: t.Object({ limit: t.Optional(t.Number()) }),
|
||||
}
|
||||
)
|
||||
.post(
|
||||
"/",
|
||||
async ({ body, auth }) => {
|
||||
return await createSession(auth, body);
|
||||
},
|
||||
{
|
||||
body: t.Object({
|
||||
appId: t.String(),
|
||||
serverId: t.String(),
|
||||
clientId: t.String(),
|
||||
}),
|
||||
}
|
||||
)
|
||||
.put(
|
||||
"/:id",
|
||||
async ({ params, body }) => {
|
||||
return await updateSession(
|
||||
params.id,
|
||||
body.status as
|
||||
| "starting"
|
||||
| "started"
|
||||
| "restarting"
|
||||
| "ending"
|
||||
| "ended"
|
||||
);
|
||||
},
|
||||
{
|
||||
params: t.Object({
|
||||
id: t.String(),
|
||||
}),
|
||||
body: t.Object({
|
||||
status: t.Union([
|
||||
t.Literal("starting"),
|
||||
t.Literal("started"),
|
||||
t.Literal("restarting"),
|
||||
t.Literal("ending"),
|
||||
t.Literal("ended"),
|
||||
t.Literal("null"),
|
||||
t.Literal("undefined"),
|
||||
]),
|
||||
}),
|
||||
}
|
||||
);
|
||||
|
||||
export default sessionsController;
|
||||
@@ -0,0 +1,18 @@
|
||||
import Elysia from "elysia";
|
||||
import authMiddleware from "../middlewares/auth";
|
||||
import me from "../services/user/me";
|
||||
|
||||
type AuthContext = {
|
||||
auth: {
|
||||
userId: string;
|
||||
};
|
||||
};
|
||||
|
||||
const usersController = new Elysia({ prefix: "/users" })
|
||||
.use(authMiddleware)
|
||||
.get("/me", async (context) => {
|
||||
const userId = (context as AuthContext).auth.userId;
|
||||
return await me(userId);
|
||||
});
|
||||
|
||||
export default usersController;
|
||||
@@ -0,0 +1,8 @@
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
import * as schema from "./schema/index";
|
||||
|
||||
const client = postgres(process.env.DB_URL);
|
||||
const db = drizzle({ client, schema });
|
||||
|
||||
export default db;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { serversTable } from "./servers";
|
||||
import { relations } from "drizzle-orm";
|
||||
|
||||
export const actionsTable = pgTable("actions", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
name: varchar("name").notNull(),
|
||||
serverId: uuid("server_id")
|
||||
.notNull()
|
||||
.references(() => serversTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const actionsRelations = relations(actionsTable, ({ one }) => ({
|
||||
server: one(serversTable, {
|
||||
fields: [actionsTable.serverId],
|
||||
references: [serversTable.id],
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,34 @@
|
||||
import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { companiesTable } from "./companies";
|
||||
import { relations } from "drizzle-orm";
|
||||
import { serversTable } from "./servers";
|
||||
|
||||
export const appsTable = pgTable("apps", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
name: varchar("name").notNull(),
|
||||
fileName: varchar("filename").notNull(),
|
||||
serverId: uuid("server_id")
|
||||
.notNull()
|
||||
.references(() => serversTable.id),
|
||||
companyId: uuid("company_id")
|
||||
.notNull()
|
||||
.references(() => companiesTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const appsRelations = relations(appsTable, ({ one }) => ({
|
||||
company: one(companiesTable, {
|
||||
fields: [appsTable.companyId],
|
||||
references: [companiesTable.id],
|
||||
}),
|
||||
server: one(serversTable, {
|
||||
fields: [appsTable.serverId],
|
||||
references: [serversTable.id],
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,29 @@
|
||||
import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { companiesTable } from "./companies";
|
||||
import { relations } from "drizzle-orm";
|
||||
import { sessionsTable } from "./sessions";
|
||||
|
||||
export const clientsTable = pgTable("clients", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
fullname: varchar("fullname").notNull(),
|
||||
email: varchar("email").notNull(),
|
||||
phone: varchar("phone", { length: 15 }),
|
||||
companyId: uuid("company_id")
|
||||
.notNull()
|
||||
.references(() => companiesTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const clientsRelations = relations(clientsTable, ({ one, many }) => ({
|
||||
company: one(companiesTable, {
|
||||
fields: [clientsTable.companyId],
|
||||
references: [companiesTable.id],
|
||||
}),
|
||||
sessions: many(sessionsTable),
|
||||
}));
|
||||
@@ -0,0 +1,24 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { usersTable } from "./users";
|
||||
import { appsTable } from "./apps";
|
||||
import { serversTable } from "./servers";
|
||||
|
||||
export const companiesTable = pgTable("companies", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
name: varchar("name").notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const companiesRelations = relations(companiesTable, ({ many }) => ({
|
||||
users: many(usersTable),
|
||||
servers: many(serversTable),
|
||||
apps: many(appsTable),
|
||||
// actions: many(actionsTable),
|
||||
}));
|
||||
@@ -0,0 +1,8 @@
|
||||
export * from "./users";
|
||||
export * from "./tokens";
|
||||
export * from "./companies";
|
||||
export * from "./servers";
|
||||
export * from "./sessions";
|
||||
export * from "./clients";
|
||||
export * from "./apps";
|
||||
export * from "./actions";
|
||||
@@ -0,0 +1,31 @@
|
||||
import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { companiesTable } from "./companies";
|
||||
import { actionsTable } from "./actions";
|
||||
import { relations } from "drizzle-orm";
|
||||
import { sessionsTable } from "./sessions";
|
||||
|
||||
export const serversTable = pgTable("servers", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
hostname: varchar("hostname", { length: 15 }).unique().notNull(),
|
||||
name: varchar("name").notNull(),
|
||||
location: varchar("location").notNull(),
|
||||
companyId: uuid("company_id")
|
||||
.notNull()
|
||||
.references(() => companiesTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const serversRelations = relations(serversTable, ({ one, many }) => ({
|
||||
company: one(companiesTable, {
|
||||
fields: [serversTable.companyId],
|
||||
references: [companiesTable.id],
|
||||
}),
|
||||
sessions: many(sessionsTable),
|
||||
actions: many(actionsTable),
|
||||
}));
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
pgTable,
|
||||
timestamp,
|
||||
uuid,
|
||||
varchar,
|
||||
uniqueIndex,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { companiesTable } from "./companies";
|
||||
import { usersTable } from "./users";
|
||||
import { relations } from "drizzle-orm";
|
||||
import { serversTable } from "./servers";
|
||||
import { clientsTable } from "./clients";
|
||||
import { appsTable } from "./apps";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
export const sessionsTable = pgTable(
|
||||
"sessions",
|
||||
{
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
status: varchar("status", {
|
||||
enum: ["starting", "started", "restarting", "ending", "ended"],
|
||||
}).notNull(),
|
||||
appId: uuid("app_id")
|
||||
.notNull()
|
||||
.references(() => appsTable.id),
|
||||
ownerId: uuid("owner_id")
|
||||
.notNull()
|
||||
.references(() => usersTable.id),
|
||||
serverId: uuid("server_id")
|
||||
.notNull()
|
||||
.references(() => serversTable.id),
|
||||
clientId: uuid("client_id")
|
||||
.notNull()
|
||||
.references(() => clientsTable.id),
|
||||
companyId: uuid("company_id")
|
||||
.notNull()
|
||||
.references(() => companiesTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
},
|
||||
(table) => ({
|
||||
activeServerSessionIdx: uniqueIndex("active_server_session_idx")
|
||||
.on(table.serverId, table.status)
|
||||
.where(sql`${table.status} IN ('starting', 'started')`),
|
||||
})
|
||||
);
|
||||
|
||||
export const sessionsRelations = relations(sessionsTable, ({ one }) => ({
|
||||
owner: one(usersTable, {
|
||||
fields: [sessionsTable.ownerId],
|
||||
references: [usersTable.id],
|
||||
}),
|
||||
server: one(serversTable, {
|
||||
fields: [sessionsTable.serverId],
|
||||
references: [serversTable.id],
|
||||
}),
|
||||
company: one(companiesTable, {
|
||||
fields: [sessionsTable.companyId],
|
||||
references: [companiesTable.id],
|
||||
}),
|
||||
client: one(clientsTable, {
|
||||
fields: [sessionsTable.clientId],
|
||||
references: [clientsTable.id],
|
||||
}),
|
||||
app: one(appsTable, {
|
||||
fields: [sessionsTable.appId],
|
||||
references: [appsTable.id],
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,25 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||
import { usersTable } from "./users";
|
||||
|
||||
export const tokensTable = pgTable("tokens", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
token: text("token").notNull(),
|
||||
userId: uuid("user_id")
|
||||
.notNull()
|
||||
.references(() => usersTable.id, { onDelete: "cascade" }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const tokensRelations = relations(tokensTable, ({ one }) => ({
|
||||
user: one(usersTable, {
|
||||
fields: [tokensTable.userId],
|
||||
references: [usersTable.id],
|
||||
}),
|
||||
}));
|
||||
@@ -0,0 +1,30 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { pgTable, text, timestamp, uuid, varchar } from "drizzle-orm/pg-core";
|
||||
import { tokensTable } from "./tokens";
|
||||
import { companiesTable } from "./companies";
|
||||
|
||||
export const usersTable = pgTable("users", {
|
||||
id: uuid("id").defaultRandom().primaryKey(),
|
||||
fullname: text("fullname"),
|
||||
email: varchar("email").unique().notNull(),
|
||||
password: varchar("password", { length: 72 }).notNull(),
|
||||
// roles: text("roles").array().notNull(),
|
||||
companyId: uuid("company_id")
|
||||
.notNull()
|
||||
.references(() => companiesTable.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
});
|
||||
|
||||
export const usersRelations = relations(usersTable, ({ one, many }) => ({
|
||||
company: one(companiesTable, {
|
||||
fields: [usersTable.companyId],
|
||||
references: [companiesTable.id],
|
||||
}),
|
||||
tokens: many(tokensTable),
|
||||
}));
|
||||
+20
-1
@@ -1,6 +1,25 @@
|
||||
import { Elysia } from "elysia";
|
||||
import cors from "@elysiajs/cors";
|
||||
import authController from "./controllers/authController";
|
||||
import usersController from "./controllers/usersController";
|
||||
import sessionsController from "./controllers/sessionsController";
|
||||
import serversController from "./controllers/serversController";
|
||||
import appsController from "./controllers/appsController";
|
||||
|
||||
const app = new Elysia().get("/", () => "Hello Elysia").listen(3000);
|
||||
const app = new Elysia();
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin: "*",
|
||||
})
|
||||
);
|
||||
app.use(authController);
|
||||
app.use(usersController);
|
||||
app.use(serversController);
|
||||
app.use(sessionsController);
|
||||
app.use(appsController);
|
||||
|
||||
app.listen(3000);
|
||||
|
||||
console.log(
|
||||
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import Elysia, { error } from "elysia";
|
||||
import { jwtVerify } from "jose";
|
||||
import { createHmac } from "crypto";
|
||||
import db from "../db";
|
||||
import { usersTable } from "../db/schema";
|
||||
|
||||
export type AuthContext = {
|
||||
userId: string;
|
||||
companyId: string;
|
||||
};
|
||||
|
||||
const authMiddleware = new Elysia()
|
||||
.derive({ as: "scoped" }, async ({ headers, body }) => {
|
||||
const type = headers["authorization"]?.split(" ")[0];
|
||||
|
||||
if (type === "Bearer") {
|
||||
const accessToken = headers["authorization"]?.split(" ")[1];
|
||||
|
||||
if (!accessToken) {
|
||||
return error(401);
|
||||
}
|
||||
|
||||
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
|
||||
|
||||
try {
|
||||
const {
|
||||
payload: { userId },
|
||||
} = await jwtVerify<{ userId: string }>(accessToken, secret);
|
||||
|
||||
const user = await db.query.usersTable.findFirst({
|
||||
where: eq(usersTable.id, userId),
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return error(401);
|
||||
}
|
||||
|
||||
return {
|
||||
auth: {
|
||||
userId: user.id,
|
||||
companyId: user.companyId,
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
return error(401);
|
||||
}
|
||||
} else if (type === "Hmac") {
|
||||
const signature = headers["authorization"]?.split(" ")[1];
|
||||
|
||||
if (!signature) {
|
||||
return error(401);
|
||||
}
|
||||
|
||||
const verified = createHmac("sha256", process.env.HMAC_SECRET)
|
||||
.update(JSON.stringify(body))
|
||||
.digest("base64");
|
||||
|
||||
if (verified !== signature) {
|
||||
return error(401);
|
||||
}
|
||||
|
||||
return {
|
||||
auth: {
|
||||
userId: "hmac-user",
|
||||
companyId: "hmac-company",
|
||||
},
|
||||
};
|
||||
} else {
|
||||
return error(401);
|
||||
}
|
||||
})
|
||||
.onError({ as: "scoped" }, ({ error, set }) => {
|
||||
if (set.status === 401) {
|
||||
return {
|
||||
error: "Unauthorized",
|
||||
};
|
||||
}
|
||||
|
||||
return error;
|
||||
});
|
||||
|
||||
export default authMiddleware;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { error } from "elysia";
|
||||
import db from "../../db";
|
||||
import { appsTable, serversTable } from "../../db/schema";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import type { AuthContext } from "./../../middlewares/auth";
|
||||
|
||||
export default async function createApp(
|
||||
auth: AuthContext,
|
||||
body: {
|
||||
apps: string[];
|
||||
serverId: string;
|
||||
companyId: string;
|
||||
}
|
||||
) {
|
||||
if (auth.userId !== "hmac-user") {
|
||||
return error(403, "Forbidden");
|
||||
}
|
||||
|
||||
try {
|
||||
const existingApp = await db.query.appsTable.findMany({
|
||||
where: inArray(appsTable.name, body.apps),
|
||||
});
|
||||
|
||||
if (existingApp.length) {
|
||||
return error(400, "App with this name already exists");
|
||||
}
|
||||
|
||||
const apps = await db
|
||||
.insert(appsTable)
|
||||
.values(
|
||||
body.apps.map((app) => ({
|
||||
name: app,
|
||||
fileName: app,
|
||||
companyId: body.companyId,
|
||||
serverId: body.serverId,
|
||||
}))
|
||||
)
|
||||
.returning();
|
||||
|
||||
return apps;
|
||||
} catch (err) {
|
||||
console.log((err as Error).message);
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import db from "../../db";
|
||||
import { tokensTable, usersTable } from "../../db/schema";
|
||||
import { error } from "elysia";
|
||||
import { generateToken } from "../../utils/generateToken";
|
||||
|
||||
export default async function login({
|
||||
email,
|
||||
password,
|
||||
}: {
|
||||
email: string;
|
||||
password: string;
|
||||
}) {
|
||||
try {
|
||||
const user = await db.query.usersTable.findFirst({
|
||||
where: eq(usersTable.email, email),
|
||||
});
|
||||
|
||||
if (!user || !Bun.password.verifySync(password, user.password))
|
||||
return error(401, { error: "Wrong credentials" });
|
||||
|
||||
const token = await generateToken(user.id);
|
||||
|
||||
await db.insert(tokensTable).values({
|
||||
token,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
return {
|
||||
token,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log((err as Error).message);
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { error } from "elysia";
|
||||
import { eq } from "drizzle-orm";
|
||||
import db from "../../db";
|
||||
import { tokensTable } from "../../db/schema";
|
||||
|
||||
export default async function logout(token: string) {
|
||||
try {
|
||||
await db.delete(tokensTable).where(eq(tokensTable.token, token));
|
||||
} catch (err) {
|
||||
console.log((err as Error).message);
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// import { error } from "elysia";
|
||||
// import { eq } from "drizzle-orm";
|
||||
// import db from "../../db";
|
||||
// import { usersTable } from "../../db/schema";
|
||||
|
||||
// export default async function register(payload: {
|
||||
// username: string;
|
||||
// password: string;
|
||||
// companyId: string;
|
||||
// }) {
|
||||
// const { companyId, username } = payload;
|
||||
|
||||
// try {
|
||||
// const candidate = await db.query.usersTable.findFirst({
|
||||
// where: eq(usersTable.username, username),
|
||||
// });
|
||||
|
||||
// if (candidate) return error(400, "user already exists");
|
||||
|
||||
// const password = Bun.hash(payload.password);
|
||||
|
||||
// const user = await db
|
||||
// .insert(usersTable)
|
||||
// .values({ companyId, username, password });
|
||||
// } catch (error) {}
|
||||
// }
|
||||
@@ -0,0 +1,41 @@
|
||||
import { error } from "elysia";
|
||||
import db from "../../db";
|
||||
import { serversTable } from "../../db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { AuthContext } from "./../../middlewares/auth";
|
||||
|
||||
export default async function createServer(
|
||||
auth: AuthContext,
|
||||
body: {
|
||||
hostname: string;
|
||||
name: string;
|
||||
location: string;
|
||||
companyId: string;
|
||||
}
|
||||
) {
|
||||
if (auth.userId !== "hmac-user") {
|
||||
return error(403, "Forbidden");
|
||||
}
|
||||
|
||||
try {
|
||||
const existingServer = await db.query.serversTable.findFirst({
|
||||
where: eq(serversTable.hostname, body.hostname),
|
||||
});
|
||||
|
||||
if (existingServer) {
|
||||
return error(400, "Server with this hostname already exists");
|
||||
}
|
||||
|
||||
const server = await db
|
||||
.insert(serversTable)
|
||||
.values({
|
||||
...body,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return server;
|
||||
} catch (err) {
|
||||
console.log((err as Error).message);
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { error } from "elysia";
|
||||
import db from "../../db";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { serversTable, sessionsTable } from "../../db/schema";
|
||||
import type { AuthContext } from "../../middlewares/auth";
|
||||
|
||||
export default async function getServers(
|
||||
auth: AuthContext,
|
||||
query?: {
|
||||
withLastSession?: boolean;
|
||||
with?: string;
|
||||
}
|
||||
) {
|
||||
try {
|
||||
const servers = await db.query.serversTable.findMany({
|
||||
where: eq(serversTable.companyId, auth.companyId),
|
||||
with: {
|
||||
...(query?.with
|
||||
? Object.fromEntries(
|
||||
JSON.parse(query.with).map((k: string) => [
|
||||
k,
|
||||
{
|
||||
orderBy: desc(sessionsTable.createdAt),
|
||||
},
|
||||
])
|
||||
)
|
||||
: query?.withLastSession
|
||||
? {
|
||||
sessions: {
|
||||
orderBy: desc(sessionsTable.createdAt),
|
||||
limit: 1,
|
||||
with: {
|
||||
client: {
|
||||
columns: {
|
||||
fullname: true,
|
||||
},
|
||||
},
|
||||
app: {
|
||||
columns: {
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
: undefined),
|
||||
},
|
||||
});
|
||||
|
||||
return servers;
|
||||
} catch (err) {
|
||||
console.log((err as Error).message);
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { and, eq, or } from "drizzle-orm";
|
||||
import db from "../../db";
|
||||
import { sessionsTable } from "../../db/schema";
|
||||
import { error } from "elysia";
|
||||
|
||||
async function createSession(
|
||||
auth: {
|
||||
userId: string;
|
||||
companyId: string;
|
||||
},
|
||||
body: {
|
||||
appId: string;
|
||||
serverId: string;
|
||||
clientId: string;
|
||||
}
|
||||
) {
|
||||
try {
|
||||
// Check for existing session
|
||||
const [existingSession] = await db
|
||||
.select()
|
||||
.from(sessionsTable)
|
||||
.where(
|
||||
and(
|
||||
eq(sessionsTable.serverId, body.serverId),
|
||||
or(
|
||||
eq(sessionsTable.status, "starting"),
|
||||
eq(sessionsTable.status, "started")
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingSession) {
|
||||
return error(409, "Session already exists");
|
||||
}
|
||||
|
||||
// Create new session
|
||||
const [newSession] = await db
|
||||
.insert(sessionsTable)
|
||||
.values({
|
||||
...body,
|
||||
ownerId: auth.userId,
|
||||
companyId: auth.companyId,
|
||||
status: "starting",
|
||||
})
|
||||
.returning();
|
||||
|
||||
return newSession;
|
||||
} catch (err) {
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
|
||||
export default createSession;
|
||||
@@ -0,0 +1,34 @@
|
||||
import db from "../../db";
|
||||
import { error } from "elysia";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { sessionsTable } from "../../db/schema";
|
||||
import type { AuthContext } from "../../middlewares/auth";
|
||||
|
||||
async function getSessions(
|
||||
auth: AuthContext,
|
||||
query?: {
|
||||
limit?: number;
|
||||
}
|
||||
) {
|
||||
try {
|
||||
const sessions = await db.query.sessionsTable.findMany({
|
||||
where: and(
|
||||
eq(sessionsTable.ownerId, auth.userId),
|
||||
eq(sessionsTable.companyId, auth.companyId)
|
||||
),
|
||||
with: {
|
||||
client: true,
|
||||
app: true,
|
||||
server: true,
|
||||
},
|
||||
limit: query?.limit,
|
||||
orderBy: desc(sessionsTable.createdAt),
|
||||
});
|
||||
|
||||
return sessions;
|
||||
} catch (err) {
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
|
||||
export default getSessions;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import db from "../../db";
|
||||
import { sessionsTable } from "../../db/schema";
|
||||
import { error } from "elysia";
|
||||
|
||||
async function updateSession(
|
||||
sessionId: string,
|
||||
status: "starting" | "started" | "restarting" | "ending" | "ended"
|
||||
) {
|
||||
try {
|
||||
const session = await db
|
||||
.update(sessionsTable)
|
||||
.set({ status })
|
||||
.where(eq(sessionsTable.id, sessionId))
|
||||
.returning();
|
||||
|
||||
return session;
|
||||
} catch (err) {
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
|
||||
export default updateSession;
|
||||
@@ -0,0 +1,21 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import db from "../../db";
|
||||
import { usersTable } from "../../db/schema";
|
||||
import { error } from "elysia";
|
||||
|
||||
export default async function me(userId: string) {
|
||||
try {
|
||||
const user = await db.query.usersTable.findFirst({
|
||||
where: eq(usersTable.id, userId),
|
||||
columns: {
|
||||
id: true,
|
||||
email: true,
|
||||
fullname: true,
|
||||
},
|
||||
});
|
||||
|
||||
return user;
|
||||
} catch (err) {
|
||||
return error(500, "Internal Server Error");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { SignJWT } from "jose";
|
||||
|
||||
export async function generateToken(userId: string) {
|
||||
return await new SignJWT({
|
||||
userId,
|
||||
})
|
||||
.setProtectedHeader({ alg: "HS256" })
|
||||
.setExpirationTime(process.env.JWT_EXPIRATION)
|
||||
.sign(new TextEncoder().encode(process.env.JWT_SECRET));
|
||||
}
|
||||
Reference in New Issue
Block a user