@arc-publishing/sdk-identity
Version:
JS Identity SDK for working with Identity API
80 lines • 3.15 kB
JavaScript
import { __awaiter, __extends, __generator } from "tslib";
import JSONResponseHandler from '../serviceHelpers/JSONResponseHandler';
import Identity from './identity';
import { isUserIdentity } from './userIdentity';
import { headers, logPrefix } from './constants';
import enforceRecaptcha, { RecaptchaMethod } from '../utils/enforceRecaptcha';
import { isJwtExpired, jwtHasExp } from '../utils/jwt';
export default function login(userName, password, options) {
if (options === void 0) { options = {}; }
Identity._isSession = !options.rememberMe;
return enforceRecaptcha(RecaptchaMethod.SIGN_IN, options.recaptchaToken)
.then(function () {
return fetch("".concat(Identity.apiOrigin, "/identity/public/v1/auth/login").concat(options.cookie ? '?cookie=true' : ''), {
method: 'POST',
headers: headers,
body: JSON.stringify({
userName: userName,
credentials: password,
grantType: 'password',
rememberMe: options.rememberMe,
recaptchaToken: options.recaptchaToken
})
});
})
.then(JSONResponseHandler)
.then(function (json) {
if (isUserIdentity(json)) {
Identity.userIdentity = json;
window.postMessage({ type: 'ARC_LOGIN_SUCCESS', grantType: 'password' }, '*');
return Identity.userIdentity;
}
else {
throw json;
}
});
}
var HttpError = (function (_super) {
__extends(HttpError, _super);
function HttpError(code, message) {
var _this = _super.call(this, message) || this;
_this.name = 'HttpError';
_this.code = code;
return _this;
}
return HttpError;
}(Error));
export function isLoggedIn() {
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(!Identity.userIdentity ||
!Identity.userIdentity.accessToken ||
!Identity.userIdentity.refreshToken)) return [3, 1];
return [2, false];
case 1:
if (!(isJwtExpired(Identity.userIdentity.accessToken) ||
!jwtHasExp(Identity.userIdentity.accessToken))) return [3, 6];
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4, Identity.extendSession()];
case 3:
_a.sent();
return [2, true];
case 4:
e_1 = _a.sent();
if (e_1 instanceof HttpError) {
console.warn("".concat(logPrefix, " code:\"").concat(e_1.code, "\", message:\"").concat(e_1.message, "\""));
}
return [2, false];
case 5: return [3, 7];
case 6: return [2, true];
case 7: return [2];
}
});
});
}
//# sourceMappingURL=login.js.map