Fixed appauth deletion

This commit is contained in:
frikky
2020-07-17 05:13:37 +02:00
parent ada6dd9e8d
commit 7578f1abae
2 changed files with 187 additions and 41 deletions
+111 -9
View File
@@ -78,12 +78,14 @@ type Org struct {
}
type AppAuthenticationStorage struct {
Active bool `json:"active" datastore:"active"`
Label string `json:"label" datastore:"label"`
Id string `json:"id" datastore:"id"`
App WorkflowApp `json:"app" datastore:"app"`
Fields []AuthenticationStore `json:"fields" datastore:"fields"`
Usage []AuthenticationUsage `json:"usage" datastore:"usage"`
Active bool `json:"active" datastore:"active"`
Label string `json:"label" datastore:"label"`
Id string `json:"id" datastore:"id"`
App WorkflowApp `json:"app" datastore:"app"`
Fields []AuthenticationStore `json:"fields" datastore:"fields"`
Usage []AuthenticationUsage `json:"usage" datastore:"usage"`
WorkflowCount int64 `json:"workflow_count" datastore:"workflow_count"`
NodeCount int64 `json:"node_count" datastore:"node_count"`
}
type AuthenticationUsage struct {
@@ -1398,6 +1400,61 @@ func deleteWorkflow(resp http.ResponseWriter, request *http.Request) {
resp.Write([]byte(`{"success": true}`))
}
// Adds app auth tracking
func updateAppAuth(auth AppAuthenticationStorage, workflowId, nodeId string, add bool) error {
workflowFound := false
workflowIndex := 0
nodeFound := false
for index, workflow := range auth.Usage {
if workflow.WorkflowId == workflowId {
// Check if node exists
workflowFound = true
workflowIndex = index
log.Printf("Found workflow: %#v", workflow)
for _, actionId := range workflow.Nodes {
if actionId == nodeId {
nodeFound = true
break
}
}
break
}
}
// FIXME: Add a way to use !add to remove
updateAuth := false
if !workflowFound && add {
log.Printf("Adding workflow things to auth!")
usageItem := AuthenticationUsage{
WorkflowId: workflowId,
Nodes: []string{nodeId},
}
auth.Usage = append(auth.Usage, usageItem)
auth.WorkflowCount += 1
auth.NodeCount += 1
updateAuth = true
} else if !nodeFound && add {
log.Printf("Adding node things to auth!")
auth.Usage[workflowIndex].Nodes = append(auth.Usage[workflowIndex].Nodes, nodeId)
auth.NodeCount += 1
updateAuth = true
}
if updateAuth {
log.Printf("Updating auth!")
ctx := context.Background()
err := setWorkflowAppAuthDatastore(ctx, auth, auth.Id)
if err != nil {
log.Printf("Failed setting up app auth %s: %s", auth.Id, err)
return err
}
}
return nil
}
// Saves a workflow to an ID
func saveWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
@@ -1496,7 +1553,6 @@ func saveWorkflow(resp http.ResponseWriter, request *http.Request) {
//log.Printf("Action: %#v", action.Authentication)
for _, action := range workflow.Actions {
log.Printf("Auth: %s", action.AuthenticationId)
allNodes = append(allNodes, action.ID)
if action.Environment == "" {
@@ -1640,6 +1696,14 @@ func saveWorkflow(resp http.ResponseWriter, request *http.Request) {
}
}
allAuths, err := getAllWorkflowAppAuth(ctx)
if userErr != nil {
log.Printf("Api authentication failed in get all apps: %s", userErr)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// Check every app action and param to see whether they exist
newActions = []Action{}
for _, action := range workflow.Actions {
@@ -1657,6 +1721,31 @@ func saveWorkflow(resp http.ResponseWriter, request *http.Request) {
}
}
// FIXME: Check auth
if len(action.AuthenticationId) > 0 {
authFound := false
for _, auth := range allAuths {
if auth.Id == action.AuthenticationId {
authFound = true
// Fix stuff here
err := updateAppAuth(auth, workflow.ID, action.ID, true)
if err != nil {
log.Printf("Failed updating the app auth reference: %s (not critical)", err)
}
break
}
}
if !authFound {
log.Printf("App auth %s doesn't exist", action.AuthenticationId)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "App auth %s doesn't exist"}`, action.AuthenticationId)))
return
}
}
if builtin {
newActions = append(newActions, action)
} else {
@@ -3020,16 +3109,29 @@ func deleteAppAuthentication(resp http.ResponseWriter, request *http.Request) {
log.Printf("%#v", location)
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
if len(location) <= 5 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
fileId = location[5]
}
// FIXME: Set affected workflows to have errors
// 1. Get the auth
// 2. Loop the workflows (.Usage) and set them to have errors
// 3. Loop the nodes in workflows and do the same
log.Printf("ID: %s", fileId)
ctx := context.Background()
err := DeleteKey(ctx, "workflowappauth", fileId)
if err != nil {
log.Printf("Failed deleting workflowapp")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed deleting workflow app"}`)))
return
}
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
+76 -32
View File
@@ -38,11 +38,40 @@ const Admin = (props) => {
const [selectedUser, setSelectedUser] = React.useState({})
const [newPassword, setNewPassword] = React.useState("");
const [selectedUserModalOpen, setSelectedUserModalOpen] = React.useState(false)
const [selectedAuthentication, setSelectedAuthentcation] = React.useState({})
const [selectedAuthentication, setSelectedAuthentication] = React.useState({})
const [selectedAuthenticationModalOpen, setSelectedAuthenticationModalOpen] = React.useState(false)
const alert = useAlert()
const deleteAuthentication = (data) => {
alert.info("Deleting auth "+data.label)
// Just use this one?
const url = globalUrl+'/api/v1/apps/authentication/'+data.id
console.log("URL: ", url)
fetch(url, {
method: 'DELETE',
credentials: "include",
headers: {
'Content-Type': 'application/json',
},
})
.then(response =>
response.json().then(responseJson => {
console.log("RESP: ", responseJson)
if (responseJson["success"] === false) {
alert.error("Failed stopping schedule")
} else {
getAppAuthentication()
alert.success("Successfully stopped schedule!")
}
}),
)
.catch(error => {
console.log("Error in userdata: ", error)
});
}
const deleteSchedule = (data) => {
// FIXME - add some check here ROFL
console.log("INPUT: ", data)
@@ -165,6 +194,7 @@ const Admin = (props) => {
const deleteEnvironment = (name) => {
// FIXME - add some check here ROFL
alert.info("Deleting environment "+name)
var newEnv = []
for (var key in environments) {
if (environments[key].Name == name) {
@@ -566,7 +596,9 @@ const Admin = (props) => {
},
}}
>
<DialogTitle><span style={{color: "white"}}>Add user</span></DialogTitle>
<DialogTitle><span style={{color: "white"}}>
{curTab === 0 ? "Add user" : "Add environment"}
</span></DialogTitle>
<DialogContent>
{curTab === 0 ?
<div>
@@ -613,7 +645,7 @@ const Admin = (props) => {
onChange={(event) => changeModalData("Password", event.target.value)}
/>
</div>
: curTab === 1 ?
: curTab === 2 ?
<div>
Environment Name
<TextField
@@ -646,7 +678,7 @@ const Admin = (props) => {
<Button variant="contained" style={{borderRadius: "0px"}} onClick={() => {
if (curTab === 0) {
submitUser(modalUser)
} else if (curTab === 1) {
} else if (curTab === 2) {
submitEnvironment(modalUser)
}
}} color="primary">
@@ -660,6 +692,7 @@ const Admin = (props) => {
<h2>
User management
</h2>
<div/>
<Button
style={{}}
variant="contained"
@@ -807,7 +840,7 @@ const Admin = (props) => {
const authenticationView = curTab === 1 ?
<div>
<h2>
Authentication
App Authentication
</h2>
<Divider style={{marginTop: 20, marginBottom: 20, backgroundColor: inputColor}}/>
<List>
@@ -824,16 +857,20 @@ const Admin = (props) => {
primary="App Name"
style={{minWidth: 150, maxWidth: 150}}
/>
<ListItemText
primary="Workflows"
style={{minWidth: 150, maxWidth: 150, overflow: "hidden"}}
/>
<ListItemText
primary="Action amount"
style={{minWidth: 150, maxWidth: 150, overflow: "hidden"}}
/>
<ListItemText
primary="Fields"
style={{minWidth: 320, maxWidth: 320, overflow: "hidden"}}
/>
<ListItemText
primary="Workflow usage"
style={{minWidth: 320, maxWidth: 320, overflow: "hidden"}}
/>
<ListItemText
primary="Actions (TBD)"
primary="Actions"
/>
</ListItem>
{authentication === undefined ? null : authentication.map(data => {
@@ -851,37 +888,27 @@ const Admin = (props) => {
primary={data.app.name}
style={{minWidth: 150, maxWidth: 150}}
/>
<ListItemText
primary={data.usage.length}
style={{minWidth: 150, maxWidth: 150, overflow: "hidden"}}
/>
<ListItemText
primary={data.node_count}
style={{minWidth: 150, maxWidth: 150, overflow: "hidden"}}
/>
<ListItemText
primary={data.fields.map(data => {
return data.key
}).join(", ")}
style={{minWidth: 320, maxWidth: 320, overflow: "hidden"}}
/>
<ListItemText
primary={data.usage.length}
style={{minWidth: 320, maxWidth: 320, overflow: "hidden"}}
/>
<ListItemText>
<Button
style={{}}
variant="contained"
variant="outlined"
color="primary"
disabled={true}
onClick={() => {
setSelectedAuthentcation(data)
setSelectedAuthenticationModalOpen(true)
}}
>
Edit
</Button>
<Button
style={{}}
variant="contained"
color="primary"
disabled={true}
onClick={() => {
setSelectedAuthentcation(data)
setSelectedAuthenticationModalOpen(true)
deleteAuthentication(data)
}}
>
Delete
@@ -909,15 +936,32 @@ const Admin = (props) => {
</Button>
<Divider style={{marginTop: 20, marginBottom: 20, backgroundColor: inputColor}}/>
<List>
<ListItem>
<ListItemText
primary="Name"
style={{minWidth: 150, maxWidth: 150}}
/>
<ListItemText
primary="Actions"
style={{minWidth: 150, maxWidth: 150}}
/>
</ListItem>
{environments === undefined ? null : environments.map(environment => {
return (
<ListItem>
<Button type="outlined" style={{borderRadius: "0px"}} onClick={() => deleteEnvironment(environment.Name)} color="primary">Delete</Button>
- {environment.Name}
<ListItemText
primary={environment.Name}
style={{minWidth: 150, maxWidth: 150, overflow: "hidden"}}
/>
<ListItemText>
<Button type="outlined" style={{borderRadius: "0px"}} onClick={() => deleteEnvironment(environment.Name)} color="primary">Delete</Button>
</ListItemText>
</ListItem>
)
})}
</List>
</div>
: null