]> source.dussan.org Git - archiva.git/blob
7272a5293dc6978a65313e0f6c682204fd81dc79
[archiva.git] /
1 package org.codehaus.redback.rest.services;
2
3 /*
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements.  See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership.  The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License.  You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied.  See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21
22 import net.sf.ehcache.CacheManager;
23 import org.apache.archiva.redback.configuration.UserConfiguration;
24 import org.apache.archiva.redback.users.UserManager;
25 import org.apache.archiva.redback.users.UserNotFoundException;
26 import org.apache.commons.lang.StringUtils;
27 import org.codehaus.plexus.cache.Cache;
28 import org.apache.archiva.redback.authentication.AuthenticationException;
29 import org.apache.archiva.redback.authentication.TokenBasedAuthenticationDataSource;
30 import org.codehaus.plexus.redback.keys.AuthenticationKey;
31 import org.codehaus.plexus.redback.keys.KeyManager;
32 import org.codehaus.plexus.redback.keys.KeyManagerException;
33 import org.codehaus.plexus.redback.keys.KeyNotFoundException;
34 import org.codehaus.plexus.redback.policy.AccountLockedException;
35 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
36 import org.codehaus.plexus.redback.policy.PasswordEncoder;
37 import org.codehaus.plexus.redback.policy.UserSecurityPolicy;
38 import org.codehaus.plexus.redback.rbac.RBACManager;
39 import org.codehaus.plexus.redback.rbac.RbacManagerException;
40 import org.codehaus.plexus.redback.rbac.RbacObjectNotFoundException;
41 import org.codehaus.plexus.redback.rbac.UserAssignment;
42 import org.codehaus.plexus.redback.role.RoleManager;
43 import org.codehaus.plexus.redback.role.RoleManagerException;
44 import org.codehaus.plexus.redback.system.SecuritySystem;
45 import org.codehaus.redback.integration.filter.authentication.HttpAuthenticator;
46 import org.codehaus.redback.integration.mail.Mailer;
47 import org.codehaus.redback.integration.security.role.RedbackRoleConstants;
48 import org.codehaus.redback.rest.api.model.ErrorMessage;
49 import org.codehaus.redback.rest.api.model.Operation;
50 import org.codehaus.redback.rest.api.model.Permission;
51 import org.codehaus.redback.rest.api.model.RegistrationKey;
52 import org.codehaus.redback.rest.api.model.Resource;
53 import org.codehaus.redback.rest.api.model.User;
54 import org.codehaus.redback.rest.api.services.RedbackServiceException;
55 import org.codehaus.redback.rest.api.services.UserService;
56 import org.codehaus.redback.rest.services.utils.PasswordValidator;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.springframework.stereotype.Service;
60
61 import javax.inject.Inject;
62 import javax.inject.Named;
63 import javax.mail.internet.AddressException;
64 import javax.mail.internet.InternetAddress;
65 import javax.servlet.http.HttpServletRequest;
66 import javax.ws.rs.core.Context;
67 import javax.ws.rs.core.Response;
68 import java.util.ArrayList;
69 import java.util.Arrays;
70 import java.util.Collection;
71 import java.util.List;
72 import java.util.Set;
73
74 @Service( "userService#rest" )
75 public class DefaultUserService
76     implements UserService
77 {
78
79     private Logger log = LoggerFactory.getLogger( getClass() );
80
81     private static final String VALID_USERNAME_CHARS = "[a-zA-Z_0-9\\-.@]*";
82
83     private UserManager userManager;
84
85     private SecuritySystem securitySystem;
86
87     @Inject
88     private UserConfiguration config;
89
90     @Inject
91     private RoleManager roleManager;
92
93     /**
94      * cache used for user assignments
95      */
96     @Inject
97     @Named( value = "cache#userAssignments" )
98     private Cache userAssignmentsCache;
99
100     /**
101      * cache used for user permissions
102      */
103     @Inject
104     @Named( value = "cache#userPermissions" )
105     private Cache userPermissionsCache;
106
107     /**
108      * Cache used for users
109      */
110     @Inject
111     @Named( value = "cache#users" )
112     private Cache usersCache;
113
114     @Inject
115     private Mailer mailer;
116
117     @Inject
118     @Named( value = "rBACManager#cached" )
119     private RBACManager rbacManager;
120
121     private HttpAuthenticator httpAuthenticator;
122
123     @Inject
124     private PasswordValidator passwordValidator;
125
126     @Context
127     private HttpServletRequest httpServletRequest;
128
129     @Inject
130     public DefaultUserService( @Named( value = "userManager#cached" ) UserManager userManager,
131                                SecuritySystem securitySystem,
132                                @Named( "httpAuthenticator#basic" ) HttpAuthenticator httpAuthenticator )
133     {
134         this.userManager = userManager;
135         this.securitySystem = securitySystem;
136         this.httpAuthenticator = httpAuthenticator;
137     }
138
139
140     public Boolean createUser( User user )
141         throws RedbackServiceException
142     {
143
144         try
145         {
146             org.apache.archiva.redback.users.User u = userManager.findUser( user.getUsername() );
147             if ( u != null )
148             {
149                 throw new RedbackServiceException(
150                     new ErrorMessage( "user " + user.getUsername() + " already exists" ) );
151             }
152         }
153         catch ( UserNotFoundException e )
154         {
155             //ignore we just want to prevent non human readable error message from backend :-)
156             log.debug( "user {} not exists", user.getUsername() );
157         }
158
159         // data validation
160         if ( StringUtils.isEmpty( user.getUsername() ) )
161         {
162             throw new RedbackServiceException( new ErrorMessage( "username cannot be empty" ) );
163         }
164
165         if ( StringUtils.isEmpty( user.getFullName() ) )
166         {
167             throw new RedbackServiceException( new ErrorMessage( "fullName cannot be empty" ) );
168         }
169
170         if ( StringUtils.isEmpty( user.getEmail() ) )
171         {
172             throw new RedbackServiceException( new ErrorMessage( "email cannot be empty" ) );
173         }
174
175         org.apache.archiva.redback.users.User u =
176             userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
177         u.setPassword( user.getPassword() );
178         u.setLocked( user.isLocked() );
179         u.setPasswordChangeRequired( user.isPasswordChangeRequired() );
180         u.setPermanent( user.isPermanent() );
181         u.setValidated( user.isValidated() );
182         u = userManager.addUser( u );
183         if ( !user.isPasswordChangeRequired() )
184         {
185             u.setPasswordChangeRequired( false );
186             try
187             {
188                 u = userManager.updateUser( u );
189                 log.debug( "user {} created", u.getUsername() );
190             }
191             catch ( UserNotFoundException e )
192             {
193                 throw new RedbackServiceException( e.getMessage() );
194             }
195         }
196         try
197         {
198             roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getPrincipal().toString() );
199         }
200         catch ( RoleManagerException rpe )
201         {
202             log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
203             throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
204         }
205         return Boolean.TRUE;
206     }
207
208     public Boolean deleteUser( String username )
209         throws RedbackServiceException
210     {
211
212         try
213         {
214
215             if ( rbacManager.userAssignmentExists( username ) )
216             {
217                 UserAssignment assignment = rbacManager.getUserAssignment( username );
218                 rbacManager.removeUserAssignment( assignment );
219             }
220
221         }
222         catch ( RbacManagerException e )
223         {
224             log.error( e.getMessage(), e );
225             throw new RedbackServiceException( e.getMessage() );
226         }
227         try
228         {
229             userManager.deleteUser( username );
230             return Boolean.TRUE;
231         }
232         catch ( UserNotFoundException e )
233         {
234             log.error( e.getMessage(), e );
235             throw new RedbackServiceException( e.getMessage() );
236         }
237         finally
238         {
239             removeFromCache( username );
240         }
241     }
242
243
244     public User getUser( String username )
245         throws RedbackServiceException
246     {
247         try
248         {
249             org.apache.archiva.redback.users.User user = userManager.findUser( username );
250             return getSimpleUser( user );
251         }
252         catch ( UserNotFoundException e )
253         {
254             return null;
255         }
256     }
257
258     public List<User> getUsers()
259         throws RedbackServiceException
260     {
261         List<org.apache.archiva.redback.users.User> users = userManager.getUsers();
262         List<User> simpleUsers = new ArrayList<User>( users.size() );
263
264         for ( org.apache.archiva.redback.users.User user : users )
265         {
266             simpleUsers.add( getSimpleUser( user ) );
267         }
268
269         return simpleUsers;
270     }
271
272     public Boolean updateMe( User user )
273         throws RedbackServiceException
274     {
275         // check username == one in the session
276         RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
277         if ( redbackRequestInformation == null || redbackRequestInformation.getUser() == null )
278         {
279             throw new RedbackServiceException( new ErrorMessage( "you must be logged to update your profile" ),
280                                                Response.Status.FORBIDDEN.getStatusCode() );
281         }
282         if ( user == null )
283         {
284             throw new RedbackServiceException( new ErrorMessage( "user parameter is mandatory" ),
285                                                Response.Status.BAD_REQUEST.getStatusCode() );
286         }
287         if ( !StringUtils.equals( redbackRequestInformation.getUser().getUsername(), user.getUsername() ) )
288         {
289             throw new RedbackServiceException( new ErrorMessage( "you can update only your profile" ),
290                                                Response.Status.FORBIDDEN.getStatusCode() );
291         }
292
293         if ( StringUtils.isEmpty( user.getPreviousPassword() ) )
294         {
295             throw new RedbackServiceException( new ErrorMessage( "previous password is empty" ),
296                                                Response.Status.BAD_REQUEST.getStatusCode() );
297         }
298
299         User realUser = getUser( user.getUsername() );
300         try
301         {
302             String previousEncodedPassword =
303                 securitySystem.getUserManager().findUser( user.getUsername() ).getEncodedPassword();
304
305             // check oldPassword with the current one
306
307             PasswordEncoder encoder = securitySystem.getPolicy().getPasswordEncoder();
308
309             if ( !encoder.isPasswordValid( previousEncodedPassword, user.getPreviousPassword() ) )
310             {
311
312                 throw new RedbackServiceException( new ErrorMessage( "password.provided.does.not.match.existing" ),
313                                                    Response.Status.BAD_REQUEST.getStatusCode() );
314             }
315         }
316         catch ( UserNotFoundException e )
317         {
318             throw new RedbackServiceException( new ErrorMessage( "user not found" ),
319                                                Response.Status.BAD_REQUEST.getStatusCode() );
320         }
321         // only 3 fields to update
322         realUser.setFullName( user.getFullName() );
323         realUser.setEmail( user.getEmail() );
324         // ui can limit to not update password
325         if ( StringUtils.isNotBlank( user.getPassword() ) )
326         {
327             passwordValidator.validatePassword( user.getPassword(), user.getUsername() );
328
329             realUser.setPassword( user.getPassword() );
330         }
331
332         updateUser( realUser );
333
334         return Boolean.TRUE;
335     }
336
337     public Boolean updateUser( User user )
338         throws RedbackServiceException
339     {
340         try
341         {
342             org.apache.archiva.redback.users.User rawUser = userManager.findUser( user.getUsername() );
343             rawUser.setFullName( user.getFullName() );
344             rawUser.setEmail( user.getEmail() );
345             rawUser.setValidated( user.isValidated() );
346             rawUser.setLocked( user.isLocked() );
347             rawUser.setPassword( user.getPassword() );
348             rawUser.setPasswordChangeRequired( user.isPasswordChangeRequired() );
349             rawUser.setPermanent( user.isPermanent() );
350
351             userManager.updateUser( rawUser );
352             return Boolean.TRUE;
353         }
354         catch ( UserNotFoundException e )
355         {
356             throw new RedbackServiceException( e.getMessage() );
357         }
358     }
359
360     public int removeFromCache( String userName )
361         throws RedbackServiceException
362     {
363         if ( userAssignmentsCache != null )
364         {
365             userAssignmentsCache.remove( userName );
366         }
367         if ( userPermissionsCache != null )
368         {
369             userPermissionsCache.remove( userName );
370         }
371         if ( usersCache != null )
372         {
373             usersCache.remove( userName );
374         }
375
376         CacheManager cacheManager = CacheManager.getInstance();
377         String[] caches = cacheManager.getCacheNames();
378         for ( String cacheName : caches )
379         {
380             if ( StringUtils.startsWith( cacheName, "org.codehaus.plexus.redback.rbac.jdo" ) )
381             {
382                 cacheManager.getCache( cacheName ).removeAll();
383             }
384         }
385
386         return 0;
387     }
388
389     public User getGuestUser()
390         throws RedbackServiceException
391     {
392         try
393         {
394             org.apache.archiva.redback.users.User user = userManager.getGuestUser();
395             return getSimpleUser( user );
396         }
397         catch ( Exception e )
398         {
399             return null;
400         }
401     }
402
403     public User createGuestUser()
404         throws RedbackServiceException
405     {
406         User u = getGuestUser();
407         if ( u != null )
408         {
409             return u;
410         }
411         // temporary disable policy during guest creation as no password !
412         try
413         {
414             securitySystem.getPolicy().setEnabled( false );
415             org.apache.archiva.redback.users.User user = userManager.createGuestUser();
416             user.setPasswordChangeRequired( false );
417             user = userManager.updateUser( user, false );
418             roleManager.assignRole( "guest", user.getPrincipal().toString() );
419             return getSimpleUser( user );
420         }
421         catch ( RoleManagerException e )
422         {
423             log.error( e.getMessage(), e );
424             throw new RedbackServiceException( e.getMessage() );
425         }
426         catch ( UserNotFoundException e )
427         {
428             // olamy I wonder how this can happen :-)
429             log.error( e.getMessage(), e );
430             throw new RedbackServiceException( e.getMessage() );
431         }
432         finally
433         {
434
435             if ( !securitySystem.getPolicy().isEnabled() )
436             {
437                 securitySystem.getPolicy().setEnabled( true );
438             }
439         }
440     }
441
442     public Boolean ping()
443         throws RedbackServiceException
444     {
445         return Boolean.TRUE;
446     }
447
448     private User getSimpleUser( org.apache.archiva.redback.users.User user )
449     {
450         if ( user == null )
451         {
452             return null;
453         }
454         return new User( user );
455     }
456
457     public Boolean createAdminUser( User adminUser )
458         throws RedbackServiceException
459     {
460         if ( isAdminUserExists() )
461         {
462             return Boolean.FALSE;
463         }
464
465         org.apache.archiva.redback.users.User user =
466             userManager.createUser( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminUser.getFullName(),
467                                     adminUser.getEmail() );
468         user.setPassword( adminUser.getPassword() );
469
470         user.setLocked( false );
471         user.setPasswordChangeRequired( false );
472         user.setPermanent( true );
473         user.setValidated( true );
474
475         userManager.addUser( user );
476
477         try
478         {
479             roleManager.assignRole( "system-administrator", user.getPrincipal().toString() );
480         }
481         catch ( RoleManagerException e )
482         {
483             throw new RedbackServiceException( e.getMessage() );
484         }
485         return Boolean.TRUE;
486     }
487
488     public Boolean isAdminUserExists()
489         throws RedbackServiceException
490     {
491         try
492         {
493             userManager.findUser( config.getString( "redback.default.admin" ) );
494             return Boolean.TRUE;
495         }
496         catch ( UserNotFoundException e )
497         {
498             // ignore
499         }
500         return Boolean.FALSE;
501     }
502
503     public Boolean resetPassword( String username )
504         throws RedbackServiceException
505     {
506         if ( StringUtils.isEmpty( username ) )
507         {
508             throw new RedbackServiceException( new ErrorMessage( "username.cannot.be.empty" ) );
509         }
510
511         UserManager userManager = securitySystem.getUserManager();
512         KeyManager keyManager = securitySystem.getKeyManager();
513         UserSecurityPolicy policy = securitySystem.getPolicy();
514
515         try
516         {
517             org.apache.archiva.redback.users.User user = userManager.findUser( username );
518
519             AuthenticationKey authkey = keyManager.createKey( username, "Password Reset Request",
520                                                               policy.getUserValidationSettings().getEmailValidationTimeout() );
521
522             mailer.sendPasswordResetEmail( Arrays.asList( user.getEmail() ), authkey, getBaseUrl() );
523
524             log.info( "password reset request for username {}", username );
525         }
526         catch ( UserNotFoundException e )
527         {
528             log.info( "Password Reset on non-existant user [{}].", username );
529             throw new RedbackServiceException( new ErrorMessage( "password.reset.failure" ) );
530         }
531         catch ( KeyManagerException e )
532         {
533             log.info( "Unable to issue password reset.", e );
534             throw new RedbackServiceException( new ErrorMessage( "password.reset.email.generation.failure" ) );
535         }
536
537         return Boolean.TRUE;
538     }
539
540     public RegistrationKey registerUser( User user )
541         throws RedbackServiceException
542     {
543         if ( user == null )
544         {
545             throw new RedbackServiceException( new ErrorMessage( "invalid.user.credentials", null ) );
546
547         }
548
549         UserSecurityPolicy securityPolicy = securitySystem.getPolicy();
550
551         boolean emailValidationRequired = securityPolicy.getUserValidationSettings().isEmailValidationRequired();
552
553         if ( emailValidationRequired )
554         {
555             validateCredentialsLoose( user );
556         }
557         else
558         {
559             validateCredentialsStrict( user );
560         }
561
562         // NOTE: Do not perform Password Rules Validation Here.
563
564         if ( userManager.userExists( user.getUsername() ) )
565         {
566             throw new RedbackServiceException(
567                 new ErrorMessage( "user.already.exists", new String[]{ user.getUsername() } ) );
568         }
569
570         org.apache.archiva.redback.users.User u =
571             userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
572         u.setPassword( user.getPassword() );
573         u.setValidated( false );
574         u.setLocked( false );
575
576         try
577         {
578             roleManager.assignRole( RedbackRoleConstants.REGISTERED_USER_ROLE_ID, u.getPrincipal().toString() );
579         }
580         catch ( RoleManagerException rpe )
581         {
582             log.error( "RoleProfile Error: " + rpe.getMessage(), rpe );
583             throw new RedbackServiceException( new ErrorMessage( "assign.role.failure", null ) );
584         }
585
586         if ( emailValidationRequired )
587         {
588             u.setLocked( true );
589
590             try
591             {
592                 AuthenticationKey authkey =
593                     securitySystem.getKeyManager().createKey( u.getPrincipal().toString(), "New User Email Validation",
594                                                               securityPolicy.getUserValidationSettings().getEmailValidationTimeout() );
595
596                 mailer.sendAccountValidationEmail( Arrays.asList( u.getEmail() ), authkey, getBaseUrl() );
597
598                 securityPolicy.setEnabled( false );
599                 userManager.addUser( u );
600                 return new RegistrationKey( authkey.getKey() );
601
602             }
603             catch ( KeyManagerException e )
604             {
605                 log.error( "Unable to register a new user.", e );
606                 throw new RedbackServiceException( new ErrorMessage( "cannot.register.user", null ) );
607             }
608             finally
609             {
610                 securityPolicy.setEnabled( true );
611             }
612         }
613         else
614         {
615             userManager.addUser( u );
616             return new RegistrationKey( "-1" );
617         }
618
619         // FIXME log this event
620         /*
621         AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
622         event.setAffectedUser( username );
623         event.log();
624         */
625
626     }
627
628     public Boolean validateUserFromKey( String key )
629         throws RedbackServiceException
630     {
631         String principal = null;
632         try
633         {
634             AuthenticationKey authkey = securitySystem.getKeyManager().findKey( key );
635
636             org.apache.archiva.redback.users.User user =
637                 securitySystem.getUserManager().findUser( authkey.getForPrincipal() );
638
639             user.setValidated( true );
640             user.setLocked( false );
641             user.setPasswordChangeRequired( true );
642             user.setEncodedPassword( "" );
643
644             principal = user.getPrincipal().toString();
645
646             TokenBasedAuthenticationDataSource authsource = new TokenBasedAuthenticationDataSource();
647             authsource.setPrincipal( principal );
648             authsource.setToken( authkey.getKey() );
649             authsource.setEnforcePasswordChange( false );
650
651             securitySystem.getUserManager().updateUser( user );
652
653             httpAuthenticator.authenticate( authsource, httpServletRequest.getSession( true ) );
654
655             log.info( "account validated for user {}", user.getUsername() );
656
657             return Boolean.TRUE;
658         }
659         catch ( MustChangePasswordException e )
660         {
661             throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
662         }
663         catch ( KeyNotFoundException e )
664         {
665             log.info( "Invalid key requested: {}", key );
666             throw new RedbackServiceException( new ErrorMessage( "cannot.find.key" ) );
667         }
668         catch ( KeyManagerException e )
669         {
670             throw new RedbackServiceException( new ErrorMessage( "cannot.find.key.at.the.momment" ) );
671
672         }
673         catch ( UserNotFoundException e )
674         {
675             throw new RedbackServiceException( new ErrorMessage( "cannot.find.user", new String[]{ principal } ) );
676
677         }
678         catch ( AccountLockedException e )
679         {
680             throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
681         }
682         catch ( AuthenticationException e )
683         {
684             throw new RedbackServiceException( e.getMessage(), Response.Status.FORBIDDEN.getStatusCode() );
685         }
686     }
687
688     public Collection<Permission> getCurrentUserPermissions()
689         throws RedbackServiceException
690     {
691         RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
692         String userName = UserManager.GUEST_USERNAME;
693         if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
694         {
695             userName = redbackRequestInformation.getUser().getUsername();
696         }
697
698         return getUserPermissions( userName );
699     }
700
701     public Collection<Operation> getCurrentUserOperations()
702         throws RedbackServiceException
703     {
704         RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get();
705         String userName = UserManager.GUEST_USERNAME;
706         if ( redbackRequestInformation != null && redbackRequestInformation.getUser() != null )
707         {
708             userName = redbackRequestInformation.getUser().getUsername();
709         }
710
711         return getUserOperations( userName );
712     }
713
714     public Collection<Operation> getUserOperations( String userName )
715         throws RedbackServiceException
716     {
717         Collection<Permission> permissions = getUserPermissions( userName );
718         List<Operation> operations = new ArrayList<Operation>( permissions.size() );
719         for ( Permission permission : permissions )
720         {
721             if ( permission.getOperation() != null )
722             {
723                 Operation operation = new Operation();
724                 operation.setName( permission.getOperation().getName() );
725                 operations.add( operation );
726             }
727         }
728         return operations;
729     }
730
731     public Collection<Permission> getUserPermissions( String userName )
732         throws RedbackServiceException
733     {
734         try
735         {
736             Set<org.codehaus.plexus.redback.rbac.Permission> permissions =
737                 rbacManager.getAssignedPermissions( userName );
738             // FIXME return guest permissions !!
739             List<Permission> userPermissions = new ArrayList<Permission>( permissions.size() );
740             for ( org.codehaus.plexus.redback.rbac.Permission p : permissions )
741             {
742                 Permission permission = new Permission();
743                 permission.setName( p.getName() );
744
745                 if ( p.getOperation() != null )
746                 {
747                     Operation operation = new Operation();
748                     operation.setName( p.getOperation().getName() );
749                     permission.setOperation( operation );
750                 }
751
752                 if ( p.getResource() != null )
753                 {
754                     Resource resource = new Resource();
755                     resource.setIdentifier( p.getResource().getIdentifier() );
756                     resource.setPattern( p.getResource().isPattern() );
757                     permission.setResource( resource );
758                 }
759
760                 userPermissions.add( permission );
761             }
762             return userPermissions;
763         }
764         catch ( RbacObjectNotFoundException e )
765         {
766             log.error( e.getMessage(), e );
767             throw new RedbackServiceException( e.getMessage() );
768         }
769         catch ( RbacManagerException e )
770         {
771             log.error( e.getMessage(), e );
772             throw new RedbackServiceException( e.getMessage() );
773         }
774     }
775
776     public void validateCredentialsLoose( User user )
777         throws RedbackServiceException
778     {
779         RedbackServiceException redbackServiceException =
780             new RedbackServiceException( "issues during validating user" );
781         if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getUsername() ) )
782         {
783             redbackServiceException.addErrorMessage( new ErrorMessage( "username.required", null ) );
784         }
785         else
786         {
787             if ( !user.getUsername().matches( VALID_USERNAME_CHARS ) )
788             {
789                 redbackServiceException.addErrorMessage( new ErrorMessage( "username.invalid.characters", null ) );
790             }
791         }
792
793         if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getFullName() ) )
794         {
795             redbackServiceException.addErrorMessage( new ErrorMessage( "fullName.required", null ) );
796         }
797
798         if ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getEmail() ) )
799         {
800             redbackServiceException.addErrorMessage( new ErrorMessage( "email.required", null ) );
801         }
802
803         if ( !org.codehaus.plexus.util.StringUtils.equals( user.getPassword(), user.getConfirmPassword() ) )
804         {
805             redbackServiceException.addErrorMessage( new ErrorMessage( "passwords.does.not.match", null ) );
806         }
807
808         try
809         {
810             if ( !org.codehaus.plexus.util.StringUtils.isEmpty( user.getEmail() ) )
811             {
812                 new InternetAddress( user.getEmail(), true );
813             }
814         }
815         catch ( AddressException e )
816         {
817             redbackServiceException.addErrorMessage( new ErrorMessage( "email.invalid", null ) );
818         }
819         if ( !redbackServiceException.getErrorMessages().isEmpty() )
820         {
821             throw redbackServiceException;
822         }
823     }
824
825     public void validateCredentialsStrict( User user )
826         throws RedbackServiceException
827     {
828         validateCredentialsLoose( user );
829
830         org.apache.archiva.redback.users.User tmpuser =
831             userManager.createUser( user.getUsername(), user.getFullName(), user.getEmail() );
832
833         user.setPassword( user.getPassword() );
834
835         securitySystem.getPolicy().validatePassword( tmpuser );
836
837         if ( ( org.codehaus.plexus.util.StringUtils.isEmpty( user.getPassword() ) ) )
838         {
839             throw new RedbackServiceException( new ErrorMessage( "password.required", null ) );
840         }
841     }
842
843     private String getBaseUrl()
844     {
845         if ( httpServletRequest != null )
846         {
847             if ( httpServletRequest != null )
848             {
849                 return httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + (
850                     httpServletRequest.getServerPort() == 80
851                         ? ""
852                         : ":" + httpServletRequest.getServerPort() ) + httpServletRequest.getContextPath();
853             }
854         }
855         return null;
856     }
857
858     public Boolean unlockUser( String username )
859         throws RedbackServiceException
860     {
861         User user = getUser( username );
862         if ( user == null )
863         {
864             user.setLocked( false );
865             updateUser( user );
866             return Boolean.TRUE;
867         }
868         return Boolean.FALSE;
869     }
870
871     public Boolean lockUser( String username )
872         throws RedbackServiceException
873     {
874         User user = getUser( username );
875         if ( user == null )
876         {
877             user.setLocked( true );
878             updateUser( user );
879             return Boolean.TRUE;
880         }
881         return Boolean.FALSE;
882     }
883
884     public Boolean passwordChangeRequired( String username )
885         throws RedbackServiceException
886     {
887         User user = getUser( username );
888         if ( user == null )
889         {
890             user.setPasswordChangeRequired( true );
891             updateUser( user );
892             return Boolean.TRUE;
893         }
894         return Boolean.FALSE;
895     }
896
897     public Boolean passwordChangeNotRequired( String username )
898         throws RedbackServiceException
899     {
900         User user = getUser( username );
901         if ( user == null )
902         {
903             user.setPasswordChangeRequired( false );
904             updateUser( user );
905             return Boolean.TRUE;
906         }
907         return Boolean.FALSE;
908     }
909 }