persist.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. const SEA = require('./sea');
  2. const Gun = SEA.Gun;
  3. const Buffer = require('./buffer')
  4. const authsettings = require('./settings')
  5. const updateStorage = require('./update')
  6. // This internal func persists User authentication if so configured
  7. const authPersist = async (user, proof, opts) => {
  8. // opts = { pin: 'string' }
  9. // no opts.pin then uses random PIN
  10. // How this works:
  11. // called when app bootstraps, with wanted options
  12. // IF authsettings.validity === 0 THEN no remember-me, ever
  13. // IF PIN then signed 'remember' to window.sessionStorage and 'auth' to IndexedDB
  14. const pin = Buffer.from(
  15. (Gun.obj.has(opts, 'pin') && opts.pin) || Gun.text.random(10),
  16. 'utf8'
  17. ).toString('base64')
  18. const alias = user.alias
  19. const exp = authsettings.validity // seconds // @mhelander what is `exp`???
  20. if (proof && alias && exp) {
  21. const iat = Math.ceil(Date.now() / 1000) // seconds
  22. const remember = Gun.obj.has(opts, 'pin') || undefined // for hook - not stored
  23. const props = authsettings.hook({ alias: alias, iat: iat, exp: exp, remember: remember })
  24. const pub = user.pub
  25. const epub = user.epub
  26. const priv = user.sea.priv
  27. const epriv = user.sea.epriv
  28. const key = { pub: pub, priv: priv, epub: epub, epriv: epriv }
  29. if (props instanceof Promise) {
  30. const asyncProps = await props.then()
  31. return await updateStorage(proof, key, pin)(asyncProps)
  32. }
  33. return await updateStorage(proof, key, pin)(props)
  34. }
  35. return await updateStorage()({ alias: 'delete' })
  36. }
  37. module.exports = authPersist