/**
* @import Entry from './Entry.js'
* @import EntryInfo from './EntryInfo.js'
* @import EntryStore from './EntryStore.js'
*/
/**
* EntryStore is the main class that is used to connect to a running server-side
* EntryStore repository.
*
* @exports module:store/Auth
*/
export default class Auth {
/**
* @param {EntryStore} entrystore - a repository instance.
*/
constructor(entrystore) {
this._entryStore = entrystore;
this._listenerCounter = 0;
/**
* @type {Map<string, Function>}
* @private
*/
this._listeners = new Map();
}
/**
*
* @param {string} topic
* @param {object} obj
*/
messageListeners(topic, obj) {
this._listeners.forEach((func) => func(topic, obj));
}
/**
* Adds an authentication listener, it will be notified of login and logout events.
*
* @param {Function} listener
*/
addAuthListener(listener) {
if (listener.__alid == null) {
listener.__alid = `idx_${this._listenerCounter}`;
this._listenerCounter += 1;
}
this._listeners.set(listener.__alid, listener);
}
/**
* Removes an authentication listener
*
* @param {Function} listener
*/
removeAuthListener(listener) {
if (listener.__alid != null) {
this._listeners.delete(listener.__alid);
}
}
/**
* Yields information about who currently is authenticated against the EntryStore repository.
*
* @param {boolean} forceLookup
* @returns {Promise.<EntryInfo>} - upon success an object containing attributes "user" being
* the username, "id" of the user entry,
* and "homecontext" being the entry-id of the home context is provided.
* @see {@link EntryStore#auth auth}
* @see {@link EntryStore#logout logout}
*/
async getUserInfo(forceLookup = false) {
if (this.userInfo && !forceLookup) {
return Promise.resolve(this.userInfo);
}
this.userInfo = await this._entryStore.handleAsync(
this._entryStore
.getREST()
.get(`${this._entryStore._baseURI}auth/user`, null, true),
'getUserInfo'
);
return this.userInfo;
}
/**
* @param {boolean} forceLookup
* @returns {Promise.<Entry>} on success the entry for the currently signed in user is provided.
*/
async getUserEntry(forceLookup = false) {
if (this.userEntry && !forceLookup) {
return Promise.resolve(this.userEntry);
}
const userInfo = await this.getUserInfo(forceLookup);
this.userEntry = await this._entryStore.getEntry(
this._entryStore.getEntryURI('_principals', userInfo.id),
{
asyncContext: 'getUserEntry',
}
);
return this.userEntry;
}
/**
* The session cookie from the last login or setAuthCookie, Node only. Use it together with
* setAuthCookie to keep a session across processes.
*
* @returns {string|undefined} "auth_token=<value>"
*/
getAuthCookie() {
return this._entryStore.getREST()._authCookie;
}
/**
* Restores a session from a cookie returned by getAuthCookie, Node only. The cookie is only
* sent to the repository's origin. Nothing is requested; the user is looked up on the next
* getUserInfo, call getUserInfo(true) to check that the session is still valid.
*
* @param {string} cookie - "auth_token=<value>"
* @throws {Error} if the repository is on plain http and not a loopback address
* (localhost, 127.0.0.1 or [::1])
*/
setAuthCookie(cookie) {
if (typeof cookie !== 'string' || !cookie.startsWith('auth_token=')) {
throw new Error('Expected a cookie on the form "auth_token=<value>"');
}
this._entryStore
.getREST()
._setAuthCookie(cookie, this._entryStore.getBaseURI());
delete this.userInfo;
delete this.userEntry;
this._entryStore.getCache().allNeedRefresh();
}
/**
* Authenticate using credentials containing a user, a password and an optional maxAge
* given in seconds. In Node, the login is refused without a request when the repository is
* on plain http and not a loopback address (localhost, 127.0.0.1 or [::1]).
*
* @param {string} user
* @param {string} password
* @param {number} maxAge
* @returns {Promise}
*/
async login(user, password, maxAge) {
if (this.userInfo && this.userInfo.user === user) {
return this.getUserInfo();
}
const credentials = {
base: this._entryStore.getBaseURI(),
user,
password,
maxAge,
};
const auth = await this._entryStore.handleAsync(
this._entryStore.getREST().auth(credentials),
'login'
);
if (typeof auth === 'object' && auth.user) {
return auth;
}
this.userInfo = await this._entryStore
.getREST()
.get(`${this._entryStore._baseURI}auth/user`, null, true);
delete this.userEntry;
this._entryStore.getCache().allNeedRefresh();
this.messageListeners('login', this.userInfo);
return this.userInfo;
}
/**
* Logout the currently authorized user.
*
* @returns {Promise.<{user, id}>} The guest user info
*/
async logout() {
if (this.userInfo && this.userInfo.user === 'guest') {
return this.getUserInfo();
}
// handleAsync returns the original promise passed
await this._entryStore.handleAsync(
this._entryStore.getREST().auth({
base: this._entryStore.getBaseURI(),
logout: true,
}),
'logout'
);
delete this.userEntry;
this._entryStore.getCache().allNeedRefresh();
this.userInfo = { user: 'guest', id: '_guest' };
this.messageListeners('logout', this.userInfo);
return this.userInfo;
}
}