use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class AuthenticationHelper method authenticate.
/**
* Helper to authenticate the current user using session based Ticket information.
* <p>
* User information is looked up in the Session. If found the ticket is retrieved and validated.
* If no User info is found or the ticket is invalid then a redirect is performed to the login page.
*
* @param forceGuest True to force a Guest login attempt
* @param allowGuest True to allow the Guest user if no user object represent
*
* @return AuthenticationStatus result.
*/
public static AuthenticationStatus authenticate(ServletContext sc, HttpServletRequest req, HttpServletResponse res, boolean forceGuest, boolean allowGuest) throws IOException {
if (logger.isDebugEnabled())
logger.debug("Authenticating the current user using session based Ticket information.");
// retrieve the User object
User user = getUser(sc, req, res);
HttpSession session = req.getSession();
// get the login bean if we're not in the portal
LoginBean loginBean = null;
if (Application.inPortalServer() == false) {
if (logger.isDebugEnabled())
logger.debug("We're not in the portal, getting the login bean.");
loginBean = (LoginBean) session.getAttribute(LOGIN_BEAN);
}
// setup the authentication context
WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
AuthenticationService auth = (AuthenticationService) wc.getBean(AUTHENTICATION_SERVICE);
if (logger.isDebugEnabled())
logger.debug("Force guest is: " + forceGuest);
if (user == null || forceGuest) {
if (logger.isDebugEnabled())
logger.debug("The user is null.");
// the last stored username string is cleared.
if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) == null) {
if (logger.isDebugEnabled())
logger.debug("The session is not invalidated.");
Cookie authCookie = getAuthCookie(req);
if (allowGuest == true && (authCookie == null || forceGuest)) {
if (logger.isDebugEnabled())
logger.debug("No previous authentication or forced Guest - attempt Guest access.");
try {
auth.authenticateAsGuest();
// if we get here then Guest access was allowed and successful
setUser(sc, req, AuthenticationUtil.getGuestUserName(), auth.getCurrentTicket(), false);
// Set up the thread context
setupThread(sc, req, res, true);
// remove the session invalidated flag
session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED);
if (logger.isDebugEnabled())
logger.debug("Successfully authenticated as guest.");
// it is the responsibilty of the caller to handle the Guest return status
return AuthenticationStatus.Guest;
} catch (AuthenticationException guestError) {
if (logger.isDebugEnabled())
logger.debug("An AuthenticationException occurred, expected if Guest access not allowed - continue to login page as usual", guestError);
} catch (AccessDeniedException accessError) {
// Guest is unable to access either properties on Person
AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
unprotAuthService.clearCurrentSecurityContext();
logger.warn("Unable to login as Guest: ", accessError);
} catch (Throwable e) {
// Some other kind of serious failure to report
AuthenticationService unprotAuthService = (AuthenticationService) wc.getBean(UNPROTECTED_AUTH_SERVICE);
unprotAuthService.invalidateTicket(unprotAuthService.getCurrentTicket());
unprotAuthService.clearCurrentSecurityContext();
throw new AlfrescoRuntimeException("Failed to authenticate as Guest user.", e);
}
}
}
if (logger.isDebugEnabled())
logger.debug("Session invalidated - return to login screen.");
return AuthenticationStatus.Failure;
} else {
if (logger.isDebugEnabled())
logger.debug("The user is: " + user.getUserName());
// set last authentication username cookie value
String loginName;
if (loginBean != null && (loginName = loginBean.getUsernameInternal()) != null) {
if (logger.isDebugEnabled())
logger.debug("Set last authentication username cookie value");
setUsernameCookie(req, res, loginName);
}
// Set up the thread context
setupThread(sc, req, res, true);
return AuthenticationStatus.Success;
}
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class AuthenticationHelper method createUser.
/**
* Creates an object for an authentication user.
*
* @param wc
* the web application context
* @param currentUsername
* the current user name
* @param ticket
* a validated ticket
* @return the user object
*/
private static User createUser(final WebApplicationContext wc, final String currentUsername, final String ticket) {
if (logger.isDebugEnabled())
logger.debug("Creating an object for " + currentUsername + " with ticket: " + ticket);
final ServiceRegistry services = (ServiceRegistry) wc.getBean(ServiceRegistry.SERVICE_REGISTRY);
// If the repository is read only, we have to settle for a read only transaction. Auto user creation
// will not be possible.
boolean readOnly = services.getTransactionService().isReadOnly();
return services.getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<User>() {
public User execute() throws Throwable {
NodeService nodeService = services.getNodeService();
PersonService personService = (PersonService) wc.getBean(PERSON_SERVICE);
NodeRef personRef = personService.getPerson(currentUsername);
User user = new User(currentUsername, ticket, personRef);
NodeRef homeRef = (NodeRef) nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER);
if (homeRef == null || !nodeService.exists(homeRef)) {
throw new AuthenticationException("Home folder is missing for user " + currentUsername);
}
user.setHomeSpaceId(homeRef.getId());
return user;
}
}, readOnly, false);
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class AlfrescoFacesPortlet method processAction.
/**
* Called by the portlet container to allow the portlet to process an action request.
*/
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
Application.setInPortalServer(true);
try {
// Set the current locale
I18NUtil.setLocale(getLanguage(request.getPortletSession()));
boolean isMultipart = PortletFileUpload.isMultipartContent(request);
if (isMultipart) {
if (logger.isDebugEnabled())
logger.debug("Handling multipart request...");
PortletSession session = request.getPortletSession();
// get the file from the request and put it in the session
DiskFileItemFactory factory = new DiskFileItemFactory();
PortletFileUpload upload = new PortletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
Iterator<FileItem> iter = fileItems.iterator();
FileUploadBean bean = new FileUploadBean();
while (iter.hasNext()) {
FileItem item = iter.next();
String filename = item.getName();
if (item.isFormField() == false) {
if (logger.isDebugEnabled())
logger.debug("Processing uploaded file: " + filename);
// workaround a bug in IE where the full path is returned
// IE is only available for Windows so only check for the Windows path separator
int idx = filename.lastIndexOf('\\');
if (idx == -1) {
// if there is no windows path separator check for *nix
idx = filename.lastIndexOf('/');
}
if (idx != -1) {
filename = filename.substring(idx + File.separator.length());
}
File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(tempFile);
bean.setFile(tempFile);
bean.setFileName(filename);
bean.setFilePath(tempFile.getAbsolutePath());
session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean, PortletSession.PORTLET_SCOPE);
}
}
// Set the VIEW_ID parameter to tell the faces portlet bridge to treat the request
// as a JSF request, this will send us back to the previous page we came from.
String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID);
if (lastViewId != null) {
response.setRenderParameter(VIEW_ID, lastViewId);
}
} else {
SessionUser sessionUser = (SessionUser) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
User user = sessionUser instanceof User ? (User) sessionUser : null;
if (user != null) {
// setup the authentication context
try {
WebApplicationContext ctx = (WebApplicationContext) getPortletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
auth.validate(user.getTicket());
// save last username into portlet preferences, get from LoginBean state
LoginBean loginBean = (LoginBean) request.getPortletSession().getAttribute(AuthenticationHelper.LOGIN_BEAN);
if (loginBean != null) {
// TODO: Need to login to the Portal to get a user here to store prefs against
// so not really a suitable solution as they get thrown away at present!
// Also would need to store prefs PER user - so auto login for each...?
String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null);
if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) {
if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
request.getPreferences().setValue(PREF_ALF_USERNAME, loginBean.getUsernameInternal());
request.getPreferences().store();
}
}
}
// do the normal JSF processing
super.processAction(request, response);
} catch (AuthenticationException authErr) {
// remove User object as it's now useless
request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER, PortletSession.APPLICATION_SCOPE);
}
} else {
// do the normal JSF processing as we may be on the login page
super.processAction(request, response);
}
}
} catch (Throwable e) {
if (getErrorPage() != null) {
handleError(request, response, e);
} else {
logger.warn("No error page configured, re-throwing exception");
if (e instanceof PortletException) {
throw (PortletException) e;
} else if (e instanceof IOException) {
throw (IOException) e;
} else {
throw new PortletException(e);
}
}
} finally {
Application.setInPortalServer(false);
}
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project acs-community-packaging by Alfresco.
the class NewUserWizard method finish.
/**
* @see org.alfresco.web.bean.wizard.AbstractWizardBean#finish()
*/
public String finish() {
String outcome = FINISH_OUTCOME;
// TODO: implement create new Person object from specified details
UserTransaction tx = null;
try {
FacesContext context = FacesContext.getCurrentInstance();
tx = Repository.getUserTransaction(context);
tx.begin();
if (this.editMode) {
// update the existing node in the repository
NodeRef nodeRef = getPerson().getNodeRef();
Map<QName, Serializable> props = this.getNodeService().getProperties(nodeRef);
props.put(ContentModel.PROP_USERNAME, this.userName);
props.put(ContentModel.PROP_FIRSTNAME, this.firstName);
props.put(ContentModel.PROP_LASTNAME, this.lastName);
// calculate whether we need to move the old home space or create new
NodeRef newHomeFolderRef;
NodeRef oldHomeFolderRef = (NodeRef) this.getNodeService().getProperty(nodeRef, ContentModel.PROP_HOMEFOLDER);
boolean moveHomeSpace = false;
boolean renameHomeSpace = false;
if (oldHomeFolderRef != null && this.getNodeService().exists(oldHomeFolderRef) == true) {
// the original home folder ref exists so may need moving if it has been changed
ChildAssociationRef childAssocRef = this.getNodeService().getPrimaryParent(oldHomeFolderRef);
NodeRef currentHomeSpaceLocation = childAssocRef.getParentRef();
if (this.homeSpaceName.length() != 0) {
if (currentHomeSpaceLocation.equals(this.homeSpaceLocation) == false && oldHomeFolderRef.equals(this.homeSpaceLocation) == false && currentHomeSpaceLocation.equals(getCompanyHomeSpace()) == false && currentHomeSpaceLocation.equals(getDefaultHomeSpace()) == false) {
moveHomeSpace = true;
}
String oldHomeSpaceName = Repository.getNameForNode(getNodeService(), oldHomeFolderRef);
if (oldHomeSpaceName.equals(this.homeSpaceName) == false && oldHomeFolderRef.equals(this.homeSpaceLocation) == false && oldHomeFolderRef.equals(this.defaultHomeSpaceRef) == false) {
renameHomeSpace = true;
}
}
}
if (logger.isDebugEnabled())
logger.debug("Moving space: " + moveHomeSpace + " and renaming space: " + renameHomeSpace);
if (moveHomeSpace == false && renameHomeSpace == false) {
if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) {
newHomeFolderRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, false);
} else if (this.homeSpaceLocation != null) {
// location selected but no home space name entered,
// so the home ref should be set to the newly selected space
newHomeFolderRef = this.homeSpaceLocation;
// set the permissions for this space so the user can access it
} else {
// nothing selected - use Company Home by default
newHomeFolderRef = getCompanyHomeSpace();
}
} else {
// either move, rename or both required
if (moveHomeSpace == true) {
this.getNodeService().moveNode(oldHomeFolderRef, this.homeSpaceLocation, ContentModel.ASSOC_CONTAINS, this.getNodeService().getPrimaryParent(oldHomeFolderRef).getQName());
}
// ref ID doesn't change
newHomeFolderRef = oldHomeFolderRef;
if (renameHomeSpace == true) {
// change HomeSpace node name
this.getNodeService().setProperty(newHomeFolderRef, ContentModel.PROP_NAME, this.homeSpaceName);
}
}
props.put(ContentModel.PROP_HOMEFOLDER, newHomeFolderRef);
props.put(ContentModel.PROP_EMAIL, this.email);
props.put(ContentModel.PROP_ORGID, this.companyId);
this.getNodeService().setProperties(nodeRef, props);
// TODO: RESET HomeSpace Ref found in top-level navigation bar!
// NOTE: not need cos only admin can do this?
} else {
if (tenantService.isEnabled()) {
String currentDomain = tenantService.getCurrentUserDomain();
if (!currentDomain.equals(TenantService.DEFAULT_DOMAIN)) {
if (!tenantService.isTenantUser(this.userName)) {
// force domain onto the end of the username
this.userName = tenantService.getDomainUser(this.userName, currentDomain);
logger.warn("Added domain to username: " + this.userName);
} else {
try {
tenantService.checkDomainUser(this.userName);
} catch (RuntimeException re) {
throw new AuthenticationException("User must belong to same domain as admin: " + currentDomain);
}
}
}
}
if (this.password.equals(this.confirm)) {
// create properties for Person type from submitted Form data
Map<QName, Serializable> props = new HashMap<QName, Serializable>(7, 1.0f);
props.put(ContentModel.PROP_USERNAME, this.userName);
props.put(ContentModel.PROP_FIRSTNAME, this.firstName);
props.put(ContentModel.PROP_LASTNAME, this.lastName);
NodeRef homeSpaceNodeRef;
if (this.homeSpaceLocation != null && this.homeSpaceName.length() != 0) {
// create new
homeSpaceNodeRef = createHomeSpace(this.homeSpaceLocation.getId(), this.homeSpaceName, true);
} else if (this.homeSpaceLocation != null) {
// set to existing
homeSpaceNodeRef = homeSpaceLocation;
setupHomeSpacePermissions(homeSpaceNodeRef);
} else {
// default to Company Home
homeSpaceNodeRef = getCompanyHomeSpace();
}
props.put(ContentModel.PROP_HOMEFOLDER, homeSpaceNodeRef);
props.put(ContentModel.PROP_EMAIL, this.email);
props.put(ContentModel.PROP_ORGID, this.companyId);
// create the node to represent the Person
NodeRef newPerson = this.getPersonService().createPerson(props);
// ensure the user can access their own Person object
this.getPermissionService().setPermission(newPerson, this.userName, getPermissionService().getAllPermission(), true);
if (logger.isDebugEnabled())
logger.debug("Created Person node for username: " + this.userName);
// create the ACEGI Authentication instance for the new user
this.getAuthenticationService().createAuthentication(this.userName, this.password.toCharArray());
if (logger.isDebugEnabled())
logger.debug("Created User Authentication instance for username: " + this.userName);
} else {
outcome = null;
Utils.addErrorMessage(Application.getMessage(context, UsersDialog.ERROR_PASSWORD_MATCH));
}
}
// commit the transaction
tx.commit();
// reset the richlist component so it rebinds to the users list
invalidateUserList();
} catch (Throwable e) {
// rollback the transaction
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), ERROR), e.getMessage()), e);
outcome = null;
}
return outcome;
}
use of org.alfresco.repo.security.authentication.AuthenticationException in project alfresco-remote-api by Alfresco.
the class PeopleImpl method updatePassword.
private void updatePassword(boolean isAdmin, String personIdToUpdate, Person person) {
MutableAuthenticationService mutableAuthenticationService = (MutableAuthenticationService) authenticationService;
boolean isOldPassword = person.wasSet(Person.PROP_PERSON_OLDPASSWORD);
boolean isPassword = person.wasSet(Person.PROP_PERSON_PASSWORD);
if (isPassword || isOldPassword) {
if (isOldPassword && ((person.getOldPassword() == null) || (person.getOldPassword().isEmpty()))) {
throw new IllegalArgumentException("'oldPassword' field cannot be empty.");
}
if (!isPassword || (person.getPassword() == null) || (person.getPassword().isEmpty())) {
throw new IllegalArgumentException("password' field cannot be empty.");
}
char[] newPassword = person.getPassword().toCharArray();
if (!isAdmin) {
// Non-admin users can update their own password, but must provide their current password.
if (!isOldPassword) {
throw new IllegalArgumentException("To change password, both 'oldPassword' and 'password' fields are required.");
}
char[] oldPassword = person.getOldPassword().toCharArray();
try {
mutableAuthenticationService.updateAuthentication(personIdToUpdate, oldPassword, newPassword);
} catch (AuthenticationException e) {
throw new PermissionDeniedException("Incorrect password.");
}
} else {
// An admin user can update without knowing the original pass - but must know their own!
// note: is it reasonable to silently ignore oldPassword if supplied ?
mutableAuthenticationService.setAuthentication(personIdToUpdate, newPassword);
}
}
}
Aggregations