|
1 | 1 | import PocketBase, { BaseAuthStore, ClientResponseError } from 'pocketbase';
|
2 | 2 | import { writable } from 'svelte/store';
|
3 | 3 |
|
4 |
| -import { error, fail } from '@sveltejs/kit'; |
| 4 | +import { error, fail, json } from '@sveltejs/kit'; |
5 | 5 |
|
6 | 6 | import config from './config';
|
7 | 7 |
|
| 8 | +import type { RecordModel } from 'pocketbase'; |
8 | 9 | import type { User } from './types/User.type';
|
9 | 10 | import type { UserSettings } from './types/UserSettings.type';
|
10 | 11 | export const pb = new PocketBase(config.POCKETBASE_URL);
|
@@ -110,3 +111,71 @@ export async function handlePBError(e: any, pb: PocketBase, form?: boolean) {
|
110 | 111 | throw error(e.status, e.message);
|
111 | 112 | }
|
112 | 113 | }
|
| 114 | + |
| 115 | +export type authenticateUserApiRequestResponse = { |
| 116 | + owner: string; |
| 117 | + disabled: boolean | null; |
| 118 | + userRecord: RecordModel | null; |
| 119 | + error: Response | null; |
| 120 | +}; |
| 121 | + |
| 122 | +export async function authenticateUserApiRequest( |
| 123 | + pb: PocketBase, |
| 124 | + request: Request |
| 125 | +): Promise<authenticateUserApiRequestResponse> { |
| 126 | + const authKey = request.headers.get('Authorization') ?? ''; |
| 127 | + |
| 128 | + const response: authenticateUserApiRequestResponse = { |
| 129 | + owner: '', |
| 130 | + disabled: null, |
| 131 | + userRecord: null, |
| 132 | + error: null |
| 133 | + }; |
| 134 | + |
| 135 | + try { |
| 136 | + const [login, password] = atob(authKey.split(' ')[1]).split(':'); |
| 137 | + |
| 138 | + const user = await pb |
| 139 | + .collection('users') |
| 140 | + .authWithPassword(login, password) |
| 141 | + .then((user) => user.record); |
| 142 | + |
| 143 | + response.owner = user.id; |
| 144 | + response.disabled = !!user.disabled; |
| 145 | + response.userRecord = user; |
| 146 | + } catch (error: any) { |
| 147 | + response.error = json( |
| 148 | + { |
| 149 | + success: false, |
| 150 | + error: `Problem with authorization token: ${error?.message}` |
| 151 | + }, |
| 152 | + { |
| 153 | + status: 401 |
| 154 | + } |
| 155 | + ); |
| 156 | + } |
| 157 | + |
| 158 | + if (!response.owner) { |
| 159 | + response.error = json( |
| 160 | + { |
| 161 | + success: false, |
| 162 | + error: 'Unauthorized' |
| 163 | + }, |
| 164 | + { |
| 165 | + status: 401 |
| 166 | + } |
| 167 | + ); |
| 168 | + } else if (response.disabled) { |
| 169 | + response.error = json( |
| 170 | + { |
| 171 | + success: false, |
| 172 | + error: 'User disabled' |
| 173 | + }, |
| 174 | + { |
| 175 | + status: 401 |
| 176 | + } |
| 177 | + ); |
| 178 | + } |
| 179 | + |
| 180 | + return response; |
| 181 | +} |
0 commit comments