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