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
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/gorilla/websocket v1.5.0
github.com/jmoiron/sqlx v1.3.5

View File

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

View File

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