Skip to content

Commit

Permalink
Add the Security model typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
torabian committed Dec 25, 2024
1 parent 1ac9fd5 commit 309dc59
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 50 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
// @ts-nocheck

import {ExecApi, IResponse, RemoteRequestOption, Query} from './http-tools';
import { ExecApi, IResponse, RemoteRequestOption, Query } from "./http-tools";
import React, {
useContext,
useState,
useEffect,
Dispatch,
SetStateAction,
useRef,
} from 'react';
import {Upload} from 'tus-js-client';
import {QueryClient, UseQueryOptions} from 'react-query';
} from "react";
import { Upload } from "tus-js-client";
import { QueryClient, UseQueryOptions } from "react-query";

/**
* Removes the workspace id which is default present everywhere
Expand All @@ -22,7 +22,7 @@ export function noWorkspaceQuery(options: any) {
...options,
headers: {
...options.headers,
['workspace-id']: '',
["workspace-id"]: "",
},
};
}
Expand Down Expand Up @@ -168,25 +168,25 @@ export const RemoteQueryContext = React.createContext<IRemoteQueryContext>({
} as any);

export function useFileUploader() {
const {session, selectedWorkspace, activeUploads, setActiveUploads} =
const { session, selectedWorkspace, activeUploads, setActiveUploads } =
useContext(RemoteQueryContext);
// const [activeUploads, setActiveUploads] = useState<ActiveUpload[]>([]);

const upload = (files: File[]): Promise<string>[] => {
const result = files.map(file => {
const result = files.map((file) => {
return new Promise((resolve: (t: string) => void) => {
const upload = new Upload(file, {
endpoint: 'http://localhost:51230/files/',
endpoint: "http://localhost:51230/files/",
onBeforeRequest(req: any) {
req.setHeader('authorization', session.token);
req.setHeader('workspace-id', selectedWorkspace);
req.setHeader("authorization", session.token);
req.setHeader("workspace-id", selectedWorkspace);
},
headers: {
// authorization: authorization,
},
metadata: {
filename: file.name,
path: '/database/users',
path: "/database/users",
filetype: file.type,
},
onSuccess() {
Expand All @@ -198,8 +198,8 @@ export function useFileUploader() {
const uploadId = upload.url?.match(/([a-z0-9]){10,}/gi)?.toString();
let updated = false;

setActiveUploads(items =>
items?.map(item => {
setActiveUploads((items) =>
items?.map((item) => {
if (item.uploadId === uploadId) {
updated = true;
return {
Expand All @@ -211,13 +211,13 @@ export function useFileUploader() {
}

return item;
}),
})
);

if (!updated && uploadId) {
setActiveUploads(activeUploads => [
setActiveUploads((activeUploads) => [
...activeUploads,
{uploadId, bytesSent, bytesTotal, filename: file.name},
{ uploadId, bytesSent, bytesTotal, filename: file.name },
]);
}
console.log(bytesSent, bytesTotal);
Expand All @@ -231,7 +231,7 @@ export function useFileUploader() {
return result;
};

return {upload, activeUploads};
return { upload, activeUploads };
}

export class ReactNativeStorage {
Expand Down Expand Up @@ -266,38 +266,38 @@ export class WebStorage implements CredentialStorage {
async function saveSession(
identifier: string,
session: ContextSession,
storagex: CredentialStorage,
storagex: CredentialStorage
) {
storagex.setItem('fb_microservice_' + identifier, JSON.stringify(session));
storagex.setItem("fb_microservice_" + identifier, JSON.stringify(session));
}

function saveWorkspace(
identifier: string,
workspaceId: UserRoleWorkspace,
storagex: CredentialStorage,
storagex: CredentialStorage
) {
storagex.setItem(
'fb_selected_workspace_' + identifier,
JSON.stringify(workspaceId),
"fb_selected_workspace_" + identifier,
JSON.stringify(workspaceId)
);
}

async function getSession(identifier: string, storagex: CredentialStorage) {
let data = null;
try {
data = JSON.parse(await storagex.getItem('fb_microservice_' + identifier));
data = JSON.parse(await storagex.getItem("fb_microservice_" + identifier));
} catch (err) {}
return data;
}

async function getWorkspace(
identifier: string,
storagex: CredentialStorage,
storagex: CredentialStorage
): UserRoleWorkspace | undefined {
let data = null;
try {
data = JSON.parse(
await storagex.getItem('fb_selected_workspace_' + identifier),
await storagex.getItem("fb_selected_workspace_" + identifier)
);
} catch (err) {}
return data;
Expand Down Expand Up @@ -334,7 +334,7 @@ export function RemoteQueryProvider({
useState<UserRoleWorkspace>();

const storage = useRef(
credentialStorage ? credentialStorage : new WebStorage(),
credentialStorage ? credentialStorage : new WebStorage()
);

const beginPreCatch = async () => {
Expand Down Expand Up @@ -372,23 +372,23 @@ export function RemoteQueryProvider({
headers: {
authorization: token || session?.token,
},
prefix: remote + (prefix || ''),
prefix: remote + (prefix || ""),
};

if (selectedWorkspaceInternal) {
options.headers['workspace-id'] = selectedWorkspaceInternal.workspaceId;
options.headers['role-id'] = selectedWorkspaceInternal.roleId;
options.headers["workspace-id"] = selectedWorkspaceInternal.workspaceId;
options.headers["role-id"] = selectedWorkspaceInternal.roleId;
} else if (selectedUrw) {
options.headers['workspace-id'] = selectedUrw.workspaceId;
options.headers['role-id'] = selectedUrw.roleId;
options.headers["workspace-id"] = selectedUrw.workspaceId;
options.headers["role-id"] = selectedUrw.roleId;
} else if (session?.userWorkspaces && session.userWorkspaces.length > 0) {
const sess2 = session.userWorkspaces[0];
options.headers['workspace-id'] = sess2.workspaceId;
options.headers['role-id'] = sess2.roleId;
options.headers["workspace-id"] = sess2.workspaceId;
options.headers["role-id"] = sess2.roleId;
}

if (preferredAcceptLanguage) {
options.headers['accept-language'] = preferredAcceptLanguage;
options.headers["accept-language"] = preferredAcceptLanguage;
}

useEffect(() => {
Expand All @@ -402,19 +402,19 @@ export function RemoteQueryProvider({

const signout = () => {
setSession$(null);
storage.current?.removeItem('fb_microservice_' + identifier);
storage.current?.removeItem("fb_microservice_" + identifier);
selectUrw(undefined);
};

const discardActiveUploads = () => {
setActiveUploads([]);
};

const {socketState} = useSocket(
const { socketState } = useSocket(
remote,
options.headers?.authorization,
(options.headers as any)['workspace-id'],
queryClient,
(options.headers as any)["workspace-id"],
queryClient
);

return (
Expand All @@ -435,7 +435,8 @@ export function RemoteQueryProvider({
setExecFn,
discardActiveUploads,
isAuthenticated,
}}>
}}
>
{children}
</RemoteQueryContext.Provider>
);
Expand All @@ -447,24 +448,24 @@ export interface PossibleStoreData<T> {
}

export function useSocket(remote, token, workspaceId, queryClient) {
const [socketState, setSocketState] = useState({state: 'unknown'});
const [socketState, setSocketState] = useState({ state: "unknown" });

useEffect(() => {
if (!remote || process.env.REACT_APP_INACCURATE_MOCK_MODE == 'true') {
if (!remote || process.env.REACT_APP_INACCURATE_MOCK_MODE == "true") {
return;
}
const wsRemote = remote.replace('https', 'wss').replace('http', 'ws');
const wsRemote = remote.replace("https", "wss").replace("http", "ws");
let conn: WebSocket;
try {
conn = new WebSocket(
`${wsRemote}ws?token=${token}&workspaceId=${workspaceId}`,
`${wsRemote}ws?token=${token}&workspaceId=${workspaceId}`
);
conn.onerror = function (evt) {
console.log('Closed', evt);
setSocketState({state: 'error'});
console.log("Closed", evt);
setSocketState({ state: "error" });
};
conn.onclose = function (evt) {
setSocketState({state: 'closed'});
setSocketState({ state: "closed" });
};
conn.onmessage = function (evt: any) {
try {
Expand All @@ -478,7 +479,7 @@ export function useSocket(remote, token, workspaceId, queryClient) {
}
};
conn.onopen = function (evt) {
setSocketState({state: 'connected'});
setSocketState({ state: "connected" });
};
} catch (err) {}

Expand All @@ -489,7 +490,7 @@ export function useSocket(remote, token, workspaceId, queryClient) {
};
}, [token, workspaceId]);

return {socketState};
return { socketState };
}

export function queryBeforeSend(query: any) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import {
BaseDto,
BaseEntity,
} from "../../core/definitions"
import {
SecurityModel,
} from "./SecurityModel"
// In this section we have sub entities related to this object
// Class body
export type AuthContextDtoKeys =
Expand All @@ -15,12 +18,17 @@ export class AuthContextDto extends BaseDto {
public skipWorkspaceId?: boolean | null;
public workspaceId?: string | null;
public token?: string | null;
public security?: SecurityModel | null;
securityId?: string | null;
public capabilities?: unknown[] | null;
public static Fields = {
...BaseEntity.Fields,
skipWorkspaceId: `skipWorkspaceId`,
workspaceId: `workspaceId`,
token: `token`,
securityId: `securityId`,
security$: `security`,
security: SecurityModel.Fields,
capabilities: `capabilities`,
}
public static definition = {
Expand All @@ -47,6 +55,14 @@ public static Fields = {
"computedType": "string",
"gormMap": {}
},
{
"IsVirtualObject": false,
"name": "security",
"type": "one",
"target": "SecurityModel",
"computedType": "SecurityModel",
"gormMap": {}
},
{
"IsVirtualObject": false,
"name": "capabilities",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class SecurityModel {
static Fields = {};
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import {
BaseDto,
BaseEntity,
} from "../../core/definitions"
import {
SecurityModel,
} from "./SecurityModel"
// In this section we have sub entities related to this object
// Class body
export type AuthContextDtoKeys =
Expand All @@ -15,12 +18,17 @@ export class AuthContextDto extends BaseDto {
public skipWorkspaceId?: boolean | null;
public workspaceId?: string | null;
public token?: string | null;
public security?: SecurityModel | null;
securityId?: string | null;
public capabilities?: unknown[] | null;
public static Fields = {
...BaseEntity.Fields,
skipWorkspaceId: `skipWorkspaceId`,
workspaceId: `workspaceId`,
token: `token`,
securityId: `securityId`,
security$: `security`,
security: SecurityModel.Fields,
capabilities: `capabilities`,
}
public static definition = {
Expand All @@ -47,6 +55,14 @@ public static Fields = {
"computedType": "string",
"gormMap": {}
},
{
"IsVirtualObject": false,
"name": "security",
"type": "one",
"target": "SecurityModel",
"computedType": "SecurityModel",
"gormMap": {}
},
{
"IsVirtualObject": false,
"name": "capabilities",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class SecurityModel {
static Fields = {};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export class SecurityModel {
static Fields = {};
}
10 changes: 8 additions & 2 deletions modules/workspaces/remotetools.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package workspaces

import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -75,8 +76,11 @@ func MakeHTTPRequest(

url += v.Encode()
}

req, err := retryablehttp.NewRequest("POST", url, options.Body)
method := "POST"
if options.Method != "" {
method = strings.ToUpper(options.Method)
}
req, err := retryablehttp.NewRequest(method, url, options.Body)

if err != nil {
return nil, nil, GormErrorToIError(err)
Expand All @@ -96,5 +100,7 @@ func MakeHTTPRequest(
return nil, resp, CastToIError(err)
}

fmt.Println("Response:", string(body))

return body, resp, nil
}

0 comments on commit 309dc59

Please sign in to comment.