Skip to content

Commit

Permalink
Merge pull request #28 from jordan-dalby/remove-base-path
Browse files Browse the repository at this point in the history
Removed BASE_DIR
  • Loading branch information
jordan-dalby authored Nov 4, 2024
2 parents 8de9b17 + 42274f9 commit e248567
Show file tree
Hide file tree
Showing 4 changed files with 149 additions and 204 deletions.
127 changes: 58 additions & 69 deletions client/src/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,108 +1,97 @@
interface AuthConfig {
authRequired: boolean;
}

interface LoginResponse {
token: string;
}

declare global {
interface Window {
BASE_PATH?: string;
}
}

const getBasePath = (): string => {
return window?.BASE_PATH?.endsWith('/') ? window.BASE_PATH.slice(0, -1) : window.BASE_PATH || '';
};

const BASE_PATH = getBasePath();
export const AUTH_API_URL = `${BASE_PATH}/api/auth`;

interface ApiError extends Error {
status?: number;
}

export const AUTH_ERROR_EVENT = 'bytestash:auth_error';
export const authErrorEvent = new CustomEvent(AUTH_ERROR_EVENT);

const handleResponse = async (response: Response) => {
if (response.status === 401 || response.status === 403) {
authRequired: boolean;
}

interface LoginResponse {
token: string;
}

export const AUTH_API_URL = '/api/auth';

interface ApiError extends Error {
status?: number;
}

export const AUTH_ERROR_EVENT = 'bytestash:auth_error';
export const authErrorEvent = new CustomEvent(AUTH_ERROR_EVENT);

const handleResponse = async (response: Response) => {
if (response.status === 401 || response.status === 403) {
window.dispatchEvent(authErrorEvent);

const error = new Error('Authentication required') as ApiError;
error.status = response.status;
throw error;
}
if (!response.ok) {
}

if (!response.ok) {
const text = await response.text();
console.error('Error response body:', text);
const error = new Error(`Request failed: ${response.status} ${response.statusText}`) as ApiError;
error.status = response.status;
throw error;
}

return response;
}

return response;
};

const getHeaders = (includeAuth = false) => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};

const getHeaders = (includeAuth = false) => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};

if (includeAuth) {
if (includeAuth) {
const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
headers['Authorization'] = `Bearer ${token}`;
}
}

return headers;
};
}

export const getAuthConfig = async (): Promise<AuthConfig> => {
try {
return headers;
};

export const getAuthConfig = async (): Promise<AuthConfig> => {
try {
const response = await fetch(`${AUTH_API_URL}/config`);
await handleResponse(response);
return response.json();
} catch (error) {
} catch (error) {
console.error('Error fetching auth config:', error);
throw error;
}
};
export const verifyToken = async (): Promise<boolean> => {
try {
}
};

export const verifyToken = async (): Promise<boolean> => {
try {
const response = await fetch(`${AUTH_API_URL}/verify`, {
headers: getHeaders(true)
headers: getHeaders(true)
});

if (response.status === 401 || response.status === 403) {
return false;
return false;
}

const data = await response.json();
return data.valid;
} catch (error) {
} catch (error) {
console.error('Error verifying token:', error);
return false;
}
};
export const login = async (username: string, password: string): Promise<string> => {
try {
}
};

export const login = async (username: string, password: string): Promise<string> => {
try {
const response = await fetch(`${AUTH_API_URL}/login`, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify({ username, password })
method: 'POST',
headers: getHeaders(),
body: JSON.stringify({ username, password })
});

await handleResponse(response);
const data: LoginResponse = await response.json();
return data.token;
} catch (error) {
} catch (error) {
console.error('Error logging in:', error);
throw error;
}
};
}
};
177 changes: 83 additions & 94 deletions client/src/api/snippets.ts
Original file line number Diff line number Diff line change
@@ -1,124 +1,113 @@
import { Snippet } from '../types/types';

declare global {
interface Window {
BASE_PATH?: string;
}
}

const getBasePath = (): string => {
return window?.BASE_PATH?.endsWith('/') ? window.BASE_PATH.slice(0, -1) : window.BASE_PATH || '';
};

const BASE_PATH = getBasePath();
export const API_URL = `${BASE_PATH}/api/snippets`;
export const API_URL = '/api/snippets';

interface ApiError extends Error {
status?: number;
status?: number;
}

export const AUTH_ERROR_EVENT = 'bytestash:auth_error';
export const authErrorEvent = new CustomEvent(AUTH_ERROR_EVENT);

const handleResponse = async (response: Response) => {
if (response.status === 401 || response.status === 403) {
window.dispatchEvent(authErrorEvent);

const error = new Error('Authentication required') as ApiError;
error.status = response.status;
throw error;
}
if (response.status === 401 || response.status === 403) {
window.dispatchEvent(authErrorEvent);
const error = new Error('Authentication required') as ApiError;
error.status = response.status;
throw error;
}

if (!response.ok) {
const text = await response.text();
console.error('Error response body:', text);
const error = new Error(`Request failed: ${response.status} ${response.statusText}`) as ApiError;
error.status = response.status;
throw error;
}
if (!response.ok) {
const text = await response.text();
console.error('Error response body:', text);
const error = new Error(`Request failed: ${response.status} ${response.statusText}`) as ApiError;
error.status = response.status;
throw error;
}

return response;
return response;
};

const getHeaders = () => {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};

const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}

return headers;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
return headers;
};

export const fetchSnippets = async (): Promise<Snippet[]> => {
try {
const response = await fetch(API_URL, {
headers: getHeaders()
});

await handleResponse(response);
const text = await response.text();

try {
return JSON.parse(text);
} catch (e) {
console.error('Failed to parse JSON:', e);
console.error('Full response:', text);
throw e;
const response = await fetch(API_URL, {
headers: getHeaders()
});

await handleResponse(response);
const text = await response.text();

try {
return JSON.parse(text);
} catch (e) {
console.error('Failed to parse JSON:', e);
console.error('Full response:', text);
throw e;
}
} catch (error) {
console.error('Error fetching snippets:', error);
throw error;
}
} catch (error) {
console.error('Error fetching snippets:', error);
throw error;
}
};

export const createSnippet = async (snippet: Omit<Snippet, 'id' | 'updated_at'>): Promise<Snippet> => {
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(snippet),
});

await handleResponse(response);
return response.json();
} catch (error) {
console.error('Error creating snippet:', error);
throw error;
}
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(snippet),
});

await handleResponse(response);
return response.json();
} catch (error) {
console.error('Error creating snippet:', error);
throw error;
}
};

export const deleteSnippet = async (id: string): Promise<string> => {
try {
const response = await fetch(`${API_URL}/${id}`, {
method: 'DELETE',
headers: getHeaders(),
});

await handleResponse(response);
await response.json();
return id;
} catch (error) {
console.error('Error deleting snippet:', error);
throw error;
}
try {
const response = await fetch(`${API_URL}/${id}`, {
method: 'DELETE',
headers: getHeaders(),
});

await handleResponse(response);
await response.json();
return id;
} catch (error) {
console.error('Error deleting snippet:', error);
throw error;
}
};

export const editSnippet = async (id: string, snippet: Omit<Snippet, 'id' | 'updated_at'>): Promise<Snippet> => {
try {
const response = await fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: getHeaders(),
body: JSON.stringify(snippet),
});

await handleResponse(response);
return response.json();
} catch (error) {
console.error('Error updating snippet:', error);
throw error;
}
try {
const response = await fetch(`${API_URL}/${id}`, {
method: 'PUT',
headers: getHeaders(),
body: JSON.stringify(snippet),
});

await handleResponse(response);
return response.json();
} catch (error) {
console.error('Error updating snippet:', error);
throw error;
}
};
3 changes: 1 addition & 2 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ services:
context: .
dockerfile: Dockerfile
ports:
- "5000:5000"
- "5001:5000"
environment:
- BASE_PATH=
# if auth username or password are left blank then authorisation is disabled
# the username used for logging in
- AUTH_USERNAME=bytestash
Expand Down
Loading

0 comments on commit e248567

Please sign in to comment.