fix user API

This commit is contained in:
Mark Nadal 2018-04-21 00:48:35 -07:00
parent c1c00595b8
commit a173c04a3c
3 changed files with 265 additions and 243 deletions

8
gun.js
View File

@ -657,7 +657,7 @@
return Gun.create(this._ = {gun: this, opt: o}); return Gun.create(this._ = {gun: this, opt: o});
} }
Gun.is = function(gun){ return (gun instanceof Gun) } Gun.is = function(gun){ return (gun instanceof Gun) || (gun && gun._ && gun._.gun && true) || false }
Gun.version = 0.9; Gun.version = 0.9;
@ -923,11 +923,11 @@
// is complicated and was extremely hard to build. If you port GUN to another // is complicated and was extremely hard to build. If you port GUN to another
// language, consider implementing an easier API to build. // language, consider implementing an easier API to build.
var Gun = USE('./root'); var Gun = USE('./root');
Gun.chain.chain = function(){ Gun.chain.chain = function(sub){
var at = this._, chain = new this.constructor(this), cat = chain._, root; var gun = this, at = gun._, chain = new (sub || gun).constructor(gun), cat = chain._, root;
cat.root = root = at.root; cat.root = root = at.root;
cat.id = ++root.once; cat.id = ++root.once;
cat.back = this._; cat.back = gun._;
cat.on = Gun.on; cat.on = Gun.on;
cat.on('in', input, cat); // For 'in' if I add my own listeners to each then I MUST do it before in gets called. If I listen globally for all incoming data instead though, regardless of individual listeners, I can transform the data there and then as well. cat.on('in', input, cat); // For 'in' if I add my own listeners to each then I MUST do it before in gets called. If I listen globally for all incoming data instead though, regardless of individual listeners, I can transform the data there and then as well.
cat.on('out', output, cat); // However for output, there isn't really the global option. I must listen by adding my own listener individually BEFORE this one is ever called. cat.on('out', output, cat); // However for output, there isn't really the global option. I must listen by adding my own listener individually BEFORE this one is ever called.

105
sea.js
View File

@ -831,7 +831,9 @@
const finalizeLogin = async (alias, key, gunRoot, opts) => { const finalizeLogin = async (alias, key, gunRoot, opts) => {
const { user } = gunRoot._ const { user } = gunRoot._
// add our credentials in-memory only to our root gun instance // add our credentials in-memory only to our root gun instance
//var tmp = user._.tag;
user._ = key.at.gun._ user._ = key.at.gun._
//user._.tag = tmp || user._.tag;
// so that way we can use the credentials to encrypt/decrypt data // so that way we can use the credentials to encrypt/decrypt data
// that is input/output through gun (see below) // that is input/output through gun (see below)
const { pub, priv, epub, epriv } = key const { pub, priv, epub, epriv } = key
@ -1015,11 +1017,43 @@
})(USE, './leave'); })(USE, './leave');
;USE(function(module){ ;USE(function(module){
// How does it work? var Gun = USE('./sea').Gun;
// TODO: Bug! Need to include SEA! Gun.chain.then = function(cb){
//const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') var gun = this, p = (new Promise(function(res, rej){
gun.once(res);
}));
return cb? p.then(cb) : p;
}
})(USE, './then');
;USE(function(module){
var SEA = USE('./sea');
var Gun = SEA.Gun;
var then = USE('./then');
function User(){
this._ = {gun: this}
Gun.call()
}
User.prototype = (function(){ function F(){}; F.prototype = Gun.chain; return new F() }()) // Object.create polyfill
User.prototype.constructor = User;
// let's extend the gun chain with a `user` function.
// only one user can be logged in at a time, per gun instance.
Gun.chain.user = function(pub){
var gun = this, root = gun.back(-1);
if(pub){ return root.get('pub/'+pub) }
return root.back('user') || ((root._).user = gun.chain(new User));
}
module.exports = User;
})(USE, './user');
;USE(function(module){
// TODO: This needs to be split into all separate functions.
// Not just everything thrown into 'create'.
const SEA = USE('./sea') const SEA = USE('./sea')
const User = USE('./user')
const authRecall = USE('./recall') const authRecall = USE('./recall')
const authsettings = USE('./settings') const authsettings = USE('./settings')
const authenticate = USE('./authenticate') const authenticate = USE('./authenticate')
@ -1028,26 +1062,10 @@
const { recall: _initial_authsettings } = USE('./settings') const { recall: _initial_authsettings } = USE('./settings')
const Gun = SEA.Gun; const Gun = SEA.Gun;
// let's extend the gun chain with a `user` function.
// only one user can be logged in at a time, per gun instance.
Gun.chain.user = function() {
const gunRoot = this.back(-1) // always reference the root gun instance.
const user = gunRoot._.user || (gunRoot._.user = gunRoot.chain()); // create a user context.
// then methods...
[ 'create', // factory
'auth', // login
'leave', // logout
'delete', // account delete
'recall', // existing auth boostrap
'alive' // keep/check auth validity
].map((method)=> user[method] = User[method])
return user // return the user!
}
var u; var u;
function User(){}
// Well first we have to actually create a user. That is what this function does. // Well first we have to actually create a user. That is what this function does.
Object.assign(User, { User.prototype.create = function(username, pass, cb){
async create(username, pass, cb) { // TODO: Needs to be cleaned up!!!
const gunRoot = this.back(-1) const gunRoot = this.back(-1)
var gun = this, cat = (gun._); var gun = this, cat = (gun._);
cb = cb || function(){}; cb = cb || function(){};
@ -1056,7 +1074,7 @@
return gun; return gun;
} }
cat.ing = true; cat.ing = true;
var p = new Promise((resolve, reject) => { // Because no Promises or async var resolve = function(){}, reject = resolve;
// Because more than 1 user might have the same username, we treat the alias as a list of those users. // Because more than 1 user might have the same username, we treat the alias as a list of those users.
if(cb){ resolve = reject = cb } if(cb){ resolve = reject = cb }
gunRoot.get(`alias/${username}`).get(async (at, ev) => { gunRoot.get(`alias/${username}`).get(async (at, ev) => {
@ -1107,11 +1125,11 @@
reject(e) reject(e)
} }
}) })
}) return gun; // gun chain commands must return gun chains!
return gun // gun chain commands must return gun chains! }
},
// now that we have created a user, we want to authenticate them! // now that we have created a user, we want to authenticate them!
async auth(alias, pass, cb, opt) { User.prototype.auth = function(alias, pass, cb, opt){
// TODO: Needs to be cleaned up!!!!
const opts = opt || (typeof cb !== 'function' && cb) const opts = opt || (typeof cb !== 'function' && cb)
let { pin, newpass } = opts || {} let { pin, newpass } = opts || {}
const gunRoot = this.back(-1) const gunRoot = this.back(-1)
@ -1124,14 +1142,15 @@
} }
cat.ing = true; cat.ing = true;
if (!pass && pin) { if (!pass && pin) { (async function(){
try { try {
var r = await authRecall(gunRoot, { alias, pin }) var r = await authRecall(gunRoot, { alias, pin })
return cat.ing = false, cb(r), gun; return cat.ing = false, cb(r), gun;
} catch (e) { } catch (e) {
var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' } var err = { err: 'Auth attempt failed! Reason: No session data for alias & PIN' }
return cat.ing = false, gun.leave(), cb(err), gun; return cat.ing = false, gun.leave(), cb(err), gun;
} }}())
return gun;
} }
const putErr = (msg) => (e) => { const putErr = (msg) => (e) => {
@ -1141,7 +1160,7 @@
return cat.ing = false, gun.leave(), cb(error), gun; return cat.ing = false, gun.leave(), cb(error), gun;
} }
try { (async function(){ try {
const keys = await authenticate(alias, pass, gunRoot) const keys = await authenticate(alias, pass, gunRoot)
if (!keys) { if (!keys) {
return putErr('Auth attempt failed!')({ message: 'No keys' }) return putErr('Auth attempt failed!')({ message: 'No keys' })
@ -1181,14 +1200,19 @@
} }
} catch (e) { } catch (e) {
return putErr('Auth attempt failed!')(e) return putErr('Auth attempt failed!')(e)
} } }());
return gun; return gun;
}, }
async leave() { User.prototype.pair = function(){
var user = this;
if(!user.is){ return false }
return user._.sea;
}
User.prototype.leave = async function(){
return await authLeave(this.back(-1)) return await authLeave(this.back(-1))
}, }
// If authenticated user wants to delete his/her account, let's support it! // If authenticated user wants to delete his/her account, let's support it!
async delete(alias, pass) { User.prototype.delete = async function(alias, pass){
const gunRoot = this.back(-1) const gunRoot = this.back(-1)
try { try {
const { pub } = await authenticate(alias, pass, gunRoot) const { pub } = await authenticate(alias, pass, gunRoot)
@ -1206,10 +1230,10 @@
Gun.log('User.delete failed! Error:', e) Gun.log('User.delete failed! Error:', e)
throw e // TODO: proper error codes??? throw e // TODO: proper error codes???
} }
}, }
// If authentication is to be remembered over reloads or browser closing, // If authentication is to be remembered over reloads or browser closing,
// set validity time in minutes. // set validity time in minutes.
async recall(setvalidity, options) { User.prototype.recall = async function(setvalidity, options){
const gunRoot = this.back(-1) const gunRoot = this.back(-1)
let validity let validity
@ -1257,8 +1281,8 @@
// instead of rejecting... // instead of rejecting...
return { err: (e && e.err) || err } return { err: (e && e.err) || err }
} }
}, }
async alive() { User.prototype.alive = async function(){
const gunRoot = this.back(-1) const gunRoot = this.back(-1)
try { try {
// All is good. Should we do something more with actual recalled data? // All is good. Should we do something more with actual recalled data?
@ -1270,8 +1294,7 @@
throw { err } throw { err }
} }
} }
}) User.prototype.trust = async function(user){
Gun.chain.trust = function(user) {
// TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too. // TODO: BUG!!! SEA `node` read listener needs to be async, which means core needs to be async too.
//gun.get('alice').get('age').trust(bob); //gun.get('alice').get('age').trust(bob);
if (Gun.is(user)) { if (Gun.is(user)) {
@ -1281,7 +1304,7 @@
} }
} }
module.exports = User module.exports = User
})(USE, './user'); })(USE, './create');
;USE(function(module){ ;USE(function(module){
const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun') const Gun = (typeof window !== 'undefined' ? window : global).Gun || USE('gun/gun')

View File

@ -17,7 +17,6 @@
<script src="../examples/jquery.js"></script> <script src="../examples/jquery.js"></script>
<script src="../gun.js"></script> <script src="../gun.js"></script>
<script src="../sea.js"></script> <script src="../sea.js"></script>
<script src="../lib/then.js"></script>
<script> <script>
var gun = Gun(); var gun = Gun();