This commit is contained in:
Magnus Åhall 2023-06-16 07:11:27 +02:00
parent b8a673fb0a
commit a76c093d44
7 changed files with 192 additions and 36 deletions

View file

@ -3,7 +3,7 @@ import 'preact/devtools'
//import { signal } from 'preact/signals'
import { h, Component, render, createRef } from 'preact'
import htm from 'htm'
import Session from 'session'
import { Session } from 'session'
const html = htm.bind(h)
class App extends Component {
@ -15,10 +15,16 @@ class App extends Component {
this.wsConnect()
this.wsLoop()
this.session = new Session(this)
this.session.initialize()
}//}}}
render() {//{{{
if(this.sessionID === null) {
if(!this.session.initialized) {
return false;
//return html`<div>Validating session</div>`
}
if(!this.session.authenticated()) {
return html`<${Login} />`
}
@ -85,8 +91,9 @@ class App extends Component {
'Content-Type': 'application/json',
}
if(this.sessionID !== null)
headers['X-SESSION-ID'] = this.sessionID
console.log(this.session)
if(this.session.UUID !== '')
headers['X-Session-Id'] = this.session.UUID
fetch(url, {
method: 'POST',
@ -116,22 +123,6 @@ class App extends Component {
break;
}
}//}}}
login(username, password) {//{{{
this.request('/session/create', {})
.then(res=>{
this.setSessionID(res.Session.UUID)
})
.catch(this.responseError)
}//}}}
getSessionID() {
return window.localStorage.getItem("sessionID")
}
setSessionID(uuid) {
console.log('wut')
this.sessionID = uuid
window.localStorage.setItem('sessionID', uuid)
}
}
class Login extends Component {
@ -152,7 +143,7 @@ class Login extends Component {
login() {//{{{
let username = document.getElementById('username').value
let password = document.getElementById('password').value
window._app.current.login(username, password)
window._app.current.session.authenticate(username, password)
}//}}}
}

51
static/js/session.mjs Normal file
View file

@ -0,0 +1,51 @@
export class Session {
constructor(app) {
this.app = app
this.UUID = ''
this.initialized = false
this.UserID = 0
}
initialize() {//{{{
// Retrieving the stored session UUID, if any.
// If one found, validate with server.
let uuid = window.localStorage.getItem("session.UUID")
if(uuid === null) {
this.create()
} else {
this.UUID = uuid
this.app.request('/session/retrieve', {})
.then(res=>{
this.UserID = res.Session.UserID
this.initialized = true
this.app.forceUpdate()
})
.catch(this.app.responseError)
}
}//}}}
create() {//{{{
this.app.request('/session/create', {})
.then(res=>{
this.UUID = res.Session.UUID
window.localStorage.setItem('session.UUID', this.UUID)
this.app.forceUpdate()
})
.catch(this.responseError)
}//}}}
authenticate(username, password) {//{{{
this.app.request('/session/authenticate', {
username,
password,
})
.then(res=>{
this.UserID = res.Session.UserID
this.app.forceUpdate()
})
.catch(this.app.responseError)
}//}}}
authenticated() {//{{{
return this.UserID != 0
}//}}}
}
// vim: foldmethod=marker