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

osmApi: switch to TEST API via .env #875

Merged
merged 1 commit into from
Jan 7, 2025
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
9 changes: 7 additions & 2 deletions .env
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# This file contains API KEYs for osmapp.org and local development
# If you want to deploy this project publicly, please obtain your own api keys.
# You may add override values to .env.local file (ignored by git)
# - If you want to deploy this project publicly, please obtain your own api keys.
# - You may add override values to `.env.local` file (ignored by git)
# - Keys prefixed with NEXT_PUBLIC_* are exposed to the client side

# https://www.openstreetmap.org/oauth2/applications
NEXT_PUBLIC_OSM_CLIENT_ID=vWUdEL3QMBCB2O9q8Vsrl3i2--tcM34rKrxSHR9Vg68
NEXT_PUBLIC_ENABLE_TEST_API=

# https://indoorequal.com/dashboard/apikeys
# optional, fill blank to disable
Expand Down
3 changes: 2 additions & 1 deletion pages/api/user.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { serverFetchOsmUser } from '../../src/server/osmApiAuthServer';
import { OSM_TOKEN_COOKIE } from '../../src/services/osmApiConsts';

export default async (req: NextApiRequest, res: NextApiResponse) => {
try {
const user = await serverFetchOsmUser(req.cookies.osmAccessToken);
const user = await serverFetchOsmUser(req.cookies[OSM_TOKEN_COOKIE]);

res.status(200).json({ user });
} catch (err) {
Expand Down
3 changes: 2 additions & 1 deletion src/components/utils/OsmAuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
OsmUser,
} from '../../services/osmApiAuth';
import { useSnackbar } from './SnackbarContext';
import { OSM_USER_COOKIE } from '../../services/osmApiConsts';

type OsmAuthType = {
loggedIn: boolean;
Expand All @@ -16,7 +17,7 @@ type OsmAuthType = {
};

const useOsmUserState = (cookies) => {
const initialState = cookies.osmUserForSSR;
const initialState = cookies[OSM_USER_COOKIE];
return useState<OsmUser | undefined>(initialState);
};

Expand Down
19 changes: 8 additions & 11 deletions src/services/osmApi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { resolveCountryCode } from 'next-codegrid';
import { FetchError, getShortId, getUrlOsmId, prod } from './helpers';
import { FetchError, getShortId, getUrlOsmId } from './helpers';
import { fetchJson } from './fetch';
import {
Feature,
Expand All @@ -26,15 +26,16 @@ import {
publishDbgObject,
} from '../utils';
import { getOverpassUrl } from './overpassSearch';
import { API_SERVER, OSM_WEBSITE } from './osmApiConsts';

const getOsmUrl = ({ type, id }: OsmId) =>
`https://api.openstreetmap.org/api/0.6/${type}/${id}.json`;
`${API_SERVER}/api/0.6/${type}/${id}.json`;
const getOsmFullUrl = ({ type, id }: OsmId) =>
`https://api.openstreetmap.org/api/0.6/${type}/${id}/full.json`;
`${API_SERVER}/api/0.6/${type}/${id}/full.json`;
const getOsmParentUrl = ({ type, id }: OsmId) =>
`https://api.openstreetmap.org/api/0.6/${type}/${id}/relations.json`;
`${API_SERVER}/api/0.6/${type}/${id}/relations.json`;
const getOsmHistoryUrl = ({ type, id }: OsmId) =>
`https://api.openstreetmap.org/api/0.6/${type}/${id}/history.json`;
`${API_SERVER}/api/0.6/${type}/${id}/history.json`;
const getOsmUrlOrFull = ({ type, id }: OsmId) =>
type === 'node' ? getOsmUrl({ type, id }) : getOsmFullUrl({ type, id });

Expand Down Expand Up @@ -395,12 +396,8 @@ export const insertOsmNote = async (
body.append('lon', `${lon}`);
body.append('text', text);

const osmUrl = prod
? 'https://api.openstreetmap.org'
: 'https://master.apis.dev.openstreetmap.org';

// {"type":"Feature","geometry":{"type":"Point","coordinates":[14.3244982,50.0927863]},"properties":{"id":26569,"url":"https://master.apis.dev.openstreetmap.org/api/0.6/notes/26569.json","comment_url":"https://master.apis.dev.openstreetmap.org/api/0.6/notes/26569/comment.json","close_url":"https://master.apis.dev.openstreetmap.org/api/0.6/notes/26569/close.json","date_created":"2021-04-17 10:37:44 UTC","status":"open","comments":[{"date":"2021-04-17 10:37:44 UTC","action":"opened","text":"way/39695868! Place was marked permanently closed.From https://osmapp.org/way/39695868","html":"\u003cp\u003eway/39695868! Place was marked permanently closed.From \u003ca href=\"https://osmapp.org/way/39695868\" rel=\"nofollow noopener noreferrer\"\u003ehttps://osmapp.org/way/39695868\u003c/a\u003e\u003c/p\u003e"}]}}
const reply = await fetchJson(`${osmUrl}/api/0.6/notes.json`, {
const reply = await fetchJson(`${API_SERVER}/api/0.6/notes.json`, {
nocache: true,
method: 'POST',
body,
Expand All @@ -410,7 +407,7 @@ export const insertOsmNote = async (
return {
type: 'note',
text,
url: `${prod ? 'https://osm.org' : osmUrl}/note/${noteId}`,
url: `${OSM_WEBSITE}/note/${noteId}`,
};
};

Expand Down
51 changes: 22 additions & 29 deletions src/services/osmApiAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
getShortId,
getUrlOsmId,
parseToXml2Js,
prod,
stringifyDomXml,
Xml2JsMultiDoc,
Xml2JsSingleDoc,
Expand All @@ -20,25 +19,26 @@ import { clearFeatureCache } from './osmApi';
import { isBrowser } from '../components/helpers';
import { getLabel } from '../helpers/featureLabel';
import { EditDataItem } from '../components/FeaturePanel/EditDialog/useEditItems';

const PROD_CLIENT_ID = 'vWUdEL3QMBCB2O9q8Vsrl3i2--tcM34rKrxSHR9Vg68';

// testable on http://127.0.0.1:3000
const TEST_CLIENT_ID = 'a_f_aB7ADY_kdwe4YHpmCSBtNtDZ-BitW8m5I6ijDwI';
const TEST_SERVER = 'https://master.apis.dev.openstreetmap.org';
const TEST_OSM_ID: OsmId = { type: 'node', id: 967531 }; // every edit goes here, https://master.apis.dev.openstreetmap.org/node/967531
import {
OSM_WEBSITE,
PROD_CLIENT_ID,
OSM_USER_COOKIE,
TEST_CLIENT_ID,
TEST_SERVER,
USE_PROD_API,
OSM_TOKEN_COOKIE,
} from './osmApiConsts';

// TS file in osm-auth is probably broken (new is required)
// @ts-ignore
const auth = osmAuth({
redirect_uri: isBrowser() && `${window.location.origin}/oauth-token.html`,
scope: 'read_prefs write_api write_notes openid',
auto: true,
client_id: prod ? PROD_CLIENT_ID : TEST_CLIENT_ID,
url: prod ? undefined : TEST_SERVER,
apiUrl: prod ? undefined : TEST_SERVER,
client_id: USE_PROD_API ? PROD_CLIENT_ID : TEST_CLIENT_ID,
url: USE_PROD_API ? undefined : TEST_SERVER,
apiUrl: USE_PROD_API ? undefined : TEST_SERVER,
});
const osmWebsite = prod ? 'https://www.openstreetmap.org' : TEST_SERVER;

const authFetch = async <T>(options: OSMAuthXHROptions): Promise<T> =>
new Promise<T>((resolve, reject) => {
Expand Down Expand Up @@ -74,18 +74,18 @@ export const loginAndfetchOsmUser = async (): Promise<OsmUser> => {
const osmUser = await fetchOsmUser();

const { url } = auth.options();
const osmAccessToken = localStorage.getItem(`${url}oauth2_access_token`);
const accessToken = localStorage.getItem(`${url}oauth2_access_token`);
const osmUserForSSR = JSON.stringify(osmUser);
Cookies.set('osmAccessToken', osmAccessToken, { path: '/', expires: 365 });
Cookies.set('osmUserForSSR', osmUserForSSR, { path: '/', expires: 365 });
Cookies.set(OSM_TOKEN_COOKIE, accessToken, { path: '/', expires: 365 });
Cookies.set(OSM_USER_COOKIE, osmUserForSSR, { path: '/', expires: 365 });

return osmUser;
};

export const osmLogout = async () => {
auth.logout();
Cookies.remove('osmAccessToken', { path: '/' });
Cookies.remove('osmUserForSSR', { path: '/' });
Cookies.remove(OSM_TOKEN_COOKIE, { path: '/' });
Cookies.remove(OSM_USER_COOKIE, { path: '/' });
};

const getChangesetXml = ({ changesetComment, feature }) => {
Expand Down Expand Up @@ -232,10 +232,6 @@ const checkVersionUnchanged = (
apiId: OsmId,
ourVersion: number,
) => {
if (apiId === TEST_OSM_ID) {
return;
}

const freshVersion = parseInt(freshItem[apiId.type].$.version, 10);
if (ourVersion !== freshVersion) {
throw new Error(
Expand All @@ -251,7 +247,7 @@ export const editOsmFeature = async (
newTags: FeatureTags,
toBeDeleted: boolean,
): Promise<SuccessInfo> => {
const apiId = prod ? feature.osmMeta : TEST_OSM_ID;
const apiId = feature.osmMeta;
const freshItem = await getItemOrLastHistoric(apiId);
checkVersionUnchanged(freshItem, apiId, feature.osmMeta.version);

Expand All @@ -275,7 +271,7 @@ export const editOsmFeature = async (
return {
type: 'edit',
text: changesetComment,
url: `${osmWebsite}/changeset/${changesetId}`,
url: `${OSM_WEBSITE}/changeset/${changesetId}`,
redirect: `${getOsmappLink(feature)}`,
};
};
Expand Down Expand Up @@ -311,7 +307,7 @@ export const addOsmFeature = async (
return {
type: 'edit',
text: changesetComment,
url: `${osmWebsite}/changeset/${changesetId}`,
url: `${OSM_WEBSITE}/changeset/${changesetId}`,
redirect: `/${getUrlOsmId(apiId)}`,
};
};
Expand All @@ -329,9 +325,6 @@ const saveChange = async (
const newNodeId = await createItem(content);
return { type: 'node', id: parseInt(newNodeId, 10) };
} else {
if (!prod) {
apiId = TEST_OSM_ID; // TODO refactor
}
const freshItem = await getItem(apiId);
checkVersionUnchanged(freshItem, apiId, version);

Expand Down Expand Up @@ -389,7 +382,7 @@ export const saveChanges = async (
return {
type: 'edit',
text: changesetComment,
url: `${osmWebsite}/changeset/${changesetId}`,
url: `${OSM_WEBSITE}/changeset/${changesetId}`,
redirect: `/${getUrlOsmId(ids[0])}`,
};
};
Expand Down Expand Up @@ -450,7 +443,7 @@ export const editCrag = async (
return {
type: 'edit',
text: changesetComment,
url: `${osmWebsite}/changeset/${changesetId}`,
url: `${OSM_WEBSITE}/changeset/${changesetId}`,
redirect: `${getOsmappLink(crag)}`,
};
};
20 changes: 20 additions & 0 deletions src/services/osmApiConsts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export const USE_PROD_API = !process.env.NEXT_PUBLIC_ENABLE_TEST_API;

export const TEST_SERVER = 'https://master.apis.dev.openstreetmap.org';
export const PROD_SERVER = 'https://api.openstreetmap.org';
export const OSM_WEBSITE = USE_PROD_API
? 'https://www.openstreetmap.org'
: TEST_SERVER;

export const API_SERVER = USE_PROD_API ? PROD_SERVER : TEST_SERVER;

export const PROD_CLIENT_ID = process.env.NEXT_PUBLIC_OSM_CLIENT_ID;
export const TEST_CLIENT_ID = 'a_f_aB7ADY_kdwe4YHpmCSBtNtDZ-BitW8m5I6ijDwI';

export const OSM_USER_COOKIE = USE_PROD_API
? 'osmUserForSSR'
: 'osmUserForSSR_TESTAPI';

export const OSM_TOKEN_COOKIE = USE_PROD_API
? 'osmAccessToken'
: 'osmAccessToken_TESTAPI';
Loading