2 * Copyright (C) 2010 Mathieu Baudier <mbaudier@argeo.org>
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org
.argeo
.security
.core
;
19 import java
.security
.NoSuchAlgorithmException
;
20 import java
.security
.SecureRandom
;
22 import java
.util
.Random
;
24 import org
.argeo
.ArgeoException
;
25 import org
.argeo
.security
.ArgeoUser
;
26 import org
.argeo
.security
.CurrentUserDao
;
27 import org
.argeo
.security
.CurrentUserService
;
28 import org
.argeo
.security
.SimpleArgeoUser
;
29 import org
.argeo
.security
.UserNature
;
30 import org
.springframework
.security
.providers
.encoding
.PasswordEncoder
;
32 public class DefaultCurrentUserService
implements CurrentUserService
{
33 private CurrentUserDao currentUserDao
;
34 private PasswordEncoder passwordEncoder
;
35 private Random random
;
37 public DefaultCurrentUserService() {
39 random
= SecureRandom
.getInstance("SHA1PRNG");
40 } catch (NoSuchAlgorithmException e
) {
41 random
= new Random(System
.currentTimeMillis());
45 public ArgeoUser
getCurrentUser() {
46 ArgeoUser argeoUser
= ArgeoUserDetails
.securityContextUser();
47 if (argeoUser
== null)
49 if (argeoUser
.getRoles().contains(currentUserDao
.getDefaultRole()))
50 argeoUser
.getRoles().remove(currentUserDao
.getDefaultRole());
54 public void updateCurrentUserPassword(String oldPassword
, String newPassword
) {
55 SimpleArgeoUser user
= new SimpleArgeoUser(getCurrentUser());
56 if (!passwordEncoder
.isPasswordValid(user
.getPassword(), oldPassword
,
58 throw new ArgeoException("Old password is not correct.");
59 user
.setPassword(encodePassword(newPassword
));
60 currentUserDao
.updateUser(user
);
63 protected String
encodePassword(String password
) {
64 byte[] salt
= new byte[16];
65 random
.nextBytes(salt
);
66 return passwordEncoder
.encodePassword(password
, salt
);
69 public void updateCurrentUserNatures(Map
<String
, UserNature
> userNatures
) {
70 // TODO Auto-generated method stub
74 public void setCurrentUserDao(CurrentUserDao dao
) {
75 this.currentUserDao
= dao
;
78 public void setPasswordEncoder(PasswordEncoder passwordEncoder
) {
79 this.passwordEncoder
= passwordEncoder
;