Skip to content

Commit

Permalink
chore(base): set device & tmp logs
Browse files Browse the repository at this point in the history
  • Loading branch information
antonstjernquist committed Sep 21, 2024
1 parent ed4ee90 commit 51b0b78
Show file tree
Hide file tree
Showing 10 changed files with 3,785 additions and 4,756 deletions.
8,411 changes: 3,702 additions & 4,709 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

36 changes: 13 additions & 23 deletions src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,13 @@ import {
} from '../shared/network';
import PhoneService from './services/PhoneService';

let activeDeviceId = GetPlayerServerId(PlayerId());

const client = new Client({
debug: true,
listeners: {
nui: NUI_CALLBACK_REGISTER_NAME,
server: SERVER_EVENT_LISTENER,
client: CLIENT_EVENT_LISTENER,
},
interceptors: {
request: ({ data, ...payload }) => {
console.log('Request interceptor:', {
...payload,
data: {
...(typeof data === 'object' ? data : {}),
deviceId: activeDeviceId,
},
});

return {
...payload,
data: {
...(typeof data === 'object' ? data : {}),
deviceId: activeDeviceId,
},
};
},
},
});

client.add('/close-phone', async () => {
Expand All @@ -50,8 +29,19 @@ client.add('/calls/set-channel', async (data: { channel: number }) => {
RegisterCommand(
'select-device',
async (_: unknown, args: string[]) => {
const deviceId = parseInt(args[0], 10);
client.post('/select-device', { deviceId });
const [deviceIdentifier] = args;
const res = await client.post('/auth/select-device', { deviceIdentifier });

console.log('select-device', res);
},
false,
);

RegisterCommand(
'debug-auth',
async () => {
const res = await client.post('/auth/debug');
console.log('debug-auth', res);
},
false,
);
Expand Down
3 changes: 2 additions & 1 deletion src/server/middlewares/deviceMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ declare module 'fivem-router' {

export const deviceMiddleware = async (ctx: RouterContext, next: () => Promise<void>) => {
const deviceIdentifier = PlayerRepository.getDevice(ctx.source);
console.log('deviceMiddleware: deviceIdentifier', deviceIdentifier);

try {
if (!deviceIdentifier) {
throw new DeviceIdentifierNotFound();
}

const device = await DeviceRepository.getDeviceByIdentifier(deviceIdentifier);

console.log('deviceMiddleware: device', device);
if (!device) {
throw new DeviceNotFoundError();
}
Expand Down
40 changes: 33 additions & 7 deletions src/server/repositories/AuthRepository.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { set } from 'zod';
import { ResourceConfig, getServerConfig } from '../utils/config';
const _exports = global.exports;

Expand All @@ -11,9 +12,18 @@ const validateFramework = (framework: unknown): framework is Framework => {
return frameworks.includes(framework as Framework);
};

const getConvarFramework = (): string | undefined => {
try {
return GetConvar('npwd:framework', '');
} catch (error) {
console.error('Failed to get framework from GetConvar');
console.error(error);
}
};

const getFramework = () => {
const config = getServerConfig();
const convarFramework = GetConvar('npwd:framework', undefined);
const convarFramework = getConvarFramework();
const framework = convarFramework || config.framework;

if (convarFramework) {
Expand All @@ -36,7 +46,13 @@ class AuthRepository {

constructor() {
this.config = getServerConfig();
this.framework = getFramework();
try {
this.framework = getFramework();
} catch (error) {
console.error('Failed to get framework');
console.error(error);
this.framework = 'standalone';
}

console.log(`Using framework: ${this.framework}`);

Expand All @@ -45,7 +61,7 @@ class AuthRepository {
}
}

private async authorizeStandalone(src: number, deviceIdentifier: string) {
private async authorizeStandalone(src: number, deviceIdentifier: string): Promise<boolean> {
/**
* Development outside FiveM.
*/
Expand Down Expand Up @@ -89,6 +105,10 @@ class AuthRepository {

for (const exportName of frameworkExports) {
if (!configExports[exportName]) {
console.log(
`The resource "${resource}" was found, but it's missing the export "${exportName}"`,
);

throw new Error(
`Missing export "${exportName}" export in the "config.json" for the custom framework.`,
);
Expand All @@ -100,13 +120,18 @@ class AuthRepository {
}

for (const exportName of frameworkExports) {
if (!_exports[resource][exportName]) {
throw new Error(`Missing export "${exportName}" in the resource "${resource}"`);
try {
console.log(`Checking export "${exportName}" in the resource "${resource}"`);
typeof _exports[resource][exportName] === 'function';
} catch (error) {
throw new Error(
`The resource "${resource}" was found, but it's missing the export "${exportName}"`,
);
}
}
}

private async authorizeCustom(src: number, deviceIdentifier: string) {
private async authorizeCustom(src: number, deviceIdentifier: string): Promise<boolean> {
await this.validateFrameworkIntegration();
const { resource } = this.config.frameworkIntegration ?? {};

Expand All @@ -115,10 +140,11 @@ class AuthRepository {
throw new Error('Missing authorization function');
}

console.log('Calling custom authorization function');
return await authorizationFunction(src, deviceIdentifier);
}

public async authorizeDevice(src: number, deviceIdentifier: string) {
public async authorizeDevice(src: number, deviceIdentifier: string): Promise<boolean> {
if (this.framework === 'standalone') {
return await this.authorizeStandalone(src, deviceIdentifier);
}
Expand Down
24 changes: 24 additions & 0 deletions src/server/router/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import DeviceService from '../services/DeviceService';
import PlayerService from '../services/PlayerService';
import SimCardService from '../services/SimCardService';
import { handleError } from '../utils/errors';
import BroadcastService from '../services/BroadcastService';

export const authRouter = new Router({
prefix: '/auth',
Expand All @@ -17,6 +18,11 @@ authRouter.add('/select-device', async (ctx) => {
try {
const { deviceIdentifier } = selectDeviceSchema.parse(ctx.request.body);
await PlayerService.selectDevice(ctx.source, deviceIdentifier);

/** Get device from DB */
const device = await DeviceService.getDeviceByIdentifier(deviceIdentifier);
ctx.emitToNui(ctx.source, 'current-device:set', device);

ctx.status = 200;
ctx.body = {
ok: true,
Expand Down Expand Up @@ -75,3 +81,21 @@ authRouter.add('/source-by-device', async (ctx) => {
handleError(error, ctx);
}
});

authRouter.add('/debug', async (ctx, next) => {
try {
const authorized = await PlayerService.authorizeDevice(ctx.source, 'debug');
console.log('Authorized', authorized);

ctx.status = 200;
ctx.body = {
ok: true,
message: 'Debugging devices',
payload: authorized,
};

return next();
} catch (error) {
handleError(error, ctx);
}
});
4 changes: 4 additions & 0 deletions src/server/services/DeviceService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ class DeviceService {
return this.deviceRepository.getDeviceById(deviceId);
}

public async getDeviceByIdentifier(deviceIdentifier: string): Promise<Device | null> {
return this.deviceRepository.getDeviceByIdentifier(deviceIdentifier);
}

public async createDevice(device: InsertDevice): Promise<Device> {
try {
return await this.deviceRepository.createDevice(device);
Expand Down
2 changes: 1 addition & 1 deletion src/server/services/PlayerService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class PlayerService {

deviceMap: Map<number, string> = new Map();

public async authorizeDevice(src: number, deviceIdentifier: string) {
public async authorizeDevice(src: number, deviceIdentifier: string): Promise<boolean> {
return await AuthRepository.authorizeDevice(src, deviceIdentifier);
}

Expand Down
14 changes: 0 additions & 14 deletions src/ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,20 +57,6 @@ function App() {
const borderRadius = useTransform(y, [-150, -40, 0], [40, 0, 0]);
const currentThemeType = useThemeType();

useEffect(() => {
const handleMessage = (event) => {
console.log('----------');
console.log('message received');
console.log(event);
console.log('----------');
};

window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);

useEffect(() => {
if (currentThemeType === 'dark') {
setTheme(darkTheme);
Expand Down
2 changes: 1 addition & 1 deletion src/ui/src/Providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const queryClient = new QueryClient({
export const Providers = () => {
return (
<QueryClientProvider client={queryClient}>
<NuiProvider debug>
<NuiProvider>
<NotificationsProvider>
<NavigationProvider>
<RouterProvider initialRoutes={routes}>
Expand Down
5 changes: 5 additions & 0 deletions src/ui/src/api/hooks/useCurrentDevice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,10 @@ export const useCurrentDevice = () => {
queryClient.setQueryData(['current-device'], { payload: data });
});

useBroadcastEvent<Device>('current-device:set', (data) => {
console.log('current-device:set', data);
queryClient.setQueryData(['current-device'], { payload: data });
});

return data?.payload || null;
};

0 comments on commit 51b0b78

Please sign in to comment.