Search in sources :

Example 11 with UserProfile

use of org.apache.wiki.auth.user.UserProfile in project jspwiki by apache.

the class UserManagerTest method testSetCollidingUserProfile.

@Test
public void testSetCollidingUserProfile() throws Exception {
    // First, count the number of users in the db now.
    int oldUserCount = m_db.getWikiNames().length;
    // Create a new user with random name
    WikiSession session = m_engine.guestSession();
    String loginName = "TestUser" + String.valueOf(System.currentTimeMillis());
    UserProfile profile = m_db.newProfile();
    profile.setEmail("jspwiki.tests@mailinator.com");
    profile.setLoginName(loginName);
    profile.setFullname("FullName" + loginName);
    profile.setPassword("password");
    // Set the login name to collide with Janne's: should prohibit saving
    profile.setLoginName("janne");
    try {
        m_mgr.setUserProfile(session, profile);
        Assert.fail("UserManager allowed saving of user with login name 'janne', but it shouldn't have.");
    } catch (DuplicateUserException e) {
        // Good! That's what we expected; reset for next test
        profile.setLoginName(loginName);
    }
    // Set the login name to collide with Janne's: should prohibit saving
    profile.setFullname("Janne Jalkanen");
    try {
        m_mgr.setUserProfile(session, profile);
        Assert.fail("UserManager allowed saving of user with login name 'janne', but it shouldn't have.");
    } catch (DuplicateUserException e) {
    // Good! That's what we expected
    }
    // There shouldn't have been any users added
    Assert.assertEquals(oldUserCount, m_db.getWikiNames().length);
}
Also used : WikiSession(org.apache.wiki.WikiSession) UserProfile(org.apache.wiki.auth.user.UserProfile) DuplicateUserException(org.apache.wiki.auth.user.DuplicateUserException) WikiSessionTest(org.apache.wiki.WikiSessionTest) Test(org.junit.Test)

Example 12 with UserProfile

use of org.apache.wiki.auth.user.UserProfile in project jspwiki by apache.

the class UserDatabaseLoginModule method login.

/**
 * @see javax.security.auth.spi.LoginModule#login()
 *
 * {@inheritDoc}
 */
public boolean login() throws LoginException {
    UserDatabaseCallback ucb = new UserDatabaseCallback();
    NameCallback ncb = new NameCallback("User name");
    PasswordCallback pcb = new PasswordCallback("Password", false);
    Callback[] callbacks = new Callback[] { ucb, ncb, pcb };
    try {
        m_handler.handle(callbacks);
        UserDatabase db = ucb.getUserDatabase();
        String username = ncb.getName();
        String password = new String(pcb.getPassword());
        // Look up the user and compare the password hash
        if (db == null) {
            throw new FailedLoginException("No user database: check the callback handler code!");
        }
        UserProfile profile = db.findByLoginName(username);
        String storedPassword = profile.getPassword();
        if (storedPassword != null && db.validatePassword(username, password)) {
            if (log.isDebugEnabled()) {
                log.debug("Logged in user database user " + username);
            }
            // If login succeeds, commit these principals/roles
            m_principals.add(new WikiPrincipal(username, WikiPrincipal.LOGIN_NAME));
            return true;
        }
        throw new FailedLoginException("The username or password is incorrect.");
    } catch (IOException e) {
        String message = "IO exception; disallowing login.";
        log.error(message, e);
        throw new LoginException(message);
    } catch (UnsupportedCallbackException e) {
        String message = "Unable to handle callback; disallowing login.";
        log.error(message, e);
        throw new LoginException(message);
    } catch (NoSuchPrincipalException e) {
        throw new FailedLoginException("The username or password is incorrect.");
    }
}
Also used : UserProfile(org.apache.wiki.auth.user.UserProfile) UserDatabase(org.apache.wiki.auth.user.UserDatabase) NoSuchPrincipalException(org.apache.wiki.auth.NoSuchPrincipalException) IOException(java.io.IOException) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) FailedLoginException(javax.security.auth.login.FailedLoginException) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) PasswordCallback(javax.security.auth.callback.PasswordCallback) LoginException(javax.security.auth.login.LoginException) FailedLoginException(javax.security.auth.login.FailedLoginException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException)

Example 13 with UserProfile

use of org.apache.wiki.auth.user.UserProfile in project jspwiki by apache.

the class UserProfileTag method doWikiStartTag.

public final int doWikiStartTag() throws IOException, WikiSecurityException {
    UserManager manager = m_wikiContext.getEngine().getUserManager();
    UserProfile profile = manager.getUserProfile(m_wikiContext.getWikiSession());
    String result = null;
    if (EXISTS.equals(m_prop) || NOT_NEW.equals(m_prop)) {
        return profile.isNew() ? SKIP_BODY : EVAL_BODY_INCLUDE;
    } else if (NEW.equals(m_prop) || NOT_EXISTS.equals(m_prop)) {
        return profile.isNew() ? EVAL_BODY_INCLUDE : SKIP_BODY;
    } else if (CREATED.equals(m_prop) && profile.getCreated() != null) {
        result = profile.getCreated().toString();
    } else if (EMAIL.equals(m_prop)) {
        result = profile.getEmail();
    } else if (FULLNAME.equals(m_prop)) {
        result = profile.getFullname();
    } else if (GROUPS.equals(m_prop)) {
        result = printGroups(m_wikiContext);
    } else if (LOGINNAME.equals(m_prop)) {
        result = profile.getLoginName();
    } else if (MODIFIED.equals(m_prop) && profile.getLastModified() != null) {
        result = profile.getLastModified().toString();
    } else if (ROLES.equals(m_prop)) {
        result = printRoles(m_wikiContext);
    } else if (WIKINAME.equals(m_prop)) {
        result = profile.getWikiName();
        if (result == null) {
            // 
            // Default back to the declared user name
            // 
            WikiEngine engine = this.m_wikiContext.getEngine();
            WikiSession wikiSession = WikiSession.getWikiSession(engine, (HttpServletRequest) pageContext.getRequest());
            Principal user = wikiSession.getUserPrincipal();
            if (user != null) {
                result = user.getName();
            }
        }
    } else if (CHANGE_PASSWORD.equals(m_prop) || CHANGE_LOGIN_NAME.equals(m_prop)) {
        AuthenticationManager authMgr = m_wikiContext.getEngine().getAuthenticationManager();
        if (!authMgr.isContainerAuthenticated()) {
            return EVAL_BODY_INCLUDE;
        }
    } else if (NOT_CHANGE_PASSWORD.equals(m_prop) || NOT_CHANGE_LOGIN_NAME.equals(m_prop)) {
        AuthenticationManager authMgr = m_wikiContext.getEngine().getAuthenticationManager();
        if (authMgr.isContainerAuthenticated()) {
            return EVAL_BODY_INCLUDE;
        }
    }
    if (result != null) {
        pageContext.getOut().print(TextUtil.replaceEntities(result));
    }
    return SKIP_BODY;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationManager(org.apache.wiki.auth.AuthenticationManager) WikiSession(org.apache.wiki.WikiSession) UserProfile(org.apache.wiki.auth.user.UserProfile) UserManager(org.apache.wiki.auth.UserManager) WikiEngine(org.apache.wiki.WikiEngine) Principal(java.security.Principal) GroupPrincipal(org.apache.wiki.auth.GroupPrincipal)

Example 14 with UserProfile

use of org.apache.wiki.auth.user.UserProfile 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 */
    }
}
Also used : UserProfile(org.apache.wiki.auth.user.UserProfile) SpamFilter(org.apache.wiki.filters.SpamFilter) FilterManager(org.apache.wiki.api.engine.FilterManager) HttpServletRequest(javax.servlet.http.HttpServletRequest) WikiSession(org.apache.wiki.WikiSession) InputValidator(org.apache.wiki.ui.InputValidator) ResourceBundle(java.util.ResourceBundle) PageFilter(org.apache.wiki.api.filters.PageFilter)

Example 15 with UserProfile

use of org.apache.wiki.auth.user.UserProfile in project jspwiki by apache.

the class UserManager method parseProfile.

/**
 * <p> Extracts user profile parameters from the HTTP request and populates
 * a UserProfile with them. The UserProfile will either be a copy of the
 * user's existing profile (if one can be found), or a new profile (if not).
 * The rules for populating the profile as as follows: </p> <ul> <li>If the
 * <code>email</code> or <code>password</code> parameter values differ
 * from those in the existing profile, the passed parameters override the
 * old values.</li> <li>For new profiles, the user-supplied
 * <code>fullname</code> parameter is always
 * used; for existing profiles the existing value is used, and whatever
 * value the user supplied is discarded. The wiki name is automatically
 * computed by taking the full name and extracting all whitespace.</li>
 * <li>In all cases, the
 * created/last modified timestamps of the user's existing or new profile
 * always override whatever values the user supplied.</li> <li>If
 * container authentication is used, the login name property of the profile
 * is set to the name of
 * {@link org.apache.wiki.WikiSession#getLoginPrincipal()}. Otherwise,
 * the value of the <code>loginname</code> parameter is used.</li> </ul>
 * @param context the current wiki context
 * @return a new, populated user profile
 */
public UserProfile parseProfile(WikiContext context) {
    // Retrieve the user's profile (may have been previously cached)
    final UserProfile profile = getUserProfile(context.getWikiSession());
    final HttpServletRequest request = context.getHttpRequest();
    // Extract values from request stream (cleanse whitespace as needed)
    String loginName = request.getParameter(PARAM_LOGINNAME);
    String password = request.getParameter(PARAM_PASSWORD);
    String fullname = request.getParameter(PARAM_FULLNAME);
    String email = request.getParameter(PARAM_EMAIL);
    loginName = InputValidator.isBlank(loginName) ? null : loginName;
    password = InputValidator.isBlank(password) ? null : password;
    fullname = InputValidator.isBlank(fullname) ? null : fullname;
    email = InputValidator.isBlank(email) ? null : email;
    // If authenticated, login name is always taken from container
    if (m_engine.getAuthenticationManager().isContainerAuthenticated() && context.getWikiSession().isAuthenticated()) {
        loginName = context.getWikiSession().getLoginPrincipal().getName();
    }
    // Set the profile fields!
    profile.setLoginName(loginName);
    profile.setEmail(email);
    profile.setFullname(fullname);
    profile.setPassword(password);
    return profile;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UserProfile(org.apache.wiki.auth.user.UserProfile)

Aggregations

UserProfile (org.apache.wiki.auth.user.UserProfile)19 Principal (java.security.Principal)10 WikiSession (org.apache.wiki.WikiSession)9 WikiSessionTest (org.apache.wiki.WikiSessionTest)6 Test (org.junit.Test)6 UserDatabase (org.apache.wiki.auth.user.UserDatabase)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 WikiPrincipal (org.apache.wiki.auth.WikiPrincipal)4 Collection (java.util.Collection)3 NoSuchPrincipalException (org.apache.wiki.auth.NoSuchPrincipalException)3 UserManager (org.apache.wiki.auth.UserManager)3 WikiSecurityException (org.apache.wiki.auth.WikiSecurityException)3 Group (org.apache.wiki.auth.authorize.Group)3 Decision (org.apache.wiki.workflow.Decision)3 DecisionRequiredException (org.apache.wiki.workflow.DecisionRequiredException)3 Fact (org.apache.wiki.workflow.Fact)3 List (java.util.List)2 WikiException (org.apache.wiki.api.exceptions.WikiException)2 GroupPrincipal (org.apache.wiki.auth.GroupPrincipal)2 UnresolvedPrincipal (org.apache.wiki.auth.acl.UnresolvedPrincipal)2