The UserDirectoryService manages end-user modeling for Sakai, including user creation, authentication, and user information retrieval.
Overview
Package: org.sakaiproject.user.api
The UserDirectoryService provides comprehensive user management capabilities including:
- User creation and modification
- Authentication and password validation
- User search and retrieval
- Email-based user lookup
- EID (Enterprise ID) to internal ID mapping
Constants
APPLICATION_ID
String
default:"sakai:user"
Application identifier for the user service
Root path for user resource references
User ID for the admin user
Enterprise ID for the admin user
Security Functions
Permission to remove a user
SECURE_UPDATE_USER_ANY
String
default:"user.upd.any"
Permission to update any user’s information
SECURE_UPDATE_USER_OWN
String
default:"user.upd.own"
Permission to update own user information
SECURE_VIEW_USER_ANY
String
default:"user.view.any"
Permission to view any user’s details
Core Methods
User Retrieval
getUser
User getUser(String id) throws UserNotDefinedException
Access a user object by internal user ID.
User object containing the user information
Throws:
UserNotDefinedException - if user not found
Example:
try {
User user = userDirectoryService.getUser(userId);
String email = user.getEmail();
String displayName = user.getDisplayName();
} catch (UserNotDefinedException e) {
// Handle user not found
}
getOptionalUser
Optional<User> getOptionalUser(String userId)
Access a user object as an Optional.
Optional containing the user information if found
Example:
Optional<User> optUser = userDirectoryService.getOptionalUser(userId);
optUser.ifPresent(user -> {
log.info("Found user: " + user.getDisplayName());
});
getUserByEid
User getUserByEid(String eid) throws UserNotDefinedException
Access a user object by enterprise ID.
The user enterprise ID (login username)
User object containing the user information
Throws:
UserNotDefinedException - if user not found
getCurrentUser
Access the user object associated with the current request.
The current user (may be anonymous)
Example:
User currentUser = userDirectoryService.getCurrentUser();
if (currentUser.equals(userDirectoryService.getAnonymousUser())) {
// User is not logged in
} else {
String userId = currentUser.getId();
}
getAnonymousUser
Access the anonymous user object. Useful for testing if current user is logged in.
The anonymous user object
User Creation
addUser (Simple)
UserEdit addUser(String id, String eid)
throws UserIdInvalidException, UserAlreadyDefinedException, UserPermissionException
Add a new user to the directory. Must call commitEdit() to save or cancelEdit() when done.
The user UUID string. Leave null for auto-assignment
The user enterprise ID (login username)
A locked UserEdit object for modification
Throws:
UserIdInvalidException - if the user eid is invalid
UserAlreadyDefinedException - if the user id or eid is already used
UserPermissionException - if current user lacks permission
Example:
try {
UserEdit user = userDirectoryService.addUser(null, "jsmith");
user.setFirstName("John");
user.setLastName("Smith");
user.setEmail("[email protected]");
user.setType("student");
userDirectoryService.commitEdit(user);
} catch (UserAlreadyDefinedException e) {
// Handle duplicate user
}
addUser (Complete)
User addUser(String id, String eid, String firstName, String lastName,
String email, String pw, String type, ResourceProperties properties)
throws UserIdInvalidException, UserAlreadyDefinedException, UserPermissionException
Add a new user to the directory, complete in one operation.
The user UUID string. Leave null for auto-assignment
The user type (e.g., “student”, “instructor”)
Additional user properties
Authentication
authenticate
User authenticate(String loginId, String password)
Authenticate a user with login ID and password.
The string identifying the user (typically EID)
The authenticated User object if successful, null if not
Example:
User user = userDirectoryService.authenticate(username, password);
if (user != null) {
// Authentication successful
sessionManager.getCurrentSession().setUserId(user.getId());
} else {
// Authentication failed
}
validatePassword
PasswordRating validatePassword(String password, User user)
Validate if a password meets the password policy requirements.
The user this password is for (optional, uses current user if null)
Enum indicating password strength: FAILED, PASSED_DEFAULT, PASSED_UNRATED, WEAK, MODERATE, or STRONG
Example:
PasswordRating rating = userDirectoryService.validatePassword(newPassword, user);
if (rating.passed()) {
// Password meets requirements
if (rating.equals(PasswordRating.WEAK)) {
// Warn user about weak password
}
} else {
// Password does not meet requirements
}
User Search
searchUsers
List<User> searchUsers(String criteria, int first, int last)
Search users matching criteria in id, email, first or last name.
This method does not search external users (e.g., from LDAP).
The search criteria string
The first record position to return (1-based)
The last record position to return
List of users matching criteria, sorted by sort name
Example:
// Search for users matching "smith" and get first 50 results
List<User> users = userDirectoryService.searchUsers("smith", 1, 50);
for (User user : users) {
System.out.println(user.getDisplayName() + " - " + user.getEmail());
}
searchExternalUsers
List<User> searchExternalUsers(String criteria, int first, int last)
Search externally provided users (e.g., from LDAP) matching criteria.
The search criteria string
The first record position to return
The last record position to return
List of external users matching criteria
findUsersByEmail
Collection<User> findUsersByEmail(String email)
Find users with a specific email address.
The email address to search for
Collection of users with this email (may be empty, never null)
User Modification
editUser
UserEdit editUser(String id)
throws UserNotDefinedException, UserPermissionException, UserLockedException
Get a locked user object for editing. Must call commitEdit() or cancelEdit() when done.
A locked UserEdit object for modification
Throws:
UserNotDefinedException - if user not found
UserPermissionException - if current user lacks permission
UserLockedException - if the user is locked by someone else
Example:
try {
UserEdit user = userDirectoryService.editUser(userId);
user.setEmail("[email protected]");
userDirectoryService.commitEdit(user);
} catch (UserLockedException e) {
// User is being edited by someone else
}
commitEdit
void commitEdit(UserEdit user) throws UserAlreadyDefinedException
Commit changes made to a UserEdit object and release the lock.
The UserEdit object to commit
Throws:
UserAlreadyDefinedException - if the User eid is already in use by another user
cancelEdit
void cancelEdit(UserEdit user)
Cancel changes made to a UserEdit object and release the lock.
The UserEdit object to cancel
User Removal
removeUser
void removeUser(UserEdit user) throws UserPermissionException
Remove a user from the directory. User must be locked with editUser().
The locked UserEdit object to remove
Throws:
UserPermissionException - if current user lacks permission
ID Mapping
getUserId
String getUserId(String eid) throws UserNotDefinedException
Find the internal user ID from an enterprise ID.
Throws:
UserNotDefinedException - if user not found
getUserEid
String getUserEid(String id) throws UserNotDefinedException
Find the enterprise ID from an internal user ID.
Throws:
UserNotDefinedException - if user not found
Permission Checks
allowAddUser
Check if the current user is allowed to add a user.
true if allowed, false otherwise
allowUpdateUser
boolean allowUpdateUser(String id)
Check if the current user is allowed to update a user.
true if allowed, false otherwise
allowRemoveUser
boolean allowRemoveUser(String id)
Check if the current user is allowed to remove a user.
true if allowed, false otherwise
Utility Methods
getUsers (Collection)
List<User> getUsers(Collection<String> ids)
Access multiple user objects by their IDs.
ids
Collection<String>
required
Collection of user IDs
List of User objects for valid IDs
getUsersByEids
List<User> getUsersByEids(Collection<String> eids)
Find users matching the given EID strings.
eids
Collection<String>
required
Collection of enterprise IDs
List of user objects corresponding to valid EIDs
countUsers
Count all users.
userReference
String userReference(String id)
Get the internal reference for accessing a user within the system.
The internal reference (e.g., “/user/“)
User Object
The User interface provides access to user properties:
User user = userDirectoryService.getUser(userId);
// Identity
String id = user.getId(); // Internal ID
String eid = user.getEid(); // Enterprise ID (username)
// Personal Information
String firstName = user.getFirstName();
String lastName = user.getLastName();
String email = user.getEmail();
// Display Names
String displayName = user.getDisplayName(); // For UI display
String sortName = user.getSortName(); // For sorting
String displayId = user.getDisplayId(); // EID for display
// Metadata
String type = user.getType(); // User type
Date created = user.getCreatedDate();
Date modified = user.getModifiedDate();
User createdBy = user.getCreatedBy();
User modifiedBy = user.getModifiedBy();
// Password Check
boolean isValid = user.checkPassword("password");
See Also