Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
35eeb87
feat: add draft for port of user registration to resource route
scheidtdav May 14, 2025
42593f0
feat: partly implement refresh token
scheidtdav May 19, 2025
dcd635f
docs: simplify contributing and add info about api routes and shared …
scheidtdav May 21, 2025
be4ebed
feat(api): finalize user registration endpoint
scheidtdav May 21, 2025
b4b8421
fix(tests): get the tests to run be reconfiguring build steps
scheidtdav May 21, 2025
8fbb075
docs(db): readd db setup and seed scripts with README info for it
scheidtdav May 21, 2025
1de6e69
fix: wrong import of utils
scheidtdav May 21, 2025
08f4405
refactor: remove leftover custom server stuff
scheidtdav May 21, 2025
4a3f8e4
fix(tests): add missing refresh token table
scheidtdav May 21, 2025
29d3034
fix(tests): reenable remaining tests for registration
scheidtdav May 22, 2025
d164738
fix(ci): remove playwright and use correct node version
scheidtdav May 27, 2025
7566724
fix(ci): run the tests with a postgres container
scheidtdav May 27, 2025
44894b4
feat(tests): add coverage report
scheidtdav May 27, 2025
77b4cc9
fix(build): reorganize server modules to correctly split client/ server
scheidtdav May 27, 2025
5612a5f
fix(build): miss an import
scheidtdav May 27, 2025
2e335d5
fix(build): remove leftovers from custom server implementation
scheidtdav May 27, 2025
bbf5430
chore(deps): bump react-router dependencies
scheidtdav May 27, 2025
bf19c7e
chore(deps): update react-router
scheidtdav May 27, 2025
7d91045
feat/user me api (#559)
scheidtdav May 27, 2025
a5699de
feat(api): add root route (#560)
scheidtdav May 27, 2025
760914b
start
JerryVincent Jun 13, 2025
81a1f9c
new commit
JerryVincent Jun 13, 2025
acf1770
tested docs
JerryVincent Jun 16, 2025
eedb806
added a route
JerryVincent Jun 16, 2025
a6245ea
Added API Docs
JerryVincent Jun 16, 2025
4712c6a
modified
JerryVincent Jun 16, 2025
f63dc07
removed unsupported packages
JerryVincent Jun 16, 2025
7741945
updated
JerryVincent Jun 16, 2025
3b620a0
Modified
JerryVincent Jun 17, 2025
f51f518
script generation without using ts-node.
JerryVincent Jun 17, 2025
5f7a6ef
modified
JerryVincent Jun 17, 2025
f9ecca4
Merge branch 'api-prod' into feat/user-registration-api
scheidtdav Jun 18, 2025
bd0e52e
fix: update package-lock.json
scheidtdav Jun 18, 2025
31f793c
Updated (#575)
JerryVincent Jun 24, 2025
c5b9835
feat: add command for drizzle studio
jona159 Jun 25, 2025
43798ff
feat: devices loader
jona159 Jun 25, 2025
a9262df
feat: load single device
jona159 Jun 25, 2025
e5f0e9f
feat: uncomment get boxes, delete box path
jona159 Jun 25, 2025
87c390d
feat(wip): add boxes test suite
jona159 Jun 25, 2025
6301974
feat: add devices service
jona159 Jun 25, 2025
e96766c
fix: some types, formatting
jona159 Jun 25, 2025
511b94a
Removed duplicate Documentation section (#576)
JerryVincent Jun 25, 2025
98617c3
Update README.md
JerryVincent Jun 25, 2025
9492e13
Feat/api email and password (#561)
scheidtdav Jun 25, 2025
8a721f7
feat/api auth (#562)
scheidtdav Jun 25, 2025
ef552e1
feat(api): boxes for user endpoints (#573)
scheidtdav Jun 25, 2025
46e89cd
feat/api misc (#571)
scheidtdav Jun 25, 2025
fcf4b8d
Merge branch 'dev' into feat/user-registration-api
jona159 Jun 25, 2025
1bd97eb
feat(api): add route and test files
scheidtdav Jun 18, 2025
46b0422
feat: add test code
scheidtdav Jun 18, 2025
787b662
feat: add dummy sensors to devices and implement getting them back
scheidtdav Jun 25, 2025
95acb53
Merge branch 'dev' into feat/api-boxes-sensors
scheidtdav Jul 2, 2025
eb84619
feat: prefer dev server in no production envs and hide dev in prod
scheidtdav Jul 2, 2025
84f57ca
feat(docs): start adding docs to route
scheidtdav Jul 2, 2025
eeb6049
feat: wip devices api
jona159 Jul 16, 2025
a232d6b
Merge branch 'dev' into feat/api-boxes-sensors
scheidtdav Jul 23, 2025
cf36b0a
feat: finish up to the point where we need measurements
scheidtdav Jul 23, 2025
0a35d3b
fix: api routes without need for measurements
scheidtdav Jul 30, 2025
89e8c04
fix: stats call
scheidtdav Jul 30, 2025
9a8e679
fix: remaining tests
scheidtdav Jul 30, 2025
32bdb9e
fix: frontend issue from changing the service implementation
scheidtdav Jul 30, 2025
711ea65
fix: tests
scheidtdav Aug 13, 2025
6f1520f
Merge branch 'feat/api-boxes-sensors' into feat/api-boxes
scheidtdav Aug 13, 2025
c0713e9
refactor: use modern syntax for assertion
scheidtdav Aug 13, 2025
1bbf604
feat: adjust for zod schema
jona159 Sep 10, 2025
38c763f
feat: add drizzle check
jona159 Sep 10, 2025
6fb23fa
feat: transfer routes
jona159 Sep 10, 2025
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
1,278 changes: 639 additions & 639 deletions app/components/device-detail/device-detail-box.tsx

Large diffs are not rendered by default.

99 changes: 99 additions & 0 deletions app/lib/devices-service.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { Device, User } from '~/schema'

Check warning on line 1 in app/lib/devices-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

All imports in the declaration are only used as types. Use `import type`
import {

Check warning on line 2 in app/lib/devices-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

`~/models/device.server` import should occur before import of `~/schema`
deleteDevice as deleteDeviceById,
} from '~/models/device.server'
import { verifyLogin } from '~/models/user.server'

Check warning on line 5 in app/lib/devices-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

`~/models/user.server` import should occur before import of `~/schema`
import { z } from 'zod'

Check warning on line 6 in app/lib/devices-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

`zod` import should occur before import of `~/schema`

export const BoxesQuerySchema = z.object({
format: z.enum(["json", "geojson"] ,{
errorMap: () => ({ message: "Format must be either 'json' or 'geojson'" }),
}).default("json"),
minimal: z.enum(["true", "false"]).default("false")
.transform((v) => v === "true"),
full: z.enum(["true", "false"]).default("false")
.transform((v) => v === "true"),
limit: z
.string()
.default("5")
.transform((val) => parseInt(val, 10))
.refine((val) => !isNaN(val), { message: "Limit must be a number" })
.refine((val) => val >= 1, { message: "Limit must be at least 1" })
.refine((val) => val <= 20, { message: "Limit must not exceed 20" }),

name: z.string().optional(),
date: z
.union([z.string().datetime(), z.array(z.string().datetime())])
.transform((val) => (Array.isArray(val) ? val : [val]))
.refine((arr) => arr.length >= 1 && arr.length <= 2, {
message: "Date must contain 1 or 2 timestamps",
})
.optional(),
phenomenon: z.string().optional(),
grouptag: z.string().transform((v) => [v]).optional(),
model: z.string().transform((v) => [v]).optional(),
exposure: z.string().transform((v) => [v]).optional(),

near: z
.string()
.regex(/^[-+]?\d+(\.\d+)?,[-+]?\d+(\.\d+)?$/, {
message: "Invalid 'near' parameter format. Expected: 'lat,lng'",
})
.transform((val) => val.split(",").map(Number) as [number, number])
.optional(),

maxDistance: z.string().transform((v) => Number(v)).optional(),

bbox: z
.string()
.transform((val) => {
const coords = val.split(",").map(Number);
if (coords.length !== 4 || coords.some((n) => isNaN(n))) {
throw new Error("Invalid bbox parameter");
}
const [swLng, swLat, neLng, neLat] = coords;
return {
coordinates: [
[
[swLat, swLng],
[neLat, swLng],
[neLat, neLng],
[swLat, neLng],
[swLat, swLng],
],
],
};
})
.optional(),

fromDate: z.string().datetime().transform((v) => new Date(v)).optional(),
toDate: z.string().datetime().transform((v) => new Date(v)).optional(),
}).refine(
(data) =>
!(data.date && !data.phenomenon) && !(data.phenomenon && !data.date),
{
message: "Date and phenomenon must be used together",
path: ["date"],
}
);


export type BoxesQueryParams = z.infer<typeof BoxesQuerySchema>;

/**
* Deletes a device after verifiying that the user is entitled by checking
* the password.
* @param user The user deleting the device
* @param password The users password to verify
* @returns True if the device was deleted, otherwise false or "unauthorized"
* if the user is not entitled to delete the device with the given parameters
*/
export const deleteDevice = async (
user: User,
device: Device,
password: string,
): Promise<boolean | 'unauthorized'> => {
const verifiedUser = await verifyLogin(user.email, password)
if (verifiedUser === null) return 'unauthorized'
return (await deleteDeviceById({ id: device.id })).count > 0
}
27 changes: 27 additions & 0 deletions app/lib/measurement-service.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { getDeviceWithoutSensors } from "~/models/device.server";
import { getSensorsWithLastMeasurement } from "~/models/sensor.server";

/**
*
* @param boxId
* @param sensorId
* @param count
*/
export const getLatestMeasurements = async (
boxId: string,
sensorId: string | undefined,
count: number | undefined,
): Promise<any | null> => {
const device = await getDeviceWithoutSensors({ id: boxId });
if (!device) return null;

const sensorsWithMeasurements = await getSensorsWithLastMeasurement(
device.id,
sensorId,
count,

Check failure on line 21 in app/lib/measurement-service.server.ts

View workflow job for this annotation

GitHub Actions / ʦ TypeScript

Expected 1-2 arguments, but got 3.
);
if (sensorId !== undefined) return sensorsWithMeasurements; // single sensor, no need for having info about device

(device as any).sensors = sensorsWithMeasurements;
return device;
};
12 changes: 7 additions & 5 deletions app/lib/openapi.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import swaggerJsdoc from "swagger-jsdoc";

const DEV_SERVER = {
url: "http://localhost:3000",
description: "Development server",
};

const options: swaggerJsdoc.Options = {
definition: {
openapi: "3.0.0",
info: {
title: "",
title: "openSenseMap API",
version: "1.0.0",
description: `## Documentation of the routes and methods to manage users, stations (also called boxes or senseBoxes), and measurements in the openSenseMap API. You can find the API running at [https://opensensemap.org/api/](https://opensensemap.org/api/).
# Timestamps
Expand Down Expand Up @@ -46,14 +51,11 @@ const options: swaggerJsdoc.Options = {
## If there is something unclear or there is a mistake in this documentation please open an [issue](https://github.com/openSenseMap/frontend/issues/new) in the GitHub repository.`,
},
servers: [
...(process.env.NODE_ENV !== "production" ? [DEV_SERVER] : []),
{
url: process.env.OSEM_API_URL || "https://opensensemap.org/api", // Uses environment variable or defaults to production URL
description: "Production server",
},
{
url: "http://localhost:3000",
description: "Development server",
},
],
components: {
schemas: {
Expand Down
129 changes: 129 additions & 0 deletions app/lib/transfer-service.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { createTransfer, getTransfer, removeTransfer, TransferCode } from "~/models/transfer.server";

Check warning on line 1 in app/lib/transfer-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

Imports "TransferCode" are only used as type
import { getDevice } from "~/models/device.server";

Check warning on line 2 in app/lib/transfer-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

`~/models/device.server` import should occur before import of `~/models/transfer.server`
import { claim, Claim, device } from "~/schema";

Check failure on line 3 in app/lib/transfer-service.server.ts

View workflow job for this annotation

GitHub Actions / ʦ TypeScript

Module '"~/schema"' has no exported member 'Claim'.

Check failure on line 3 in app/lib/transfer-service.server.ts

View workflow job for this annotation

GitHub Actions / ʦ TypeScript

Module '"~/schema"' has no exported member 'claim'.

Check warning on line 3 in app/lib/transfer-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

Imports "Claim" are only used as type
import { drizzleClient } from "~/db.server";

Check warning on line 4 in app/lib/transfer-service.server.ts

View workflow job for this annotation

GitHub Actions / ⬣ Lint

`~/db.server` import should occur before import of `~/models/transfer.server`
import { eq } from "drizzle-orm";


export const createBoxTransfer = async (
userId: string,
boxId: string,
expiresAt?: string
): Promise<TransferCode> => {
const box = await getDevice({id: boxId});
if (!box) {
throw new Error("Box not found");
}

if (box.user.id !== userId) {
throw new Error("You don't have permission to transfer this box");
}

let expirationDate: Date;
if (expiresAt) {
expirationDate = new Date(expiresAt);
if (isNaN(expirationDate.getTime())) {
throw new Error("Invalid expiration date format");
}
} else {
expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() + 24);
}

if (expirationDate <= new Date()) {
throw new Error("Expiration date must be in the future");
}

const transferCode = await createTransfer(boxId, userId, expirationDate);

return transferCode;
};

export const getBoxTransfer = async (
boxId: string,
): Promise<Claim> => {
const transfer = await getTransfer({id: boxId});
if (!transfer) {
throw new Error("Transfer not found");
}

// if (transfer.user.id !== userId) {
// throw new Error("You don't have permission to transfer this box");
// }
return transfer;
};

export const removeBoxTransfer = async (
userId: string,
boxId: string,
token: string
): Promise<void> => {
const box = await getDevice({id: boxId});
if (!box) {
throw new Error("Box not found");
}

if (box.user.id !== userId) {
throw new Error("You don't have permission to remove this transfer");
}

await removeTransfer(boxId, token);
};

export const claimBoxTransfer = async (userId: string, token: string) => {
const [activeClaim] = await drizzleClient
.select()
.from(claim)
.where(eq(claim.token, token))
.limit(1);

if (!activeClaim) {
throw new Error("Invalid or expired transfer token");
}

if (activeClaim.expiresAt && activeClaim.expiresAt <= new Date()) {
throw new Error("Transfer token has expired");
}

const [box] = await drizzleClient
.select()
.from(device)
.where(eq(device.id, activeClaim.boxId))
.limit(1);

if (!box) {
throw new Error("Device not found");
}

await drizzleClient
.update(device)
.set({ userId })
.where(eq(device.id, activeClaim.boxId));

await drizzleClient
.delete(claim)
.where(eq(claim.id, activeClaim.id));

return { message: "Device successfully claimed!", boxId: activeClaim.boxId };
};

export const validateTransferParams = (
boxId?: string,
expiresAt?: string
): { isValid: boolean; error?: string } => {
if (!boxId || boxId.trim() === "") {
return { isValid: false, error: "Box ID is required" };
}

if (expiresAt) {
const date = new Date(expiresAt);
if (isNaN(date.getTime())) {
return { isValid: false, error: "Invalid date format" };
}
if (date <= new Date()) {
return { isValid: false, error: "Expiration date must be in the future" };
}
}

return { isValid: true };
};
Loading
Loading