I've been looking for answers to questions regarding data privacy in gun
, and here's my answer:
- Import and definition of variables
<script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>
<script src="https://cdn.jsdelivr.net/npm/gun/sea.js"></script>
var gun = Gun()
- Create first author of microblog
gun.user().create('firstMicroblogAuthor', 'somePassword')
gun.user().auth('firstMicroblogAuthor', 'somePassword')
- Create post and get author
var post = {
title: 'First post',
text: 'Hello world!'
}
var author = gun.get('~@firstMicroblogAuthor') // There should be the same `username` in Step 2
- Save post
gun
.user()
.get('posts')
.set(post) // At this step, we saved the post in a user schedule, which by default is only writable by the user
.once(function() {
this.get('author').put(author) // In this step, we link our post with the author (with our user)
gun.get('posts').set(this) // At this step, we save the post with the author installed in the main graph
})
- Check that our posts are protected from editing by other users:
gun.user().leave()
gun.user().create('secondMicroblogAuthor', 'somePassword')
gun.user().auth('secondMicroblogAuthor', 'somePassword')
gun
.get('posts') // Read posts from public graph
.once(function() {
this.get('text').put('Goodbye world!') // In this case, we will get an error, because this post was protected
})
gun.user()
( gun.eco/docs/Todo-Dapp ) already is public-read user-only-write. – Exoergic