Refactor auth #112

Open
jessopb wants to merge 3 commits from refactorAuth into master
3 changed files with 365 additions and 331 deletions

196
dist/bundle.es.js vendored
View file

@ -219,7 +219,8 @@ const Lbryio = {
CONNECTION_STRING: 'https://api.lbry.com/' CONNECTION_STRING: 'https://api.lbry.com/'
}; };
const EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000; const EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000;
const INTERNAL_APIS_DOWN = 'internal_apis_down'; // We can't use env's because they aren't passed into node_modules const INTERNAL_APIS_DOWN = 'internal_apis_down';
Lbryio.fetchingUser = false; // We can't use env's because they aren't passed into node_modules
Lbryio.setLocalApi = endpoint => { Lbryio.setLocalApi = endpoint => {
Lbryio.CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end; Lbryio.CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end;
@ -262,11 +263,30 @@ Lbryio.call = (resource, action, params = {}, method = 'get') => {
return fetch(url, options).then(checkAndParse); return fetch(url, options).then(checkAndParse);
} }
return Lbryio.getAuthToken().then(token => { return Lbryio.getTokens().then(tokens => {
const fullParams = { // TOKENS = { auth_token, access_token }
auth_token: token, const fullParams = { ...params
...params
}; };
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}; // TODO refactor this
// Send both tokens to userMe
// delete auth token after success
if (action === 'me') {
// when we support transition from auth to access, bring this in
// if (tokens && tokens.access_token) {
// headers.Authorization = `Bearer ${tokens.access_token}`;
// }
if (tokens && tokens.auth_token) {
fullParams.auth_token = tokens.auth_token;
}
} else if (tokens && tokens.access_token) {
headers.Authorization = `Bearer ${tokens.access_token}`;
} else {
fullParams.auth_token = tokens.auth_token;
}
Object.keys(fullParams).forEach(key => { Object.keys(fullParams).forEach(key => {
const value = fullParams[key]; const value = fullParams[key];
@ -295,113 +315,77 @@ Lbryio.call = (resource, action, params = {}, method = 'get') => {
}); });
}; };
Lbryio.authToken = null;
Lbryio.getAuthToken = () => new Promise(resolve => { Lbryio.getAuthToken = () => new Promise(resolve => {
if (Lbryio.authToken) { Lbryio.overrides.getAuthToken().then(token => {
resolve(Lbryio.authToken); resolve(token);
} else if (Lbryio.overrides.getAuthToken) { });
Lbryio.overrides.getAuthToken().then(token => {
resolve(token);
});
} else if (typeof window !== 'undefined') {
const {
store
} = window;
if (store) {
const state = store.getState();
const token = state.auth ? state.auth.authToken : null;
Lbryio.authToken = token;
resolve(token);
}
resolve(null);
} else {
resolve(null);
}
}); });
Lbryio.getCurrentUser = () => Lbryio.call('user', 'me'); Lbryio.getTokens = () => new Promise(resolve => {
Lbryio.overrides.getTokens().then(tokens => {
resolve(tokens);
});
});
Lbryio.authenticate = (domain, language) => { Lbryio.deleteAuthToken = () => new Promise(resolve => {
if (!Lbryio.enabled) { Lbryio.overrides.deleteAuthToken().then(() => {
const params = { resolve(true);
id: 1, });
primary_email: 'disabled@lbry.io', });
has_verified_email: true,
is_identity_verified: true, Lbryio.fetchCurrentUser = () => Lbryio.call('user', 'me').catch(e => ({
is_reward_approved: false, error: {
language: language || 'en' message: e.message
}
}));
Lbryio.fetchUser = async (domain, language) => {
if (!Lbryio.fetchingUser) {
let user;
Lbryio.fetchingUser = true;
const tokens = await Lbryio.getTokens(domain, language);
if (!tokens.auth_token && !tokens.access_token) {
user = await Lbryio.fetchNewUser();
} else {
user = await Lbryio.fetchCurrentUser();
}
if (tokens.access_token) {
if (tokens.auth_token) {
await Lbryio.deleteAuthToken();
}
}
return user;
}
};
Lbryio.fetchNewUser = async (domain, language) => {
try {
const status = await lbryRedux.Lbry.status();
const appId = domain && domain !== 'lbry.tv' ? (domain.replace(/[.]/gi, '') + status.installation_id).slice(0, 66) : status.installation_id;
const userResponse = await Lbryio.call('user', 'new', {
auth_token: '',
language: language || 'en',
app_id: appId
}, 'post');
if (!userResponse.auth_token) {
throw new Error('auth_token was not set in the response');
} else {
await Lbryio.overrides.setAuthToken(userResponse.auth_token);
}
return userResponse;
} catch (e) {
console.log('error', e.message);
return {
error: {
message: e.message
}
}; };
return new Promise(resolve => {
resolve(params);
});
} }
if (Lbryio.authenticationPromise === null) {
Lbryio.authenticationPromise = new Promise((resolve, reject) => {
Lbryio.getAuthToken().then(token => {
if (!token || token.length > 60) {
return false;
} // check that token works
return Lbryio.getCurrentUser().then(user => user).catch(error => {
if (error === INTERNAL_APIS_DOWN) {
throw new Error('Internal APIS down');
}
return false;
});
}).then(user => {
if (user) {
return user;
}
return lbryRedux.Lbry.status().then(status => new Promise((res, rej) => {
const appId = domain && domain !== 'lbry.tv' ? (domain.replace(/[.]/gi, '') + status.installation_id).slice(0, 66) : status.installation_id;
Lbryio.call('user', 'new', {
auth_token: '',
language: language || 'en',
app_id: appId
}, 'post').then(response => {
if (!response.auth_token) {
throw new Error('auth_token was not set in the response');
}
const {
store
} = window;
if (Lbryio.overrides.setAuthToken) {
Lbryio.overrides.setAuthToken(response.auth_token);
}
if (store) {
store.dispatch({
type: GENERATE_AUTH_TOKEN_SUCCESS,
data: {
authToken: response.auth_token
}
});
}
Lbryio.authToken = response.auth_token;
return res(response);
}).catch(error => rej(error));
})).then(newUser => {
if (!newUser) {
return Lbryio.getCurrentUser();
}
return newUser;
});
}).then(resolve, reject);
});
}
return Lbryio.authenticationPromise;
}; };
Lbryio.getStripeToken = () => Lbryio.CONNECTION_STRING.startsWith('http://localhost:') ? 'pk_test_NoL1JWL7i1ipfhVId5KfDZgo' : 'pk_live_e8M4dRNnCCbmpZzduEUZBgJO'; Lbryio.getStripeToken = () => Lbryio.CONNECTION_STRING.startsWith('http://localhost:') ? 'pk_test_NoL1JWL7i1ipfhVId5KfDZgo' : 'pk_live_e8M4dRNnCCbmpZzduEUZBgJO';

299
dist/bundle.js vendored
View file

@ -499,11 +499,14 @@ var REFERRER_NOT_FOUND = 'A lbry.tv account could not be found for the referrer
"use strict"; "use strict";
__webpack_require__.r(__webpack_exports__); __webpack_require__.r(__webpack_exports__);
/* harmony import */ var constants_action_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); /* harmony import */ var lbry_redux__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var lbry_redux__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5); /* harmony import */ var lbry_redux__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lbry_redux__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lbry_redux__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(lbry_redux__WEBPACK_IMPORTED_MODULE_1__); /* harmony import */ var querystring__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var querystring__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); /* harmony import */ var querystring__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(querystring__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var querystring__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(querystring__WEBPACK_IMPORTED_MODULE_2__); function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
@ -512,7 +515,6 @@ function _defineProperty(obj, key, value) { if (key in obj) { Object.definePrope
var Lbryio = { var Lbryio = {
enabled: true, enabled: true,
authenticationPromise: null, authenticationPromise: null,
@ -521,7 +523,8 @@ var Lbryio = {
CONNECTION_STRING: 'https://api.lbry.com/' CONNECTION_STRING: 'https://api.lbry.com/'
}; };
var EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000; var EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000;
var INTERNAL_APIS_DOWN = 'internal_apis_down'; // We can't use env's because they aren't passed into node_modules var INTERNAL_APIS_DOWN = 'internal_apis_down';
Lbryio.fetchingUser = false; // We can't use env's because they aren't passed into node_modules
Lbryio.setLocalApi = function (endpoint) { Lbryio.setLocalApi = function (endpoint) {
Lbryio.CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end; Lbryio.CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end;
@ -567,10 +570,29 @@ Lbryio.call = function (resource, action) {
return fetch(url, options).then(checkAndParse); return fetch(url, options).then(checkAndParse);
} }
return Lbryio.getAuthToken().then(function (token) { return Lbryio.getTokens().then(function (tokens) {
var fullParams = _objectSpread({ // TOKENS = { auth_token, access_token }
auth_token: token var fullParams = _objectSpread({}, params);
}, params);
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}; // TODO refactor this
// Send both tokens to userMe
// delete auth token after success
if (action === 'me') {
// when we support transition from auth to access, bring this in
// if (tokens && tokens.access_token) {
// headers.Authorization = `Bearer ${tokens.access_token}`;
// }
if (tokens && tokens.auth_token) {
fullParams.auth_token = tokens.auth_token;
}
} else if (tokens && tokens.access_token) {
headers.Authorization = "Bearer ".concat(tokens.access_token);
} else {
fullParams.auth_token = tokens.auth_token;
}
Object.keys(fullParams).forEach(function (key) { Object.keys(fullParams).forEach(function (key) {
var value = fullParams[key]; var value = fullParams[key];
@ -579,7 +601,7 @@ Lbryio.call = function (resource, action) {
fullParams[key] = JSON.stringify(value); fullParams[key] = JSON.stringify(value);
} }
}); });
var qs = querystring__WEBPACK_IMPORTED_MODULE_2___default.a.stringify(fullParams); var qs = querystring__WEBPACK_IMPORTED_MODULE_1___default.a.stringify(fullParams);
var url = "".concat(Lbryio.CONNECTION_STRING).concat(resource, "/").concat(action, "?").concat(qs); var url = "".concat(Lbryio.CONNECTION_STRING).concat(resource, "/").concat(action, "?").concat(qs);
var options = { var options = {
method: 'GET' method: 'GET'
@ -602,122 +624,177 @@ Lbryio.call = function (resource, action) {
}); });
}; };
Lbryio.authToken = null;
Lbryio.getAuthToken = function () { Lbryio.getAuthToken = function () {
return new Promise(function (resolve) { return new Promise(function (resolve) {
if (Lbryio.authToken) { Lbryio.overrides.getAuthToken().then(function (token) {
resolve(Lbryio.authToken); resolve(token);
} else if (Lbryio.overrides.getAuthToken) { });
Lbryio.overrides.getAuthToken().then(function (token) {
resolve(token);
});
} else if (typeof window !== 'undefined') {
var _window = window,
store = _window.store;
if (store) {
var state = store.getState();
var token = state.auth ? state.auth.authToken : null;
Lbryio.authToken = token;
resolve(token);
}
resolve(null);
} else {
resolve(null);
}
}); });
}; };
Lbryio.getCurrentUser = function () { Lbryio.getTokens = function () {
return Lbryio.call('user', 'me'); return new Promise(function (resolve) {
Lbryio.overrides.getTokens().then(function (tokens) {
resolve(tokens);
});
});
}; };
Lbryio.authenticate = function (domain, language) { Lbryio.deleteAuthToken = function () {
if (!Lbryio.enabled) { return new Promise(function (resolve) {
var params = { Lbryio.overrides.deleteAuthToken().then(function () {
id: 1, resolve(true);
primary_email: 'disabled@lbry.io',
has_verified_email: true,
is_identity_verified: true,
is_reward_approved: false,
language: language || 'en'
};
return new Promise(function (resolve) {
resolve(params);
}); });
} });
};
if (Lbryio.authenticationPromise === null) { Lbryio.fetchCurrentUser = function () {
Lbryio.authenticationPromise = new Promise(function (resolve, reject) { return Lbryio.call('user', 'me')["catch"](function (e) {
Lbryio.getAuthToken().then(function (token) { return {
if (!token || token.length > 60) { error: {
return false; message: e.message
} // check that token works }
};
});
};
Lbryio.fetchUser =
/*#__PURE__*/
function () {
var _ref = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(domain, language) {
var user, tokens;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (Lbryio.fetchingUser) {
_context.next = 19;
break;
}
return Lbryio.getCurrentUser().then(function (user) { Lbryio.fetchingUser = true;
return user; _context.next = 4;
})["catch"](function (error) { return Lbryio.getTokens(domain, language);
if (error === INTERNAL_APIS_DOWN) {
throw new Error('Internal APIS down');
}
return false; case 4:
}); tokens = _context.sent;
}).then(function (user) {
if (user) { if (!(!tokens.auth_token && !tokens.access_token)) {
return user; _context.next = 11;
break;
}
_context.next = 8;
return Lbryio.fetchNewUser();
case 8:
user = _context.sent;
_context.next = 14;
break;
case 11:
_context.next = 13;
return Lbryio.fetchCurrentUser();
case 13:
user = _context.sent;
case 14:
if (!tokens.access_token) {
_context.next = 18;
break;
}
if (!tokens.auth_token) {
_context.next = 18;
break;
}
_context.next = 18;
return Lbryio.deleteAuthToken();
case 18:
return _context.abrupt("return", user);
case 19:
case "end":
return _context.stop();
} }
}
}, _callee);
}));
return lbry_redux__WEBPACK_IMPORTED_MODULE_1__["Lbry"].status().then(function (status) { return function (_x, _x2) {
return new Promise(function (res, rej) { return _ref.apply(this, arguments);
var appId = domain && domain !== 'lbry.tv' ? (domain.replace(/[.]/gi, '') + status.installation_id).slice(0, 66) : status.installation_id; };
Lbryio.call('user', 'new', { }();
Lbryio.fetchNewUser =
/*#__PURE__*/
function () {
var _ref2 = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(domain, language) {
var status, appId, userResponse;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.prev = 0;
_context2.next = 3;
return lbry_redux__WEBPACK_IMPORTED_MODULE_0__["Lbry"].status();
case 3:
status = _context2.sent;
appId = domain && domain !== 'lbry.tv' ? (domain.replace(/[.]/gi, '') + status.installation_id).slice(0, 66) : status.installation_id;
_context2.next = 7;
return Lbryio.call('user', 'new', {
auth_token: '', auth_token: '',
language: language || 'en', language: language || 'en',
app_id: appId app_id: appId
}, 'post').then(function (response) { }, 'post');
if (!response.auth_token) {
throw new Error('auth_token was not set in the response'); case 7:
userResponse = _context2.sent;
if (userResponse.auth_token) {
_context2.next = 12;
break;
}
throw new Error('auth_token was not set in the response');
case 12:
_context2.next = 14;
return Lbryio.overrides.setAuthToken(userResponse.auth_token);
case 14:
return _context2.abrupt("return", userResponse);
case 17:
_context2.prev = 17;
_context2.t0 = _context2["catch"](0);
console.log('error', _context2.t0.message);
return _context2.abrupt("return", {
error: {
message: _context2.t0.message
} }
var _window2 = window,
store = _window2.store;
if (Lbryio.overrides.setAuthToken) {
Lbryio.overrides.setAuthToken(response.auth_token);
}
if (store) {
store.dispatch({
type: constants_action_types__WEBPACK_IMPORTED_MODULE_0__["GENERATE_AUTH_TOKEN_SUCCESS"],
data: {
authToken: response.auth_token
}
});
}
Lbryio.authToken = response.auth_token;
return res(response);
})["catch"](function (error) {
return rej(error);
}); });
});
}).then(function (newUser) {
if (!newUser) {
return Lbryio.getCurrentUser();
}
return newUser; case 21:
}); case "end":
}).then(resolve, reject); return _context2.stop();
}); }
} }
}, _callee2, null, [[0, 17]]);
}));
return Lbryio.authenticationPromise; return function (_x3, _x4) {
}; return _ref2.apply(this, arguments);
};
}();
Lbryio.getStripeToken = function () { Lbryio.getStripeToken = function () {
return Lbryio.CONNECTION_STRING.startsWith('http://localhost:') ? 'pk_test_NoL1JWL7i1ipfhVId5KfDZgo' : 'pk_live_e8M4dRNnCCbmpZzduEUZBgJO'; return Lbryio.CONNECTION_STRING.startsWith('http://localhost:') ? 'pk_test_NoL1JWL7i1ipfhVId5KfDZgo' : 'pk_live_e8M4dRNnCCbmpZzduEUZBgJO';
@ -726,10 +803,10 @@ Lbryio.getStripeToken = function () {
Lbryio.getExchangeRates = function () { Lbryio.getExchangeRates = function () {
if (!Lbryio.exchangeLastFetched || Date.now() - Lbryio.exchangeLastFetched > EXCHANGE_RATE_TIMEOUT) { if (!Lbryio.exchangeLastFetched || Date.now() - Lbryio.exchangeLastFetched > EXCHANGE_RATE_TIMEOUT) {
Lbryio.exchangePromise = new Promise(function (resolve, reject) { Lbryio.exchangePromise = new Promise(function (resolve, reject) {
Lbryio.call('lbc', 'exchange_rate', {}, 'get', true).then(function (_ref) { Lbryio.call('lbc', 'exchange_rate', {}, 'get', true).then(function (_ref3) {
var LBC_USD = _ref.lbc_usd, var LBC_USD = _ref3.lbc_usd,
LBC_BTC = _ref.lbc_btc, LBC_BTC = _ref3.lbc_btc,
BTC_USD = _ref.btc_usd; BTC_USD = _ref3.btc_usd;
var rates = { var rates = {
LBC_USD: LBC_USD, LBC_USD: LBC_USD,
LBC_BTC: LBC_BTC, LBC_BTC: LBC_BTC,

View file

@ -1,4 +1,3 @@
import * as ACTIONS from 'constants/action_types';
import { Lbry } from 'lbry-redux'; import { Lbry } from 'lbry-redux';
import querystring from 'querystring'; import querystring from 'querystring';
@ -13,6 +12,7 @@ const Lbryio = {
const EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000; const EXCHANGE_RATE_TIMEOUT = 20 * 60 * 1000;
const INTERNAL_APIS_DOWN = 'internal_apis_down'; const INTERNAL_APIS_DOWN = 'internal_apis_down';
Lbryio.fetchingUser = false;
// We can't use env's because they aren't passed into node_modules // We can't use env's because they aren't passed into node_modules
Lbryio.setLocalApi = endpoint => { Lbryio.setLocalApi = endpoint => {
Lbryio.CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end; Lbryio.CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end;
@ -53,8 +53,30 @@ Lbryio.call = (resource, action, params = {}, method = 'get') => {
return fetch(url, options).then(checkAndParse); return fetch(url, options).then(checkAndParse);
} }
return Lbryio.getAuthToken().then(token => { return Lbryio.getTokens().then(tokens => {
const fullParams = { auth_token: token, ...params }; // TOKENS = { auth_token, access_token }
const fullParams = { ...params };
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
// TODO refactor this
// Send both tokens to userMe
// delete auth token after success
if (action === 'me') {
// when we support transition from auth to access, bring this in
// if (tokens && tokens.access_token) {
// headers.Authorization = `Bearer ${tokens.access_token}`;
// }
if (tokens && tokens.auth_token) {
fullParams.auth_token = tokens.auth_token;
}
} else if (tokens && tokens.access_token) {
headers.Authorization = `Bearer ${tokens.access_token}`;
} else {
fullParams.auth_token = tokens.auth_token;
}
Object.keys(fullParams).forEach(key => { Object.keys(fullParams).forEach(key => {
const value = fullParams[key]; const value = fullParams[key];
if (typeof value === 'object') { if (typeof value === 'object') {
@ -84,125 +106,76 @@ Lbryio.call = (resource, action, params = {}, method = 'get') => {
}); });
}; };
Lbryio.authToken = null;
Lbryio.getAuthToken = () => Lbryio.getAuthToken = () =>
new Promise(resolve => { new Promise(resolve => {
if (Lbryio.authToken) { Lbryio.overrides.getAuthToken().then(token => {
resolve(Lbryio.authToken); resolve(token);
} else if (Lbryio.overrides.getAuthToken) { });
Lbryio.overrides.getAuthToken().then(token => {
resolve(token);
});
} else if (typeof window !== 'undefined') {
const { store } = window;
if (store) {
const state = store.getState();
const token = state.auth ? state.auth.authToken : null;
Lbryio.authToken = token;
resolve(token);
}
resolve(null);
} else {
resolve(null);
}
}); });
Lbryio.getCurrentUser = () => Lbryio.call('user', 'me'); Lbryio.getTokens = () =>
new Promise(resolve => {
Lbryio.authenticate = (domain, language) => { Lbryio.overrides.getTokens().then(tokens => {
if (!Lbryio.enabled) { resolve(tokens);
const params = {
id: 1,
primary_email: 'disabled@lbry.io',
has_verified_email: true,
is_identity_verified: true,
is_reward_approved: false,
language: language || 'en',
};
return new Promise(resolve => {
resolve(params);
}); });
} });
if (Lbryio.authenticationPromise === null) { Lbryio.deleteAuthToken = () =>
Lbryio.authenticationPromise = new Promise((resolve, reject) => { new Promise(resolve => {
Lbryio.getAuthToken() Lbryio.overrides.deleteAuthToken().then(() => {
.then(token => { resolve(true);
if (!token || token.length > 60) {
return false;
}
// check that token works
return Lbryio.getCurrentUser()
.then(user => user)
.catch(error => {
if (error === INTERNAL_APIS_DOWN) {
throw new Error('Internal APIS down');
}
return false;
});
})
.then(user => {
if (user) {
return user;
}
return Lbry.status()
.then(
status =>
new Promise((res, rej) => {
const appId =
domain && domain !== 'lbry.tv'
? (domain.replace(/[.]/gi, '') + status.installation_id).slice(0, 66)
: status.installation_id;
Lbryio.call(
'user',
'new',
{
auth_token: '',
language: language || 'en',
app_id: appId,
},
'post'
)
.then(response => {
if (!response.auth_token) {
throw new Error('auth_token was not set in the response');
}
const { store } = window;
if (Lbryio.overrides.setAuthToken) {
Lbryio.overrides.setAuthToken(response.auth_token);
}
if (store) {
store.dispatch({
type: ACTIONS.GENERATE_AUTH_TOKEN_SUCCESS,
data: { authToken: response.auth_token },
});
}
Lbryio.authToken = response.auth_token;
return res(response);
})
.catch(error => rej(error));
})
)
.then(newUser => {
if (!newUser) {
return Lbryio.getCurrentUser();
}
return newUser;
});
})
.then(resolve, reject);
}); });
} });
return Lbryio.authenticationPromise; Lbryio.fetchCurrentUser = () =>
Lbryio.call('user', 'me').catch(e => ({ error: { message: e.message } }));
Lbryio.fetchUser = async (domain, language) => {
if (!Lbryio.fetchingUser) {
let user;
Lbryio.fetchingUser = true;
const tokens = await Lbryio.getTokens(domain, language);
if (!tokens.auth_token && !tokens.access_token) {
user = await Lbryio.fetchNewUser();
} else {
user = await Lbryio.fetchCurrentUser();
}
if (tokens.access_token) {
if (tokens.auth_token) {
await Lbryio.deleteAuthToken();
}
}
return user;
}
};
Lbryio.fetchNewUser = async (domain, language) => {
try {
const status = await Lbry.status();
const appId =
domain && domain !== 'lbry.tv'
? (domain.replace(/[.]/gi, '') + status.installation_id).slice(0, 66)
: status.installation_id;
const userResponse = await Lbryio.call(
'user',
'new',
{
auth_token: '',
language: language || 'en',
app_id: appId,
},
'post'
);
if (!userResponse.auth_token) {
throw new Error('auth_token was not set in the response');
} else {
await Lbryio.overrides.setAuthToken(userResponse.auth_token);
}
return userResponse;
} catch (e) {
console.log('error', e.message);
return { error: { message: e.message } };
}
}; };
Lbryio.getStripeToken = () => Lbryio.getStripeToken = () =>