use of org.apache.wiki.WikiSession in project jspwiki by apache.
the class SessionMonitor method find.
/**
* <p>Looks up the wiki session associated with a user's Http session
* and adds it to the session cache. This method will return the
* "guest session" as constructed by {@link WikiSession#guestSession(WikiEngine)}
* if the HttpSession is not currently associated with a WikiSession.
* This method is guaranteed to return a non-<code>null</code> WikiSession.</p>
* <p>Internally, the session is stored in a HashMap; keys are
* the HttpSession objects, while the values are
* {@link java.lang.ref.WeakReference}-wrapped WikiSessions.</p>
* @param session the HTTP session
* @return the wiki session
*/
public final WikiSession find(HttpSession session) {
WikiSession wikiSession = findSession(session);
String sid = (session == null) ? "(null)" : session.getId();
// Otherwise, create a new guest session and stash it.
if (wikiSession == null) {
if (log.isDebugEnabled()) {
log.debug("Looking up WikiSession for session ID=" + sid + "... not found. Creating guestSession()");
}
wikiSession = WikiSession.guestSession(m_engine);
synchronized (m_sessions) {
m_sessions.put(sid, wikiSession);
}
}
return wikiSession;
}
use of org.apache.wiki.WikiSession in project jspwiki by apache.
the class UserManager method validateProfile.
/**
* Validates a user profile, and appends any errors to the session errors
* list. If the profile is new, the password will be checked to make sure it
* isn't null. Otherwise, the password is checked for length and that it
* matches the value of the 'password2' HTTP parameter. Note that we have a
* special case when container-managed authentication is used and the user
* is not authenticated; this will always cause validation to fail. Any
* validation errors are added to the wiki session's messages collection
* (see {@link WikiSession#getMessages()}.
* @param context the current wiki context
* @param profile the supplied UserProfile
*/
public void validateProfile(WikiContext context, UserProfile profile) {
final boolean isNew = profile.isNew();
final WikiSession session = context.getWikiSession();
final InputValidator validator = new InputValidator(SESSION_MESSAGES, context);
final ResourceBundle rb = Preferences.getBundle(context, InternationalizationManager.CORE_BUNDLE);
//
// Query the SpamFilter first
//
final FilterManager fm = m_engine.getFilterManager();
final List<PageFilter> ls = fm.getFilterList();
for (final PageFilter pf : ls) {
if (pf instanceof SpamFilter) {
if (((SpamFilter) pf).isValidUserProfile(context, profile) == false) {
session.addMessage(SESSION_MESSAGES, "Invalid userprofile");
return;
}
break;
}
}
// If container-managed auth and user not logged in, throw an error
if (m_engine.getAuthenticationManager().isContainerAuthenticated() && !context.getWikiSession().isAuthenticated()) {
session.addMessage(SESSION_MESSAGES, rb.getString("security.error.createprofilebeforelogin"));
}
validator.validateNotNull(profile.getLoginName(), rb.getString("security.user.loginname"));
validator.validateNotNull(profile.getFullname(), rb.getString("security.user.fullname"));
validator.validate(profile.getEmail(), rb.getString("security.user.email"), InputValidator.EMAIL);
// If new profile, passwords must match and can't be null
if (!m_engine.getAuthenticationManager().isContainerAuthenticated()) {
final String password = profile.getPassword();
if (password == null) {
if (isNew) {
session.addMessage(SESSION_MESSAGES, rb.getString("security.error.blankpassword"));
}
} else {
final HttpServletRequest request = context.getHttpRequest();
final String password2 = (request == null) ? null : request.getParameter("password2");
if (!password.equals(password2)) {
session.addMessage(SESSION_MESSAGES, rb.getString("security.error.passwordnomatch"));
}
}
}
UserProfile otherProfile;
final String fullName = profile.getFullname();
final String loginName = profile.getLoginName();
final String email = profile.getEmail();
// It's illegal to use as a full name someone else's login name
try {
otherProfile = getUserDatabase().find(fullName);
if (otherProfile != null && !profile.equals(otherProfile) && !fullName.equals(otherProfile.getFullname())) {
final Object[] args = { fullName };
session.addMessage(SESSION_MESSAGES, MessageFormat.format(rb.getString("security.error.illegalfullname"), args));
}
} catch (final NoSuchPrincipalException e) {
/* It's clean */
}
// It's illegal to use as a login name someone else's full name
try {
otherProfile = getUserDatabase().find(loginName);
if (otherProfile != null && !profile.equals(otherProfile) && !loginName.equals(otherProfile.getLoginName())) {
final Object[] args = { loginName };
session.addMessage(SESSION_MESSAGES, MessageFormat.format(rb.getString("security.error.illegalloginname"), args));
}
} catch (final NoSuchPrincipalException e) {
/* It's clean */
}
// It's illegal to use multiple accounts with the same email
try {
otherProfile = getUserDatabase().findByEmail(email);
if (otherProfile != null && // Issue JSPWIKI-1042
!profile.getUid().equals(otherProfile.getUid()) && !profile.equals(otherProfile) && StringUtils.lowerCase(email).equals(StringUtils.lowerCase(otherProfile.getEmail()))) {
final Object[] args = { email };
session.addMessage(SESSION_MESSAGES, MessageFormat.format(rb.getString("security.error.email.taken"), args));
}
} catch (final NoSuchPrincipalException e) {
/* It's clean */
}
}
use of org.apache.wiki.WikiSession in project jspwiki by apache.
the class AuthenticationManager method logout.
/**
* Logs the user out by retrieving the WikiSession associated with the
* HttpServletRequest and unbinding all of the Subject's Principals,
* except for {@link Role#ALL}, {@link Role#ANONYMOUS}.
* is a cheap-and-cheerful way to do it without invoking JAAS LoginModules.
* The logout operation will also flush the JSESSIONID cookie from
* the user's browser session, if it was set.
* @param request the current HTTP request
*/
public void logout(HttpServletRequest request) {
if (request == null) {
log.error("No HTTP reqest provided; cannot log out.");
return;
}
HttpSession session = request.getSession();
String sid = (session == null) ? "(null)" : session.getId();
if (log.isDebugEnabled()) {
log.debug("Invalidating WikiSession for session ID=" + sid);
}
// Retrieve the associated WikiSession and clear the Principal set
WikiSession wikiSession = WikiSession.getWikiSession(m_engine, request);
Principal originalPrincipal = wikiSession.getLoginPrincipal();
wikiSession.invalidate();
// Remove the wikiSession from the WikiSession cache
WikiSession.removeWikiSession(m_engine, request);
// We need to flush the HTTP session too
if (session != null) {
session.invalidate();
}
// Log the event
fireEvent(WikiSecurityEvent.LOGOUT, originalPrincipal, null);
}
use of org.apache.wiki.WikiSession in project jspwiki by apache.
the class AuthenticationManager method login.
/**
* <p>Logs in the user by attempting to populate a WikiSession Subject from
* a web servlet request by examining the request
* for the presence of container credentials and user cookies. The processing
* logic is as follows:
* </p>
* <ul>
* <li>If the WikiSession had previously been unauthenticated, check to see if
* user has subsequently authenticated. To be considered "authenticated,"
* the request must supply one of the following (in order of preference):
* the container <code>userPrincipal</code>, container <code>remoteUser</code>,
* or authentication cookie. If the user is authenticated, this method fires event
* {@link org.apache.wiki.event.WikiSecurityEvent#LOGIN_AUTHENTICATED}
* with two parameters: a Principal representing the login principal,
* and the current WikiSession. In addition, if the authorizer is of type
* WebContainerAuthorizer, this method iterates through the container roles returned by
* {@link org.apache.wiki.auth.authorize.WebContainerAuthorizer#getRoles()},
* tests for membership in each one, and adds those that pass to the Subject's principal set.</li>
* <li>If, after checking for authentication, the WikiSession is still Anonymous,
* this method next checks to see if the user has "asserted" an identity
* by supplying an assertion cookie. If the user is found to be asserted,
* this method fires event {@link org.apache.wiki.event.WikiSecurityEvent#LOGIN_ASSERTED}
* with two parameters: <code>WikiPrincipal(<em>cookievalue</em>)</code>, and
* the current WikiSession.</li>
* <li>If, after checking for authenticated and asserted status, the WikiSession is
* <em>still</em> anonymous, this method fires event
* {@link org.apache.wiki.event.WikiSecurityEvent#LOGIN_ANONYMOUS} with
* two parameters: <code>WikiPrincipal(<em>remoteAddress</em>)</code>,
* and the current WikiSession </li>
* </ul>
* @param request servlet request for this user
* @return always returns <code>true</code> (because anonymous login, at least, will always succeed)
* @throws org.apache.wiki.auth.WikiSecurityException if the user cannot be logged in for any reason
* @since 2.3
*/
public boolean login(HttpServletRequest request) throws WikiSecurityException {
HttpSession httpSession = request.getSession();
WikiSession session = SessionMonitor.getInstance(m_engine).find(httpSession);
AuthenticationManager authenticationMgr = m_engine.getAuthenticationManager();
AuthorizationManager authorizationMgr = m_engine.getAuthorizationManager();
CallbackHandler handler = null;
Map<String, String> options = EMPTY_MAP;
// there's an authentication cookie
if (!session.isAuthenticated()) {
// Create a callback handler
handler = new WebContainerCallbackHandler(m_engine, request);
// Execute the container login module, then (if that fails) the cookie auth module
Set<Principal> principals = authenticationMgr.doJAASLogin(WebContainerLoginModule.class, handler, options);
if (principals.size() == 0 && authenticationMgr.allowsCookieAuthentication()) {
principals = authenticationMgr.doJAASLogin(CookieAuthenticationLoginModule.class, handler, options);
}
// If the container logged the user in successfully, tell the WikiSession (and add all of the Principals)
if (principals.size() > 0) {
fireEvent(WikiSecurityEvent.LOGIN_AUTHENTICATED, getLoginPrincipal(principals), session);
for (Principal principal : principals) {
fireEvent(WikiSecurityEvent.PRINCIPAL_ADD, principal, session);
}
// Add all appropriate Authorizer roles
injectAuthorizerRoles(session, authorizationMgr.getAuthorizer(), request);
}
}
// If user still not authenticated, check if assertion cookie was supplied
if (!session.isAuthenticated() && authenticationMgr.allowsCookieAssertions()) {
// Execute the cookie assertion login module
Set<Principal> principals = authenticationMgr.doJAASLogin(CookieAssertionLoginModule.class, handler, options);
if (principals.size() > 0) {
fireEvent(WikiSecurityEvent.LOGIN_ASSERTED, getLoginPrincipal(principals), session);
}
}
// If user still anonymous, use the remote address
if (session.isAnonymous()) {
Set<Principal> principals = authenticationMgr.doJAASLogin(AnonymousLoginModule.class, handler, options);
if (principals.size() > 0) {
fireEvent(WikiSecurityEvent.LOGIN_ANONYMOUS, getLoginPrincipal(principals), session);
return true;
}
}
// If by some unusual turn of events the Anonymous login module doesn't work, login failed!
return false;
}
use of org.apache.wiki.WikiSession in project jspwiki by apache.
the class GroupManager method actionPerformed.
/**
* Listens for {@link org.apache.wiki.event.WikiSecurityEvent#PROFILE_NAME_CHANGED}
* events. If a user profile's name changes, each group is inspected. If an entry contains
* a name that has changed, it is replaced with the new one. No group events are emitted
* as a consequence of this method, because the group memberships are still the same; it is
* only the representations of the names within that are changing.
* @param event the incoming event
*/
public void actionPerformed(WikiEvent event) {
if (!(event instanceof WikiSecurityEvent)) {
return;
}
WikiSecurityEvent se = (WikiSecurityEvent) event;
if (se.getType() == WikiSecurityEvent.PROFILE_NAME_CHANGED) {
WikiSession session = se.getSrc();
UserProfile[] profiles = (UserProfile[]) se.getTarget();
Principal[] oldPrincipals = new Principal[] { new WikiPrincipal(profiles[0].getLoginName()), new WikiPrincipal(profiles[0].getFullname()), new WikiPrincipal(profiles[0].getWikiName()) };
Principal newPrincipal = new WikiPrincipal(profiles[1].getFullname());
// Examine each group
int groupsChanged = 0;
try {
for (Group group : m_groupDatabase.groups()) {
boolean groupChanged = false;
for (Principal oldPrincipal : oldPrincipals) {
if (group.isMember(oldPrincipal)) {
group.remove(oldPrincipal);
group.add(newPrincipal);
groupChanged = true;
}
}
if (groupChanged) {
setGroup(session, group);
groupsChanged++;
}
}
} catch (WikiException e) {
// Oooo! This is really bad...
log.error("Could not change user name in Group lists because of GroupDatabase error:" + e.getMessage());
}
log.info("Profile name change for '" + newPrincipal.toString() + "' caused " + groupsChanged + " groups to change also.");
}
}
Aggregations