Sample Code

The Java SDK now lets you create users, assign them roles and associated privileges, and remove them from the system.

User-Management APIs

Users who have been assigned the Admin role for the cluster are able to create, edit, and remove users. The Java SDK provides APIs to support these activities. A high-level summary of the APIs can be found in User-Management.

Java User-Management Example

The following code-example demonstrates how the user-management APIs can be used. It assumes that Couchbase Server is established on localhost; that the Full Administrator username and password are Administrator and password respectively; and that the travel-sample bucket is installed. For information on installing the travel-sample bucket, see Sample Buckets.

Use of the Full Administrator username and password gives an application complete access to all resources within the Couchbase Server-environment: use of the Full Administrator username and password may therefore be useful during code-development. However, for production purposes, the Full Administrator username and password should only be used when absolutely essential: in all other circumstances, the specified username and password should correspond to some lesser role, which appropriately delimits access to server-resources. Creation of such a role, and the establishment of its associated username and password, is demonstrated in the following code-example.
package com.cb.cbusermgmnt;

import java.util.Arrays;
import java.util.List;

import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.cluster.User;
import com.couchbase.client.java.cluster.UserRole;
import com.couchbase.client.java.cluster.UserSettings;
import com.couchbase.client.java.document.JsonDocument;
import com.couchbase.client.java.document.json.JsonObject;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;

public class CouchbaseUserManagement
{
    public static void main(String [] args)
    {
        // Access the cluster that is running on the local host, authenticating with
        // the username and password of the Full Administrator. This
        // provides all privileges.
        //
        Cluster adminCluster = CouchbaseCluster.create("localhost");

        System.out.println("Authenticating as administrator.");
        adminCluster.authenticate("Administrator", "password");

        // Create a user and assign roles.
        //
        System.out.println("Upserting new user.");
        adminCluster.clusterManager().upsertUser("cbtestuser", UserSettings.build()

            .password("cbtestuserpwd")
            .name("Constance Lambert")
            .roles(Arrays.asList(

                // Roles required for the reading of data from
                // the bucket.
                //
                new UserRole("data_reader", "*"),
                new UserRole("query_select", "*"),

                // Roles required for the writing of data into
                // the bucket.
                //
                new UserRole("data_writer", "travel-sample"),
                new UserRole("query_insert", "travel-sample"),
                new UserRole("query_delete", "travel-sample"),

                // Role required for the creation of indexes
                // on the bucket.
                //
                new UserRole("query_manage_index", "travel-sample")))

            );

        // List current users.
        //
        System.out.println("Listing current users.");
        List<User> listOfUsers = adminCluster.clusterManager().getUsers();

        for (int j = 0; j < listOfUsers.size(); j++)
        {
            User currentUser = listOfUsers.get(j);

            System.out.println("\n" + "\n" + "USER #" + j + ": " + "\n");

            System.out.println("User's name is: " + currentUser.name() + '\n');
            System.out.println("User's id is: " + currentUser.userId() + '\n');
            System.out.println("User's domain is: " + currentUser.domain() + '\n');

            UserRole currentRoles[] = currentUser.roles();

            for (int i = 0; i < currentRoles.length; i++)
            {
                System.out.println("User has the role: " + currentRoles[i].role()
                    + ", applicable to bucket "
                        + currentRoles[i].bucket() + '\n');
            }
        }

        adminCluster.disconnect();

        // Access the cluster that is running on the local host, specifying
        // the username and password already assigned by the administrator
        // (see the program CbBucketCreation).
        //
        Cluster userCluster = CouchbaseCluster.create("localhost");
        System.out.println("Authenticating as user.");
        userCluster.authenticate("cbtestuser", "cbtestuserpwd");

        // Open a known, existing bucket (created by the administrator).
        //
        System.out.println("Opening travel-sample bucket as user.");
        Bucket travelSample = userCluster.openBucket("travel-sample");

        // Create a N1QL Primary Index (but ignore if one already exists).
        //
        travelSample.bucketManager().createN1qlPrimaryIndex(true, false);

        // Read out a known, existing document within the bucket (created
        // by the administrator).
        //
        System.out.println("Reading out airline_10 document" + "\n");
        JsonDocument returnedAirline10doc = travelSample.get("airline_10");
        System.out.println("Found: " + returnedAirline10doc);

        // Create a new document.
        //
        System.out.println("Creating new document as user.");
        JsonObject airline11Object = JsonObject.empty()
            .put("callsign", "MILE-AIR")
            .put("iata", "Q5")
            .put("icao", "MLA")
            .put("id", 11)
            .put("name", "40-Mile Air")
            .put("type", "airline");

        JsonDocument airline11Document = JsonDocument.create("airline_11", airline11Object);

        // Upsert the document to the bucket.
        //
        System.out.println("Upserting new document as user.");
        travelSample.upsert(airline11Document);

        System.out.println("Reading out airline11Document as user.");
        JsonDocument returnedAirline11Doc = travelSample.get("airline_11");
        System.out.println("Found: " + returnedAirline11Doc);

        // Perform a N1QL Query.
        //
        System.out.println("Performing query as user.\n");
        String returnedValues = "Query-results are: \n\t";

        N1qlQueryResult result = travelSample.query(
            N1qlQuery.simple("SELECT * FROM `travel-sample` LIMIT 5")
        );

        // Print each row returned by the query.
        //
        for (N1qlQueryRow row : result)
        {
            returnedValues = returnedValues + row + '\n' + '\n' + '\t';
        }

        System.out.println(returnedValues);

        userCluster.disconnect();

        // Access the cluster that is running on the local host, authenticating with
        // the username and password of the Full Administrator. This
        // provides all privileges.
        //
        System.out.println("Re-authenticating as administrator.");
        adminCluster.authenticate("Administrator", "password");

        // Remove known user.
        //
        System.out.println("Removing user as administrator.");
        String userToBeRemoved = "cbtestuser";
        boolean userWasRemoved = adminCluster.clusterManager().removeUser(userToBeRemoved);

        if (!userWasRemoved)
        {
            System.out.println("Could not delete user " + userToBeRemoved + ".");
        }
        else
        {
            System.out.println("Deleted user " + userToBeRemoved + ".");
        }

        // Disconnect from the cluster.
        //
        adminCluster.disconnect();
    }
}