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