@stackend/api
Version:
JS bindings to api.stackend.com
652 lines • 22.2 kB
JavaScript
;
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 __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a, _b;
Object.defineProperty(exports, "__esModule", { value: true });
exports.listOnline = exports.setBlocked = exports.listAuthenticationOptions = exports.isPasswordAcceptable = exports.getStatistics = exports.registerUser = exports.verifyEmail = exports.sendVerificationEmail = exports.registerOAuth2User = exports.registerGoogleUser = exports.removeGoogleReference = exports.removeFacebookReference = exports.registerFacebookUser = exports.getFacebookRegistrationData = exports.isAliasFree = exports.isEmailFree = exports.getUserFeedUrl = exports.removeProfileImage = exports.setProfileImage = exports.search = exports.getUserPrivileges = exports.storeUser = exports.getMutableUser = exports.getUsers = exports.getUser = exports.hasElevatedPrivilege = exports.getProfileLink = exports.getProfilePageUrl = exports.getCurrentUser = exports.OrderBy = exports.COMPONENT_CLASS = exports.COMPONENT_NAME = exports.CONTEXT = exports.Gender = exports.GenderId = exports.getStatusName = exports.Status = exports.TYPE_USER = void 0;
var api_1 = require("../api");
var Order_1 = require("../api/Order");
var login_1 = require("../login");
var get_1 = __importDefault(require("lodash/get"));
exports.TYPE_USER = 'net.josh.community.user.backend.xcap.XcapUser';
/**
* User status
* @type {{OK: number, NOT_VERIFIED: number, BLOCKED: number, DELETED_BY_USER: number, DELETED_BY_ADMIN: number}}
*/
var Status;
(function (Status) {
Status[Status["OK"] = 0] = "OK";
Status[Status["NOT_VERIFIED"] = 5] = "NOT_VERIFIED";
Status[Status["BLOCKED"] = 10] = "BLOCKED";
Status[Status["DELETED_BY_USER"] = 15] = "DELETED_BY_USER";
Status[Status["DELETED_BY_ADMIN"] = 20] = "DELETED_BY_ADMIN";
})(Status = exports.Status || (exports.Status = {}));
var STATUS_NAMES = (_a = {},
_a[Status.BLOCKED] = 'Blocked',
_a[Status.DELETED_BY_ADMIN] = 'Deleted by admin',
_a[Status.DELETED_BY_USER] = 'Deleted',
_a[Status.NOT_VERIFIED] = 'Not verified',
_a[Status.OK] = 'OK',
_a);
/**
* Get a human readable form of the status
* @param statusId
* @returns string
*/
function getStatusName(statusId) {
if (typeof statusId === 'undefined') {
return '?';
}
return STATUS_NAMES[statusId] || '?';
}
exports.getStatusName = getStatusName;
/**
* Gender
*/
var GenderId;
(function (GenderId) {
GenderId[GenderId["UNKNOWN"] = 0] = "UNKNOWN";
GenderId[GenderId["FEMALE"] = 1] = "FEMALE";
GenderId[GenderId["MALE"] = 2] = "MALE";
})(GenderId = exports.GenderId || (exports.GenderId = {}));
/**
* Gender constants
*/
exports.Gender = {
UNKNOWN: 'UNKNOWN',
FEMALE: 'FEMALE',
MALE: 'MALE',
// TODO: Better alternative? Typescript does not support functions in enums like java
getByGenderId: function (id) {
switch (id) {
case GenderId.FEMALE:
return exports.Gender.FEMALE;
case GenderId.MALE:
return exports.Gender.MALE;
default:
return exports.Gender.UNKNOWN;
}
},
getGenderId: function (gender) {
switch (gender) {
case exports.Gender.FEMALE:
return GenderId.FEMALE;
case exports.Gender.MALE:
return GenderId.MALE;
default:
return GenderId.UNKNOWN;
}
}
};
/**
* User context-type
* @type {string}
*/
exports.CONTEXT = 'members';
/**
* User Component name
* @type {string}
*/
exports.COMPONENT_NAME = 'user';
/**
* User manager component class
* @type {string}
*/
exports.COMPONENT_CLASS = 'net.josh.community.user.UserManager';
/**
* Sort order for user search
*/
var OrderBy;
(function (OrderBy) {
OrderBy["ALIAS"] = "ALIAS";
OrderBy["CREATED"] = "CREATED";
OrderBy["CITY"] = "CITY";
OrderBy["AGE"] = "AGE";
OrderBy["LAST_LOGIN"] = "LAST_LOGIN";
OrderBy["GENDER"] = "GENDER";
OrderBy["LAST_MODIFIED"] = "LAST_MODIFIED";
OrderBy["STATUS"] = "STATUS";
})(OrderBy = exports.OrderBy || (exports.OrderBy = {}));
/**
* Get the current user in the current community, or null if not authorized.
* This involves a server request.
* @see index.ts:getCurrentStackendUser()
* @return {Thunk}
*/
function getCurrentUser() {
// TODO: Implement caching here
return (0, api_1.getJson)({
url: '/user/get',
componentName: exports.COMPONENT_NAME,
context: exports.CONTEXT
});
}
exports.getCurrentUser = getCurrentUser;
/**
* Construct a link to a users profile page.
* @param request
* @param userId
* @param userName
* @param absolute
*/
function getProfilePageUrl(_a) {
var request = _a.request, userId = _a.userId, userName = _a.userName, absolute = _a.absolute;
return (0, api_1.createCommunityUrl)({
request: request,
path: "/user/".concat(userId, "/").concat(encodeURIComponent(userName)),
absolute: absolute
});
}
exports.getProfilePageUrl = getProfilePageUrl;
/**
* Construct a link to a users profile page, supports remote profile links as well as local
* @param request
* @param user
* @param community
*/
function getProfileLink(request, user, community) {
var useRemoteProfileLink = (0, get_1.default)(community, 'settings.useRemoteProfileLink', false);
var profileLink = null;
var isRemote = false;
if (useRemoteProfileLink && user.profile && user.profile.remoteProfileUrl) {
profileLink = user.profile.remoteProfileUrl;
isRemote = true;
}
if (!profileLink) {
profileLink = getProfilePageUrl({
request: request,
userId: user.id,
userName: user.userName
});
}
return {
url: profileLink,
isRemote: isRemote
};
}
exports.getProfileLink = getProfileLink;
/**
* Check if the current user has elevated privileges (does not include rules etc).
*
* @param currentUser
* @param componentContext {String} Context name, for example "members", "news", "cms"
* @param componentClass {String} Component, for example "net.josh.community.user.UserManager", "net.josh.community.blog.BlogManager",
* "se.josh.xcap.cms.CmsManager", "net.josh.community.forum.ForumManager"
* @param privilegeTypeId {number} Minimum required privilege
*/
function hasElevatedPrivilege(currentUser, componentContext, componentClass, privilegeTypeId) {
if (!currentUser) {
return false;
}
var privs = null;
if (typeof currentUser.privileges !== 'undefined') {
privs = currentUser.privileges;
}
else if (currentUser.user) {
var user = currentUser.user;
if (!user) {
return false;
}
privs = user.privileges;
}
if (typeof privs === 'undefined' || !privs) {
return false;
}
var prefix = componentContext + ',' + componentClass;
for (var i = 0; i < privs.length; i++) {
var p = privs[i];
if (!p.startsWith(prefix)) {
continue;
}
var pt = parseInt(p.split(',')[2]);
if (pt >= privilegeTypeId) {
return true;
}
}
return false;
}
exports.hasElevatedPrivilege = hasElevatedPrivilege;
/**
* Get a user.
* Use id, alias to look up a user.
*
* @param id User id (required)
* @param alias User alias (optional)
* @returns {Promise}
*/
function getUser(_a) {
var id = _a.id, alias = _a.alias;
return (0, api_1.getJson)({ url: '/user/get', parameters: arguments });
}
exports.getUser = getUser;
/**
* Get multiple users by id
* @param id
* @returns {Promise}
*/
function getUsers(_a) {
var id = _a.id;
return (0, api_1.getJson)({ url: '/user/get-multiple', parameters: arguments });
}
exports.getUsers = getUsers;
/**
* Transform into a mutable user data that is accepted by store user
* @param user
*/
function getMutableUser(user) {
var birthYear = undefined, birthMonth = undefined, birthDay = undefined;
var profileEntries = (0, get_1.default)(user, 'profile', {});
if (user && user.birthDate) {
var d = new Date(user.birthDate);
birthYear = d.getFullYear();
birthMonth = d.getMonth() + 1;
birthDay = d.getDate();
}
return __assign({ id: (0, get_1.default)(user, 'id'), email: (0, get_1.default)(user, 'email'), firstName: (0, get_1.default)(user, 'firstName', ''), lastName: (0, get_1.default)(user, 'lastName', ''), gender: (0, get_1.default)(user, 'gender', GenderId.UNKNOWN), cityId: (0, get_1.default)(user, 'cityId', 0), birthYear: birthYear, birthMonth: birthMonth, birthDay: birthDay, showBirthDay: birthYear ? true : false, zipCode: (0, get_1.default)(user, 'zipCode', undefined), termsAccept: true }, profileEntries);
}
exports.getMutableUser = getMutableUser;
/**
* Store a user.
*
* All parameters except id are optional. If not present, they will not be changed.
*
* @param id
* @param alias
* @param email
* @param firstName
* @param lastName
* @param gender
* @param cityId
* @param birthYear
* @param birthMonth
* @param birthDay
* @param showBirthDay
* @param zipCode
* @param termsAccept Accept the terms and conditions
* @param profileEntries Other entries
*/
function storeUser(_a) {
var id = _a.id, alias = _a.alias, email = _a.email, firstName = _a.firstName, lastName = _a.lastName, gender = _a.gender, cityId = _a.cityId, birthYear = _a.birthYear, birthMonth = _a.birthMonth, birthDay = _a.birthDay, showBirthDay = _a.showBirthDay, zipCode = _a.zipCode, termsAccept = _a.termsAccept, profileEntries = __rest(_a, ["id", "alias", "email", "firstName", "lastName", "gender", "cityId", "birthYear", "birthMonth", "birthDay", "showBirthDay", "zipCode", "termsAccept"]);
return (0, api_1.post)({ url: '/user/store', parameters: arguments });
}
exports.storeUser = storeUser;
/**
* Get the current users privileges for a given component/context
* @param componentContext {String} Context name, for example "members", "news", "cms"
* @param componentClass {String} Component, for example "net.josh.community.user.UserManager", "net.josh.community.blog.BlogManager",
* "se.josh.xcap.cms.CmsManager", "net.josh.community.forum.ForumManager"
* @param externalTypeId {number}
* @returns {Promise}
*/
function getUserPrivileges(_a) {
var componentContext = _a.componentContext, componentClass = _a.componentClass, externalTypeId = _a.externalTypeId;
return (0, api_1.getJson)({ url: '/user/get-privileges', parameters: arguments });
}
exports.getUserPrivileges = getUserPrivileges;
var ORDER_MAPPING = (_b = {},
_b[OrderBy.ALIAS + Order_1.Order.DESCENDING] = 1,
_b[OrderBy.ALIAS + Order_1.Order.ASCENDING] = 2,
_b[OrderBy.CREATED + Order_1.Order.DESCENDING] = 3,
_b[OrderBy.CREATED + Order_1.Order.ASCENDING] = 4,
_b[OrderBy.CITY + Order_1.Order.ASCENDING] = 5,
_b[OrderBy.CITY + Order_1.Order.DESCENDING] = 6,
_b[OrderBy.AGE + Order_1.Order.ASCENDING] = 7,
_b[OrderBy.AGE + Order_1.Order.DESCENDING] = 8,
_b[OrderBy.LAST_LOGIN + Order_1.Order.ASCENDING] = 9,
_b[OrderBy.LAST_LOGIN + Order_1.Order.DESCENDING] = 10,
_b[OrderBy.GENDER + Order_1.Order.DESCENDING] = 11,
_b[OrderBy.GENDER + Order_1.Order.ASCENDING] = 12,
_b[OrderBy.LAST_MODIFIED + Order_1.Order.DESCENDING] = 13,
_b[OrderBy.STATUS + Order_1.Order.ASCENDING] = 14,
_b);
/**
* Maps order by and order to xcap values
* @param orderBy
* @param order
* @returns {number}
*/
function convertSortOrder(orderBy, order) {
var k = (orderBy || OrderBy.ALIAS) + (order || Order_1.Order.ASCENDING);
var v = ORDER_MAPPING[k];
if (v) {
return v;
}
// Order may not be supported. Try the inverted order
k = (orderBy || OrderBy.ALIAS) + (0, Order_1.invertOrder)(order || Order_1.Order.ASCENDING);
v = ORDER_MAPPING[k];
if (v) {
return v;
}
return ORDER_MAPPING[OrderBy.ALIAS + Order_1.Order.ASCENDING];
}
/**
* Search for users.
*
* @param q Serch string
* @param allowEmptySearch Will empty searches be allowed and return all matches?
* @param excludeCurrentUser Should the current user be ignored?
* @param p Page number
* @param pageSie Page size
*/
function search(_a) {
var _b = _a.q, q = _b === void 0 ? null : _b, _c = _a.allowEmptySearch, allowEmptySearch = _c === void 0 ? true : _c, _d = _a.excludeCurrentUser, excludeCurrentUser = _d === void 0 ? false : _d, _e = _a.p, p = _e === void 0 ? 1 : _e, _f = _a.pageSize, pageSize = _f === void 0 ? 10 : _f, _g = _a.orderBy, orderBy = _g === void 0 ? OrderBy.ALIAS : _g, _h = _a.order, order = _h === void 0 ? Order_1.Order.ASCENDING : _h, community = _a.community;
var sortOrder = convertSortOrder(orderBy, order);
return (0, api_1.getJson)({
url: '/user/search',
parameters: {
q: q,
allowEmptySearch: allowEmptySearch,
excludeCurrentUser: excludeCurrentUser,
p: p,
pageSize: pageSize,
orderBy: sortOrder
},
community: community
});
}
exports.search = search;
/**
* Set profile image of the current user
*
* @param imageId Image id (from the members context)
* @param community
* @returns {Promise}
*/
function setProfileImage(_a) {
var imageId = _a.imageId, community = _a.community;
return (0, api_1.post)({
url: '/user/set-profile-image',
parameters: { imageId: imageId },
community: community
});
}
exports.setProfileImage = setProfileImage;
/**
* Remove profile image of the current user
*
* @returns {Promise}
*/
function removeProfileImage(_a) {
var community = _a.community;
return (0, api_1.post)({
url: '/user/remove-profile-image',
community: community
});
}
exports.removeProfileImage = removeProfileImage;
/**
* Get the url to a users feed.
* @param userId optional, defaults to current user
* @returns {String}
*/
function getUserFeedUrl(_a) {
var userId = _a.userId;
return (0, api_1.getApiUrl)({
url: '/user/feed',
parameters: arguments
});
}
exports.getUserFeedUrl = getUserFeedUrl;
/**
* Check if the email is free for registration
* @param email
*/
function isEmailFree(_a) {
var email = _a.email;
return (0, api_1.getJson)({
url: '/user/register/is-email-free',
parameters: arguments
});
}
exports.isEmailFree = isEmailFree;
/**
* Check if the alias is free for registration
* @param email
*/
function isAliasFree(_a) {
var alias = _a.alias;
return (0, api_1.getJson)({
url: '/user/register/is-alias-free',
parameters: arguments
});
}
exports.isAliasFree = isAliasFree;
/**
* Get data needed to make a registration.
*
* @returns {Thunk<GetRegistrationDataResult>}
*/
function getFacebookRegistrationData(_a) {
return (0, api_1.getJson)({
url: '/user/register/facebook',
parameters: arguments
});
}
exports.getFacebookRegistrationData = getFacebookRegistrationData;
/**
* Submit additional information when registering a facebook user
*
* @param email
* @param username
* @param firstName
* @param lastName
* @param gender
* @param birthDate
* @param termsAccept
* @param returnUrl optional return url
* @returns {Thunk<XcapJsonResult>}
*/
function registerFacebookUser(_a) {
var email = _a.email, username = _a.username, firstName = _a.firstName, lastName = _a.lastName, gender = _a.gender, birthDate = _a.birthDate, termsAccept = _a.termsAccept, returnUrl = _a.returnUrl;
return (0, api_1.post)({
url: '/user/register/facebook/save',
parameters: arguments
});
}
exports.registerFacebookUser = registerFacebookUser;
/**
* Remove a facebook login reference
* @param facebookId
* @returns {Thunk<XcapJsonResult>}
*/
function removeFacebookReference(_a) {
var facebookId = _a.facebookId;
return (0, api_1.post)({
url: '/user/auth/facebook/remove',
parameters: arguments
});
}
exports.removeFacebookReference = removeFacebookReference;
/**
* Remove a Google login reference
* @param userReferenceId
* @returns {Thunk<XcapJsonResult>}
*/
function removeGoogleReference(_a) {
var userReferenceId = _a.userReferenceId;
return (0, api_1.post)({
url: '/user/auth/google/remove',
parameters: arguments
});
}
exports.removeGoogleReference = removeGoogleReference;
/**
* Submit additional information when registering a google user
*
* @param email
* @param username
* @param firstName
* @param lastName
* @param gender
* @param birthDate
* @param termsAccept
* @param returnUrl optional return url
* @returns {Thunk<XcapJsonResult>}
*/
function registerGoogleUser(_a) {
var email = _a.email, username = _a.username, firstName = _a.firstName, lastName = _a.lastName, gender = _a.gender, birthDate = _a.birthDate, termsAccept = _a.termsAccept, returnUrl = _a.returnUrl;
return (0, api_1.post)({
url: '/user/register/google',
parameters: arguments
});
}
exports.registerGoogleUser = registerGoogleUser;
/**
* Submit additional information when registering a OAuth2 user
*
* @param email
* @param username
* @param firstName
* @param lastName
* @param gender
* @param birthDate
* @param termsAccept
* @param returnUrl optional return url
* @returns {Thunk<XcapJsonResult>}
*/
function registerOAuth2User(_a) {
var email = _a.email, username = _a.username, firstName = _a.firstName, lastName = _a.lastName, gender = _a.gender, birthDate = _a.birthDate, termsAccept = _a.termsAccept, returnUrl = _a.returnUrl;
return (0, api_1.post)({
url: '/user/register/oauth2',
parameters: arguments
});
}
exports.registerOAuth2User = registerOAuth2User;
/**
* Send an email with a verification code link.
* This is done to validate that this is an actual email address owned by the user.
*
* @param email
* @param authenticationType
* @param returnUrl optional returnUrl to include in the mail
* @returns {Thunk<VerifyEmailResult>}
* @see verifyEmail
*/
function sendVerificationEmail(_a) {
var email = _a.email, _b = _a.authenticationType, authenticationType = _b === void 0 ? login_1.AuthenticationType.FACEBOOK : _b, returnUrl = _a.returnUrl;
return (0, api_1.post)({
url: '/user/register/send-verification-email',
parameters: arguments
});
}
exports.sendVerificationEmail = sendVerificationEmail;
/**
* Verify a user email by posting the code recieved in an email.
*
* @param email
* @param code
* @param login. Should the user be logged in on successufull verification?s
* @param returnUrl Optional return url
* @returns {Thunk<VerifyEmailResult>}
* @see sendVerificationEmail
*/
function verifyEmail(_a) {
var email = _a.email, code = _a.code, login = _a.login, returnUrl = _a.returnUrl;
return (0, api_1.post)({
url: '/user/register/verify-email',
parameters: arguments
});
}
exports.verifyEmail = verifyEmail;
/**
* Register a user using an email address.
*
* @param email
* @param username
* @param firstName
* @param lastName
* @param gender
* @param birthYear
* @param birthMonth
* @param birthDay
* @param showBirthDay
* @param termsAccept
* @param returnUrl optional return url
* @returns {Thunk<RegisterUserResult>}
*/
function registerUser(_a) {
var email = _a.email, username = _a.username, firstName = _a.firstName, lastName = _a.lastName, gender = _a.gender, birthYear = _a.birthYear, birthMonth = _a.birthMonth, birthDay = _a.birthDay, showBirthDay = _a.showBirthDay, termsAccept = _a.termsAccept, returnUrl = _a.returnUrl;
return (0, api_1.post)({
url: '/user/register/email',
parameters: arguments
});
}
exports.registerUser = registerUser;
/**
* Get activity counters for a user
* @param id
* @returns {*}
*/
function getStatistics(_a) {
var id = _a.id;
return (0, api_1.getJson)({
url: '/user/statistics',
parameters: { id: id }
});
}
exports.getStatistics = getStatistics;
/**
* Check if a password is acceptable
* @param password
* @returns {string|boolean|(Array<string>&{index: number, input: string, groups})}
*/
function isPasswordAcceptable(password) {
return !!password && password.length >= 6 && !!password.match(/[0-9]/);
}
exports.isPasswordAcceptable = isPasswordAcceptable;
/**
* List available and enabled authentication options of the current user.
* @returns {Thunk<XcapJsonResult>}
*/
function listAuthenticationOptions(_a) {
return (0, api_1.getJson)({
url: '/user/auth/list-options',
parameters: arguments
});
}
exports.listAuthenticationOptions = listAuthenticationOptions;
/**
* Block/unblock a user. Requires stackend community admin status.
* @param id
* @param block
* @param comment
*/
function setBlocked(_a) {
var id = _a.id, block = _a.block, comment = _a.comment;
return (0, api_1.post)({
url: '/user/set-blocked',
parameters: arguments
});
}
exports.setBlocked = setBlocked;
function listOnline(_a) {
return (0, api_1.getJson)({
url: '/user/list-online',
parameters: arguments
});
}
exports.listOnline = listOnline;
//# sourceMappingURL=index.js.map