]> source.dussan.org Git - archiva.git/blob
a6077bafe61bfc18650b697e3f0b587c58f6cbad
[archiva.git] /
1 package org.codehaus.plexus.redback.struts2.action.admin;
2
3 /*
4  * Copyright 2005-2006 The Codehaus.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 import org.apache.struts2.ServletActionContext;
20 import org.codehaus.plexus.redback.authentication.AuthenticationConstants;
21 import org.codehaus.plexus.redback.authentication.AuthenticationDataSource;
22 import org.codehaus.plexus.redback.authentication.AuthenticationException;
23 import org.codehaus.plexus.redback.authentication.AuthenticationResult;
24 import org.codehaus.plexus.redback.authentication.PasswordBasedAuthenticationDataSource;
25 import org.codehaus.plexus.redback.configuration.UserConfiguration;
26 import org.codehaus.plexus.redback.policy.AccountLockedException;
27 import org.codehaus.plexus.redback.policy.MustChangePasswordException;
28 import org.codehaus.plexus.redback.role.RoleManager;
29 import org.codehaus.plexus.redback.role.RoleManagerException;
30 import org.codehaus.plexus.redback.struts2.action.AuditEvent;
31 import org.codehaus.plexus.redback.system.SecuritySession;
32 import org.codehaus.plexus.redback.users.User;
33 import org.codehaus.plexus.redback.users.UserManager;
34 import org.codehaus.plexus.redback.users.UserNotFoundException;
35 import org.codehaus.redback.integration.interceptor.SecureActionBundle;
36 import org.codehaus.redback.integration.interceptor.SecureActionException;
37 import org.codehaus.redback.integration.model.EditUserCredentials;
38 import org.codehaus.redback.integration.util.AutoLoginCookies;
39 import org.springframework.context.annotation.Scope;
40 import org.springframework.stereotype.Controller;
41
42 import javax.inject.Inject;
43 import java.util.Arrays;
44 import java.util.Date;
45
46 /**
47  * AddAdminUserAction
48  *
49  * @author <a href="mailto:joakim@erdfelt.com">Joakim Erdfelt</a>
50  * @version $Id$
51  */
52 @Controller( "redback-admin-account" )
53 @Scope( "prototype" )
54 public class AddAdminUserAction
55     extends AbstractAdminUserCredentialsAction
56 {
57     private static final String LOGIN_ERROR = "login-error";
58
59     private static final String LOGIN_SUCCESS = "security-login-success";
60
61     private static final String PASSWORD_CHANGE = "security-must-change-password";
62
63     private static final String ACCOUNT_LOCKED = "security-login-locked";
64
65     @Inject
66     private RoleManager roleManager;
67
68
69     @Inject
70     private UserConfiguration config;
71
72     private EditUserCredentials user;
73
74     @Inject
75     private AutoLoginCookies autologinCookies;
76
77     public String show()
78     {
79         if ( user == null )
80         {
81             user = new EditUserCredentials( config.getString( "redback.default.admin" ) );
82         }
83
84         return INPUT;
85     }
86
87     /**
88      * TODO this must done in a service !!
89      * @return
90      */
91     public String submit()
92     {
93         if ( user == null )
94         {
95             user = new EditUserCredentials( config.getString( "redback.default.admin" ) );
96             addActionError( getText( "invalid.admin.credentials" ) );
97             return ERROR;
98         }
99
100         log.info( "user = {}", user );
101
102         internalUser = user;
103
104         validateCredentialsStrict();
105
106         UserManager userManager = super.securitySystem.getUserManager();
107
108         if ( userManager.userExists( config.getString( "redback.default.admin" ) ) )
109         {
110             // Means that the role name exist already.
111             // We need to fail fast and return to the previous page.
112             addActionError( getText( "admin.user.already.exists" ) );
113             return ERROR;
114         }
115
116         if ( hasActionErrors() || hasFieldErrors() )
117         {
118             return ERROR;
119         }
120
121         User u =
122             userManager.createUser( config.getString( "redback.default.admin" ), user.getFullName(), user.getEmail() );
123         if ( u == null )
124         {
125             addActionError( getText( "cannot.operate.on.null.user" ) );
126             return ERROR;
127         }
128
129         u.setPassword( user.getPassword() );
130         u.setLocked( false );
131         u.setPasswordChangeRequired( false );
132         u.setPermanent( true );
133
134         userManager.addUser( u );
135
136         AuditEvent event = new AuditEvent( getText( "log.account.create" ) );
137         event.setAffectedUser( u.getUsername() );
138         event.log();
139
140         try
141         {
142             roleManager.assignRole( "system-administrator", u.getPrincipal().toString() );
143             event = new AuditEvent( getText( "log.assign.role" ) );
144             event.setAffectedUser( u.getUsername() );
145             event.setRole( "system-administrator" );
146             event.log();
147         }
148         catch ( RoleManagerException rpe )
149         {
150             addActionError( getText( "cannot.assign.admin.role" ) );
151             return ERROR;
152         }
153
154         PasswordBasedAuthenticationDataSource authdatasource = new PasswordBasedAuthenticationDataSource();
155         authdatasource.setPrincipal( user.getUsername() );
156         authdatasource.setPassword( user.getPassword() );
157
158         return webLogin( authdatasource );
159     }
160
161     public EditUserCredentials getUser()
162     {
163         return user;
164     }
165
166     public void setUser( EditUserCredentials user )
167     {
168         this.user = user;
169     }
170
171     public SecureActionBundle initSecureActionBundle()
172         throws SecureActionException
173     {
174         return SecureActionBundle.OPEN;
175     }
176
177     /**
178      * 1) attempts to authentication based on the passed in data source
179      * 2) if successful sets cookies and returns LOGIN_SUCCESS
180      * 3) if failure then check what kinda failure and return error
181      *
182      * @param authdatasource
183      * @return
184      */
185     private String webLogin( AuthenticationDataSource authdatasource )
186     {
187         // An attempt should log out your authentication tokens first!
188         setAuthTokens( null );
189
190         clearErrorsAndMessages();
191
192         String principal = authdatasource.getPrincipal();
193
194         try
195         {
196             SecuritySession securitySession = securitySystem.authenticate( authdatasource );
197
198             if ( securitySession.getAuthenticationResult().isAuthenticated() )
199             {
200                 // Success!  Create tokens.
201                 setAuthTokens( securitySession );
202
203                 setCookies( authdatasource );
204
205                 AuditEvent event = new AuditEvent( getText( "log.login.success" ) );
206                 event.setAffectedUser( principal );
207                 event.log();
208
209                 User u = securitySession.getUser();
210                 u.setLastLoginDate( new Date() );
211                 securitySystem.getUserManager().updateUser( u );
212
213                 return LOGIN_SUCCESS;
214             }
215             else
216             {
217                 log.debug( "Login Action failed against principal : {}",
218                            securitySession.getAuthenticationResult().getPrincipal(),
219                            securitySession.getAuthenticationResult().getException() );
220
221                 AuthenticationResult result = securitySession.getAuthenticationResult();
222                 if ( result.getExceptionsMap() != null && !result.getExceptionsMap().isEmpty() )
223                 {
224                     if ( result.getExceptionsMap().get( AuthenticationConstants.AUTHN_NO_SUCH_USER ) != null )
225                     {
226                         addActionError( getText( "incorrect.username.password" ) );
227                     }
228                     else
229                     {
230                         addActionError( getText( "authentication.failed" ) );
231                     }
232                 }
233                 else
234                 {
235                     addActionError( getText( "authentication.failed" ) );
236                 }
237
238                 AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
239                 event.setAffectedUser( principal );
240                 event.log();
241
242                 return LOGIN_ERROR;
243             }
244         }
245         catch ( AuthenticationException ae )
246         {
247             addActionError( getText( "authentication.exception", Arrays.asList( (Object) ae.getMessage() ) ) );
248             return LOGIN_ERROR;
249         }
250         catch ( UserNotFoundException ue )
251         {
252             addActionError(
253                 getText( "user.not.found.exception", Arrays.asList( (Object) principal, ue.getMessage() ) ) );
254
255             AuditEvent event = new AuditEvent( getText( "log.login.fail" ) );
256             event.setAffectedUser( principal );
257             event.log();
258             return LOGIN_ERROR;
259         }
260         catch ( AccountLockedException e )
261         {
262             addActionError( getText( "account.locked" ) );
263
264             AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
265             event.setAffectedUser( principal );
266             event.log();
267             return ACCOUNT_LOCKED;
268         }
269         catch ( MustChangePasswordException e )
270         {
271             // TODO: preferably we would not set the cookies for this "partial" login state
272             setCookies( authdatasource );
273
274             AuditEvent event = new AuditEvent( getText( "log.login.fail.locked" ) );
275             event.setAffectedUser( principal );
276             event.log();
277             return PASSWORD_CHANGE;
278         }
279     }
280
281     private void setCookies( AuthenticationDataSource authdatasource )
282     {
283         autologinCookies.setSignonCookie( authdatasource.getPrincipal(), ServletActionContext.getResponse(),
284                                           ServletActionContext.getRequest() );
285     }
286 }