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