001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.auth;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.logging.log4j.LogManager;
023import org.apache.logging.log4j.Logger;
024import org.apache.wiki.ajax.WikiAjaxDispatcherServlet;
025import org.apache.wiki.ajax.WikiAjaxServlet;
026import org.apache.wiki.api.core.Context;
027import org.apache.wiki.api.core.Engine;
028import org.apache.wiki.api.core.Session;
029import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
030import org.apache.wiki.api.exceptions.WikiException;
031import org.apache.wiki.api.filters.PageFilter;
032import org.apache.wiki.auth.permissions.AllPermission;
033import org.apache.wiki.auth.permissions.WikiPermission;
034import org.apache.wiki.auth.user.DummyUserDatabase;
035import org.apache.wiki.auth.user.DuplicateUserException;
036import org.apache.wiki.auth.user.UserDatabase;
037import org.apache.wiki.auth.user.UserProfile;
038import org.apache.wiki.event.WikiEventListener;
039import org.apache.wiki.event.WikiEventManager;
040import org.apache.wiki.event.WikiSecurityEvent;
041import org.apache.wiki.filters.FilterManager;
042import org.apache.wiki.filters.SpamFilter;
043import org.apache.wiki.i18n.InternationalizationManager;
044import org.apache.wiki.pages.PageManager;
045import org.apache.wiki.preferences.Preferences;
046import org.apache.wiki.tasks.TasksManager;
047import org.apache.wiki.ui.InputValidator;
048import org.apache.wiki.util.ClassUtil;
049import org.apache.wiki.util.Synchronizer;
050import org.apache.wiki.util.TextUtil;
051import org.apache.wiki.workflow.Decision;
052import org.apache.wiki.workflow.DecisionRequiredException;
053import org.apache.wiki.workflow.Fact;
054import org.apache.wiki.workflow.Step;
055import org.apache.wiki.workflow.Workflow;
056import org.apache.wiki.workflow.WorkflowBuilder;
057import org.apache.wiki.workflow.WorkflowManager;
058
059import jakarta.servlet.ServletException;
060import jakarta.servlet.http.HttpServletRequest;
061import jakarta.servlet.http.HttpServletResponse;
062import java.io.IOException;
063import java.security.Permission;
064import java.security.Principal;
065import java.text.MessageFormat;
066import java.util.List;
067import java.util.Map;
068import java.util.NoSuchElementException;
069import java.util.Properties;
070import java.util.ResourceBundle;
071import java.util.WeakHashMap;
072import org.apache.wiki.auth.authorize.Group;
073import org.apache.wiki.auth.authorize.GroupManager;
074import tools.jackson.databind.ObjectMapper;
075import tools.jackson.databind.node.ObjectNode;
076import java.util.concurrent.locks.ReentrantLock;
077
078
079/**
080 * Default implementation for {@link UserManager}.
081 *
082 * @since 2.3
083 */
084public class DefaultUserManager implements UserManager {
085
086    private static final String USERDATABASE_PACKAGE = "org.apache.wiki.auth.user";
087    public static final String SESSION_MESSAGES = "profile";
088    private static final String PARAM_EMAIL = "email";
089    private static final String PARAM_FULLNAME = "fullname";
090    private static final String PARAM_PASSWORD = "password";
091    private static final String PARAM_LOGINNAME = "loginname";
092    private static final String UNKNOWN_CLASS = "<unknown>";
093
094    /** Property with the number of hours between two passes of {@link AccountLifecycle} over the accounts. */
095    static final String PROP_LIFECYCLE_HOURS = "jspwiki.credentials.lifecycle.hours";
096
097    private static final int DEFAULT_LIFECYCLE_HOURS = 24;
098
099    private Engine m_engine;
100
101    private static final Logger LOG = LogManager.getLogger( DefaultUserManager.class);
102
103    /** Associates wiki sessions with profiles */
104    private final Map< Session, UserProfile > m_profiles = new WeakHashMap<>();
105
106    /** The user database loads, manages and persists user identities */
107    private UserDatabase m_database;
108
109    /**
110     * A lock used to ensure thread safety when accessing shared resources.
111     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
112     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
113     * waiting to acquire a lock.
114     *
115     * @see java.util.concurrent.locks.ReentrantLock
116     */
117    private final ReentrantLock lock = new ReentrantLock();
118
119    /** {@inheritDoc} */
120    @Override
121    public void initialize( final Engine engine, final Properties props ) {
122        m_engine = engine;
123
124        // Attach the PageManager as a listener
125        // TODO: it would be better if we did this in PageManager directly
126        addWikiEventListener( engine.getManager( PageManager.class ) );
127
128        //TODO: Replace with custom annotations. See JSPWIKI-566
129        WikiAjaxDispatcherServlet.registerServlet( JSON_USERS, new JSONUserModule(this), new AllPermission(null));
130
131        // What happens to the accounts as their passwords get older, if the wiki is set up for it
132        final AccountLifecycle lifecycle = new AccountLifecycle( props, this::getUserDatabase, new AccountLifecycleMailer( engine ) );
133        if( lifecycle.isEnabled() ) {
134            final int hours = Math.max( 1, TextUtil.getIntegerProperty( props, PROP_LIFECYCLE_HOURS, DEFAULT_LIFECYCLE_HOURS ) );
135            new AccountLifecycleThread( engine, lifecycle, hours * 3600 ).start();
136        }
137    }
138
139    /** {@inheritDoc} */
140    @Override
141    public UserDatabase getUserDatabase() {
142        return Synchronizer.synchronize( lock, () -> {
143            if( m_database != null ) {
144                return m_database;
145            }
146
147            String dbClassName = UNKNOWN_CLASS;
148
149            try {
150                dbClassName = TextUtil.getRequiredProperty( m_engine.getWikiProperties(), PROP_DATABASE );
151
152                LOG.info( "Attempting to load user database class {}", dbClassName );
153                m_database = ClassUtil.buildInstance( USERDATABASE_PACKAGE, dbClassName );
154                m_database.initialize( m_engine, m_engine.getWikiProperties() );
155                LOG.info( "UserDatabase initialized." );
156            } catch( final NoSuchElementException | NoRequiredPropertyException e ) {
157                LOG.error( "You have not set the '{}'. You need to do this if you want to enable user management by JSPWiki.", PROP_DATABASE, e );
158            } catch( final ReflectiveOperationException e ) {
159                LOG.error( "UserDatabase {} cannot be instantiated", dbClassName, e );
160            } catch( final WikiSecurityException e ) {
161                LOG.error( "Exception initializing user database: {}", e.getMessage(), e );
162            } finally {
163                if( m_database == null ) {
164                    LOG.info( "I could not create a database object you specified (or didn't specify), so I am falling back to a default." );
165                    m_database = new DummyUserDatabase();
166                }
167            }
168
169            return m_database;
170        } );
171    }
172
173    /** {@inheritDoc} */
174    @Override
175    public UserProfile getUserProfile( final Session session ) {
176        // Look up cached user profile
177        UserProfile profile = m_profiles.get( session );
178        boolean newProfile = profile == null;
179        Principal user = null;
180
181        // If user is authenticated, figure out if this is an existing profile
182        if ( session.isAuthenticated() ) {
183            user = session.getUserPrincipal();
184            try {
185                profile = findExistingProfile( session, user );
186                newProfile = false;
187            } catch( final NoSuchPrincipalException e ) {
188                LOG.debug(e.getMessage(), e);
189            }
190        }
191
192        if ( newProfile ) {
193            profile = getUserDatabase().newProfile();
194            if ( user != null ) {
195                profile.setLoginName( user.getName() );
196            } else {
197                LOG.warn("new profile however the user principal is null. this shouldn't happen");
198            }
199            if ( !profile.isNew() ) {
200                throw new IllegalStateException( "New profile should be marked 'new'. Check your UserProfile implementation." );
201            }
202        }
203
204        // Stash the profile for next time
205        m_profiles.put( session, profile );
206        return profile;
207    }
208
209    /**
210     * Finds the stored profile of an authenticated user. The user principal usually carries the full name, which is not
211     * the wiki name when it has spaces, so the login name is tried first and the user principal name second.
212     */
213    private UserProfile findExistingProfile( final Session session, final Principal user ) throws NoSuchPrincipalException {
214        final Principal login = session.getLoginPrincipal();
215        if( login != null ) {
216            try {
217                return getUserDatabase().findByLoginName( login.getName() );
218            } catch( final NoSuchPrincipalException e ) {
219                LOG.debug( e.getMessage(), e );
220            }
221        }
222        return getUserDatabase().findByWikiName( user.getName() );
223    }
224
225    /** {@inheritDoc} */
226    @Override
227    public void setUserProfile( final Context context, final UserProfile profile ) throws DuplicateUserException, WikiException {
228        final Session session = context.getWikiSession();
229        // Verify user is allowed to save profile!
230        final Permission p = new WikiPermission( m_engine.getApplicationName(), WikiPermission.EDIT_PROFILE_ACTION );
231        if ( !m_engine.getManager( AuthorizationManager.class ).checkPermission( session, p ) ) {
232            throw new WikiSecurityException( "You are not allowed to save wiki profiles." );
233        }
234
235        // Check if profile is new, and see if container allows creation
236        final boolean newProfile = profile.isNew();
237
238        // Check if another user profile already has the fullname or loginname
239        final UserProfile oldProfile = getUserProfile( session );
240        final boolean nameChanged = ( oldProfile != null && oldProfile.getFullname() != null ) &&
241                                    !( oldProfile.getFullname().equals( profile.getFullname() ) &&
242                                    oldProfile.getLoginName().equals( profile.getLoginName() ) );
243        UserProfile otherProfile;
244        try {
245            otherProfile = getUserDatabase().findByLoginName( profile.getLoginName() );
246            if( otherProfile != null && !otherProfile.equals( oldProfile ) ) {
247                throw new DuplicateUserException( "security.error.login.taken", profile.getLoginName() );
248            }
249        } catch (final NoSuchPrincipalException e) {
250            LOG.debug(e.getMessage(), e);
251        }
252        try {
253            otherProfile = getUserDatabase().findByFullName( profile.getFullname() );
254            if( otherProfile != null && !otherProfile.equals( oldProfile ) ) {
255                throw new DuplicateUserException( "security.error.fullname.taken", profile.getFullname() );
256            }
257        } catch( final NoSuchPrincipalException e ) {
258            LOG.debug(e.getMessage(), e);
259        }
260
261        // For new accounts, create approval workflow for user profile save.
262        if( newProfile && oldProfile != null && oldProfile.isNew() ) {
263            startUserProfileCreationWorkflow( context, profile );
264
265            // If the profile doesn't need approval, then just log the user in
266
267            try {
268                final AuthenticationManager mgr = m_engine.getManager( AuthenticationManager.class );
269                if( !mgr.isContainerAuthenticated() ) {
270                    mgr.login( session, null, profile.getLoginName(), profile.getPassword() );
271                }
272            } catch( final WikiException e ) {
273                throw new WikiSecurityException( e.getMessage(), e );
274            }
275
276            // Alert all listeners that the profile changed...
277            // ...this will cause credentials to be reloaded in the wiki session
278            fireEvent( WikiSecurityEvent.PROFILE_SAVE, session, profile );
279        } else { // For existing accounts, just save the profile
280            // If login name changed, rename it first
281            if( nameChanged && !oldProfile.getLoginName().equals( profile.getLoginName() ) ) {
282                getUserDatabase().rename( oldProfile.getLoginName(), profile.getLoginName() );
283            }
284
285            // Now, save the profile (userdatabase will take care of timestamps for us)
286            getUserDatabase().save( profile );
287
288            if( nameChanged ) {
289                // Fire an event if the login name or full name changed
290                final UserProfile[] profiles = new UserProfile[] { oldProfile, profile };
291                fireEvent( WikiSecurityEvent.PROFILE_NAME_CHANGED, session, profiles );
292            } else {
293                // Fire an event that says we have new a new profile (new principals)
294                fireEvent( WikiSecurityEvent.PROFILE_SAVE, session, profile );
295            }
296        }
297        m_profiles.put( session, profile );
298    }
299
300    /** {@inheritDoc} */
301    @Override
302    public void startUserProfileCreationWorkflow( final Context context, final UserProfile profile ) throws WikiException {
303        final WorkflowBuilder builder = WorkflowBuilder.getBuilder( m_engine );
304        final Principal submitter = context.getWikiSession().getUserPrincipal();
305        final Step completionTask = m_engine.getManager( TasksManager.class ).buildSaveUserProfileTask( context.getWikiSession().getLocale() );
306
307        // Add user profile attribute as Facts for the approver (if required)
308        final boolean hasEmail = profile.getEmail() != null;
309        final Fact[] facts = new Fact[ hasEmail ? 4 : 3 ];
310        facts[ 0 ] = new Fact( WorkflowManager.WF_UP_CREATE_SAVE_FACT_PREFS_FULL_NAME, profile.getFullname() );
311        facts[ 1 ] = new Fact( WorkflowManager.WF_UP_CREATE_SAVE_FACT_PREFS_LOGIN_NAME, profile.getLoginName() );
312        facts[ 2 ] = new Fact( WorkflowManager.WF_UP_CREATE_SAVE_FACT_SUBMITTER, submitter.getName() );
313        if ( hasEmail ) {
314            facts[ 3 ] = new Fact( WorkflowManager.WF_UP_CREATE_SAVE_FACT_PREFS_EMAIL, profile.getEmail() );
315        }
316        final Workflow workflow = builder.buildApprovalWorkflow( submitter,
317                                                                 WorkflowManager.WF_UP_CREATE_SAVE_APPROVER,
318                                                                 null,
319                                                                 WorkflowManager.WF_UP_CREATE_SAVE_DECISION_MESSAGE_KEY,
320                                                                 facts,
321                                                                 completionTask,
322                                                                 null );
323
324        workflow.setAttribute( WorkflowManager.WF_UP_CREATE_SAVE_ATTR_SAVED_PROFILE, profile );
325        workflow.start( context );
326
327        final boolean approvalRequired = workflow.getCurrentStep() instanceof Decision;
328
329        // If the profile requires approval, redirect user to message page
330        if ( approvalRequired ) {
331            throw new DecisionRequiredException( "This profile must be approved before it becomes active" );
332        }
333    }
334
335    /** {@inheritDoc} */
336    @Override
337    public UserProfile parseProfile( final Context context ) {
338        // Retrieve the user's profile (may have been previously cached)
339        final UserProfile profile = getUserProfile( context.getWikiSession() );
340        final HttpServletRequest request = context.getHttpRequest();
341
342        // Extract values from request stream (cleanse whitespace as needed)
343        String loginName = request.getParameter( PARAM_LOGINNAME );
344        String password = request.getParameter( PARAM_PASSWORD );
345        String fullname = request.getParameter( PARAM_FULLNAME );
346        String email = request.getParameter( PARAM_EMAIL );
347        loginName = StringUtils.trim( loginName );
348        password = InputValidator.isBlank( password ) ? null : password;
349        fullname = StringUtils.trim( fullname );
350        email = StringUtils.trim( email );
351
352        // A special case if we have container authentication: if authenticated, login name is always taken from container
353        if ( m_engine.getManager( AuthenticationManager.class ).isContainerAuthenticated() && context.getWikiSession().isAuthenticated() ) {
354            loginName = context.getWikiSession().getLoginPrincipal().getName();
355        }
356
357        // Set the profile fields!
358        profile.setLoginName( loginName );
359        profile.setEmail( email );
360        profile.setFullname( fullname );
361        profile.setPassword( password );
362        return profile;
363    }
364
365    /** {@inheritDoc} */
366    @Override
367    public void validateProfile( final Context context, final UserProfile profile ) {
368        final Session session = context.getWikiSession();
369        final InputValidator validator = new InputValidator( SESSION_MESSAGES, context );
370        final ResourceBundle rb = Preferences.getBundle( context, InternationalizationManager.CORE_BUNDLE );
371
372        //  Query the SpamFilter first
373        final FilterManager fm = m_engine.getManager( FilterManager.class );
374        final List< PageFilter > ls = fm.getFilterList();
375        for( final PageFilter pf : ls ) {
376            if( pf instanceof SpamFilter ) {
377                if( !( ( SpamFilter )pf ).isValidUserProfile( context, profile ) ) {
378                    session.addMessage( SESSION_MESSAGES, "Invalid userprofile" );
379                    return;
380                }
381                break;
382            }
383        }
384
385        // If container-managed auth and user not logged in, throw an error
386        if ( m_engine.getManager( AuthenticationManager.class ).isContainerAuthenticated()
387             && !context.getWikiSession().isAuthenticated() ) {
388            session.addMessage( SESSION_MESSAGES, rb.getString("security.error.createprofilebeforelogin") );
389        }
390
391        validator.validateNotNull( profile.getLoginName(), rb.getString("security.user.loginname") );
392        validator.validateNotNull( profile.getFullname(), rb.getString("security.user.fullname") );
393        validator.validate( profile.getEmail(), rb.getString("security.user.email"), InputValidator.EMAIL );
394
395        if( !m_engine.getManager( AuthenticationManager.class ).isContainerAuthenticated() ) {
396            // passwords must match and can't be null
397            
398            //this is the new password
399            final String newpassword = profile.getPassword();
400            if( newpassword == null ) {
401                session.addMessage( SESSION_MESSAGES, rb.getString( "security.error.blankpassword" ) );
402            } else {
403                final HttpServletRequest request = context.getHttpRequest();
404                //the existing password
405                final String existingPassword = ( request == null ) ? null : request.getParameter( "password0" );
406                //the new password confirmation
407                final String passwordConfirmation = ( request == null ) ? null : request.getParameter( "password2" );
408                if (!newpassword.equals(passwordConfirmation)) {
409                    //password confirmation does not match
410                    session.addMessage( SESSION_MESSAGES, rb.getString( "security.error.passwordnomatch" ) );
411                }
412                if( !profile.isNew() && (existingPassword==null || existingPassword.equals( newpassword ) ) ) {
413                    //existing account and the existing password matches the new password
414                    session.addMessage( SESSION_MESSAGES, "existing password matches the proposed new one" );
415                }
416                if( !profile.isNew() && !getUserDatabase().validatePassword( profile.getLoginName(), existingPassword ) ) {
417                    //existing account and the provided password does not match what we currently have
418                    session.addMessage( SESSION_MESSAGES, rb.getString( "security.error.passwordnomatch" ) );
419                }
420                List<String> msg = PasswordComplexityVerifier.validate(passwordConfirmation, existingPassword, context);
421                for (String s : msg) {
422                    session.addMessage( SESSION_MESSAGES, s );
423                }
424                int reuseCount = Integer.parseInt(m_engine.getWikiProperties().getProperty("jspwiki.credentials.reuseCount", "-1"));
425                if (reuseCount > 0) {
426                    //if it's set to 0 or less, we don't store it so we can skip this check
427                    if (!m_database.validatePasswordReuse(profile.getLoginName(), passwordConfirmation)) {
428                        //password reuse detected
429                        session.addMessage(SESSION_MESSAGES,
430                                MessageFormat.format(rb.getString("security.error.passwordReuseError"), reuseCount));
431                    }
432                }
433            }
434        }
435
436        UserProfile otherProfile;
437        final String fullName = profile.getFullname();
438        final String loginName = profile.getLoginName();
439        final String wikiName = profile.getWikiName();
440        final String email = profile.getEmail();
441
442        
443        if ("true".equalsIgnoreCase(m_engine.getWikiProperties().getProperty(Engine.PROP_USE_2_X_ACL_LOGIC, "false"))) {
444            // It's illegal to use as a full name someone else's login name
445            try {
446                otherProfile = getUserDatabase().findByFullName(fullName );
447                if( otherProfile != null && !profile.equals( otherProfile ) && !fullName.equals( otherProfile.getFullname() ) ) {
448                    final Object[] args = { fullName };
449                    session.addMessage( SESSION_MESSAGES, MessageFormat.format( rb.getString( "security.error.illegalfullname" ), args ) );
450                }
451            } catch( final NoSuchPrincipalException e ) {
452                LOG.debug(e.getMessage(), e);
453                /* It's clean */ 
454            }
455
456            // It's illegal to use as a login name someone else's full name
457            try {
458                otherProfile = getUserDatabase().findByLoginName(loginName );
459                if( otherProfile != null && !profile.equals( otherProfile ) && !loginName.equals( otherProfile.getLoginName() ) ) {
460                    final Object[] args = { loginName };
461                    session.addMessage( SESSION_MESSAGES, MessageFormat.format( rb.getString( "security.error.illegalloginname" ), args ) );
462                }
463            } catch( final NoSuchPrincipalException e ) { 
464                LOG.debug(e.getMessage(), e);
465                /* It's clean */ 
466            }
467        } else {
468            //JSPWIKI-130, v3+ behavior
469            // It is legal to use as a full name someone else's login name
470
471            // It's illegal to use as a login name someone else's full name
472            try {
473                otherProfile = getUserDatabase().findByLoginName(loginName );
474                if( otherProfile != null && !profile.equals( otherProfile ) && !loginName.equals( otherProfile.getLoginName() ) ) {
475                    final Object[] args = { loginName };
476                    session.addMessage( SESSION_MESSAGES, MessageFormat.format( 
477                            rb.getString( "security.error.illegalloginname" ), args ) );
478                }
479            } catch( final NoSuchPrincipalException e ) { 
480                LOG.debug(e.getMessage(), e);
481                /* It's clean */ 
482            }
483            //it's illegal to use a username, email or wiki name as a group name
484            try {
485                Group[] groups = m_engine.getManager(GroupManager.class).getGroupDatabase().groups();
486                for (Group grp : groups) {
487                    if (grp.getName().equals(loginName)) {
488                        final Object[] args = {loginName};
489                        session.addMessage(SESSION_MESSAGES,
490                                MessageFormat.format(rb.getString("security.error.illegalloginname"), args));
491                    }
492                    if (grp.getName().equals(wikiName)) {
493                        final Object[] args = {wikiName};
494                        session.addMessage(SESSION_MESSAGES,
495                                MessageFormat.format(rb.getString("security.error.illegalloginname"), args));
496                    }
497                    if (grp.getName().equals(email)) {
498                        final Object[] args = {email};
499                        session.addMessage(SESSION_MESSAGES,
500                                MessageFormat.format(rb.getString("security.error.illegalloginname"), args));
501                    }
502                }
503            } catch (WikiSecurityException ex) {
504                session.addMessage(SESSION_MESSAGES,
505                        "Processing failed. see log for details.");
506                LOG.error("failed to query for groups", ex);
507            }
508            //wiki names must be unique as well.
509            try {
510                otherProfile = getUserDatabase().findByWikiName(wikiName );
511                if( otherProfile != null && !profile.equals( otherProfile ) && !loginName.equals( otherProfile.getLoginName() ) ) {
512                    final Object[] args = { loginName };
513                    session.addMessage( SESSION_MESSAGES, MessageFormat.format( rb.getString( "security.error.illegalloginname" ), args ) );
514                }
515            } catch( final NoSuchPrincipalException e ) { 
516                LOG.debug(e.getMessage(), e);
517                /* It's clean */ 
518            }
519        }
520        
521
522        // It's illegal to use multiple accounts with the same email
523        if (email != null && email.trim().length() > 0) {
524            try {
525                otherProfile = getUserDatabase().findByEmail( email );
526                if( otherProfile != null && !profile.getUid().equals( otherProfile.getUid() ) // Issue JSPWIKI-1042
527                        && !profile.equals( otherProfile ) && StringUtils.lowerCase( email )
528                        .equals( StringUtils.lowerCase( otherProfile.getEmail() ) ) ) {
529                    final Object[] args = { email };
530                    session.addMessage( SESSION_MESSAGES, MessageFormat.format( rb.getString( "security.error.email.taken" ), args ) );
531                }
532            } catch( final NoSuchPrincipalException e ) { 
533                LOG.debug(e.getMessage(), e);
534                /* It's clean */ 
535            }
536        }
537    }
538
539    /** {@inheritDoc} */
540    @Override
541    public Principal[] listWikiNames() throws WikiSecurityException {
542        return getUserDatabase().getWikiNames();
543    }
544
545    // events processing .......................................................
546
547    /**
548     * Registers a WikiEventListener with this instance.
549     * This is a convenience method.
550     * @param listener the event listener
551     */
552    @Override
553    public void addWikiEventListener( final WikiEventListener listener ) {
554        Synchronizer.synchronize(lock, () -> {
555            WikiEventManager.addWikiEventListener( this, listener );
556        });
557    }
558
559    /**
560     * Un-registers a WikiEventListener with this instance.
561     * This is a convenience method.
562     * @param listener the event listener
563     */
564    @Override
565    public void removeWikiEventListener( final WikiEventListener listener ) {
566        Synchronizer.synchronize(lock, () -> {
567            WikiEventManager.removeWikiEventListener( this, listener );
568        });
569    }
570
571    /**
572     *  Implements the JSON API for usermanager.
573     *  <p>
574     *  Even though this gets serialized whenever container shuts down/restarts, this gets reinstalled to the session when JSPWiki starts.
575     *  This means that it's not actually necessary to save anything.
576     */
577    public static final class JSONUserModule implements WikiAjaxServlet {
578
579        private final DefaultUserManager m_manager;
580
581        /**
582         *  Create a new JSONUserModule.
583         *  @param mgr Manager
584         */
585        public JSONUserModule( final DefaultUserManager mgr )
586        {
587            m_manager = mgr;
588        }
589
590        @Override
591        public String getServletMapping() {
592            return JSON_USERS;
593        }
594
595        @Override
596        public void service( final HttpServletRequest req, final HttpServletResponse resp, final String actionName, final List<String> params) throws ServletException, IOException {
597            try {
598                if( params.isEmpty() ) {
599                    return;
600                }
601                resp.setContentType("application/json");
602                final String uid = params.get(0);
603                LOG.debug("uid="+uid);
604                if (StringUtils.isNotBlank(uid)) {
605                    final UserProfile prof = getUserInfo(uid);
606                    //clone the object
607                    ObjectMapper om = new ObjectMapper();
608                    ObjectNode node = om.convertValue(prof, ObjectNode.class);
609                    node.remove("password");
610                    node.remove("previousHashedCredentials");
611                    resp.getWriter().write(node.toString());
612                }
613            } catch (final NoSuchPrincipalException e) {
614                    throw new ServletException(e);
615            }
616        }
617
618        /**
619         *  Directly returns the UserProfile object attached to an uid.
620         *
621         *  @param uid The user id (e.g. WikiName)
622         *  @return A UserProfile object
623         *  @throws NoSuchPrincipalException If such a name does not exist.
624         */
625        public UserProfile getUserInfo( final String uid ) throws NoSuchPrincipalException {
626            if( m_manager != null ) {
627                return m_manager.getUserDatabase().findByUid( uid );
628            }
629
630            throw new IllegalStateException( "The manager is offline." );
631        }
632    }
633
634}