-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathlogin.ts
More file actions
1093 lines (1018 loc) · 34.6 KB
/
login.ts
File metadata and controls
1093 lines (1018 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable camelcase */
/**
* Signing in, signing up, profile and preferences reloading
* Type index management
*
* Many functions in this module take a context object which
* holds various RDF symbols, add to it, and return a promise of it.
*
* * `me` RDF symbol for the user's WebID
* * `publicProfile` The user's public profile, iff loaded
* * `preferencesFile` The user's personal preference file, iff loaded
* * `index.public` The user's public type index file
* * `index.private` The user's private type index file
*
* Not RDF symbols:
* * `noun` A string in english for the type of thing -- like "address book"
* * `instance` An array of nodes which are existing instances
* * `containers` An array of nodes of containers of instances
* * `div` A DOM element where UI can be displayed
* * `statusArea` A DOM element (opt) progress stuff can be displayed, or error messages
* *
* * Vocabulary: "load" loads a file if it exists;
* * 'Ensure" CREATES the file if it does not exist (if it can) and then loads it.
* @packageDocumentation
*/
import { PaneDefinition } from 'pane-registry'
import { BlankNode, NamedNode, st } from 'rdflib'
import { Quad_Object } from 'rdflib/lib/tf-types'
import {
AppDetails,
AuthenticationContext,
authn,
authSession,
CrossOriginForbiddenError,
FetchError,
getSuggestedIssuers,
NotEditableError,
offlineTestID,
SameOriginForbiddenError,
solidLogicSingleton,
UnauthorizedError,
WebOperationError
} from 'solid-logic'
import * as debug from '../debug'
import { style } from '../style'
import { alert } from '../log'
import ns from '../ns'
import { Signup } from '../signup/signup.js'
import * as utils from '../utils'
import * as widgets from '../widgets'
const store = solidLogicSingleton.store
const {
loadPreferences,
loadProfile
} = solidLogicSingleton.profile
const {
getScopedAppInstances,
getRegistrations,
loadAllTypeIndexes,
getScopedAppsFromIndex,
deleteTypeIndexRegistration
} = solidLogicSingleton.typeIndex
/**
* Resolves with the logged in user's WebID
*
* @param context
*/
// used to be logIn
export function ensureLoggedIn (context: AuthenticationContext): Promise<AuthenticationContext> {
const me = authn.currentUser()
if (me) {
authn.saveUser(me, context)
return Promise.resolve(context)
}
return new Promise((resolve) => {
authn.checkUser().then((webId) => {
// Already logged in?
if (webId) {
debug.log(`logIn: Already logged in as ${webId}`)
return resolve(context)
}
if (!context.div || !context.dom) {
return resolve(context)
}
const box = loginStatusBox(context.dom, (webIdUri) => {
authn.saveUser(webIdUri, context)
resolve(context) // always pass growing context
})
context.div.appendChild(box)
})
})
}
/**
* Loads preference file
* Do this after having done log in and load profile
*
* @private
*
* @param context
*/
// used to be logInLoadPreferences
export async function ensureLoadedPreferences (
context: AuthenticationContext
): Promise<AuthenticationContext> {
if (context.preferencesFile) return Promise.resolve(context) // already done
// const statusArea = context.statusArea || context.div || null
let progressDisplay
/* COMPLAIN FUNCTION NOT USED/TAKING IT OUT FOR NOW
function complain (message) {
message = `ensureLoadedPreferences: ${message}`
if (statusArea) {
// statusArea.innerHTML = ''
statusArea.appendChild(widgets.errorMessageBlock(context.dom, message))
}
debug.log(message)
// reject(new Error(message))
} */
try {
context = await ensureLoadedProfile(context)
// console.log('back in Solid UI after logInLoadProfile', context)
const preferencesFile = await loadPreferences(context.me as NamedNode)
if (progressDisplay) {
progressDisplay.parentNode.removeChild(progressDisplay)
}
context.preferencesFile = preferencesFile
} catch (err) {
let m2: string
if (err instanceof UnauthorizedError) {
m2 =
'Oops — you are not authenticated (properly logged in), so SolidOS cannot read your preferences file. Try logging out and then logging back in.'
alert(m2)
} else if (err instanceof CrossOriginForbiddenError) {
m2 = `Unauthorized: Assuming preference file blocked for origin ${window.location.origin}`
context.preferencesFileError = m2
return context
} else if (err instanceof SameOriginForbiddenError) {
m2 =
'You are not authorized to read your preference file. This may be because you are using an untrusted web app.'
debug.warn(m2)
return context
} else if (err instanceof NotEditableError) {
m2 =
'You are not authorized to edit your preference file. This may be because you are using an untrusted web app.'
debug.warn(m2)
return context
} else if (err instanceof WebOperationError) {
m2 =
'You are not authorized to edit your preference file. This may be because you are using an untrusted web app.'
debug.warn(m2)
} else if (err instanceof FetchError) {
m2 = `Strange: Error ${err.status} trying to read your preference file.${err.message}`
alert(m2)
} else {
throw new Error(`(via loadPrefs) ${err}`)
}
}
return context
}
/**
* Logs the user in and loads their WebID profile document into the store
*
* @param context
*
* @returns Resolves with the context after login / fetch
*/
// used to be logInLoadProfile
export async function ensureLoadedProfile (
context: AuthenticationContext
): Promise<AuthenticationContext> {
if (context.publicProfile) {
return context
} // already done
try {
const logInContext = await ensureLoggedIn(context)
if (!logInContext.me) {
throw new Error('Could not log in')
}
context.publicProfile = await loadProfile(logInContext.me)
} catch (err) {
if (context.div && context.dom) {
context.div.appendChild(widgets.errorMessageBlock(context.dom, err.message))
}
throw new Error(`Can't log in: ${err}`)
}
return context
}
/**
* Returns promise of context with arrays of symbols
*
* leaving the `isPublic` param undefined will bring in community index things, too
*/
export async function findAppInstances (
context: AuthenticationContext,
theClass: NamedNode,
isPublic?: boolean
): Promise<AuthenticationContext> {
let items = context.me ? await getScopedAppInstances(theClass, context.me) : []
if (isPublic === true) { // old API - not recommended!
items = items.filter(item => item.scope.label === 'public')
} else if (isPublic === false) {
items = items.filter(item => item.scope.label === 'private')
}
context.instances = items.map(item => item.instance)
return context
}
export function scopeLabel (context, scope) {
const mine = context.me && context.me.sameTerm(scope.agent)
const name = mine ? '' : utils.label(scope.agent) + ' '
return `${name}${scope.label}`
}
/**
* UI to control registration of instance
*/
export async function registrationControl (
context: AuthenticationContext,
instance,
theClass
): Promise<AuthenticationContext | void> {
function registrationStatements (index) {
const registrations = getRegistrations(instance, theClass)
const reg = registrations.length ? registrations[0] : widgets.newThing(index)
return [
st(reg, ns.solid('instance'), instance, index),
st(reg, ns.solid('forClass'), theClass, index)
]
}
function renderScopeCheckbox (scope) {
const statements = registrationStatements(scope.index)
const name = scopeLabel(context, scope)
const label = `${name} link to this ${context.noun}`
return widgets.buildCheckboxForm(
context.dom,
solidLogicSingleton.store,
label,
null,
statements,
form,
scope.index
)
}
/// / body of registrationControl
const dom = context.dom
if (!dom || !context.div) {
throw new Error('registrationControl: need dom and div')
}
const box = dom.createElement('div')
context.div.appendChild(box)
context.me = authn.currentUser() // @@
const me = context.me
if (!me) {
box.innerHTML = '<p style="margin:2em;">(Log in to save a link to this)</p>'
return context
}
let scopes // @@ const
try {
scopes = await loadAllTypeIndexes(me)
} catch (e) {
let msg
if (context.div && context.preferencesFileError) {
msg = '(Lists of stuff not available)'
context.div.appendChild(dom.createElement('p')).textContent = msg
} else if (context.div) {
msg = `registrationControl: Type indexes not available: ${e}`
context.div.appendChild(widgets.errorMessageBlock(context.dom, e))
}
debug.log(msg)
return context
}
box.innerHTML = '<table><tbody></tbody></table>' // tbody will be inserted anyway
box.setAttribute('style', 'font-size: 120%; text-align: right; padding: 1em; border: solid gray 0.05em;')
const tbody = box.children[0].children[0]
const form = new BlankNode() // @@ say for now
for (const scope of scopes) {
const row = tbody.appendChild(dom.createElement('tr'))
row.appendChild(renderScopeCheckbox(scope)) // @@ index
}
return context
}
export function renderScopeHeadingRow (context, store, scope) {
const backgroundColor = { private: '#fee', public: '#efe' }
const { dom } = context
const name = scopeLabel(context, scope)
const row = dom.createElement('tr')
const cell = row.appendChild(dom.createElement('td'))
cell.setAttribute('colspan', '3')
cell.style.backgoundColor = backgroundColor[scope.label] || 'white'
const header = cell.appendChild(dom.createElement('h3'))
header.textContent = name + ' links'
header.style.textAlign = 'left'
return row
}
/**
* UI to List at all registered things
*/
export async function registrationList (context: AuthenticationContext, options: {
private?: boolean
public?: boolean
type?: NamedNode
}): Promise<AuthenticationContext> {
const dom = context.dom as HTMLDocument
const div = context.div as HTMLElement
const box = dom.createElement('div')
div.appendChild(box)
context.me = authn.currentUser() // @@
if (!context.me) {
box.innerHTML = '<p style="margin:2em;">(Log in list your stuff)</p>'
return context
}
const scopes = await loadAllTypeIndexes(context.me) // includes community indexes
// console.log('@@ registrationList ', scopes)
box.innerHTML = '<table><tbody></tbody></table>' // tbody will be inserted anyway
box.setAttribute('style', 'font-size: 120%; text-align: right; padding: 1em; border: solid #eee 0.5em;')
const table = box.firstChild as HTMLElement
const tbody = table.firstChild as HTMLElement
for (const scope of scopes) { // need some predicate for listing/adding agents
const headingRow = renderScopeHeadingRow(context, store, scope)
tbody.appendChild(headingRow)
const items = await getScopedAppsFromIndex(scope, options.type || null) // any class
if (items.length === 0) headingRow.style.display = 'none'
// console.log(`registrationList: @@ instance items for class ${options.type || 'undefined' }:`, items)
for (const item of items) {
const row = widgets.personTR(dom, ns.solid('instance'), item.instance, {
deleteFunction: async () => {
await deleteTypeIndexRegistration(item)
tbody.removeChild(row)
}
})
row.children[0].style.paddingLeft = '3em'
tbody.appendChild(row)
}
}
return context
} // registrationList
/**
* Bootstrapping identity
* (Called by `loginStatusBox()`)
*
* @param dom
* @param setUserCallback
*
* @returns
*/
function signInOrSignUpBox (
dom: HTMLDocument,
setUserCallback: (user: string) => void,
options: {
buttonStyle?: string;
} = {}
): HTMLElement {
options = options || {}
const signInButtonStyle = options.buttonStyle || style.signInAndUpButtonStyle
const box: any = dom.createElement('div')
const magicClassName = 'SolidSignInOrSignUpBox'
debug.log('widgets.signInOrSignUpBox')
box.setUserCallback = setUserCallback
box.setAttribute('class', magicClassName)
box.setAttribute('style', 'display:flex;')
// Sign in button with PopUP
const signInPopUpButton = dom.createElement('input') // multi
box.appendChild(signInPopUpButton)
signInPopUpButton.setAttribute('type', 'button')
signInPopUpButton.setAttribute('value', 'Log in')
signInPopUpButton.setAttribute('style', `${signInButtonStyle}${style.headerBannerLoginInput}` + style.signUpBackground)
authSession.events.on('login', () => {
const me = authn.currentUser()
// const sessionInfo = authSession.info
// if (sessionInfo && sessionInfo.isLoggedIn) {
if (me) {
// const webIdURI = sessionInfo.webId
const webIdURI = me.uri
// setUserCallback(webIdURI)
const divs = dom.getElementsByClassName(magicClassName)
debug.log(`Logged in, ${divs.length} panels to be serviced`)
// At the same time, satisfy all the other login boxes
for (let i = 0; i < divs.length; i++) {
const div: any = divs[i]
// @@ TODO Remove the need to manipulate HTML elements
if (div.setUserCallback) {
try {
div.setUserCallback(webIdURI)
const parent = div.parentNode
if (parent) {
parent.removeChild(div)
}
} catch (e) {
debug.log(`## Error satisfying login box: ${e}`)
div.appendChild(widgets.errorMessageBlock(dom, e))
}
}
}
}
})
signInPopUpButton.addEventListener(
'click',
() => {
const offline = offlineTestID()
if (offline) return setUserCallback(offline.uri)
renderSignInPopup(dom)
},
false
)
// Sign up button
const signupButton = dom.createElement('input')
box.appendChild(signupButton)
signupButton.setAttribute('type', 'button')
signupButton.setAttribute('value', 'Sign Up for Solid')
signupButton.setAttribute('style', `${signInButtonStyle}${style.headerBannerLoginInput}` + style.signInBackground)
signupButton.addEventListener(
'click',
function (_event) {
const signupMgr = new Signup()
signupMgr.signup().then(function (uri) {
debug.log('signInOrSignUpBox signed up ' + uri)
setUserCallback(uri)
})
},
false
)
return box
}
export function renderSignInPopup (dom: HTMLDocument) {
/**
* Issuer Menu
*/
const issuerPopup = dom.createElement('div')
issuerPopup.setAttribute(
'style',
'position: fixed; top: 0; left: 0; right: 0; bottom: 0; display: flex; justify-content: center; align-items: center;'
)
dom.body.appendChild(issuerPopup)
const issuerPopupBox = dom.createElement('div')
issuerPopupBox.setAttribute(
'style',
`
background-color: white;
box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);
-webkit-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);
-o-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);
border-radius: 4px;
min-width: 400px;
padding: 10px;
z-index : 10;
`
)
issuerPopup.appendChild(issuerPopupBox)
const issuerPopupBoxTopMenu = dom.createElement('div')
issuerPopupBoxTopMenu.setAttribute(
'style',
`
border-bottom: 1px solid #DDD;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
`
)
issuerPopupBox.appendChild(issuerPopupBoxTopMenu)
const issuerPopupBoxLabel = dom.createElement('label')
issuerPopupBoxLabel.setAttribute('style', 'margin-right: 5px; font-weight: 800')
issuerPopupBoxLabel.innerText = 'Select an identity provider'
const issuerPopupBoxCloseButton = dom.createElement('button')
issuerPopupBoxCloseButton.innerHTML =
'<img src="https://solidos.github.io/solid-ui/src/icons/noun_1180156.svg" style="width: 2em; height: 2em;" title="Cancel">'
issuerPopupBoxCloseButton.setAttribute('style', 'background-color: transparent; border: none;')
issuerPopupBoxCloseButton.addEventListener('click', () => {
issuerPopup.remove()
})
issuerPopupBoxTopMenu.appendChild(issuerPopupBoxLabel)
issuerPopupBoxTopMenu.appendChild(issuerPopupBoxCloseButton)
const loginToIssuer = async (issuerUri: string) => {
try {
// clear authorization metadata from store
solidLogicSingleton.store.updater.flagAuthorizationMetadata() as any
// Save hash
const preLoginRedirectHash = new URL(window.location.href).hash
if (preLoginRedirectHash) {
window.localStorage.setItem('preLoginRedirectHash', preLoginRedirectHash)
}
window.localStorage.setItem('loginIssuer', issuerUri)
// Login
const locationUrl = new URL(window.location.href)
locationUrl.hash = '' // remove hash part
await authSession.login({
redirectUrl: locationUrl.href,
oidcIssuer: issuerUri
})
} catch (err) {
alert(err.message)
}
}
/**
* Text-based idp selection
*/
const issuerTextContainer = dom.createElement('div')
issuerTextContainer.setAttribute(
'style',
`
border-bottom: 1px solid #DDD;
display: flex;
flex-direction: column;
padding-top: 10px;
`
)
const issuerTextInputContainer = dom.createElement('div')
issuerTextInputContainer.setAttribute(
'style',
`
display: flex;
flex-direction: row;
`
)
const issuerTextLabel = dom.createElement('label')
issuerTextLabel.innerText = 'Enter the URL of your identity provider:'
issuerTextLabel.setAttribute('style', 'color: #888')
const issuerTextInput = dom.createElement('input')
issuerTextInput.setAttribute('type', 'text')
issuerTextInput.setAttribute(
'style',
'margin-left: 0 !important; flex: 1; margin-right: 5px !important'
)
issuerTextInput.setAttribute('placeholder', 'https://example.com')
issuerTextInput.value = localStorage.getItem('loginIssuer') || ''
const issuerTextGoButton = dom.createElement('button')
issuerTextGoButton.innerText = 'Go'
issuerTextGoButton.setAttribute('style', 'margin-top: 12px; margin-bottom: 12px;')
issuerTextGoButton.addEventListener('click', () => {
loginToIssuer(issuerTextInput.value)
})
issuerTextContainer.appendChild(issuerTextLabel)
issuerTextInputContainer.appendChild(issuerTextInput)
issuerTextInputContainer.appendChild(issuerTextGoButton)
issuerTextContainer.appendChild(issuerTextInputContainer)
issuerPopupBox.appendChild(issuerTextContainer)
/**
* Button-based idp selection
*/
const issuerButtonContainer = dom.createElement('div')
issuerButtonContainer.setAttribute(
'style',
`
display: flex;
flex-direction: column;
padding-top: 10px;
`
)
const issuerBottonLabel = dom.createElement('label')
issuerBottonLabel.innerText = 'Or pick an identity provider from the list below:'
issuerBottonLabel.setAttribute('style', 'color: #888')
issuerButtonContainer.appendChild(issuerBottonLabel)
getSuggestedIssuers().forEach((issuerInfo) => {
const issuerButton = dom.createElement('button')
issuerButton.innerText = issuerInfo.name
issuerButton.setAttribute('style', 'height: 38px; margin-top: 10px')
issuerButton.addEventListener('click', () => {
loginToIssuer(issuerInfo.uri)
})
issuerButtonContainer.appendChild(issuerButton)
})
issuerPopupBox.appendChild(issuerButtonContainer)
}
/**
* Login status box
*
* A big sign-up/sign in box or a logout box depending on the state
*
* @param dom
* @param listener
*
* @returns
*/
export function loginStatusBox (
dom: HTMLDocument,
listener: ((uri: string | null) => void) | null = null,
options: {
buttonStyle?: string;
} = {}
): HTMLElement {
// 20190630
let me = offlineTestID()
// @@ TODO Remove the need to cast HTML element to any
const box: any = dom.createElement('div')
function setIt (newidURI) {
if (!newidURI) {
return
}
// const uri = newidURI.uri || newidURI
// me = sym(uri)
me = authn.saveUser(newidURI)
box.refresh()
if (listener) listener(me!.uri)
}
function logoutButtonHandler (_event) {
const oldMe = me
authSession.logout().then(
function () {
const message = `Your WebID was ${oldMe}. It has been forgotten.`
me = null
try {
alert(message)
} catch (_e) {
window.alert(message)
}
box.refresh()
if (listener) listener(null)
},
(err) => {
alert('Fail to log out:' + err)
}
)
}
function logoutButton (me, options) {
const signInButtonStyle = options.buttonStyle || style.signInAndUpButtonStyle
let logoutLabel = 'WebID logout'
if (me) {
const nick =
solidLogicSingleton.store.any(me, ns.foaf('nick')) ||
solidLogicSingleton.store.any(me, ns.foaf('name'))
if (nick) {
logoutLabel = 'Logout ' + nick.value
}
}
const signOutButton = dom.createElement('input')
// signOutButton.className = 'WebIDCancelButton'
signOutButton.setAttribute('type', 'button')
signOutButton.setAttribute('value', logoutLabel)
signOutButton.setAttribute('style', `${signInButtonStyle}`)
signOutButton.addEventListener('click', logoutButtonHandler, false)
return signOutButton
}
box.refresh = function () {
const sessionInfo = authSession.info
if (sessionInfo && sessionInfo.webId && sessionInfo.isLoggedIn) {
me = solidLogicSingleton.store.sym(sessionInfo.webId)
} else {
me = null
}
if ((me && box.me !== me.uri) || (!me && box.me)) {
widgets.clearElement(box)
if (me) {
box.appendChild(logoutButton(me, options))
} else {
box.appendChild(signInOrSignUpBox(dom, setIt, options))
}
}
box.me = me ? me.uri : null
}
box.refresh()
function trackSession () {
me = authn.currentUser()
box.refresh()
}
trackSession()
authSession.events.on('login', trackSession)
authSession.events.on('logout', trackSession)
box.me = '99999' // Force refresh
box.refresh()
return box
}
authSession.events.on('logout', async () => {
const issuer = window.localStorage.getItem('loginIssuer')
if (issuer) {
try {
// clear authorization metadata from store
solidLogicSingleton.store.updater.flagAuthorizationMetadata() as any
const wellKnownUri = new URL(issuer)
wellKnownUri.pathname = '/.well-known/openid-configuration'
const wellKnownResult = await fetch(wellKnownUri.toString())
if (wellKnownResult.status === 200) {
const openidConfiguration = await wellKnownResult.json()
if (openidConfiguration && openidConfiguration.end_session_endpoint) {
await fetch(openidConfiguration.end_session_endpoint, { credentials: 'include' })
}
}
} catch (_err) {
// Do nothing
}
}
window.location.reload()
})
/**
* Workspace selection etc
* See https://github.com/solidos/userguide/issues/16
*/
/**
* Returns a UI object which, if it selects a workspace,
* will callback(workspace, newBase).
* See https://github.com/solidos/userguide/issues/16 for more info on workspaces.
*
* If necessary, will get an account, preference file, etc. In sequence:
*
* - If not logged in, log in.
* - Load preference file
* - Prompt user for workspaces
* - Allows the user to just type in a URI by hand
*
* Calls back with the workspace and the base URI
*
* @param dom
* @param appDetails
* @param callbackWS
*/
export function selectWorkspace (
dom: HTMLDocument,
appDetails: AppDetails,
callbackWS: (workspace: string | null, newBase: string) => void
): HTMLElement {
const noun = appDetails.noun
const appPathSegment = appDetails.appPathSegment
const me = offlineTestID()
const box = dom.createElement('div')
const context: AuthenticationContext = { me, dom, div: box }
function say (s, background) {
box.appendChild(widgets.errorMessageBlock(dom, s, background))
}
function figureOutBase (ws) {
const newBaseNode: NamedNode = solidLogicSingleton.store.any(
ws,
ns.space('uriPrefix')
) as NamedNode
let newBaseString: string
if (!newBaseNode) {
newBaseString = ws.uri.split('#')[0]
} else {
newBaseString = newBaseNode.value
}
if (newBaseString.slice(-1) !== '/') {
debug.log(`${appPathSegment}: No / at end of uriPrefix ${newBaseString}`) // @@ paramater?
newBaseString = `${newBaseString}/`
}
const now = new Date()
newBaseString += `${appPathSegment}/id${now.getTime()}/` // unique id
return newBaseString
}
function displayOptions (context) {
// console.log('displayOptions!', context)
async function makeNewWorkspace (_event) {
const row = table.appendChild(dom.createElement('tr'))
const cell = row.appendChild(dom.createElement('td'))
cell.setAttribute('colspan', '3')
cell.style.padding = '0.5em'
const newBase = encodeURI(
await widgets.askName(
dom,
solidLogicSingleton.store,
cell,
ns.solid('URL'),
ns.space('Workspace'),
'Workspace'
)
)
const newWs = widgets.newThing(context.preferencesFile)
const newData = [
st(context.me, ns.space('workspace'), newWs, context.preferencesFile),
st(
newWs,
ns.space('uriPrefix'),
newBase as unknown as Quad_Object,
context.preferencesFile
)
]
if (!solidLogicSingleton.store.updater) {
throw new Error('store has no updater')
}
await solidLogicSingleton.store.updater.update([], newData)
// @@ now refresh list of workspaces
}
// const status = ''
const id = context.me
const preferencesFile = context.preferencesFile
let newBase: any = null
// A workspace specifically defined in the private preference file:
let w: any = solidLogicSingleton.store.each(
id,
ns.space('workspace'),
undefined,
preferencesFile
) // Only trust preference file here
// A workspace in a storage in the public profile:
const storages = solidLogicSingleton.store.each(id, ns.space('storage')) // @@ No provenance requirement at the moment
if (w.length === 0 && storages) {
say(
`You don't seem to have any workspaces. You have ${storages.length} storage spaces.`,
'white'
)
storages
.map(function (s: any) {
w = w.concat(solidLogicSingleton.store.each(s, ns.ldp('contains')))
return w
})
.filter((file) => {
return file.id ? ['public', 'private'].includes(file.id().toLowerCase()) : ''
})
}
if (w.length === 1) {
say(`Workspace used: ${w[0].uri}`, 'white') // @@ allow user to see URI
newBase = figureOutBase(w[0])
// callbackWS(w[0], newBase)
// } else if (w.length === 0) {
}
// Prompt for ws selection or creation
// say( w.length + " workspaces for " + id + "Choose one.");
const table = dom.createElement('table')
table.setAttribute('style', 'border-collapse:separate; border-spacing: 0.5em;')
// const popup = window.open(undefined, '_blank', { height: 300, width:400 }, false)
box.appendChild(table)
// Add a field for directly adding the URI yourself
// const hr = box.appendChild(dom.createElement('hr')) // @@
box.appendChild(dom.createElement('hr')) // @@
const p = box.appendChild(dom.createElement('p'))
p.setAttribute('style', style.commentStyle)
p.textContent = `Where would you like to store the data for the ${noun}?
Give the URL of the folder where you would like the data stored.
It can be anywhere in solid world - this URI is just an idea.`
// @@ TODO Remove the need to cast baseField to any
const baseField: any = box.appendChild(dom.createElement('input'))
baseField.setAttribute('type', 'text')
baseField.setAttribute('style', style.textInputStyle)
baseField.size = 80 // really a string
baseField.label = 'base URL'
baseField.autocomplete = 'on'
if (newBase) {
// set to default
baseField.value = newBase
}
context.baseField = baseField
box.appendChild(dom.createElement('br')) // @@
const button = box.appendChild(dom.createElement('button'))
button.setAttribute('style', style.buttonStyle)
button.textContent = `Start new ${noun} at this URI`
button.addEventListener('click', function (_event) {
let newBase = baseField.value.replace(' ', '%20') // do not re-encode in general, as % encodings may exist
if (newBase.slice(-1) !== '/') {
newBase += '/'
}
callbackWS(null, newBase)
})
// Now go set up the table of spaces
// const row = 0
w = w.filter(function (x) {
return !solidLogicSingleton.store.holds(
x,
ns.rdf('type'), // Ignore master workspaces
ns.space('MasterWorkspace')
)
})
let col1, col2, col3, tr, ws, localStyle, comment
const cellStyle = 'height: 3em; margin: 1em; padding: 1em white; border-radius: 0.3em;'
const deselectedStyle = `${cellStyle}border: 0px;`
// const selectedStyle = cellStyle + 'border: 1px solid black;'
for (let i = 0; i < w.length; i++) {
ws = w[i]
tr = dom.createElement('tr')
if (i === 0) {
col1 = dom.createElement('td')
col1.setAttribute('rowspan', `${w.length}`)
col1.textContent = 'Choose a workspace for this:'
col1.setAttribute('style', 'vertical-align:middle;')
tr.appendChild(col1)
}
col2 = dom.createElement('td')
localStyle = solidLogicSingleton.store.anyValue(ws, ns.ui('style'))
if (!localStyle) {
// Otherwise make up arbitrary colour
const hash = function (x) {
return x.split('').reduce(function (a, b) {
a = (a << 5) - a + b.charCodeAt(0)
return a & a
}, 0)
}
const bgcolor = `#${((hash(ws.uri) & 0xffffff) | 0xc0c0c0).toString(16)}` // c0c0c0 forces pale
localStyle = `color: black ; background-color: ${bgcolor};`
}
col2.setAttribute('style', deselectedStyle + localStyle)
tr.target = ws.uri
let label = solidLogicSingleton.store.any(ws, ns.rdfs('label'))
if (!label) {
label = ws.uri.split('/').slice(-1)[0] || ws.uri.split('/').slice(-2)[0]
}
col2.textContent = label || '???'
tr.appendChild(col2)
if (i === 0) {
col3 = dom.createElement('td')
col3.setAttribute('rowspan', `${w.length}1`)
// col3.textContent = '@@@@@ remove';
col3.setAttribute('style', 'width:50%;')
tr.appendChild(col3)
}
table.appendChild(tr)
comment = solidLogicSingleton.store.any(ws, ns.rdfs('comment'))
comment = comment ? comment.value : 'Use this workspace'
col2.addEventListener(
'click',
function (_event) {
col3.textContent = comment ? comment.value : ''
col3.setAttribute('style', deselectedStyle + localStyle)
const button = dom.createElement('button')
button.textContent = 'Continue'
// button.setAttribute('style', style);
const newBase = figureOutBase(ws)
baseField.value = newBase // show user proposed URI
button.addEventListener(
'click',
function (_event) {
button.disabled = true
callbackWS(ws, newBase)
button.textContent = '---->'
},
true
) // capture vs bubble
col3.appendChild(button)
},
true
) // capture vs bubble
}
// last line with "Make new workspace"
const trLast = dom.createElement('tr')
col2 = dom.createElement('td')
col2.setAttribute('style', cellStyle)
col2.textContent = '+ Make a new workspace'
col2.addEventListener('click', makeNewWorkspace)
trLast.appendChild(col2)
table.appendChild(trLast)
} // displayOptions
// console.log('kicking off async operation')
ensureLoadedPreferences(context) // kick off async operation
.then(displayOptions)
.catch((err) => {
// console.log("err from async op")
box.appendChild(widgets.errorMessageBlock(context.dom, err))
})