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