appwrite
Version:
Appwrite is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API
1,264 lines (1,255 loc) • 154 kB
JavaScript
'use strict';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(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());
});
}
function __classPrivateFieldGet(receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
class Service {
constructor(client) {
this.client = client;
}
static flatten(data, prefix = '') {
let output = {};
for (const [key, value] of Object.entries(data)) {
let finalKey = prefix ? prefix + '[' + key + ']' : key;
if (Array.isArray(value)) {
output = Object.assign(Object.assign({}, output), Service.flatten(value, finalKey));
}
else {
output[finalKey] = value;
}
}
return output;
}
}
Service.CHUNK_SIZE = 5 * 1024 * 1024; // 5MB
class Query {
constructor(method, attribute, values) {
this.method = method;
this.attribute = attribute;
if (values !== undefined) {
if (Array.isArray(values)) {
this.values = values;
}
else {
this.values = [values];
}
}
}
toString() {
return JSON.stringify({
method: this.method,
attribute: this.attribute,
values: this.values,
});
}
}
Query.equal = (attribute, value) => new Query("equal", attribute, value).toString();
Query.notEqual = (attribute, value) => new Query("notEqual", attribute, value).toString();
Query.lessThan = (attribute, value) => new Query("lessThan", attribute, value).toString();
Query.lessThanEqual = (attribute, value) => new Query("lessThanEqual", attribute, value).toString();
Query.greaterThan = (attribute, value) => new Query("greaterThan", attribute, value).toString();
Query.greaterThanEqual = (attribute, value) => new Query("greaterThanEqual", attribute, value).toString();
Query.isNull = (attribute) => new Query("isNull", attribute).toString();
Query.isNotNull = (attribute) => new Query("isNotNull", attribute).toString();
Query.between = (attribute, start, end) => new Query("between", attribute, [start, end]).toString();
Query.startsWith = (attribute, value) => new Query("startsWith", attribute, value).toString();
Query.endsWith = (attribute, value) => new Query("endsWith", attribute, value).toString();
Query.select = (attributes) => new Query("select", undefined, attributes).toString();
Query.search = (attribute, value) => new Query("search", attribute, value).toString();
Query.orderDesc = (attribute) => new Query("orderDesc", attribute).toString();
Query.orderAsc = (attribute) => new Query("orderAsc", attribute).toString();
Query.cursorAfter = (documentId) => new Query("cursorAfter", undefined, documentId).toString();
Query.cursorBefore = (documentId) => new Query("cursorBefore", undefined, documentId).toString();
Query.limit = (limit) => new Query("limit", undefined, limit).toString();
Query.offset = (offset) => new Query("offset", undefined, offset).toString();
Query.contains = (attribute, value) => new Query("contains", attribute, value).toString();
Query.or = (queries) => new Query("or", undefined, queries.map((query) => JSON.parse(query))).toString();
Query.and = (queries) => new Query("and", undefined, queries.map((query) => JSON.parse(query))).toString();
class AppwriteException extends Error {
constructor(message, code = 0, type = '', response = '') {
super(message);
this.name = 'AppwriteException';
this.message = message;
this.code = code;
this.type = type;
this.response = response;
}
}
class Client {
constructor() {
this.config = {
endpoint: 'https://cloud.appwrite.io/v1',
endpointRealtime: '',
project: '',
jwt: '',
locale: '',
session: '',
};
this.headers = {
'x-sdk-name': 'Web',
'x-sdk-platform': 'client',
'x-sdk-language': 'web',
'x-sdk-version': '15.0.0',
'X-Appwrite-Response-Format': '1.5.0',
};
this.realtime = {
socket: undefined,
timeout: undefined,
url: '',
channels: new Set(),
subscriptions: new Map(),
subscriptionsCounter: 0,
reconnect: true,
reconnectAttempts: 0,
lastMessage: undefined,
connect: () => {
clearTimeout(this.realtime.timeout);
this.realtime.timeout = window === null || window === void 0 ? void 0 : window.setTimeout(() => {
this.realtime.createSocket();
}, 50);
},
getTimeout: () => {
switch (true) {
case this.realtime.reconnectAttempts < 5:
return 1000;
case this.realtime.reconnectAttempts < 15:
return 5000;
case this.realtime.reconnectAttempts < 100:
return 10000;
default:
return 60000;
}
},
createSocket: () => {
var _a, _b, _c;
if (this.realtime.channels.size < 1) {
this.realtime.reconnect = false;
(_a = this.realtime.socket) === null || _a === void 0 ? void 0 : _a.close();
return;
}
const channels = new URLSearchParams();
channels.set('project', this.config.project);
this.realtime.channels.forEach(channel => {
channels.append('channels[]', channel);
});
const url = this.config.endpointRealtime + '/realtime?' + channels.toString();
if (url !== this.realtime.url || // Check if URL is present
!this.realtime.socket || // Check if WebSocket has not been created
((_b = this.realtime.socket) === null || _b === void 0 ? void 0 : _b.readyState) > WebSocket.OPEN // Check if WebSocket is CLOSING (3) or CLOSED (4)
) {
if (this.realtime.socket &&
((_c = this.realtime.socket) === null || _c === void 0 ? void 0 : _c.readyState) < WebSocket.CLOSING // Close WebSocket if it is CONNECTING (0) or OPEN (1)
) {
this.realtime.reconnect = false;
this.realtime.socket.close();
}
this.realtime.url = url;
this.realtime.socket = new WebSocket(url);
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
this.realtime.socket.addEventListener('open', _event => {
this.realtime.reconnectAttempts = 0;
});
this.realtime.socket.addEventListener('close', event => {
var _a, _b, _c;
if (!this.realtime.reconnect ||
(((_b = (_a = this.realtime) === null || _a === void 0 ? void 0 : _a.lastMessage) === null || _b === void 0 ? void 0 : _b.type) === 'error' && // Check if last message was of type error
((_c = this.realtime) === null || _c === void 0 ? void 0 : _c.lastMessage.data).code === 1008 // Check for policy violation 1008
)) {
this.realtime.reconnect = true;
return;
}
const timeout = this.realtime.getTimeout();
console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`, event.reason);
setTimeout(() => {
this.realtime.reconnectAttempts++;
this.realtime.createSocket();
}, timeout);
});
}
},
onMessage: (event) => {
var _a, _b;
try {
const message = JSON.parse(event.data);
this.realtime.lastMessage = message;
switch (message.type) {
case 'connected':
const cookie = JSON.parse((_a = window.localStorage.getItem('cookieFallback')) !== null && _a !== void 0 ? _a : '{}');
const session = cookie === null || cookie === void 0 ? void 0 : cookie[`a_session_${this.config.project}`];
const messageData = message.data;
if (session && !messageData.user) {
(_b = this.realtime.socket) === null || _b === void 0 ? void 0 : _b.send(JSON.stringify({
type: 'authentication',
data: {
session
}
}));
}
break;
case 'event':
let data = message.data;
if (data === null || data === void 0 ? void 0 : data.channels) {
const isSubscribed = data.channels.some(channel => this.realtime.channels.has(channel));
if (!isSubscribed)
return;
this.realtime.subscriptions.forEach(subscription => {
if (data.channels.some(channel => subscription.channels.includes(channel))) {
setTimeout(() => subscription.callback(data));
}
});
}
break;
case 'error':
throw message.data;
default:
break;
}
}
catch (e) {
console.error(e);
}
},
cleanUp: channels => {
this.realtime.channels.forEach(channel => {
if (channels.includes(channel)) {
let found = Array.from(this.realtime.subscriptions).some(([_key, subscription]) => {
return subscription.channels.includes(channel);
});
if (!found) {
this.realtime.channels.delete(channel);
}
}
});
}
};
}
/**
* Set Endpoint
*
* Your project endpoint
*
* @param {string} endpoint
*
* @returns {this}
*/
setEndpoint(endpoint) {
this.config.endpoint = endpoint;
this.config.endpointRealtime = this.config.endpointRealtime || this.config.endpoint.replace('https://', 'wss://').replace('http://', 'ws://');
return this;
}
/**
* Set Realtime Endpoint
*
* @param {string} endpointRealtime
*
* @returns {this}
*/
setEndpointRealtime(endpointRealtime) {
this.config.endpointRealtime = endpointRealtime;
return this;
}
/**
* Set Project
*
* Your project ID
*
* @param value string
*
* @return {this}
*/
setProject(value) {
this.headers['X-Appwrite-Project'] = value;
this.config.project = value;
return this;
}
/**
* Set JWT
*
* Your secret JSON Web Token
*
* @param value string
*
* @return {this}
*/
setJWT(value) {
this.headers['X-Appwrite-JWT'] = value;
this.config.jwt = value;
return this;
}
/**
* Set Locale
*
* @param value string
*
* @return {this}
*/
setLocale(value) {
this.headers['X-Appwrite-Locale'] = value;
this.config.locale = value;
return this;
}
/**
* Set Session
*
* The user session to authenticate with
*
* @param value string
*
* @return {this}
*/
setSession(value) {
this.headers['X-Appwrite-Session'] = value;
this.config.session = value;
return this;
}
/**
* Subscribes to Appwrite events and passes you the payload in realtime.
*
* @param {string|string[]} channels
* Channel to subscribe - pass a single channel as a string or multiple with an array of strings.
*
* Possible channels are:
* - account
* - collections
* - collections.[ID]
* - collections.[ID].documents
* - documents
* - documents.[ID]
* - files
* - files.[ID]
* - executions
* - executions.[ID]
* - functions.[ID]
* - teams
* - teams.[ID]
* - memberships
* - memberships.[ID]
* @param {(payload: RealtimeMessage) => void} callback Is called on every realtime update.
* @returns {() => void} Unsubscribes from events.
*/
subscribe(channels, callback) {
let channelArray = typeof channels === 'string' ? [channels] : channels;
channelArray.forEach(channel => this.realtime.channels.add(channel));
const counter = this.realtime.subscriptionsCounter++;
this.realtime.subscriptions.set(counter, {
channels: channelArray,
callback
});
this.realtime.connect();
return () => {
this.realtime.subscriptions.delete(counter);
this.realtime.cleanUp(channelArray);
this.realtime.connect();
};
}
call(method, url, headers = {}, params = {}) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
method = method.toUpperCase();
headers = Object.assign({}, this.headers, headers);
let options = {
method,
headers,
credentials: 'include'
};
if (typeof window !== 'undefined' && window.localStorage) {
const cookieFallback = window.localStorage.getItem('cookieFallback');
if (cookieFallback) {
headers['X-Fallback-Cookies'] = cookieFallback;
}
}
if (method === 'GET') {
for (const [key, value] of Object.entries(Service.flatten(params))) {
url.searchParams.append(key, value);
}
}
else {
switch (headers['content-type']) {
case 'application/json':
options.body = JSON.stringify(params);
break;
case 'multipart/form-data':
let formData = new FormData();
for (const key in params) {
if (Array.isArray(params[key])) {
params[key].forEach((value) => {
formData.append(key + '[]', value);
});
}
else {
formData.append(key, params[key]);
}
}
options.body = formData;
delete headers['content-type'];
break;
}
}
try {
let data = null;
const response = yield fetch(url.toString(), options);
if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) {
data = yield response.json();
}
else {
data = {
message: yield response.text()
};
}
if (400 <= response.status) {
throw new AppwriteException(data === null || data === void 0 ? void 0 : data.message, response.status, data === null || data === void 0 ? void 0 : data.type, data);
}
const cookieFallback = response.headers.get('X-Fallback-Cookies');
if (typeof window !== 'undefined' && window.localStorage && cookieFallback) {
window.console.warn('Appwrite is using localStorage for session management. Increase your security by adding a custom domain as your API endpoint.');
window.localStorage.setItem('cookieFallback', cookieFallback);
}
return data;
}
catch (e) {
if (e instanceof AppwriteException) {
throw e;
}
throw new AppwriteException(e.message);
}
});
}
}
class Account extends Service {
constructor(client) {
super(client);
}
/**
* Get account
*
* Get the currently logged in user.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
get() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create account
*
* Use this endpoint to allow a new user to register a new account in your
* project. After the user registration completes successfully, you can use
* the
* [/account/verfication](https://appwrite.io/docs/references/cloud/client-web/account#createVerification)
* route to start verifying the user email address. To allow the new user to
* login to their new account, you need to create a new [account
* session](https://appwrite.io/docs/references/cloud/client-web/account#createEmailSession).
*
* @param {string} userId
* @param {string} email
* @param {string} password
* @param {string} name
* @throws {AppwriteException}
* @returns {Promise}
*/
create(userId, email, password, name) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof userId === 'undefined') {
throw new AppwriteException('Missing required parameter: "userId"');
}
if (typeof email === 'undefined') {
throw new AppwriteException('Missing required parameter: "email"');
}
if (typeof password === 'undefined') {
throw new AppwriteException('Missing required parameter: "password"');
}
const apiPath = '/account';
const payload = {};
if (typeof userId !== 'undefined') {
payload['userId'] = userId;
}
if (typeof email !== 'undefined') {
payload['email'] = email;
}
if (typeof password !== 'undefined') {
payload['password'] = password;
}
if (typeof name !== 'undefined') {
payload['name'] = name;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update email
*
* Update currently logged in user account email address. After changing user
* address, the user confirmation status will get reset. A new confirmation
* email is not sent automatically however you can use the send confirmation
* email endpoint again to send the confirmation email. For security measures,
* user password is required to complete this request.
* This endpoint can also be used to convert an anonymous account to a normal
* one, by passing an email address and a new password.
*
*
* @param {string} email
* @param {string} password
* @throws {AppwriteException}
* @returns {Promise}
*/
updateEmail(email, password) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof email === 'undefined') {
throw new AppwriteException('Missing required parameter: "email"');
}
if (typeof password === 'undefined') {
throw new AppwriteException('Missing required parameter: "password"');
}
const apiPath = '/account/email';
const payload = {};
if (typeof email !== 'undefined') {
payload['email'] = email;
}
if (typeof password !== 'undefined') {
payload['password'] = password;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* List Identities
*
* Get the list of identities for the currently logged in user.
*
* @param {string[]} queries
* @throws {AppwriteException}
* @returns {Promise}
*/
listIdentities(queries) {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/identities';
const payload = {};
if (typeof queries !== 'undefined') {
payload['queries'] = queries;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Delete identity
*
* Delete an identity by its unique ID.
*
* @param {string} identityId
* @throws {AppwriteException}
* @returns {Promise}
*/
deleteIdentity(identityId) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof identityId === 'undefined') {
throw new AppwriteException('Missing required parameter: "identityId"');
}
const apiPath = '/account/identities/{identityId}'.replace('{identityId}', identityId);
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('delete', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create JWT
*
* Use this endpoint to create a JSON Web Token. You can use the resulting JWT
* to authenticate on behalf of the current user when working with the
* Appwrite server-side API and SDKs. The JWT secret is valid for 15 minutes
* from its creation and will be invalid if the user will logout in that time
* frame.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
createJWT() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/jwt';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* List logs
*
* Get the list of latest security activity logs for the currently logged in
* user. Each log returns user IP address, location and date and time of log.
*
* @param {string[]} queries
* @throws {AppwriteException}
* @returns {Promise}
*/
listLogs(queries) {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/logs';
const payload = {};
if (typeof queries !== 'undefined') {
payload['queries'] = queries;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update MFA
*
* Enable or disable MFA on an account.
*
* @param {boolean} mfa
* @throws {AppwriteException}
* @returns {Promise}
*/
updateMFA(mfa) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof mfa === 'undefined') {
throw new AppwriteException('Missing required parameter: "mfa"');
}
const apiPath = '/account/mfa';
const payload = {};
if (typeof mfa !== 'undefined') {
payload['mfa'] = mfa;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Add Authenticator
*
* Add an authenticator app to be used as an MFA factor. Verify the
* authenticator using the [verify
* authenticator](/docs/references/cloud/client-web/account#updateMfaAuthenticator)
* method.
*
* @param {AuthenticatorType} type
* @throws {AppwriteException}
* @returns {Promise}
*/
createMfaAuthenticator(type) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof type === 'undefined') {
throw new AppwriteException('Missing required parameter: "type"');
}
const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type);
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Verify Authenticator
*
* Verify an authenticator app after adding it using the [add
* authenticator](/docs/references/cloud/client-web/account#createMfaAuthenticator)
* method. add
*
* @param {AuthenticatorType} type
* @param {string} otp
* @throws {AppwriteException}
* @returns {Promise}
*/
updateMfaAuthenticator(type, otp) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof type === 'undefined') {
throw new AppwriteException('Missing required parameter: "type"');
}
if (typeof otp === 'undefined') {
throw new AppwriteException('Missing required parameter: "otp"');
}
const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type);
const payload = {};
if (typeof otp !== 'undefined') {
payload['otp'] = otp;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('put', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Delete Authenticator
*
* Delete an authenticator for a user by ID.
*
* @param {AuthenticatorType} type
* @param {string} otp
* @throws {AppwriteException}
* @returns {Promise}
*/
deleteMfaAuthenticator(type, otp) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof type === 'undefined') {
throw new AppwriteException('Missing required parameter: "type"');
}
if (typeof otp === 'undefined') {
throw new AppwriteException('Missing required parameter: "otp"');
}
const apiPath = '/account/mfa/authenticators/{type}'.replace('{type}', type);
const payload = {};
if (typeof otp !== 'undefined') {
payload['otp'] = otp;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('delete', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create 2FA Challenge
*
* Begin the process of MFA verification after sign-in. Finish the flow with
* [updateMfaChallenge](/docs/references/cloud/client-web/account#updateMfaChallenge)
* method.
*
* @param {AuthenticationFactor} factor
* @throws {AppwriteException}
* @returns {Promise}
*/
createMfaChallenge(factor) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof factor === 'undefined') {
throw new AppwriteException('Missing required parameter: "factor"');
}
const apiPath = '/account/mfa/challenge';
const payload = {};
if (typeof factor !== 'undefined') {
payload['factor'] = factor;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create MFA Challenge (confirmation)
*
* Complete the MFA challenge by providing the one-time password. Finish the
* process of MFA verification by providing the one-time password. To begin
* the flow, use
* [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge)
* method.
*
* @param {string} challengeId
* @param {string} otp
* @throws {AppwriteException}
* @returns {Promise}
*/
updateMfaChallenge(challengeId, otp) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof challengeId === 'undefined') {
throw new AppwriteException('Missing required parameter: "challengeId"');
}
if (typeof otp === 'undefined') {
throw new AppwriteException('Missing required parameter: "otp"');
}
const apiPath = '/account/mfa/challenge';
const payload = {};
if (typeof challengeId !== 'undefined') {
payload['challengeId'] = challengeId;
}
if (typeof otp !== 'undefined') {
payload['otp'] = otp;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('put', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* List Factors
*
* List the factors available on the account to be used as a MFA challange.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
listMfaFactors() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/mfa/factors';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Get MFA Recovery Codes
*
* Get recovery codes that can be used as backup for MFA flow. Before getting
* codes, they must be generated using
* [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes)
* method. An OTP challenge is required to read recovery codes.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
getMfaRecoveryCodes() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/mfa/recovery-codes';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create MFA Recovery Codes
*
* Generate recovery codes as backup for MFA flow. It's recommended to
* generate and show then immediately after user successfully adds their
* authehticator. Recovery codes can be used as a MFA verification type in
* [createMfaChallenge](/docs/references/cloud/client-web/account#createMfaChallenge)
* method.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
createMfaRecoveryCodes() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/mfa/recovery-codes';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Regenerate MFA Recovery Codes
*
* Regenerate recovery codes that can be used as backup for MFA flow. Before
* regenerating codes, they must be first generated using
* [createMfaRecoveryCodes](/docs/references/cloud/client-web/account#createMfaRecoveryCodes)
* method. An OTP challenge is required to regenreate recovery codes.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
updateMfaRecoveryCodes() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/mfa/recovery-codes';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update name
*
* Update currently logged in user account name.
*
* @param {string} name
* @throws {AppwriteException}
* @returns {Promise}
*/
updateName(name) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof name === 'undefined') {
throw new AppwriteException('Missing required parameter: "name"');
}
const apiPath = '/account/name';
const payload = {};
if (typeof name !== 'undefined') {
payload['name'] = name;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update password
*
* Update currently logged in user password. For validation, user is required
* to pass in the new password, and the old password. For users created with
* OAuth, Team Invites and Magic URL, oldPassword is optional.
*
* @param {string} password
* @param {string} oldPassword
* @throws {AppwriteException}
* @returns {Promise}
*/
updatePassword(password, oldPassword) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof password === 'undefined') {
throw new AppwriteException('Missing required parameter: "password"');
}
const apiPath = '/account/password';
const payload = {};
if (typeof password !== 'undefined') {
payload['password'] = password;
}
if (typeof oldPassword !== 'undefined') {
payload['oldPassword'] = oldPassword;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update phone
*
* Update the currently logged in user's phone number. After updating the
* phone number, the phone verification status will be reset. A confirmation
* SMS is not sent automatically, however you can use the [POST
* /account/verification/phone](https://appwrite.io/docs/references/cloud/client-web/account#createPhoneVerification)
* endpoint to send a confirmation SMS.
*
* @param {string} phone
* @param {string} password
* @throws {AppwriteException}
* @returns {Promise}
*/
updatePhone(phone, password) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof phone === 'undefined') {
throw new AppwriteException('Missing required parameter: "phone"');
}
if (typeof password === 'undefined') {
throw new AppwriteException('Missing required parameter: "password"');
}
const apiPath = '/account/phone';
const payload = {};
if (typeof phone !== 'undefined') {
payload['phone'] = phone;
}
if (typeof password !== 'undefined') {
payload['password'] = password;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Get account preferences
*
* Get the preferences as a key-value object for the currently logged in user.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
getPrefs() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/prefs';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update preferences
*
* Update currently logged in user account preferences. The object you pass is
* stored as is, and replaces any previous value. The maximum allowed prefs
* size is 64kB and throws error if exceeded.
*
* @param {Partial<Preferences>} prefs
* @throws {AppwriteException}
* @returns {Promise}
*/
updatePrefs(prefs) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof prefs === 'undefined') {
throw new AppwriteException('Missing required parameter: "prefs"');
}
const apiPath = '/account/prefs';
const payload = {};
if (typeof prefs !== 'undefined') {
payload['prefs'] = prefs;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('patch', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create password recovery
*
* Sends the user an email with a temporary secret key for password reset.
* When the user clicks the confirmation link he is redirected back to your
* app password reset URL with the secret key and email address values
* attached to the URL query string. Use the query string params to submit a
* request to the [PUT
* /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#updateRecovery)
* endpoint to complete the process. The verification link sent to the user's
* email address is valid for 1 hour.
*
* @param {string} email
* @param {string} url
* @throws {AppwriteException}
* @returns {Promise}
*/
createRecovery(email, url) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof email === 'undefined') {
throw new AppwriteException('Missing required parameter: "email"');
}
if (typeof url === 'undefined') {
throw new AppwriteException('Missing required parameter: "url"');
}
const apiPath = '/account/recovery';
const payload = {};
if (typeof email !== 'undefined') {
payload['email'] = email;
}
if (typeof url !== 'undefined') {
payload['url'] = url;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create password recovery (confirmation)
*
* Use this endpoint to complete the user account password reset. Both the
* **userId** and **secret** arguments will be passed as query parameters to
* the redirect URL you have provided when sending your request to the [POST
* /account/recovery](https://appwrite.io/docs/references/cloud/client-web/account#createRecovery)
* endpoint.
*
* Please note that in order to avoid a [Redirect
* Attack](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.md)
* the only valid redirect URLs are the ones from domains you have set when
* adding your platforms in the console interface.
*
* @param {string} userId
* @param {string} secret
* @param {string} password
* @throws {AppwriteException}
* @returns {Promise}
*/
updateRecovery(userId, secret, password) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof userId === 'undefined') {
throw new AppwriteException('Missing required parameter: "userId"');
}
if (typeof secret === 'undefined') {
throw new AppwriteException('Missing required parameter: "secret"');
}
if (typeof password === 'undefined') {
throw new AppwriteException('Missing required parameter: "password"');
}
const apiPath = '/account/recovery';
const payload = {};
if (typeof userId !== 'undefined') {
payload['userId'] = userId;
}
if (typeof secret !== 'undefined') {
payload['secret'] = secret;
}
if (typeof password !== 'undefined') {
payload['password'] = password;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('put', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* List sessions
*
* Get the list of active sessions across different devices for the currently
* logged in user.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
listSessions() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/sessions';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Delete sessions
*
* Delete all sessions from the user account and remove any sessions cookies
* from the end client.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
deleteSessions() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/sessions';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('delete', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create anonymous session
*
* Use this endpoint to allow a new user to register an anonymous account in
* your project. This route will also create a new session for the user. To
* allow the new user to convert an anonymous account to a normal account, you
* need to update its [email and
* password](https://appwrite.io/docs/references/cloud/client-web/account#updateEmail)
* or create an [OAuth2
* session](https://appwrite.io/docs/references/cloud/client-web/account#CreateOAuth2Session).
*
* @throws {AppwriteException}
* @returns {Promise}
*/
createAnonymousSession() {
return __awaiter(this, void 0, void 0, function* () {
const apiPath = '/account/sessions/anonymous';
const payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create email password session
*
* Allow the user to login into their account by providing a valid email and
* password combination. This route will create a new session for the user.
*
* A user is limited to 10 active sessions at a time by default. [Learn more
* about session
* limits](https://appwrite.io/docs/authentication-security#limits).
*
* @param {string} email
* @param {string} password
* @throws {AppwriteException}
* @returns {Promise}
*/
createEmailPasswordSession(email, password) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof email === 'undefined') {
throw new AppwriteException('Missing required parameter: "email"');
}
if (typeof password === 'undefined') {
throw new AppwriteException('Missing required parameter: "password"');
}
const apiPath = '/account/sessions/email';
const payload = {};
if (typeof email !== 'undefined') {
payload['email'] = email;
}
if (typeof password !== 'undefined') {
payload['password'] = password;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('post', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Update magic URL session
*
* Use this endpoint to create a session from token. Provide the **userId**
* and **secret** parameters from the successful response of authentication
* flows initiated by token creation. For example, magic URL and phone login.
*
* @param {string} userId
* @param {string} secret
* @throws {AppwriteException}
* @returns {Promise}
*/
updateMagicURLSession(userId, secret) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof userId === 'undefined') {
throw new AppwriteException('Missing required parameter: "userId"');
}
if (typeof secret === 'undefined') {
throw new AppwriteException('Missing required parameter: "secret"');
}
const apiPath = '/account/sessions/magic-url';
const payload = {};
if (typeof userId !== 'undefined') {
payload['userId'] = userId;
}
if (typeof secret !== 'undefined') {
payload['secret'] = secret;
}
const uri = new URL(this.client.config.endpoint + apiPath);
return yield this.client.call('put', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Create OAuth2 session
*
* Allow the user to login to their account using the OAuth2 provider of their
* choice. Each OAuth2 provider should be enabled from the A