Auth Service
The Blocklet SDK's Auth Service provides comprehensive functionalities for managing user authentication, authorization, and user data within your Blocklet applications. It simplifies interactions with the Blocklet Server's underlying identity and access control mechanisms, enabling you to build secure and robust decentralized applications.
This section focuses on the AuthService
class and its methods. For details on integrating DID Connect authentication flows, refer to the DID Connect section. To understand the middleware used for authentication, see Authentication.
AuthService Class Overview#
The AuthService
class acts as a high-level wrapper around the @abtnode/client
(referred to as Client
in the SDK's internal types), abstracting away direct GraphQL queries and HTTP requests. It initializes the underlying Client
with the current Blocklet's DID and Component DID, ensuring all requests are properly authenticated and scoped to your application's environment.
The service provides a wide array of APIs categorized for session management, user data handling, tagging, role-based access control (RBAC), user passport issuance, and access key management.
Login and Session Management#
login(data)#
Facilitates user login by sending a request to the Blocklet Server's user login API. This method handles the underlying HTTP POST request and processes the response, including user information and session tokens.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing login credentials or session details. The exact structure depends on the authentication method used by the Blocklet Server. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the authenticated user's details. |
|
| The user's session token. |
|
| A token used to refresh the session. |
|
| The login provider (e.g., |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function userLogin(loginData) {
try {
const result = await authService.login(loginData);
console.log('Login successful:', result.user.fullName, result.token);
return result;
} catch (error) {
console.error('Login failed:', error.message);
throw error;
}
}
// Example usage (replace with actual login data)
userLogin({ username: 'testuser', password: 'password' });
Example Response
{
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"avatar": "https://example.com/avatar.png",
"emailVerified": true
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "someRefreshTokenString",
"provider": "WALLET"
}
This example demonstrates how to use the login
method to authenticate a user with the Blocklet Server.
refreshSession(data)#
Refreshes an expired user session using a refresh token. This allows applications to maintain user sessions without requiring re-authentication.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the |
|
| The refresh token obtained from a previous login or session refresh. |
|
| Optional. An identifier for the visitor. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the refreshed user's details. |
|
| The new session token. |
|
| The new refresh token. |
|
| The login provider. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function refreshUserSession(currentRefreshToken) {
try {
const result = await authService.refreshSession({ refreshToken: currentRefreshToken });
console.log('Session refreshed for user:', result.user.fullName);
return result;
} catch (error) {
console.error('Failed to refresh session:', error.message);
throw error;
}
}
// Example usage
refreshUserSession('your_current_refresh_token');
Example Response
{
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User"
},
"token": "new_session_token_string",
"refreshToken": "new_refresh_token_string",
"provider": "WALLET"
}
This example shows how to use a refresh token to obtain a new session token and updated user information.
switchProfile(did, profile)#
Allows an authenticated user to update their profile information, such as avatar, email, or full name.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID of the user whose profile is to be switched. |
|
| An object containing the profile fields to update. |
|
| Optional. The URL of the new avatar. |
|
| Optional. The new email address. |
|
| Optional. The new full name. |
Returns
Name | Type | Description |
---|---|---|
|
| The updated user object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function updateUserProfile(userDid, newProfile) {
try {
const updatedUser = await authService.switchProfile(userDid, newProfile);
console.log('User profile updated:', updatedUser.user.fullName);
return updatedUser;
} catch (error) {
console.error('Failed to update user profile:', error.message);
throw error;
}
}
// Example usage
updateUserProfile('did:abt:zNKgL8xYf1r...', {
fullName: 'New Full Name',
email: 'new.email@example.com'
});
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "New Full Name",
"email": "new.email@example.com",
"avatar": "https://example.com/new_avatar.png",
"updatedAt": 1678886400000
}
}
This example demonstrates how to update a user's full name and email using the switchProfile
method.
User Management#
getUser(did, options)#
Retrieves detailed information for a specific user identified by their DID.
Parameters
Name | Type | Description |
---|---|---|
|
| The Decentralized Identifier (DID) of the user to retrieve. |
|
| Optional settings for the query. |
|
| Optional. If |
|
| Optional. If |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the user's detailed information. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchUserDetails(userDid) {
try {
const userDetails = await authService.getUser(userDid, { includeTags: true });
console.log('User details:', userDetails.user.fullName, userDetails.user.tags);
return userDetails;
} catch (error) {
console.error('Failed to fetch user details:', error.message);
throw error;
}
}
// Example usage
fetchUserDetails('did:abt:zNKgL8xYf1r...');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"pk": "0x...",
"role": "user",
"avatar": "https://example.com/avatar.png",
"fullName": "John Doe",
"email": "john.doe@example.com",
"approved": true,
"createdAt": 1678800000000,
"updatedAt": 1678886400000,
"locale": "en-US",
"passports": [],
"firstLoginAt": 1678800000000,
"lastLoginAt": 1678886400000,
"remark": "",
"lastLoginIp": "192.168.1.1",
"sourceProvider": "WALLET",
"sourceAppPid": "did:abt:zNKgL8xYf1r...",
"connectedAccounts": [],
"extra": {},
"tags": [
{
"id": 1,
"title": "Premium",
"description": "Premium user",
"color": "#FF0000",
"createdAt": 1678800000000,
"updatedAt": 1678800000000
}
],
"didSpace": {},
"userSessions": [],
"url": "",
"phone": "",
"inviter": "",
"generation": 1,
"emailVerified": true,
"phoneVerified": false,
"metadata": {},
"address": {},
"userSessionsCount": 0
}
}
This example retrieves the details for a specified user, including their tags.
getUsers(args)#
Retrieves a paginated list of users within the Blocklet. This method supports filtering and sorting options.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing query, sort, and pagination parameters. |
|
| Optional. Filtering criteria (e.g., |
|
| Optional. Sorting criteria (e.g., |
|
| Optional. Pagination details ( |
|
| Optional. An array of specific user DIDs to retrieve. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing a list of user objects and pagination information. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function listApprovedUsers(page = 1, pageSize = 10) {
try {
const usersList = await authService.getUsers({
query: { approved: true },
paging: { page, pageSize },
sort: { createdAt: -1 },
});
console.log(`Found ${usersList.paging.total} approved users. Page ${usersList.paging.page} of ${usersList.paging.pageCount}:`);
usersList.users.forEach(user => console.log(`- ${user.fullName} (${user.did})`));
return usersList;
} catch (error) {
console.error('Failed to list users:', error.message);
throw error;
}
}
// Example usage
listApprovedUsers();
Example Response
{
"code": "OK",
"users": [
{
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Jane Doe",
"approved": true,
"role": "user"
},
{
"did": "did:abt:zNKuA7xYf1r...",
"fullName": "Bob Smith",
"approved": true,
"role": "guest"
}
],
"paging": {
"total": 2,
"pageSize": 10,
"pageCount": 1,
"page": 1
}
}
This example fetches a paginated list of approved users, sorted by creation date in descending order.
updateUserApproval(did, approved)#
Updates the approval status of a specific user. Approved users typically have full access to Blocklet features, while unapproved users may have restricted access.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID of the user to update. |
|
| The new approval status ( |
Returns
Name | Type | Description |
---|---|---|
|
| The updated user object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function approveUser(userDid) {
try {
const updatedUser = await authService.updateUserApproval(userDid, true);
console.log(`User ${updatedUser.user.fullName} approval status: ${updatedUser.user.approved}`);
return updatedUser;
} catch (error) {
console.error('Failed to update user approval:', error.message);
throw error;
}
}
// Example usage
approveUser('did:abt:zNKgL8xYf1r...');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"approved": true
}
}
This example approves a specified user, granting them full access.
updateUserInfo(userInfo, options)#
Updates general information for a user, such as their full name, email, or locale. This method requires a valid authentication cookie in the request headers.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID and the fields to update. |
|
| An object containing request headers, specifically a |
Returns
Name | Type | Description |
---|---|---|
|
| The updated user object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function modifyUserInfo(userDid, newFullName, cookieHeader) {
try {
const updatedUser = await authService.updateUserInfo(
{ did: userDid, fullName: newFullName },
{ headers: { cookie: cookieHeader } }
);
console.log('User info updated:', updatedUser.user.fullName);
return updatedUser;
} catch (error) {
console.error('Failed to update user info:', error.message);
throw error;
}
}
// Example usage (replace with actual user DID and cookie)
modifyUserInfo('did:abt:zNKgL8xYf1r...', 'Alice Wonderland', 'your_auth_cookie_here');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Alice Wonderland",
"email": "alice@example.com"
}
}
This example updates a user's full name, requiring an authentication cookie.
updateUserAddress(args, options)#
Updates the geographical address information for a user. This method also requires a valid authentication cookie.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID and the address fields to update. |
|
| An object containing request headers, specifically a |
Returns
Name | Type | Description |
---|---|---|
|
| The updated user object with new address details. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function updateAddress(userDid, country, city, cookieHeader) {
try {
const updatedUser = await authService.updateUserAddress(
{ did: userDid, address: { country, city } },
{ headers: { cookie: cookieHeader } }
);
console.log('User address updated:', updatedUser.user.address);
return updatedUser;
} catch (error) {
console.error('Failed to update user address:', error.message);
throw error;
}
}
// Example usage
updateAddress('did:abt:zNKgL8xYf1r...', 'USA', 'New York', 'your_auth_cookie_here');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Alice Wonderland",
"address": {
"country": "USA",
"province": "NY",
"city": "New York",
"postalCode": "10001",
"line1": "123 Main St",
"line2": "Apt 4B"
}
}
}
This example updates a user's country and city in their address information.
updateUserTags(args)#
Assigns or updates tags associated with a user. Tags can be used for categorization, segmentation, or custom permissions.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID and an array of tag IDs. |
|
| The DID of the user whose tags are to be updated. |
|
| An array of numeric IDs representing the tags to associate with the user. |
Returns
Name | Type | Description |
---|---|---|
|
| The updated user object, including their new tags. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function setUserTags(userDid, tagIds) {
try {
const updatedUser = await authService.updateUserTags({ did: userDid, tags: tagIds });
console.log('User tags updated for:', updatedUser.user.fullName, updatedUser.user.tags);
return updatedUser;
} catch (error) {
console.error('Failed to update user tags:', error.message);
throw error;
}
}
// Example usage: assign tags with IDs 1 and 2 to a user
setUserTags('did:abt:zNKgL8xYf1r...', [1, 2]);
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"tags": [
{ "id": 1, "title": "VIP" },
{ "id": 2, "title": "Beta Tester" }
]
}
}
This example assigns two specific tags to a user.
updateUserExtra(args)#
Updates extra arbitrary data associated with a user. This can be used to store custom user-specific information.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID, a remark, and the extra data. |
|
| The DID of the user whose extra data is to be updated. |
|
| Optional. A remark for the update. |
|
| A JSON string or other stringified data representing the extra information. |
Returns
Name | Type | Description |
---|---|---|
|
| The updated user object, including the new extra data. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function setUserExtraData(userDid, customData) {
try {
const updatedUser = await authService.updateUserExtra({
did: userDid,
extra: JSON.stringify(customData),
remark: 'Updated custom user data'
});
console.log('User extra data updated for:', updatedUser.user.fullName, updatedUser.user.extra);
return updatedUser;
} catch (error) {
console.error('Failed to update user extra data:', error.message);
throw error;
}
}
// Example usage
setUserExtraData('did:abt:zNKgL8xYf1r...', { lastActivity: Date.now(), preferences: { notify: true } });
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"extra": {
"lastActivity": 1678886400000,
"preferences": {
"notify": true
}
}
}
}
This example updates a user's extra data with custom activity and preference information.
Role-Based Access Control (RBAC)#
getRoles()#
Retrieves a list of all defined roles within the Blocklet Server, including their descriptions and associated permissions.
Parameters
None.
Returns
Name | Type | Description |
---|---|---|
|
| An object containing an array of role objects. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchAllRoles() {
try {
const allRoles = await authService.getRoles();
console.log('Available roles:');
allRoles.roles.forEach(role => console.log(`- ${role.title} (${role.name}): ${role.description}`));
return allRoles;
} catch (error) {
console.error('Failed to fetch roles:', error.message);
throw error;
}
}
// Example usage
fetchAllRoles();
Example Response
{
"code": "OK",
"roles": [
{
"name": "admin",
"title": "Administrator",
"description": "Full access to all Blocklet functionalities.",
"grants": ["blocklet:read", "blocklet:write", "user:manage"],
"isProtected": true
},
{
"name": "user",
"title": "Standard User",
"description": "Basic access to Blocklet features.",
"grants": ["blocklet:read"],
"isProtected": false
}
]
}
This example retrieves and displays all roles configured on the Blocklet Server.
getRole(name)#
Retrieves detailed information for a specific role by its unique name.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique name of the role to retrieve. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the role's details. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchRoleDetails(roleName) {
try {
const roleDetails = await authService.getRole(roleName);
console.log(`Details for role '${roleName}':`, roleDetails.role);
return roleDetails;
} catch (error) {
console.error(`Failed to fetch role '${roleName}':`, error.message);
throw error;
}
}
// Example usage
fetchRoleDetails('admin');
Example Response
{
"code": "OK",
"role": {
"name": "admin",
"description": "Full access to all Blocklet functionalities.",
"grants": [
"blocklet:read",
"blocklet:write",
"user:manage"
],
"title": "Administrator",
"isProtected": true,
"extra": {}
}
}
This example fetches and displays the details of the 'admin' role.
createRole({ name, title, description, extra })#
Creates a new role with a specified name, title, description, and optional extra metadata.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique programmatic name for the new role. |
|
| The display title for the role. |
|
| A description of the role's purpose or permissions. |
|
| Optional. Additional arbitrary data associated with the role. |
Returns
Name | Type | Description |
---|---|---|
|
| The newly created role object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function createNewRole() {
try {
const newRole = await authService.createRole({
name: 'moderator',
title: 'Content Moderator',
description: 'Manages user-generated content and comments.',
extra: { department: 'community' }
});
console.log('New role created:', newRole.role.name);
return newRole;
} catch (error) {
console.error('Failed to create role:', error.message);
throw error;
}
}
// Example usage
createNewRole();
Example Response
{
"code": "OK",
"role": {
"name": "moderator",
"title": "Content Moderator",
"description": "Manages user-generated content and comments.",
"grants": [],
"isProtected": false,
"extra": {"department": "community"}
}
}
This example creates a new 'moderator' role with a description and custom metadata.
updateRole(name, { title, description, extra })#
Updates the title, description, or extra metadata of an existing role.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique name of the role to update. |
|
| An object containing the fields to update. |
|
| Optional. The new display title for the role. |
|
| Optional. The new description for the role. |
|
| Optional. New arbitrary data to associate with the role. |
Returns
Name | Type | Description |
---|---|---|
|
| The updated role object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function modifyRoleDescription(roleName, newDescription) {
try {
const updatedRole = await authService.updateRole(roleName, { description: newDescription });
console.log(`Role '${updatedRole.role.name}' description updated: ${updatedRole.role.description}`);
return updatedRole;
} catch (error) {
console.error('Failed to update role:', error.message);
throw error;
}
}
// Example usage
modifyRoleDescription('moderator', 'Updated description: Oversees user contributions.');
Example Response
{
"code": "OK",
"role": {
"name": "moderator",
"title": "Content Moderator",
"description": "Updated description: Oversees user contributions.",
"grants": [],
"isProtected": false,
"extra": {"department": "community"}
}
}
This example updates the description of the 'moderator' role.
deleteRole(name)#
Deletes a role from the Blocklet Server. This action is irreversible and should be performed with caution.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique name of the role to delete. |
Returns
Name | Type | Description |
---|---|---|
|
| A general response indicating the success or failure of the operation. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function removeRole(roleName) {
try {
const response = await authService.deleteRole(roleName);
if (response.code === 'OK') {
console.log(`Role '${roleName}' deleted successfully.`);
} else {
console.warn(`Failed to delete role '${roleName}':`, response.code);
}
return response;
} catch (error) {
console.error('Error deleting role:', error.message);
throw error;
}
}
// Example usage
removeRole('temporary_role');
Example Response
{
"code": "OK"
}
This example deletes a role named 'temporary_role'.
grantPermissionForRole(roleName, permissionName)#
Grants a specific permission to a designated role, allowing users with that role to perform actions associated with the permission.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the role to which the permission will be granted. |
|
| The name of the permission to grant. |
Returns
Name | Type | Description |
---|---|---|
|
| A general response indicating the success or failure of the operation. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function grantUserWritePermission(role, permission) {
try {
const response = await authService.grantPermissionForRole(role, permission);
if (response.code === 'OK') {
console.log(`Permission '${permission}' granted to role '${role}'.`);
} else {
console.warn(`Failed to grant permission '${permission}' to role '${role}':`, response.code);
}
return response;
} catch (error) {
console.error('Error granting permission:', error.message);
throw error;
}
}
// Example usage
grantUserWritePermission('editor', 'content:write');
Example Response
{
"code": "OK"
}
This example grants 'content:write' permission to the 'editor' role.
revokePermissionFromRole(roleName, permissionName)#
Revokes a specific permission from a role, restricting users with that role from performing actions associated with the permission.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the role from which the permission will be revoked. |
|
| The name of the permission to revoke. |
Returns
Name | Type | Description |
---|---|---|
|
| A general response indicating the success or failure of the operation. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function revokeOldPermission(role, permission) {
try {
const response = await authService.revokePermissionFromRole(role, permission);
if (response.code === 'OK') {
console.log(`Permission '${permission}' revoked from role '${role}'.`);
} else {
console.warn(`Failed to revoke permission '${permission}' from role '${role}':`, response.code);
}
return response;
} catch (error) {
console.error('Error revoking permission:', error.message);
throw error;
}
}
// Example usage
revokeOldPermission('viewer', 'data:export');
Example Response
{
"code": "OK"
}
This example revokes the 'data:export' permission from the 'viewer' role.
updatePermissionsForRole(roleName, permissionNames)#
Replaces the entire set of permissions for a given role with a new list of permissions.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the role whose permissions are to be updated. |
|
| An array of permission names that will replace the role's current permissions. |
Returns
Name | Type | Description |
---|---|---|
|
| The updated role object with its new permissions. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function setRolePermissions(role, newPermissions) {
try {
const updatedRole = await authService.updatePermissionsForRole(role, newPermissions);
console.log(`Permissions for role '${updatedRole.role.name}' updated to: ${updatedRole.role.grants.join(', ')}`);
return updatedRole;
} catch (error) {
console.error('Failed to update role permissions:', error.message);
throw error;
}
}
// Example usage
setRolePermissions('contributor', ['content:read', 'content:create']);
Example Response
{
"code": "OK",
"role": {
"name": "contributor",
"title": "Contributor",
"description": "",
"grants": [
"content:read",
"content:create"
],
"isProtected": false,
"extra": {}
}
}
This example sets the permissions for the 'contributor' role to 'content:read' and 'content:create'.
hasPermission(role, permission)#
Checks if a specified role possesses a particular permission.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the role to check. |
|
| The name of the permission to verify. |
Returns
Name | Type | Description |
---|---|---|
|
| An object indicating whether the role has the permission ( |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function checkRolePermission(role, permission) {
try {
const response = await authService.hasPermission(role, permission);
console.log(`Does role '${role}' have permission '${permission}'? ${response.result}`);
return response;
} catch (error) {
console.error('Error checking permission:', error.message);
throw error;
}
}
// Example usage
checkRolePermission('admin', 'user:delete');
checkRolePermission('viewer', 'user:delete');
Example Response (for 'admin', 'user:delete')
{
"code": "OK",
"result": true
}
Example Response (for 'viewer', 'user:delete')
{
"code": "OK",
"result": false
}
These examples demonstrate checking if the 'admin' and 'viewer' roles have the 'user:delete' permission.
Permissions Management#
getPermissions()#
Retrieves a list of all defined permissions within the Blocklet Server.
Parameters
None.
Returns
Name | Type | Description |
---|---|---|
|
| An object containing an array of permission objects. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchAllPermissions() {
try {
const allPermissions = await authService.getPermissions();
console.log('Available permissions:');
allPermissions.permissions.forEach(p => console.log(`- ${p.name}: ${p.description}`));
return allPermissions;
} catch (error) {
console.error('Failed to fetch permissions:', error.message);
throw error;
}
}
// Example usage
fetchAllPermissions();
Example Response
{
"code": "OK",
"permissions": [
{
"name": "blocklet:read",
"description": "Allow read access to blocklet data",
"isProtected": true
},
{
"name": "user:manage",
"description": "Allow managing users",
"isProtected": true
}
]
}
This example retrieves and displays all available permissions.
createPermission({ name, description })#
Creates a new permission with a unique name and a description.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique programmatic name for the new permission. |
|
| A description explaining what the permission allows. |
Returns
Name | Type | Description |
---|---|---|
|
| The newly created permission object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function createNewPermission() {
try {
const newPermission = await authService.createPermission({
name: 'item:delete',
description: 'Allow deleting items'
});
console.log('New permission created:', newPermission.permission.name);
return newPermission;
} catch (error) {
console.error('Failed to create permission:', error.message);
throw error;
}
}
// Example usage
createNewPermission();
Example Response
{
"code": "OK",
"permission": {
"name": "item:delete",
"description": "Allow deleting items",
"isProtected": false
}
}
This example creates a new permission named 'item:delete'.
updatePermission(name, { description })#
Updates the description of an existing permission.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique name of the permission to update. |
|
| An object containing the new description for the permission. |
|
| The new description for the permission. |
Returns
Name | Type | Description |
---|---|---|
|
| The updated permission object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function modifyPermissionDescription(permissionName, newDescription) {
try {
const updatedPermission = await authService.updatePermission(permissionName, { description: newDescription });
console.log(`Permission '${updatedPermission.permission.name}' description updated: ${updatedPermission.permission.description}`);
return updatedPermission;
} catch (error) {
console.error('Failed to update permission:', error.message);
throw error;
}
}
// Example usage
modifyPermissionDescription('item:delete', 'Allow permanent deletion of inventory items.');
Example Response
{
"code": "OK",
"permission": {
"name": "item:delete",
"description": "Allow permanent deletion of inventory items.",
"isProtected": false
}
}
This example updates the description for the 'item:delete' permission.
deletePermission(name)#
Deletes a permission from the Blocklet Server. This action is irreversible and should be performed with caution.
Parameters
Name | Type | Description |
---|---|---|
|
| The unique name of the permission to delete. |
Returns
Name | Type | Description |
---|---|---|
|
| A general response indicating the success or failure of the operation. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function removePermission(permissionName) {
try {
const response = await authService.deletePermission(permissionName);
if (response.code === 'OK') {
console.log(`Permission '${permissionName}' deleted successfully.`);
} else {
console.warn(`Failed to delete permission '${permissionName}':`, response.code);
}
return response;
} catch (error) {
console.error('Error deleting permission:', error.message);
throw error;
}
}
// Example usage
removePermission('old:permission');
Example Response
{
"code": "OK"
}
This example deletes a permission named 'old:permission'.
getPermissionsByRole(name)#
Retrieves all permissions associated with a specific role.
Parameters
Name | Type | Description |
---|---|---|
|
| The name of the role for which to retrieve permissions. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing an array of permission objects associated with the role. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchPermissionsForRole(roleName) {
try {
const rolePermissions = await authService.getPermissionsByRole(roleName);
console.log(`Permissions for role '${roleName}':`);
rolePermissions.permissions.forEach(p => console.log(`- ${p.name}`));
return rolePermissions;
} catch (error) {
console.error(`Failed to fetch permissions for role '${roleName}':`, error.message);
throw error;
}
}
// Example usage
fetchPermissionsForRole('editor');
Example Response
{
"code": "OK",
"permissions": [
{
"name": "content:read",
"description": "Allow read access to content",
"isProtected": false
},
{
"name": "content:edit",
"description": "Allow editing content",
"isProtected": false
}
]
}
This example fetches and lists all permissions granted to the 'editor' role.
Passport Management#
issuePassportToUser(args)#
Issues a new Passport to a specified user, assigning them a role and optionally including display information and a notification.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing details for the Passport issuance. |
|
| The DID of the user to whom the Passport will be issued. |
|
| The role to assign to the user via this Passport. |
|
| Optional. Display information for the Passport. |
|
| Optional. If |
|
| Optional. The content of the notification to send. |
Returns
Name | Type | Description |
---|---|---|
|
| The user object updated with the newly issued Passport. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function issueNewPassport(userDid, role) {
try {
const updatedUser = await authService.issuePassportToUser({
userDid,
role,
display: { type: 'text', content: `You are now a ${role}!` },
notify: true,
notification: `Welcome, you have been granted the ${role} role.`
});
console.log(`Passport issued for ${updatedUser.user.fullName} with role ${role}.`);
return updatedUser;
} catch (error) {
console.error('Failed to issue Passport:', error.message);
throw error;
}
}
// Example usage
issueNewPassport('did:abt:zNKgL8xYf1r...', 'subscriber');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"passports": [
{
"id": "passportId1",
"name": "subscriber",
"role": "subscriber",
"display": {"type": "text", "content": "You are now a subscriber!"}
}
]
}
}
This example issues a 'subscriber' Passport to a user and sends them a notification.
revokeUserPassport(args)#
Revokes a specific Passport from a user, effectively removing the associated role or privileges.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID and the Passport ID to revoke. |
|
| The DID of the user from whom the Passport will be revoked. |
|
| The unique ID of the Passport to revoke. |
Returns
Name | Type | Description |
---|---|---|
|
| The user object after the Passport has been revoked. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function revokePassport(userDid, passportId) {
try {
const updatedUser = await authService.revokeUserPassport({ userDid, passportId });
console.log(`Passport '${passportId}' revoked from ${updatedUser.user.fullName}.`);
return updatedUser;
} catch (error) {
console.error('Failed to revoke Passport:', error.message);
throw error;
}
}
// Example usage
revokePassport('did:abt:zNKgL8xYf1r...', 'passportId1');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"passports": []
}
}
This example revokes a specific Passport from a user.
enableUserPassport(args)#
Enables an existing Passport for a user, restoring its associated role or privileges.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID and the Passport ID to enable. |
|
| The DID of the user whose Passport will be enabled. |
|
| The unique ID of the Passport to enable. |
Returns
Name | Type | Description |
---|---|---|
|
| The user object after the Passport has been enabled. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function enablePassport(userDid, passportId) {
try {
const updatedUser = await authService.enableUserPassport({ userDid, passportId });
console.log(`Passport '${passportId}' enabled for ${updatedUser.user.fullName}.`);
return updatedUser;
} catch (error) {
console.error('Failed to enable Passport:', error.message);
throw error;
}
}
// Example usage
enablePassport('did:abt:zNKgL8xYf1r...', 'passportId2');
Example Response
{
"code": "OK",
"user": {
"did": "did:abt:zNKgL8xYf1r...",
"fullName": "Test User",
"passports": [
{
"id": "passportId2",
"name": "moderator",
"status": "active"
}
]
}
}
This example enables a specific Passport for a user.
removeUserPassport(args)#
Removes a Passport record entirely from a user's profile. This is a permanent deletion of the Passport record.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the user's DID and the Passport ID to remove. |
|
| The DID of the user from whom the Passport will be removed. |
|
| The unique ID of the Passport to remove. |
Returns
Name | Type | Description |
---|---|---|
|
| A general response indicating the success or failure of the operation. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function deleteUserPassport(userDid, passportId) {
try {
const response = await authService.removeUserPassport({ userDid, passportId });
if (response.code === 'OK') {
console.log(`Passport '${passportId}' permanently removed from user '${userDid}'.`);
} else {
console.warn(`Failed to remove Passport '${passportId}':`, response.code);
}
return response;
} catch (error) {
console.error('Error removing Passport:', error.message);
throw error;
}
}
// Example usage
deleteUserPassport('did:abt:zNKgL8xYf1r...', 'passportId3');
Example Response
{
"code": "OK"
}
This example permanently removes a specific Passport from a user's record.
Access Key Management#
createAccessKey(params)#
Creates a new access key for programmatically interacting with the Blocklet. Access keys can be scoped to specific resources and components.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing details for the new access key. |
|
| Optional. A remark or description for the access key. |
|
| The Passport role associated with this access key (e.g., |
|
| The authentication type (e.g., |
|
| Optional. The DID of the component this key is for. |
|
| Optional. The type of resource this key can access. |
|
| Optional. The ID of the specific resource this key can access. |
|
| Optional. How the key was created (e.g., |
|
| Optional. Unix timestamp when the key expires. |
Returns
Name | Type | Description |
---|---|---|
|
| The newly created access key details, including its |
Example
import Auth from '@blocklet/sdk/service/auth';
import { SERVER_ROLES } from '@abtnode/constant';
const authService = new Auth();
async function generateAccessKey() {
try {
const newKey = await authService.createAccessKey({
remark: 'API access for data synchronization',
passport: SERVER_ROLES.GUEST,
resourceType: 'data',
expireAt: Date.now() + 3600 * 1000 // Expires in 1 hour
});
console.log('Access key created:', newKey.data.accessKeyId, newKey.data.accessKeySecret);
return newKey;
} catch (error) {
console.error('Failed to create access key:', error.message);
throw error;
}
}
// Example usage
generateAccessKey();
Example Response
{
"code": "OK",
"data": {
"accessKeyId": "blocklet-abcdef1234567890",
"accessKeyPublic": "0x...",
"accessKeySecret": "secret_value_here",
"remark": "API access for data synchronization",
"passport": "GUEST",
"createdAt": 1678886400000,
"lastUsedAt": 0,
"authType": "simple",
"componentDid": "",
"resourceType": "data",
"resourceId": "",
"createdVia": "sdk",
"expireAt": 1678890000000
}
}
This example creates an access key for data synchronization, set to expire in one hour.
verifyAccessKey(params)#
Verifies an existing access key against a specified resource and component. This is typically used internally by the Blocklet Server to validate incoming API requests.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing details for verification. |
|
| The ID of the access key to verify. |
|
| The type of resource being accessed. |
|
| The ID of the specific resource being accessed. |
|
| The DID of the component attempting to use the key. |
Returns
Name | Type | Description |
---|---|---|
|
| The verified access key object if valid. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function checkAccessKeyValidity(keyId, resourceType, resourceId) {
try {
const verificationResult = await authService.verifyAccessKey({
accessKeyId: keyId,
resourceType,
resourceId,
componentDid: process.env.BLOCKLET_COMPONENT_DID // Assuming current component's DID
});
console.log('Access key verification successful:', verificationResult.data.accessKeyId);
return verificationResult;
} catch (error) {
console.error('Access key verification failed:', error.message);
throw error;
}
}
// Example usage
checkAccessKeyValidity('blocklet-abcdef1234567890', 'data', 'user_records');
Example Response
{
"code": "OK",
"data": {
"accessKeyId": "blocklet-abcdef1234567890",
"remark": "API access for data synchronization",
"passport": "GUEST",
"createdAt": 1678886400000,
"expireAt": 1678890000000,
"authType": "simple",
"componentDid": "",
"resourceType": "data",
"resourceId": "",
"createdVia": "sdk",
"lastUsedAt": 1678887000000
}
}
This example attempts to verify an access key for accessing 'user_records' data.
getAccessKeys(params)#
Retrieves a paginated list of access keys associated with the Blocklet. This allows for auditing and management of issued keys.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing paging, remark, and filtering criteria. |
|
| Optional. Pagination details ( |
|
| Optional. Filter keys by their remark. |
|
| Optional. Filter keys by the component DID they are associated with. |
|
| Optional. Filter keys by resource type. |
|
| Optional. Filter keys by resource ID. |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing an array of access key objects and pagination information. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function listAllAccessKeys() {
try {
const keys = await authService.getAccessKeys({
paging: { page: 1, pageSize: 10 },
remark: 'API access'
});
console.log(`Found ${keys.paging.total} access keys:`);
keys.list.forEach(key => console.log(`- ${key.accessKeyId} (Remark: ${key.remark})`));
return keys;
} catch (error) {
console.error('Failed to list access keys:', error.message);
throw error;
}
}
// Example usage
listAllAccessKeys();
Example Response
{
"code": "OK",
"list": [
{
"accessKeyId": "blocklet-abcdef1234567890",
"remark": "API access for data synchronization",
"passport": "GUEST",
"createdAt": 1678886400000
}
],
"paging": {
"total": 1,
"pageSize": 10,
"pageCount": 1,
"page": 1
}
}
This example lists access keys with the remark 'API access', showing the first 10 results.
getAccessKey(params)#
Retrieves detailed information for a specific access key by its ID.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing the |
|
| The unique ID of the access key to retrieve. |
Returns
Name | Type | Description |
---|---|---|
|
| The detailed access key object. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchAccessKeyDetails(keyId) {
try {
const keyDetails = await authService.getAccessKey({ accessKeyId: keyId });
console.log('Access key details:', keyDetails.data);
return keyDetails;
} catch (error) {
console.error('Failed to fetch access key details:', error.message);
throw error;
}
}
// Example usage
fetchAccessKeyDetails('blocklet-abcdef1234567890');
Example Response
{
"code": "OK",
"data": {
"accessKeyId": "blocklet-abcdef1234567890",
"accessKeyPublic": "0x...",
"remark": "API access for data synchronization",
"passport": "GUEST",
"createdAt": 1678886400000,
"lastUsedAt": 1678887000000,
"authType": "simple",
"componentDid": "",
"resourceType": "data",
"resourceId": "",
"createdVia": "sdk",
"expireAt": 1678890000000
}
}
This example fetches the full details of a specific access key.
Other Utilities#
getBlocklet(attachRuntimeInfo)#
Retrieves detailed information about the current Blocklet application, including its metadata, status, and optional runtime statistics.
Parameters
Name | Type | Description |
---|---|---|
|
| Optional. If |
Returns
Name | Type | Description |
---|---|---|
|
| An object containing the Blocklet's state and metadata. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchBlockletInfo() {
try {
const blockletInfo = await authService.getBlocklet(true);
console.log('Current Blocklet Name:', blockletInfo.blocklet.meta.name);
console.log('Status:', blockletInfo.blocklet.status);
if (blockletInfo.blocklet.runtimeInfo) {
console.log('CPU Usage:', blockletInfo.blocklet.runtimeInfo.cpuUsage);
console.log('Memory Usage:', blockletInfo.blocklet.runtimeInfo.memoryUsage);
}
return blockletInfo;
} catch (error) {
console.error('Failed to fetch Blocklet info:', error.message);
throw error;
}
}
// Example usage
fetchBlockletInfo();
Example Response
{
"code": "OK",
"blocklet": {
"meta": {
"did": "did:abt:zNKgL8xYf1r...",
"name": "my-awesome-blocklet",
"version": "1.0.0",
"title": "My Awesome Blocklet"
},
"status": "running",
"runtimeInfo": {
"cpuUsage": 0.15,
"memoryUsage": 128,
"uptime": "1h 30m"
}
}
}
This example retrieves the current Blocklet's information, including its runtime statistics.
getComponent(did)#
Retrieves the state and metadata for a specific component installed within the current Blocklet application.
Parameters
Name | Type | Description |
---|---|---|
|
| The DID of the component to retrieve. |
Returns
Name | Type | Description |
---|---|---|
|
| The state object of the requested component. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchComponentDetails(componentDid) {
try {
const componentDetails = await authService.getComponent(componentDid);
console.log('Component details:', componentDetails.meta.name, componentDetails.status);
return componentDetails;
} catch (error) {
console.error('Failed to fetch component details:', error.message);
throw error;
}
}
// Example usage
fetchComponentDetails('did:abt:zNKuA7xYf1r...'); // Replace with an actual component DID
Example Response
{
"meta": {
"did": "did:abt:zNKuA7xYf1r...",
"name": "my-sub-component",
"version": "0.5.0",
"title": "My Sub Component"
},
"status": "running",
"mountPoint": "/sub"
}
This example fetches the details of a specified sub-component.
getTrustedDomains()#
Retrieves a list of domains that are configured as trusted by the Blocklet Server. This is relevant for cross-domain interactions and security policies.
Parameters
None.
Returns
Name | Type | Description |
---|---|---|
|
| An array of trusted domain strings. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchTrustedDomains() {
try {
const trustedDomains = await authService.getTrustedDomains();
console.log('Trusted domains:', trustedDomains);
return trustedDomains;
} catch (error) {
console.error('Failed to fetch trusted domains:', error.message);
throw error;
}
}
// Example usage
fetchTrustedDomains();
Example Response
[
"https://example.com",
"https://another-trusted-domain.org"
]
This example fetches and logs the list of trusted domains.
clearCache(args)#
Clears internal caches on the Blocklet Server, which can be useful for ensuring the latest data is fetched or after configuration changes.
Parameters
Name | Type | Description |
---|---|---|
|
| An object containing a |
|
| Optional. A pattern to match specific cache entries to clear. If not provided, all caches are cleared. |
Returns
Name | Type | Description |
---|---|---|
|
| An object indicating the success of the operation and listing removed cache entries. |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function invalidateCache(pattern) {
try {
const result = await authService.clearCache({ pattern });
console.log('Cache cleared. Removed entries:', result.removed);
return result;
} catch (error) {
console.error('Failed to clear cache:', error.message);
throw error;
}
}
// Example usage: Clear all caches
invalidateCache('');
// Example usage: Clear caches matching a pattern
invalidateCache('user:*');
Example Response
{
"code": "OK",
"removed": [
"cache_key_1",
"cache_key_2"
]
}
This example clears all internal caches and logs the removed entries.
getVault()#
Retrieves information about the Blocklet's vault, which stores sensitive data like application secrets. This method verifies the vault using the permanent wallet's address.
Parameters
None.
Returns
Name | Type | Description |
---|---|---|
|
| A string representing the vault's status or content (specific format depends on internal implementation, often a DID or status). |
Example
import Auth from '@blocklet/sdk/service/auth';
const authService = new Auth();
async function fetchVaultStatus() {
try {
const vaultStatus = await authService.getVault();
console.log('Vault Status:', vaultStatus);
return vaultStatus;
} catch (error) {
console.error('Failed to get vault status:', error.message);
throw error;
}
}
// Example usage
fetchVaultStatus();
Example Response
"vault_did:abt:zNKgL8xYf1r..."
This example retrieves the current status or identifier of the Blocklet's vault.
The Auth Service provides a robust set of APIs for managing identities and access within your Blocklet. From user authentication to fine-grained permission control, these functionalities are essential for building secure applications. Next, explore how to integrate decentralized identity authentication flows using DID Connect.