fsl-js-sdk
Version:
sdk for web
369 lines (368 loc) • 18.6 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = void 0;
var auth_1 = require("firebase/auth");
var app_1 = require("firebase/app");
var utils_1 = require("../../utils");
var api_1 = require("../../api");
var LoginBase = /** @class */ (function () {
function LoginBase(options) {
this.refresh = false;
this.googleProvider = new auth_1.GoogleAuthProvider();
var refresh = options.refresh, googleOptions = options.googleOptions, appleOptions = options.appleOptions, cloudOptions = options.cloudOptions, googleCloudOptions = options.googleCloudOptions, platform = options.platform;
this.refresh = refresh;
this.googleOptions = googleOptions;
this.appleOptions = appleOptions;
this.cloudOptions = cloudOptions;
this.googleCloudOptions = googleCloudOptions;
this.platform = platform || '';
this._googleApp = (0, app_1.initializeApp)(googleOptions);
this.auth = (0, auth_1.getAuth)();
this.initAppleEnvironment();
}
LoginBase.init = function (options) {
var urlParams = new URLSearchParams(window.location.search);
var refresh = (urlParams.get('refresh') && true) || false;
return new LoginBase(__assign(__assign({}, options), { refresh: refresh }));
};
LoginBase.prototype.checkHasLogin = function () {
return __awaiter(this, void 0, void 0, function () {
var data, _err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.refresh) {
return [2 /*return*/, null];
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, (0, api_1.getUserInfo)()];
case 2:
data = (_a.sent());
return [2 /*return*/, data];
case 3:
_err_1 = _a.sent();
return [2 /*return*/, null];
case 4: return [2 /*return*/];
}
});
});
};
LoginBase.prototype.initAppleEnvironment = function () {
var _a = this.appleOptions, clientId = _a.clientId, scope = _a.scope, redirectURI = _a.redirectURI, state = _a.state, usePopup = _a.usePopup;
return (0, utils_1.loadScript)('https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js', { async: true }).then(function () {
window.AppleID.auth.init({
clientId: clientId,
scope: scope || 'name email',
redirectURI: redirectURI,
state: state || 'state',
usePopup: usePopup,
});
});
};
LoginBase.prototype.initAppleCloudEnvironment = function () {
var _this = this;
var _a = this.cloudOptions, apiToken = _a.apiToken, container = _a.container, _b = _a.environment, environment = _b === void 0 ? 'production' : _b, _c = _a.databaseName, databaseName = _c === void 0 ? 'private' : _c;
var handleAppleLoaded = function () { return __awaiter(_this, void 0, void 0, function () {
var handleCloud;
return __generator(this, function (_a) {
handleCloud = function () {
window.CloudKit.configure({
containers: [
{
containerIdentifier: container,
apiTokenAuth: {
apiToken: apiToken,
persist: true,
},
environment: environment,
},
],
});
};
window.removeEventListener('cloudkitloaded', handleCloud);
window.addEventListener('cloudkitloaded', handleCloud);
// return iCloudProxy([
// 'get',
// `https://api.apple-cloudkit.com/database/1/${container}/${environment}/${databaseName}/users/current?ckAPIToken=${apiToken}`, // ${process.env.NODE_ENV}
// ]).catch((err: any) => {
// console.log('cloud err', err);
// });
return [2 /*return*/, fetch("https://api.apple-cloudkit.com/database/1/".concat(container, "/").concat(environment, "/").concat(databaseName, "/users/current?ckAPIToken=").concat(apiToken))
.then(function (res) { return res.json(); })
.catch(function (err) {
console.log('cloud err', err);
return err;
})];
});
}); };
if (window.CloudKit) {
return handleAppleLoaded();
}
return (0, utils_1.loadScript)('https://cdn.apple-cloudkit.com/ck/2/cloudkit.js', {
async: true,
}).then(handleAppleLoaded);
};
LoginBase.prototype.initGoogleCloudEnvironment = function () {
var _this = this;
// Discovery doc URL for APIs used by the quickstart
var DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/drive.file';
var _a = this.googleCloudOptions, clientId = _a.clientId, _b = _a.scopes, scopes = _b === void 0 ? SCOPES : _b, _c = _a.discoveryDoc, discoveryDoc = _c === void 0 ? DISCOVERY_DOC : _c, apiKey = _a.apiKey;
if (window.google) {
gapi.load('client', function () { return __awaiter(_this, void 0, void 0, function () {
var discoveryDoc;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch(DISCOVERY_DOC).then(function (r) { return r.json(); })];
case 1:
discoveryDoc = _a.sent();
return [4 /*yield*/, gapi.client.load(discoveryDoc)];
case 2:
_a.sent();
return [2 /*return*/];
}
});
}); });
this.tokenClient = window.google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: scopes,
});
return;
}
return Promise.all([
(0, utils_1.loadScript)('https://apis.google.com/js/api.js', {
async: true,
}),
(0, utils_1.loadScript)('https://accounts.google.com/gsi/client', {
async: true,
}),
]).then(function () {
return new Promise(function (resolve) {
gapi.load('client', function () { return __awaiter(_this, void 0, void 0, function () {
var discoveryDoc;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, fetch(DISCOVERY_DOC).then(function (r) { return r.json(); })];
case 1:
discoveryDoc = _a.sent();
return [4 /*yield*/, gapi.client.load(discoveryDoc)];
case 2:
_a.sent();
resolve(true);
return [2 /*return*/];
}
});
}); });
_this.tokenClient = window.google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: scopes,
});
});
});
};
LoginBase.prototype.loginGoogleCloud = function () {
var _this = this;
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/drive.file';
var _a = this.googleCloudOptions, clientId = _a.clientId, _b = _a.scopes, scopes = _b === void 0 ? SCOPES : _b;
return new Promise(function (resolve) {
var token = gapi.client.getToken();
var accessToken = token === null || token === void 0 ? void 0 : token.access_token;
if (!accessToken) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
if (!_this.tokenClient) {
_this.tokenClient = window.google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: scopes,
});
}
_this.tokenClient.callback = function () {
var token = gapi.client.getToken();
var accessToken = token.access_token;
resolve(accessToken);
};
_this.tokenClient.requestAccessToken({ prompt: 'consent' });
}
else {
resolve(accessToken);
}
});
};
LoginBase.prototype.handleLogin = function (_a) {
var type = _a.type, data = _a.data;
return __awaiter(this, void 0, void 0, function () {
var _b, email, code, _c, email, code, data_1, authorization, id_token, error_1;
var _this = this;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
if (!(type === 'FSL')) return [3 /*break*/, 1];
_b = data || {}, email = _b.email, code = _b.code;
return [2 /*return*/, (0, api_1.loginByPassword)([email, code, this.platform])];
case 1:
if (!(type === '2FA')) return [3 /*break*/, 2];
_c = data || {}, email = _c.email, code = _c.code;
return [2 /*return*/, (0, api_1.loginBy2FA)([email, code, this.platform])];
case 2:
if (!(type === 'GOOGLE')) return [3 /*break*/, 3];
// Google login
return [2 /*return*/, (0, auth_1.signInWithPopup)(this.auth, this.googleProvider)
.then(function (result) {
if (result) {
var credential = auth_1.GoogleAuthProvider.credentialFromResult(result);
var _a = (credential || {}).idToken, idToken = _a === void 0 ? '' : _a;
return (0, api_1.loginByGoogle)([idToken, _this.platform]);
}
})
.catch(function (err) {
if (err && (err.message || err.msg).indexOf('popup-blocked') > -1) {
return Promise.reject({ error: 403, msg: 'popup_blocked' });
}
return Promise.reject(err);
})];
case 3:
if (!(type === 'APPLE')) return [3 /*break*/, 7];
_d.label = 4;
case 4:
_d.trys.push([4, 6, , 7]);
return [4 /*yield*/, window.AppleID.auth.signIn()];
case 5:
data_1 = _d.sent();
authorization = data_1.authorization;
id_token = authorization.id_token;
// const { clientId, clientSecret, redirectURI } = this.appleOptions;
// const { access_token } = await getAppleAuthToken([
// clientId,
// clientSecret,
// code,
// 'authorization_code',
// redirectURI,
// id_token,
// ]);
return [2 /*return*/, (0, api_1.loginByAppleID)([id_token, this.platform])];
case 6:
error_1 = _d.sent();
// Handle error.
if (error_1 && error_1.error.indexOf('popup_blocked') > -1) {
return [2 /*return*/, Promise.reject({ error: 403, msg: 'popup_blocked' })];
}
return [2 /*return*/, Promise.reject(error_1)];
case 7: return [2 /*return*/];
}
});
});
};
LoginBase.prototype.sendSms = function (email) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, (0, api_1.sendSms)([email, this.platform])];
});
});
};
LoginBase.prototype.getBindQrCode = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, (0, api_1.getBindQrCode)()];
});
});
};
LoginBase.prototype.doCodeCheck = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, (0, api_1.doCodeCheck)(data)];
});
});
};
LoginBase.prototype.getFilePwdMsg = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, (0, api_1.getFilePwdMsg)(data)];
});
});
};
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "checkHasLogin", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "initAppleCloudEnvironment", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "loginGoogleCloud", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "handleLogin", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "sendSms", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "getBindQrCode", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "doCodeCheck", null);
__decorate([
utils_1.addNotifyFunction
], LoginBase.prototype, "getFilePwdMsg", null);
return LoginBase;
}());
exports.default = LoginBase;