forked from SolidOS/solid-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthn.ts
More file actions
1439 lines (1323 loc) · 43.3 KB
/
Copy pathauthn.ts
File metadata and controls
1439 lines (1323 loc) · 43.3 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
/**
* 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
* @packageDocumentation
*/
import SolidTls from 'solid-auth-tls'
import * as $rdf from 'rdflib'
import widgets from '../widgets'
import solidAuthClient from 'solid-auth-client'
import ns from '../ns.js'
import kb from '../store.js'
import utils from '../utils.js'
import log from '../log.js'
import { AppDetails, AuthenticationContext } from './types'
import { PaneDefinition } from 'pane-registry'
export { solidAuthClient }
// const userCheckSite = 'https://databox.me/'
/**
* Look for and load the User who has control over it
*/
export function findOriginOwner (doc: $rdf.NamedNode | string): string | boolean {
const uri = (typeof doc === 'string') ? doc : doc.uri
const i = uri.indexOf('://')
if (i < 0) return false
const j = uri.indexOf('/', i + 3)
if (j < 0) return false
const origin = uri.slice(0, j + 1) // @@ TBC
return origin
}
/**
* Saves `webId` in `context.me`
* @param webId
* @param context
*
* @returns Returns the WebID, after setting it
*/
export function saveUser (
webId: $rdf.NamedNode | string | null,
context?: AuthenticationContext
): $rdf.NamedNode | null {
// @@ TODO Remove the need for having context as output argument
let webIdUri: string
if (webId) {
webIdUri = (typeof webId === 'string') ? webId : webId.uri
const me = $rdf.namedNode(webIdUri)
if (context) {
context.me = me
}
return me
}
return null
}
/**
* Wrapper around [[offlineTestID]]
* @returns {NamedNode|null}
*/
export function defaultTestUser (): $rdf.NamedNode | null {
// Check for offline override
const offlineId = offlineTestID()
if (offlineId) {
return offlineId
}
return null
}
/**
* Checks synchronously whether user is logged in
*
* @returns Named Node or null
*/
export function currentUser (): $rdf.NamedNode | null {
const str = localStorage['solid-auth-client']
if (str) {
const da = JSON.parse(str)
if (da.session && da.session.webId) {
// @@ TODO check has not expired
return $rdf.sym(da.session.webId)
}
}
return offlineTestID() // null unless testing
// JSON.parse(localStorage['solid-auth-client']).session.webId
}
/**
* Resolves with the logged in user's WebID
*
* @param context
*/
export function logIn (context: AuthenticationContext): Promise<AuthenticationContext> {
const me = defaultTestUser() // me is a NamedNode or null
if (me) {
context.me = me
return Promise.resolve(context)
}
return new Promise(resolve => {
checkUser().then(webId => {
// Already logged in?
if (webId) {
context.me = $rdf.sym(webId as string)
console.log(`logIn: Already logged in as ${context.me}`)
return resolve(context)
}
if (!context.div || !context.dom) {
return resolve(context)
}
const box = loginStatusBox(context.dom, webIdUri => {
saveUser(webIdUri, context)
resolve(context) // always pass growing context
})
context.div.appendChild(box)
})
})
}
/**
* Logs the user in and loads their WebID profile document into the store
*
* @param context
*
* @returns Resolves with the context after login / fetch
*/
export function logInLoadProfile (context: AuthenticationContext): Promise<AuthenticationContext> {
if (context.publicProfile) {
return Promise.resolve(context)
} // already done
const fetcher = kb.fetcher
let profileDocument
return new Promise(function (resolve, reject) {
return logIn(context)
.then(context => {
const webID = context.me
if (!webID) {
return reject(new Error('Could not log in'))
}
profileDocument = webID.doc()
// Load the profile into the knowledge base (fetcher.store)
// withCredentials: Web arch should let us just load by turning off creds helps CORS
// reload: Gets around a specific old Chrome bug caching/origin/cors
fetcher
.load(profileDocument, { withCredentials: false, cache: 'reload' })
.then(_response => {
context.publicProfile = profileDocument
resolve(context)
})
.catch(err => {
const message = `Logged in but cannot load profile ${profileDocument} : ${err}`
if (context.div && context.dom) {
context.div.appendChild(
widgets.errorMessageBlock(context.dom, message)
)
}
reject(message)
})
})
.catch(err => {
reject(new Error(`Can't log in: ${err}`))
})
})
}
/**
* Loads preference file
* Do this after having done log in and load profile
*
* @private
*
* @param context
*/
export function logInLoadPreferences (context: AuthenticationContext): Promise<AuthenticationContext> {
if (context.preferencesFile) return Promise.resolve(context) // already done
const statusArea = context.statusArea || context.div || null
let progressDisplay
return new Promise(function (resolve, reject) {
return logInLoadProfile(context)
.then(context => {
const preferencesFile = kb.any(context.me, ns.space('preferencesFile'))
function complain (message) {
message = `logInLoadPreferences: ${message}`
if (statusArea) {
// statusArea.innerHTML = ''
statusArea.appendChild(
widgets.errorMessageBlock(context.dom, message)
)
}
console.log(message)
reject(new Error(message))
}
/**
* Are we working cross-origin?
* Returns True if we are in a webapp at an origin, and the file origin is different
*/
function differentOrigin (): boolean {
return `${window.location.origin}/` !== preferencesFile.site().uri
}
if (!preferencesFile) {
return reject(new Error(`Can't find a preference file pointer in profile ${context.publicProfile}`))
}
// //// Load preference file
return kb.fetcher
.load(preferencesFile, { withCredentials: true })
.then(function () {
if (progressDisplay) {
progressDisplay.parentNode.removeChild(progressDisplay)
}
context.preferencesFile = preferencesFile
return resolve(context)
})
.catch(function (err) {
// Really important to look at why
const status = err.status
const message = err.message
console.log(
`HTTP status ${status} for preference file ${preferencesFile}`
)
let m2
if (status === 401) {
m2 = 'Strange - you are not authenticated (properly logged in) to read preference file.'
alert(m2)
} else if (status === 403) {
if (differentOrigin()) {
m2 = `Unauthorized: Assuming preference file blocked for origin ${window.location.origin}`
context.preferencesFileError = m2
return resolve(context)
}
m2 = 'You are not authorized to read your preference file. This may be because you are using an untrusted web app.'
console.warn(m2)
} else if (status === 404) {
if (
confirm(`You do not currently have a preference file. OK for me to create an empty one? ${preferencesFile}`)
) {
// @@@ code me ... weird to have a name of the file but no file
alert(`Sorry; I am not prepared to do this. Please create an empty file at ${preferencesFile}`)
return complain(
new Error('Sorry; no code yet to create a preference file at ')
)
} else {
reject(
new Error(`User declined to create a preference file at ${preferencesFile}`)
)
}
} else {
m2 = `Strange: Error ${status} trying to read your preference file.${message}`
alert(m2)
}
}) // load preference file then
})
.catch(err => {
// Fail initial login load preferences
reject(new Error(`(via loadPrefs) ${err}`))
})
})
}
/**
* Resolves with the same context, outputting
* output: index.public, index.private
*
* @see https://github.com/solid/solid/blob/master/proposals/data-discovery.md#discoverability
*/
export async function loadTypeIndexes (context: AuthenticationContext): Promise<AuthenticationContext> {
await loadPublicTypeIndex(context)
await loadPrivateTypeIndex(context)
return context
}
async function loadPublicTypeIndex (context: AuthenticationContext): Promise<AuthenticationContext> {
return loadIndex(context, ns.solid('publicTypeIndex'), true)
}
async function loadPrivateTypeIndex (context: AuthenticationContext): Promise<AuthenticationContext> {
return loadIndex(context, ns.solid('privateTypeIndex'), false)
}
async function loadOneTypeIndex (context: AuthenticationContext, isPublic: boolean): Promise<AuthenticationContext> {
const predicate = isPublic
? ns.solid('publicTypeIndex')
: ns.solid('privateTypeIndex')
return loadIndex(context, predicate, isPublic)
}
async function loadIndex (
context: AuthenticationContext,
predicate: $rdf.NamedNode,
isPublic: boolean
): Promise<AuthenticationContext> {
// Loading preferences is more than loading profile
try {
;(await isPublic)
? logInLoadProfile(context)
: logInLoadPreferences(context)
} catch (err) {
widgets.complain(context, `loadPubicIndex: login and load problem ${err}`)
}
const me = context.me
let ixs
context.index = context.index || {}
if (isPublic) {
ixs = kb.each(me, predicate, undefined, context.publicProfile)
context.index.public = ixs
} else {
if (!context.preferencesFileError) {
ixs = kb.each(
me,
ns.solid('privateTypeIndex'),
undefined,
context.preferencesFile
)
context.index.private = ixs
if (ixs.length === 0) {
widgets.complain(`Your preference file ${context.preferencesFile} does not point to a private type index.`)
return context
}
} else {
console.log(
'We know your preference file is not available, so we are not bothering with private type indexes.'
)
}
}
try {
await kb.fetcher.load(ixs)
} catch (err) {
widgets.complain(context, `loadPubicIndex: loading public type index ${err}`)
}
return context
}
/**
* Resolves with the same context, outputting
* @see https://github.com/solid/solid/blob/master/proposals/data-discovery.md#discoverability
*/
async function ensureTypeIndexes (context: AuthenticationContext): Promise<AuthenticationContext> {
await ensureOneTypeIndex(context, true)
await ensureOneTypeIndex(context, false)
return context
}
/**
* Load or create ONE type index
* Find one or make one or fail
* Many reasons for failing including script not having permission etc
*
* Adds its output to the context
* @see https://github.com/solid/solid/blob/master/proposals/data-discovery.md#discoverability
*/
async function ensureOneTypeIndex (context: AuthenticationContext, isPublic: boolean): Promise<AuthenticationContext | void> {
async function makeIndexIfNecessary (context, isPublic) {
const relevant = isPublic ? context.publicProfile : context.preferencesFile
const visibility = isPublic ? 'public' : 'private'
async function putIndex (newIndex) {
try {
await kb.fetcher.webOperation('PUT', newIndex.uri, {
data: `# ${new Date()} Blank initial Type index
`,
contentType: 'text/turtle'
})
return context
} catch (e) {
const msg = `Error creating new index ${e}`
widgets.complain(context, msg)
}
} // putIndex
context.index = context.index || {}
context.index[visibility] = context.index[visibility] || []
let newIndex
if (context.index[visibility].length === 0) {
newIndex = $rdf.sym(`${relevant.dir().uri + visibility}TypeIndex.ttl`)
console.log(`Linking to new fresh type index ${newIndex}`)
if (!confirm(`OK to create a new empty index file at ${newIndex}, overwriting anything that is now there?`)) {
throw new Error('cancelled by user')
}
console.log(`Linking to new fresh type index ${newIndex}`)
const addMe = [
$rdf.st(context.me, ns.solid(`${visibility}TypeIndex`), newIndex, relevant)
]
try {
await updatePromise(kb.updater, [], addMe)
} catch (err) {
const msg = `Error saving type index link saving back ${newIndex}: ${err}`
widgets.complain(context, msg)
return context
}
console.log(`Creating new fresh type index file${newIndex}`)
await putIndex(newIndex)
context.index[visibility].push(newIndex) // @@ wait
} else {
// officially exists
const ixs = context.index[visibility]
try {
await kb.fetcher.load(ixs)
} catch (err) {
widgets.complain(context, `ensureOneTypeIndex: loading indexes ${err}`)
}
}
} // makeIndexIfNecessary
try {
await loadOneTypeIndex(context, isPublic)
if (context.index) {
console.log(
`ensureOneTypeIndex: Type index exists already ${isPublic}`
? context.index.public[0]
: context.index.private[0]
)
}
return context
} catch (error) {
await makeIndexIfNecessary(context, isPublic)
// widgets.complain(context, 'calling loadOneTypeIndex:' + error)
}
}
/**
* Returns promise of context with arrays of symbols
*
* 2016-12-11 change to include forClass arc a la
* https://github.com/solid/solid/blob/master/proposals/data-discovery.md
*/
export async function findAppInstances (
context: AuthenticationContext,
klass: $rdf.NamedNode,
isPublic: boolean
): Promise<AuthenticationContext> {
const fetcher = kb.fetcher
if (isPublic === undefined) {
// Then both public and private
await findAppInstances(context, klass, true)
await findAppInstances(context, klass, false)
return context
}
const visibility = isPublic ? 'public' : 'private'
try {
await loadOneTypeIndex(context, isPublic)
} catch (err) {
}
const index = context.index as { [key: string]: Array<$rdf.NamedNode> }
const thisIndex = index[visibility]
const registrations = thisIndex
.map(ix => kb.each(undefined, ns.solid('forClass'), klass, ix))
.flat()
const instances = registrations
.map(reg => kb.each(reg, ns.solid('instance')))
.flat()
const containers = registrations
.map(reg => kb.each(reg, ns.solid('instanceContainer')))
.flat()
context.instances = context.instances || []
context.instances = context.instances.concat(instances)
context.containers = context.containers || []
context.containers = context.containers.concat(containers)
if (!containers.length) {
return context
}
// If the index gives containers, then look up all things within them
try {
await fetcher.load(containers)
} catch (err) {
const e = new Error(`[FAI] Unable to load containers${err}`)
console.log(e) // complain
widgets.complain(context, `Error looking for ${utils.label(klass)}: ${err}`)
// but then ignore it
// throw new Error(e)
}
for (let i = 0; i < containers.length; i++) {
const cont = containers[i]
context.instances = context.instances.concat(
kb.each(cont, ns.ldp('contains'))
)
}
return context
}
// @@@@ use the one in rdflib.js when it is available and delete this
function updatePromise (
updater: $rdf.UpdateManager,
del: Array<$rdf.Statement>,
ins: Array<$rdf.Statement> = []
): Promise<void> {
return new Promise(function (resolve, reject) {
updater.update(del, ins, function (uri, ok, errorBody) {
if (!ok) {
reject(new Error(errorBody))
} else {
resolve()
}
}) // callback
}) // promise
}
/**
* Register a new app in a type index
*/
export async function registerInTypeIndex (
context: AuthenticationContext,
instance: $rdf.NamedNode,
klass: $rdf.NamedNode,
isPublic: boolean
): Promise<AuthenticationContext> {
await ensureOneTypeIndex(context, isPublic)
if (!context.index) {
throw new Error('registerInTypeIndex: No type index found')
}
const indexes = isPublic ? context.index.public : context.index.private
if (!indexes.length) {
throw new Error('registerInTypeIndex: What no type index?')
}
const index = indexes[0]
const registration = widgets.newThing(index)
const ins = [
// See https://github.com/solid/solid/blob/master/proposals/data-discovery.md
$rdf.st(registration, ns.rdf('type'), ns.solid('TypeRegistration'), index),
$rdf.st(registration, ns.solid('forClass'), klass, index),
$rdf.st(registration, ns.solid('instance'), instance, index)
]
try {
await updatePromise(kb.updater, [], ins)
} catch (e) {
console.log(e)
alert(e)
}
return context
}
/**
* UI to control registration of instance
*/
export function registrationControl (
context: AuthenticationContext,
instance,
klass
): Promise<AuthenticationContext | void> {
const dom = context.dom
if (!dom || !context.div) {
return Promise.resolve()
}
const box = dom.createElement('div')
context.div.appendChild(box)
return ensureTypeIndexes(context)
.then(function () {
box.innerHTML = '<table><tbody><tr></tr><tr></tr></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 = kb.bnode() // @@ say for now
const registrationStatements = function (index) {
const registrations = kb
.each(undefined, ns.solid('instance'), instance)
.filter(function (r) {
return kb.holds(r, ns.solid('forClass'), klass)
})
const reg = registrations.length
? registrations[0]
: widgets.newThing(index)
return [
$rdf.st(reg, ns.solid('instance'), instance, index),
$rdf.st(reg, ns.solid('forClass'), klass, index)
]
}
let index, statements
if (context.index && context.index.public && context.index.public.length > 0) {
index = context.index.public[0]
statements = registrationStatements(index)
tbody.children[0].appendChild(
widgets.buildCheckboxForm(
context.dom,
kb,
`Public link to this ${context.noun}`,
null,
statements,
form,
index
)
)
}
if (context.index && context.index.private && context.index.private.length > 0) {
index = context.index.private[0]
statements = registrationStatements(index)
tbody.children[1].appendChild(
widgets.buildCheckboxForm(
context.dom,
kb,
`Personal note of this ${context.noun}`,
null,
statements,
form,
index
)
)
}
return context
},
function (e) {
let msg
if (context.div && context.preferencesFileError) {
msg = '(Preferences 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))
}
console.log(msg)
}
)
.catch(function (e) {
const msg = `registrationControl: Error making panel: ${e}`
if (context.div) {
context.div.appendChild(widgets.errorMessageBlock(context.dom, e))
}
console.log(msg)
})
}
/**
* UI to List at all registered things
*/
export function registrationList (context: AuthenticationContext, options: {
private?: boolean
public?: boolean
}): Promise<AuthenticationContext> {
const dom = context.dom as HTMLDocument
const div = context.div as HTMLElement
const box = dom.createElement('div')
div.appendChild(box)
return ensureTypeIndexes(context).then(_indexes => {
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
let ix: Array<$rdf.NamedNode> = []
let sts = []
const vs = ['private', 'public']
vs.forEach(function (visibility) {
if (context.index && options[visibility]) {
ix = ix.concat(context.index[visibility][0])
sts = sts.concat(
kb.statementsMatching(
undefined,
ns.solid('instance'),
undefined,
context.index[visibility][0]
)
)
}
})
for (let i = 0; i < sts.length; i++) {
const statement: $rdf.Statement = sts[i]
// const cla = statement.subject
const inst = statement.object
// if (false) {
// const tr = table.appendChild(dom.createElement('tr'))
// const anchor = tr.appendChild(dom.createElement('a'))
// anchor.setAttribute('href', inst.uri)
// anchor.textContent = utils.label(inst)
// } else {
// }
table.appendChild(widgets.personTR(dom, ns.solid('instance'), inst, {
deleteFunction: function (_x) {
kb.updater.update([statement], [], function (uri, ok, errorBody) {
if (ok) {
console.log(`Removed from index: ${statement.subject}`)
} else {
console.log(`Error: Cannot delete ${statement}: ${errorBody}`)
}
})
}
}))
}
/*
//const containers = kb.each(klass, ns.solid('instanceContainer'));
if (containers.length) {
fetcher.load(containers).then(function(xhrs){
for (const i=0; i<containers.length; i++) {
const cont = containers[i];
instances = instances.concat(kb.each(cont, ns.ldp('contains')));
}
});
}
*/
return context
})
}
/**
* Simple Access Control
*
* This function sets up a simple default ACL for a resource, with
* RWC for the owner, and a specified access (default none) for the public.
* In all cases owner has read write control.
* Parameter lists modes allowed to public
*
* @param options
* @param options.public eg ['Read', 'Write']
*
* @returns Resolves with aclDoc uri on successful write
*/
export function setACLUserPublic (
docURI: $rdf.NamedNode,
me: $rdf.NamedNode,
options: {
defaultForNew?: boolean,
public?: []
}
): Promise<$rdf.NamedNode> {
const aclDoc = kb.any(
kb.sym(docURI),
kb.sym('http://www.iana.org/assignments/link-relations/acl')
)
return Promise.resolve()
.then(() => {
if (aclDoc) {
return aclDoc
}
return fetchACLRel(docURI).catch(err => {
throw new Error(`Error fetching rel=ACL header for ${docURI}: ${err}`)
})
})
.then(aclDoc => {
const aclText = genACLText(docURI, me, aclDoc.uri, options)
return kb.fetcher
.webOperation('PUT', aclDoc.uri, {
data: aclText,
contentType: 'text/turtle'
})
.then(result => {
if (!result.ok) {
throw new Error('Error writing ACL text: ' + result.error)
}
return aclDoc
})
})
}
/**
* @param docURI
* @returns
*/
function fetchACLRel (docURI: $rdf.NamedNode): Promise<$rdf.NamedNode> {
const fetcher = kb.fetcher
return fetcher.load(docURI).then(result => {
if (!result.ok) {
throw new Error('fetchACLRel: While loading:' + result.error)
}
const aclDoc = kb.any(
kb.sym(docURI),
kb.sym('http://www.iana.org/assignments/link-relations/acl')
)
if (!aclDoc) {
throw new Error('fetchACLRel: No Link rel=ACL header for ' + docURI)
}
return aclDoc
})
}
/**
* @param docURI
* @param me
* @param aclURI
* @param options
*
* @returns Serialized ACL
*/
function genACLText (
docURI: $rdf.NamedNode,
me: $rdf.NamedNode,
aclURI: $rdf.NamedNode,
options: {
defaultForNew?: boolean,
public?: []
} = {}
): string {
const optPublic = options.public || []
const g = $rdf.graph()
const auth = $rdf.Namespace('http://www.w3.org/ns/auth/acl#')
let a = g.sym(`${aclURI}#a1`)
const acl = g.sym(aclURI)
const doc = g.sym(docURI)
g.add(a, ns.rdf('type'), auth('Authorization'), acl)
g.add(a, auth('accessTo'), doc, acl)
if (options.defaultForNew) {
// TODO: Should this be auth('default') instead?
g.add(a, auth('defaultForNew'), doc, acl)
}
g.add(a, auth('agent'), me, acl)
g.add(a, auth('mode'), auth('Read'), acl)
g.add(a, auth('mode'), auth('Write'), acl)
g.add(a, auth('mode'), auth('Control'), acl)
if (optPublic.length) {
a = g.sym(`${aclURI}#a2`)
g.add(a, ns.rdf('type'), auth('Authorization'), acl)
g.add(a, auth('accessTo'), doc, acl)
g.add(a, auth('agentClass'), ns.foaf('Agent'), acl)
for (let p = 0; p < optPublic.length; p++) {
g.add(a, auth('mode'), auth(optPublic[p]), acl) // Like 'Read' etc
}
}
// @@ TODO Remove casting of $rdf
return ($rdf as any).serialize(acl, g, aclURI, 'text/turtle')
}
/**
* Returns `$rdf.sym($SolidTestEnvironment.username)` if
* `$SolidTestEnvironment.username` is defined as a global
* @returns {NamedNode|null}
*/
export function offlineTestID (): $rdf.NamedNode | null {
const { $SolidTestEnvironment }: any = window
if (
typeof $SolidTestEnvironment !== 'undefined' &&
$SolidTestEnvironment.username
) {
// Test setup
console.log('Assuming the user is ' + $SolidTestEnvironment.username)
return $rdf.sym($SolidTestEnvironment.username)
}
if (
typeof document !== 'undefined' &&
document.location &&
('' + document.location).slice(0, 16) === 'http://localhost'
) {
const div = document.getElementById('appTarget')
if (!div) return null
const id = div.getAttribute('testID')
if (!id) return null
/* me = kb.any(subject, ns.acl('owner')); // when testing on plane with no WebID
*/
console.log('Assuming user is ' + id)
return $rdf.sym(id)
}
return null
}
function getDefaultSignInButtonStyle (): string {
return 'padding: 1em; border-radius:0.5em; margin: 2em; font-size: 100%;'
}
/**
* 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 || getDefaultSignInButtonStyle()
// @@ TODO Remove the need to cast HTML element to any
const box: any = dom.createElement('div')
const magicClassName = 'SolidSignInOrSignUpBox'
console.log('widgets.signInOrSignUpBox')
box.setUserCallback = setUserCallback
box.setAttribute('class', magicClassName)
box.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}background-color: #eef;`)
signInPopUpButton.addEventListener('click', () => {
const offline = offlineTestID()
if (offline) return setUserCallback(offline.uri)
return solidAuthClient.popupLogin().then(session => {
const webIdURI = session.webId
// setUserCallback(webIdURI)
const divs = dom.getElementsByClassName(magicClassName)
console.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) {
console.log(`## Error satisfying login box: ${e}`)
div.appendChild(widgets.errorMessageBlock(dom, e))
}
}
}
})
}, 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}background-color: #efe;`)
signupButton.addEventListener('click', function (_event) {
const signupMgr = new SolidTls.Signup()
signupMgr.signup().then(function (uri) {
console.log('signInOrSignUpBox signed up ' + uri)
setUserCallback(uri)
})
}, false)
return box
}
/**
* @returns {Promise<string|null>} Resolves with WebID URI or null
*/
function webIdFromSession (session?: { webId: string }): string | null {
const webId = session ? session.webId : null
if (webId) {
saveUser(webId)
}
return webId
}
/**
* @returns {Promise<string|null>} Resolves with WebID URI or null
*/
/*
function checkCurrentUser () {
return checkUser()
}
*/
/**
* Retrieves currently logged in webId from either
* defaultTestUser or SolidAuthClient
* @param [setUserCallback] Optional callback
*
* @returns Resolves with webId uri, if no callback provided
*/
export function checkUser<T> (