Fixed problem when session not found

This commit is contained in:
Magnus Åhall 2024-01-06 11:40:58 +01:00
parent 7031c0100e
commit ddb49bad13
3 changed files with 106 additions and 96 deletions

2
go.mod
View File

@ -3,7 +3,7 @@ module notes
go 1.21.0 go 1.21.0
require ( require (
git.gibonuddevalla.se/go/webservice v0.1.1 git.gibonuddevalla.se/go/webservice v0.2.0
github.com/google/uuid v1.5.0 github.com/google/uuid v1.5.0
github.com/gorilla/websocket v1.5.0 github.com/gorilla/websocket v1.5.0
github.com/jmoiron/sqlx v1.3.5 github.com/jmoiron/sqlx v1.3.5

View File

@ -30,11 +30,11 @@ class App extends Component {
render() {//{{{ render() {//{{{
let app_el = document.getElementById('app') let app_el = document.getElementById('app')
if(!this.session.initialized) { if (!this.session.initialized) {
return html`<div>Validating session</div>` return
} }
if(!this.session.authenticated()) { if (!this.session.authenticated()) {
app_el.classList.remove('node') app_el.classList.remove('node')
app_el.classList.add('login') app_el.classList.add('login')
return html`<${Login} ref=${this.login} />` return html`<${Login} ref=${this.login} />`
@ -49,8 +49,8 @@ class App extends Component {
}//}}} }//}}}
wsLoop() {//{{{ wsLoop() {//{{{
setInterval(()=>{ setInterval(() => {
if(this.websocket === null) { if (this.websocket === null) {
console.log("wsLoop connect") console.log("wsLoop connect")
this.wsConnect() this.wsConnect()
} }
@ -58,10 +58,10 @@ class App extends Component {
}//}}} }//}}}
wsConnect() {//{{{ wsConnect() {//{{{
this.websocket = new WebSocket(this.websocket_uri) this.websocket = new WebSocket(this.websocket_uri)
this.websocket.onopen = evt=>this.wsOpen(evt) this.websocket.onopen = evt => this.wsOpen(evt)
this.websocket.onmessage = evt=>this.wsMessage(evt) this.websocket.onmessage = evt => this.wsMessage(evt)
this.websocket.onerror = evt=>this.wsError(evt) this.websocket.onerror = evt => this.wsError(evt)
this.websocket.onclose = evt=>this.wsClose(evt) this.websocket.onclose = evt => this.wsClose(evt)
}//}}} }//}}}
wsOpen() {//{{{ wsOpen() {//{{{
this.setState({ wsConnected: true }) this.setState({ wsConnected: true })
@ -80,40 +80,40 @@ class App extends Component {
let msg = JSON.parse(evt.data) let msg = JSON.parse(evt.data)
// Broadcast message // Broadcast message
if(msg.ID == '') { if (msg.ID == '') {
this.broadcastHandler(msg) this.broadcastHandler(msg)
} else { } else {
this.msgHandler(msg) this.msgHandler(msg)
} }
}//}}} }//}}}
responseError({comm, app, upload}) {//{{{ responseError({ comm, app, upload }) {//{{{
if(comm !== undefined) { if (comm !== undefined) {
comm.text().then(body=>alert(body)) comm.text().then(body => alert(body))
return return
} }
if(app !== undefined && app.hasOwnProperty('Error')) { if (app !== undefined && app.hasOwnProperty('Error')) {
alert(app.Error) alert(app.Error)
return return
} }
if(app !== undefined) { if (app !== undefined) {
alert(JSON.stringify(app)) alert(JSON.stringify(app))
} }
if(upload !== undefined) { if (upload !== undefined) {
alert(upload) alert(upload)
return return
} }
}//}}} }//}}}
async request(url, params) {//{{{ async request(url, params) {//{{{
return new Promise((resolve, reject)=>{ return new Promise((resolve, reject) => {
let headers = { let headers = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
} }
if(this.session.UUID !== '') if (this.session.UUID !== '')
headers['X-Session-ID'] = this.session.UUID headers['X-Session-ID'] = this.session.UUID
fetch(url, { fetch(url, {
@ -121,25 +121,33 @@ class App extends Component {
headers, headers,
body: JSON.stringify(params), body: JSON.stringify(params),
}) })
.then(response=>{ .then(response => {
// A HTTP communication level error occured // A HTTP communication level error occured
if(!response.ok || response.status != 200) if (!response.ok || response.status != 200)
return reject({comm: response}) return reject({ comm: response })
return response.json() return response.json()
}) })
.then(json=>{ .then(json => {
// An application level error occured // An application level error occured
if(!json.OK) { if (!json.OK) {
return reject({app: json}) switch (json.Code) {
} case '001-0001': // Session not found
return resolve(json) this.session.reset()
}) location.href = '/'
.catch(err=>reject({comm: err})) break
default:
return reject({ app: json })
}
}
return resolve(json)
})
.catch(err => reject({ comm: err }))
}) })
}//}}} }//}}}
broadcastHandler(msg) {//{{{ broadcastHandler(msg) {//{{{
switch(msg.Op) { switch (msg.Op) {
case 'css_reload': case 'css_reload':
refreshCSS() refreshCSS()
break; break;
@ -161,9 +169,9 @@ class Login extends Component {
password: '', password: '',
} }
}//}}} }//}}}
render({}, { username, password }) {//{{{ render({ }, { username, password }) {//{{{
let authentication_failed = html``; let authentication_failed = html``;
if(this.authentication_failed.value) if (this.authentication_failed.value)
authentication_failed = html`<div class="auth-failed">Authentication failed</div>`; authentication_failed = html`<div class="auth-failed">Authentication failed</div>`;
return html` return html`
@ -173,9 +181,9 @@ class Login extends Component {
</div> </div>
<div class="fields"> <div class="fields">
<input id="username" type="text" placeholder="Username" value=${username} oninput=${evt=>this.setState({ username: evt.target.value})} onkeydown=${evt=>{ if(evt.code == 'Enter') this.login() }} /> <input id="username" type="text" placeholder="Username" value=${username} oninput=${evt => this.setState({ username: evt.target.value })} onkeydown=${evt => { if (evt.code == 'Enter') this.login() }} />
<input id="password" type="password" placeholder="Password" value=${password} oninput=${evt=>this.setState({ password: evt.target.value})} onkeydown=${evt=>{ if(evt.code == 'Enter') this.login() }} /> <input id="password" type="password" placeholder="Password" value=${password} oninput=${evt => this.setState({ password: evt.target.value })} onkeydown=${evt => { if (evt.code == 'Enter') this.login() }} />
<button onclick=${()=>this.login()}>Login</button> <button onclick=${() => this.login()}>Login</button>
${authentication_failed} ${authentication_failed}
</div> </div>
</div> </div>
@ -204,60 +212,60 @@ class Tree extends Component {
this.retrieve() this.retrieve()
}//}}} }//}}}
render({ app }) {//{{{ render({ app }) {//{{{
let renderedTreeTrunk = this.treeTrunk.map(node=>{ let renderedTreeTrunk = this.treeTrunk.map(node => {
this.treeNodeComponents[node.ID] = createRef() this.treeNodeComponents[node.ID] = createRef()
return html`<${TreeNode} key=${"treenode_"+node.ID} tree=${this} node=${node} ref=${this.treeNodeComponents[node.ID]} selected=${node.ID == app.startNode.ID} />` return html`<${TreeNode} key=${"treenode_" + node.ID} tree=${this} node=${node} ref=${this.treeNodeComponents[node.ID]} selected=${node.ID == app.startNode.ID} />`
}) })
return html`<div id="tree">${renderedTreeTrunk}</div>` return html`<div id="tree">${renderedTreeTrunk}</div>`
}//}}} }//}}}
retrieve(callback = null) {//{{{ retrieve(callback = null) {//{{{
this.props.app.request('/node/tree', { StartNodeID: 0 }) this.props.app.request('/node/tree', { StartNodeID: 0 })
.then(res=>{ .then(res => {
this.treeNodes = {} this.treeNodes = {}
this.treeNodeComponents = {} this.treeNodeComponents = {}
this.treeTrunk = [] this.treeTrunk = []
this.selectedTreeNode = null this.selectedTreeNode = null
// A tree of nodes is built. This requires the list of nodes // A tree of nodes is built. This requires the list of nodes
// returned from the server to be sorted in such a way that // returned from the server to be sorted in such a way that
// a parent node always appears before a child node. // a parent node always appears before a child node.
// The server uses a recursive SQL query delivering this. // The server uses a recursive SQL query delivering this.
res.Nodes.forEach(nodeData=>{ res.Nodes.forEach(nodeData => {
let node = new Node( let node = new Node(
this, this,
nodeData.ID, nodeData.ID,
) )
node.Children = [] node.Children = []
node.Crumbs = [] node.Crumbs = []
node.Files = [] node.Files = []
node.Level = nodeData.Level node.Level = nodeData.Level
node.Name = nodeData.Name node.Name = nodeData.Name
node.ParentID = nodeData.ParentID node.ParentID = nodeData.ParentID
node.Updated = nodeData.Updated node.Updated = nodeData.Updated
node.UserID = nodeData.UserID node.UserID = nodeData.UserID
this.treeNodes[node.ID] = node this.treeNodes[node.ID] = node
if (node.ParentID == 0)
this.treeTrunk.push(node)
else if (this.treeNodes[node.ParentID] !== undefined)
this.treeNodes[node.ParentID].Children.push(node)
})
// When starting with an explicit node value, expanding all nodes
// on its path gives the user a sense of location. Not necessarily working
// as the start node isn't guaranteed to have returned data yet.
this.crumbsUpdateNodes()
this.forceUpdate()
if (callback)
callback()
if(node.ParentID == 0)
this.treeTrunk.push(node)
else if(this.treeNodes[node.ParentID] !== undefined)
this.treeNodes[node.ParentID].Children.push(node)
}) })
// When starting with an explicit node value, expanding all nodes .catch(this.responseError)
// on its path gives the user a sense of location. Not necessarily working
// as the start node isn't guaranteed to have returned data yet.
this.crumbsUpdateNodes()
this.forceUpdate()
if(callback)
callback()
})
.catch(this.responseError)
}//}}} }//}}}
setSelected(node) {//{{{ setSelected(node) {//{{{
if(this.selectedTreeNode) if (this.selectedTreeNode)
this.selectedTreeNode.selected.value = false this.selectedTreeNode.selected.value = false
this.selectedTreeNode = this.treeNodeComponents[node.ID].current this.selectedTreeNode = this.treeNodeComponents[node.ID].current
@ -266,30 +274,30 @@ class Tree extends Component {
this.expandToTrunk(node.ID) this.expandToTrunk(node.ID)
}//}}} }//}}}
crumbsUpdateNodes(node) {//{{{ crumbsUpdateNodes(node) {//{{{
this.props.app.startNode.Crumbs.forEach(crumb=>{ this.props.app.startNode.Crumbs.forEach(crumb => {
// Start node is loaded before the tree. // Start node is loaded before the tree.
let node = this.treeNodes[crumb.ID] let node = this.treeNodes[crumb.ID]
if(node) if (node)
node._expanded = true node._expanded = true
// Tree is done before the start node. // Tree is done before the start node.
let component = this.treeNodeComponents[crumb.ID] let component = this.treeNodeComponents[crumb.ID]
if(component && component.current) if (component && component.current)
component.current.expanded.value = true component.current.expanded.value = true
}) })
// Will be undefined when called from tree initialization // Will be undefined when called from tree initialization
// (as tree nodes aren't rendered yet) // (as tree nodes aren't rendered yet)
if(node !== undefined) if (node !== undefined)
this.setSelected(node) this.setSelected(node)
}//}}} }//}}}
expandToTrunk(nodeID) {//{{{ expandToTrunk(nodeID) {//{{{
let node = this.treeNodes[nodeID] let node = this.treeNodes[nodeID]
if(node === undefined) if (node === undefined)
return return
node = this.treeNodes[node.ParentID] node = this.treeNodes[node.ParentID]
while(node !== undefined) { while (node !== undefined) {
this.treeNodeComponents[node.ID].current.expanded.value = true this.treeNodeComponents[node.ID].current.expanded.value = true
node = this.treeNodes[node.ParentID] node = this.treeNodes[node.ParentID]
} }
@ -304,16 +312,16 @@ class TreeNode extends Component {
}//}}} }//}}}
render({ tree, node }) {//{{{ render({ tree, node }) {//{{{
let children = node.Children.map(node=>{ let children = node.Children.map(node => {
tree.treeNodeComponents[node.ID] = createRef() tree.treeNodeComponents[node.ID] = createRef()
return html`<${TreeNode} key=${"treenode_"+node.ID} tree=${tree} node=${node} ref=${tree.treeNodeComponents[node.ID]} selected=${node.ID == tree.props.app.startNode.ID} />` return html`<${TreeNode} key=${"treenode_" + node.ID} tree=${tree} node=${node} ref=${tree.treeNodeComponents[node.ID]} selected=${node.ID == tree.props.app.startNode.ID} />`
}) })
let expandImg = '' let expandImg = ''
if(node.Children.length == 0) if (node.Children.length == 0)
expandImg = html`<img src="/images/${window._VERSION}/leaf.svg" />` expandImg = html`<img src="/images/${window._VERSION}/leaf.svg" />`
else { else {
if(this.expanded.value) if (this.expanded.value)
expandImg = html`<img src="/images/${window._VERSION}/expanded.svg" />` expandImg = html`<img src="/images/${window._VERSION}/expanded.svg" />`
else else
expandImg = html`<img src="/images/${window._VERSION}/collapsed.svg" />` expandImg = html`<img src="/images/${window._VERSION}/collapsed.svg" />`
@ -324,8 +332,8 @@ class TreeNode extends Component {
return html` return html`
<div class="node"> <div class="node">
<div class="expand-toggle" onclick=${()=>this.expanded.value ^= true}>${expandImg}</div> <div class="expand-toggle" onclick=${() => this.expanded.value ^= true}>${expandImg}</div>
<div class="name ${selected}" onclick=${()=>window._app.current.nodeUI.current.goToNode(node.ID)}>${node.Name}</div> <div class="name ${selected}" onclick=${() => window._app.current.nodeUI.current.goToNode(node.ID)}>${node.Name}</div>
<div class="children ${node.Children.length > 0 && this.expanded.value ? 'expanded' : 'collapsed'}">${children}</div> <div class="children ${node.Children.length > 0 && this.expanded.value ? 'expanded' : 'collapsed'}">${children}</div>
</div>` </div>`
}//}}} }//}}}

View File

@ -32,9 +32,6 @@ export class Session {
this.UserID = res.Session.UserID // could be 0 this.UserID = res.Session.UserID // could be 0
this.initialized = true this.initialized = true
this.app.forceUpdate() this.app.forceUpdate()
} else {
// Session has probably expired. A new is required.
this.create()
} }
}) })
.catch(this.app.responseError) .catch(this.app.responseError)
@ -43,12 +40,17 @@ export class Session {
this.app.request('/_session/new', {}) this.app.request('/_session/new', {})
.then(res => { .then(res => {
this.UUID = res.Session.UUID this.UUID = res.Session.UUID
window.localStorage.setItem('session.UUID', this.Session.UUID) window.localStorage.setItem('session.UUID', this.UUID)
this.initialized = true this.initialized = true
this.app.forceUpdate() this.app.forceUpdate()
}) })
.catch(this.responseError) .catch(this.responseError)
}//}}} }//}}}
reset() {//{{{
window.localStorage.removeItem('session.UUID')
this.initialized = false
this.UserID = 0
}//}}}
authenticate(username, password) {//{{{ authenticate(username, password) {//{{{
this.app.login.current.authentication_failed.value = false this.app.login.current.authentication_failed.value = false