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.user;
020
021import org.apache.commons.lang3.StringUtils;
022import org.apache.commons.text.StringEscapeUtils;
023import org.apache.wiki.api.core.Engine;
024import org.apache.wiki.api.exceptions.NoRequiredPropertyException;
025import org.apache.wiki.auth.NoSuchPrincipalException;
026import org.apache.wiki.auth.WikiPrincipal;
027import org.apache.wiki.auth.WikiSecurityException;
028import org.apache.wiki.util.Serializer;
029import org.apache.wiki.util.TextUtil;
030import org.w3c.dom.Document;
031import org.w3c.dom.Element;
032import org.w3c.dom.Node;
033import org.w3c.dom.NodeList;
034import org.w3c.dom.Text;
035import org.xml.sax.SAXException;
036
037import javax.xml.parsers.DocumentBuilderFactory;
038import javax.xml.parsers.ParserConfigurationException;
039import java.io.BufferedWriter;
040import java.io.File;
041import java.io.FileNotFoundException;
042import java.io.IOException;
043import java.io.OutputStreamWriter;
044import java.io.Serializable;
045import java.nio.charset.StandardCharsets;
046import java.nio.file.Files;
047import java.security.Principal;
048import java.text.DateFormat;
049import java.text.ParseException;
050import java.text.SimpleDateFormat;
051import java.util.Date;
052import java.util.Map;
053import java.util.Properties;
054import java.util.SortedSet;
055import java.util.TreeSet;
056import java.util.stream.Collectors;
057import java.util.stream.IntStream;
058
059/**
060 * <p>Manages {@link DefaultUserProfile} objects using XML files for persistence. Passwords are hashed using SHA1. User entries are simple
061 * <code>&lt;user&gt;</code> elements under the root. User profile properties are attributes of the element. For example:</p>
062 * <blockquote><code>
063 * &lt;users&gt;<br/>
064 * &nbsp;&nbsp;&lt;user loginName="janne" fullName="Janne Jalkanen"<br/>
065 * &nbsp;&nbsp;&nbsp;&nbsp;wikiName="JanneJalkanen" email="janne@ecyrd.com"<br/>
066 * &nbsp;&nbsp;&nbsp;&nbsp;password="{SHA}457b08e825da547c3b77fbc1ff906a1d00a7daee"/&gt;<br/>
067 * &lt;/users&gt;
068 * </code></blockquote>
069 * <p>In this example, the un-hashed password is <code>myP@5sw0rd</code>. Passwords are hashed without salt.</p>
070 * @since 2.3
071 */
072
073// FIXME: If the DB is shared across multiple systems, it's possible to lose accounts
074//        if two people add new accounts right after each other from different wikis.
075public class XMLUserDatabase extends AbstractUserDatabase {
076
077    /** The jspwiki.properties property specifying the file system location of the user database. */
078    public static final String  PROP_USERDATABASE = "jspwiki.xmlUserDatabaseFile";
079    private static final String DEFAULT_USERDATABASE = "userdatabase.xml";
080    private static final String ATTRIBUTES_TAG    = "attributes";
081    private static final String CREATED           = "created";
082    private static final String EMAIL             = "email";
083    private static final String FULL_NAME         = "fullName";
084    private static final String LOGIN_NAME        = "loginName";
085    private static final String LAST_MODIFIED     = "lastModified";
086    private static final String LOCK_EXPIRY       = "lockExpiry";
087    private static final String PASSWORD          = "password";
088    private static final String UID               = "uid";
089    private static final String USER_TAG          = "user";
090    private static final String WIKI_NAME         = "wikiName";
091    private static final String DATE_FORMAT       = "yyyy.MM.dd 'at' HH:mm:ss:SSS z";
092    private Document            c_dom;
093    private File                c_file;
094
095    /** {@inheritDoc} */
096    @Override
097    public synchronized void deleteByLoginName( final String loginName ) throws WikiSecurityException {
098        if( c_dom == null ) {
099            throw new WikiSecurityException( "FATAL: database does not exist" );
100        }
101
102        final NodeList users = c_dom.getDocumentElement().getElementsByTagName( USER_TAG );
103        for( int i = 0; i < users.getLength(); i++ ) {
104            final Element user = ( Element )users.item( i );
105            if( user.getAttribute( LOGIN_NAME ).equals( loginName ) ) {
106                c_dom.getDocumentElement().removeChild( user );
107
108                // Commit to disk
109                saveDOM();
110                return;
111            }
112        }
113        throw new NoSuchPrincipalException( "Not in database: " + loginName );
114    }
115
116    /** {@inheritDoc} */
117    @Override
118    public UserProfile findByEmail( final String index ) throws NoSuchPrincipalException {
119        return findBy( EMAIL, index );
120    }
121
122    /** {@inheritDoc} */
123    @Override
124    public UserProfile findByFullName( final String index ) throws NoSuchPrincipalException {
125        return findBy( FULL_NAME, index );
126    }
127
128    /** {@inheritDoc} */
129    @Override
130    public UserProfile findByLoginName( final String index ) throws NoSuchPrincipalException {
131        return findBy( LOGIN_NAME, index );
132    }
133
134    /** {@inheritDoc} */
135    @Override
136    public UserProfile findByUid( final String uid ) throws NoSuchPrincipalException {
137        return findBy( UID, uid );
138    }
139
140    /** {@inheritDoc} */
141    @Override
142    public UserProfile findByWikiName( final String index ) throws NoSuchPrincipalException {
143        return findBy( WIKI_NAME, index );
144    }
145
146    public UserProfile findBy( final String attr, final String value ) throws NoSuchPrincipalException {
147        final UserProfile profile = findByAttribute( attr, value );
148        if ( profile != null ) {
149            return profile;
150        }
151        throw new NoSuchPrincipalException( "Not in database: " + value );
152    }
153
154    /** {@inheritDoc} */
155    @Override
156    public Principal[] getWikiNames() throws WikiSecurityException {
157        if ( c_dom == null ) {
158            throw new IllegalStateException( "FATAL: database does not exist" );
159        }
160        final SortedSet< WikiPrincipal > principals = new TreeSet<>();
161        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
162        for( int i = 0; i < users.getLength(); i++ ) {
163            final Element user = ( Element )users.item( i );
164            final String wikiName = user.getAttribute( WIKI_NAME );
165            if( StringUtils.isEmpty( wikiName ) ) {
166                LOG.warn( "Detected null or empty wiki name for {} in XMLUserDataBase. Check your user database.", user.getAttribute( LOGIN_NAME ) );
167            } else {
168                final WikiPrincipal principal = new WikiPrincipal( wikiName, WikiPrincipal.WIKI_NAME );
169                principals.add( principal );
170            }
171        }
172        return principals.toArray( new Principal[0] );
173    }
174
175    /** {@inheritDoc} */
176    @Override
177    public void initialize( final Engine engine, final Properties props ) throws NoRequiredPropertyException {
178        final File defaultFile;
179        if( engine.getRootPath() == null ) {
180            LOG.warn( "Cannot identify JSPWiki root path" );
181            defaultFile = new File( "WEB-INF/" + DEFAULT_USERDATABASE ).getAbsoluteFile();
182        } else {
183            defaultFile = new File( engine.getRootPath() + "/WEB-INF/" + DEFAULT_USERDATABASE );
184        }
185
186        // Get database file location
187        final String file = TextUtil.getStringProperty( props, PROP_USERDATABASE, defaultFile.getAbsolutePath() );
188        if( file == null ) {
189            LOG.warn( "XML user database property " + PROP_USERDATABASE + " not found; trying " + defaultFile );
190            c_file = defaultFile;
191        } else {
192            c_file = new File( file );
193        }
194
195        LOG.info( "XML user database at " + c_file.getAbsolutePath() );
196
197        buildDOM();
198        sanitizeDOM();
199    }
200
201    private void buildDOM() {
202        // Read DOM
203        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
204        factory.setValidating( false );
205        factory.setExpandEntityReferences( false );
206        factory.setIgnoringComments( true );
207        factory.setNamespaceAware( false );
208        //factory.setAttribute( XMLConstants.ACCESS_EXTERNAL_DTD, "" );
209        //factory.setAttribute( XMLConstants.ACCESS_EXTERNAL_SCHEMA, "" );
210        try {
211            c_dom = factory.newDocumentBuilder().parse( c_file );
212            LOG.debug( "Database successfully initialized" );
213            c_lastModified = c_file.lastModified();
214            c_lastCheck = System.currentTimeMillis();
215        } catch( final ParserConfigurationException e ) {
216            LOG.error( "Configuration error: {}", e.getMessage() );
217        } catch( final SAXException e ) {
218            LOG.error( "SAX error: {}", e.getMessage() );
219        } catch( final FileNotFoundException e ) {
220            LOG.info( "User database not found; creating from scratch..." );
221        } catch( final IOException e ) {
222            LOG.error( "IO error: {}", e.getMessage() );
223        }
224        if( c_dom == null ) {
225            try {
226                //  Create the DOM from scratch
227                c_dom = factory.newDocumentBuilder().newDocument();
228                c_dom.appendChild( c_dom.createElement( "users" ) );
229            } catch( final ParserConfigurationException e ) {
230                LOG.fatal( "Could not create in-memory DOM" );
231            }
232        }
233    }
234
235    private void saveDOM() throws WikiSecurityException {
236        if( c_dom == null ) {
237            throw new IllegalStateException( "FATAL: database does not exist" );
238        }
239
240        final File newFile = new File( c_file.getAbsolutePath() + ".new" );
241        try( final BufferedWriter io = new BufferedWriter( new OutputStreamWriter( Files.newOutputStream( newFile.toPath() ), StandardCharsets.UTF_8 ) ) ) {
242
243            // Write the file header and document root
244            io.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
245            io.write( "<users>\n" );
246
247            // Write each profile as a <user> node
248            final Element root = c_dom.getDocumentElement();
249            final NodeList nodes = root.getElementsByTagName( USER_TAG );
250            for( int i = 0; i < nodes.getLength(); i++ ) {
251                final Element user = ( Element )nodes.item( i );
252                io.write( "    <" + USER_TAG + " " );
253                io.write( UID );
254                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( UID ) ) + "\" " );
255                io.write( LOGIN_NAME );
256                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( LOGIN_NAME ) ) + "\" " );
257                io.write( WIKI_NAME );
258                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( WIKI_NAME ) ) + "\" " );
259                io.write( FULL_NAME );
260                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( FULL_NAME ) ) + "\" " );
261                io.write( EMAIL );
262                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( EMAIL ) ) + "\" " );
263                io.write( PASSWORD );
264                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( PASSWORD ) ) + "\" " );
265                io.write( CREATED );
266                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( CREATED ) ) + "\" " );
267                io.write( LAST_MODIFIED );
268                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( LAST_MODIFIED ) ) + "\" " );
269                io.write( LOCK_EXPIRY );
270                io.write( "=\"" + StringEscapeUtils.escapeXml11( user.getAttribute( LOCK_EXPIRY ) ) + "\" " );
271                io.write( ">" );
272                final NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );
273                for( int j = 0; j < attributes.getLength(); j++ ) {
274                    final Element attribute = ( Element )attributes.item( j );
275                    final String value = extractText( attribute );
276                    io.write( "\n        <" + ATTRIBUTES_TAG + ">" );
277                    io.write( value );
278                    io.write( "</" + ATTRIBUTES_TAG + ">" );
279                }
280                io.write( "\n    </" + USER_TAG + ">\n" );
281            }
282            io.write( "</users>" );
283        } catch( final IOException e ) {
284            throw new WikiSecurityException( e.getLocalizedMessage(), e );
285        }
286
287        // Copy new file over old version
288        final File backup = new File( c_file.getAbsolutePath() + ".old" );
289        if( backup.exists() ) {
290            if( !backup.delete() ) {
291                LOG.error( "Could not delete old user database backup: " + backup );
292            }
293        }
294        if( !c_file.renameTo( backup ) ) {
295            LOG.error( "Could not create user database backup: " + backup );
296        }
297        if( !newFile.renameTo( c_file ) ) {
298            LOG.error( "Could not save database: " + backup + " restoring backup." );
299            if( !backup.renameTo( c_file ) ) {
300                LOG.error( "Restore failed. Check the file permissions." );
301            }
302            LOG.error( "Could not save database: " + c_file + ". Check the file permissions" );
303        }
304    }
305
306    private long c_lastCheck;
307    private long c_lastModified;
308
309    private void checkForRefresh() {
310        final long time = System.currentTimeMillis();
311        if( time - c_lastCheck > 60 * 1000L ) {
312            final long lastModified = c_file.lastModified();
313
314            if( lastModified > c_lastModified ) {
315                buildDOM();
316            }
317        }
318    }
319
320    /**
321     * {@inheritDoc}
322     *
323     * @see org.apache.wiki.auth.user.UserDatabase#rename(String, String)
324     */
325    @Override
326    public synchronized void rename( final String loginName, final String newName) throws DuplicateUserException, WikiSecurityException {
327        if( c_dom == null ) {
328            LOG.fatal( "Could not rename profile '" + loginName + "'; database does not exist" );
329            throw new IllegalStateException( "FATAL: database does not exist" );
330        }
331        checkForRefresh();
332
333        // Get the existing user; if not found, throws NoSuchPrincipalException
334        final UserProfile profile = findByLoginName( loginName );
335
336        // Get user with the proposed name; if found, it's a collision
337        try {
338            final UserProfile otherProfile = findByLoginName( newName );
339            if( otherProfile != null ) {
340                throw new DuplicateUserException( "security.error.cannot.rename", newName );
341            }
342        } catch( final NoSuchPrincipalException e ) {
343            // Good! That means it's safe to save using the new name
344        }
345
346        // Find the user with the old login id attribute, and change it
347        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
348        for( int i = 0; i < users.getLength(); i++ ) {
349            final Element user = ( Element )users.item( i );
350            if( user.getAttribute( LOGIN_NAME ).equals( loginName ) ) {
351                final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
352                final Date modDate = new Date( System.currentTimeMillis() );
353                setAttribute( user, LOGIN_NAME, newName );
354                setAttribute( user, LAST_MODIFIED, c_format.format( modDate ) );
355                profile.setLoginName( newName );
356                profile.setLastModified( modDate );
357                break;
358            }
359        }
360
361        // Commit to disk
362        saveDOM();
363    }
364
365    /** {@inheritDoc} */
366    @Override
367    public synchronized void save( final UserProfile profile ) throws WikiSecurityException {
368        if ( c_dom == null ) {
369            LOG.fatal( "Could not save profile " + profile + " database does not exist" );
370            throw new IllegalStateException( "FATAL: database does not exist" );
371        }
372
373        checkForRefresh();
374
375        final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
376        final String index = profile.getLoginName();
377        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
378        Element user = IntStream.range(0, users.getLength()).mapToObj(i -> (Element) users.item(i)).filter(currentUser -> currentUser.getAttribute(LOGIN_NAME).equals(index)).findFirst().orElse(null);
379
380        boolean isNew = false;
381
382        final Date modDate = new Date( System.currentTimeMillis() );
383        if( user == null ) {
384            // Create new user node
385            profile.setCreated( modDate );
386            LOG.info( "Creating new user " + index );
387            user = c_dom.createElement( USER_TAG );
388            c_dom.getDocumentElement().appendChild( user );
389            setAttribute( user, CREATED, c_format.format( profile.getCreated() ) );
390            isNew = true;
391        } else {
392            // To update existing user node, delete old attributes first...
393            final NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );
394            for( int i = 0; i < attributes.getLength(); i++ ) {
395                user.removeChild( attributes.item( i ) );
396            }
397        }
398
399        setAttribute( user, UID, profile.getUid() );
400        setAttribute( user, LAST_MODIFIED, c_format.format( modDate ) );
401        setAttribute( user, LOGIN_NAME, profile.getLoginName() );
402        setAttribute( user, FULL_NAME, profile.getFullname() );
403        setAttribute( user, WIKI_NAME, profile.getWikiName() );
404        setAttribute( user, EMAIL, profile.getEmail() );
405        final Date lockExpiry = profile.getLockExpiry();
406        setAttribute( user, LOCK_EXPIRY, lockExpiry == null ? "" : c_format.format( lockExpiry ) );
407
408        // Hash and save the new password if it's different from old one
409        final String newPassword = profile.getPassword();
410        if( newPassword != null && !newPassword.equals( "" ) ) {
411            final String oldPassword = user.getAttribute( PASSWORD );
412            if( !oldPassword.equals( newPassword ) ) {
413                setAttribute( user, PASSWORD, getHash( newPassword ) );
414            }
415        }
416
417        // Save the attributes as Base64 string
418        if(!profile.getAttributes().isEmpty()) {
419            try {
420                final String encodedAttributes = Serializer.serializeToBase64( profile.getAttributes() );
421                final Element attributes = c_dom.createElement( ATTRIBUTES_TAG );
422                user.appendChild( attributes );
423                final Text value = c_dom.createTextNode( encodedAttributes );
424                attributes.appendChild( value );
425            } catch( final IOException e ) {
426                throw new WikiSecurityException( "Could not save user profile attribute. Reason: " + e.getMessage(), e );
427            }
428        }
429
430        // Set the profile timestamps
431        if( isNew ) {
432            profile.setCreated( modDate );
433        }
434        profile.setLastModified( modDate );
435
436        // Commit to disk
437        saveDOM();
438    }
439
440    /**
441     * Private method that returns the first {@link UserProfile}matching a &lt;user&gt; element's supplied attribute. This method will also
442     * set the UID if it has not yet been set.
443     *
444     * @param matchAttribute matching attribute
445     * @param index value to match
446     * @return the profile, or <code>null</code> if not found
447     */
448    private UserProfile findByAttribute( final String matchAttribute, String index ) {
449        if ( c_dom == null ) {
450            throw new IllegalStateException( "FATAL: database does not exist" );
451        }
452
453        checkForRefresh();
454        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
455        if( users == null ) {
456            return null;
457        }
458
459        // check if we have to do a case-insensitive compare
460        final boolean caseSensitiveCompare = !matchAttribute.equals( EMAIL );
461
462        for( int i = 0; i < users.getLength(); i++ ) {
463            final Element user = (Element) users.item( i );
464            String userAttribute = user.getAttribute( matchAttribute );
465            if( !caseSensitiveCompare ) {
466                userAttribute = StringUtils.lowerCase(userAttribute);
467                index = StringUtils.lowerCase(index);
468            }
469            if( userAttribute.equals( index ) ) {
470                final UserProfile profile = newProfile();
471
472                // Parse basic attributes
473                profile.setUid( user.getAttribute( UID ) );
474                if( profile.getUid() == null || profile.getUid().isEmpty() ) {
475                    profile.setUid( generateUid( this ) );
476                }
477                profile.setLoginName( user.getAttribute( LOGIN_NAME ) );
478                profile.setFullname( user.getAttribute( FULL_NAME ) );
479                profile.setPassword( user.getAttribute( PASSWORD ) );
480                profile.setEmail( user.getAttribute( EMAIL ) );
481
482                // Get created/modified timestamps
483                final String created = user.getAttribute( CREATED );
484                final String modified = user.getAttribute( LAST_MODIFIED );
485                profile.setCreated( parseDate( profile, created ) );
486                profile.setLastModified( parseDate( profile, modified ) );
487
488                // Is the profile locked?
489                final String lockExpiry = user.getAttribute( LOCK_EXPIRY );
490                if( StringUtils.isEmpty( lockExpiry ) || lockExpiry.isEmpty() ) {
491                    profile.setLockExpiry( null );
492                } else {
493                    profile.setLockExpiry( new Date( Long.parseLong( lockExpiry ) ) );
494                }
495
496                // Extract all the user's attributes (should only be one attributes tag, but you never know!)
497                final NodeList attributes = user.getElementsByTagName( ATTRIBUTES_TAG );
498                for( int j = 0; j < attributes.getLength(); j++ ) {
499                    final Element attribute = ( Element )attributes.item( j );
500                    final String serializedMap = extractText( attribute );
501                    try {
502                        final Map< String, ? extends Serializable > map = Serializer.deserializeFromBase64( serializedMap );
503                        profile.getAttributes().putAll( map );
504                    } catch( final IOException e ) {
505                        LOG.error( "Could not parse user profile attributes!", e );
506                    }
507                }
508
509                return profile;
510            }
511        }
512        return null;
513    }
514
515    /**
516     * Extracts all the text nodes that are immediate children of an Element.
517     *
518     * @param element the base element
519     * @return the text nodes that are immediate children of the base element, concatenated together
520     */
521    private String extractText( final Element element ) {
522        String text = "";
523        if( element.getChildNodes().getLength() > 0 ) {
524            final NodeList children = element.getChildNodes();
525            text = IntStream.range(0, children.getLength()).mapToObj(children::item).filter(child -> child.getNodeType() == Node.TEXT_NODE).map(child -> ((Text) child).getData()).collect(Collectors.joining());
526        }
527        return text;
528    }
529
530    /**
531     *  Tries to parse a date using the default format - then, for backwards compatibility reasons, tries the platform default.
532     *
533     *  @param profile profile associated to the date.
534     *  @param date date to be parsed.
535     *  @return A parsed date, or null, if both parse attempts fail.
536     */
537    private Date parseDate( final UserProfile profile, final String date ) {
538        try {
539            final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
540            return c_format.parse( date );
541        } catch( final ParseException e ) {
542            try {
543                return DateFormat.getDateTimeInstance().parse( date );
544            } catch( final ParseException e2 ) {
545                LOG.warn( "Could not parse 'created' or 'lastModified' attribute for profile '" + profile.getLoginName() + "'." +
546                          " It may have been tampered with.", e2 );
547            }
548        }
549        return null;
550    }
551
552    /**
553     * After loading the DOM, this method sanity-checks the dates in the DOM and makes sure they are formatted properly. This is sort-of
554     * hacky, but it should work.
555     */
556    private void sanitizeDOM() {
557        if( c_dom == null ) {
558            throw new IllegalStateException( "FATAL: database does not exist" );
559        }
560
561        final NodeList users = c_dom.getElementsByTagName( USER_TAG );
562        for( int i = 0; i < users.getLength(); i++ ) {
563            final Element user = ( Element )users.item( i );
564
565            // Sanitize UID (and generate a new one if one does not exist)
566            String uid = user.getAttribute( UID ).trim();
567            if( StringUtils.isEmpty( uid ) || "-1".equals( uid ) ) {
568                uid = String.valueOf( generateUid( this ) );
569                user.setAttribute( UID, uid );
570            }
571
572            // Sanitize dates
573            final String loginName = user.getAttribute( LOGIN_NAME );
574            String created = user.getAttribute( CREATED );
575            String modified = user.getAttribute( LAST_MODIFIED );
576            final DateFormat c_format = new SimpleDateFormat( DATE_FORMAT );
577            try {
578                created = c_format.format( c_format.parse( created ) );
579                modified = c_format.format( c_format.parse( modified ) );
580                user.setAttribute( CREATED, created );
581                user.setAttribute( LAST_MODIFIED, modified );
582            } catch( final ParseException e ) {
583                try {
584                    created = c_format.format( DateFormat.getDateTimeInstance().parse( created ) );
585                    modified = c_format.format( DateFormat.getDateTimeInstance().parse( modified ) );
586                    user.setAttribute( CREATED, created );
587                    user.setAttribute( LAST_MODIFIED, modified );
588                } catch( final ParseException e2 ) {
589                    LOG.warn( "Could not parse 'created' or 'lastModified' attribute for profile '" + loginName + "'."
590                            + " It may have been tampered with." );
591                }
592            }
593        }
594    }
595
596    /**
597     * Private method that sets an attribute value for a supplied DOM element.
598     *
599     * @param element the element whose attribute is to be set
600     * @param attribute the name of the attribute to set
601     * @param value the desired attribute value
602     */
603    private void setAttribute( final Element element, final String attribute, final String value ) {
604        if( value != null ) {
605            element.setAttribute( attribute, value );
606        }
607    }
608
609}