View Javadoc

1   /***
2    * 
3    */
4   package hu.elte.tribus.services;
5   
6   import java.io.Serializable;
7   
8   import hu.elte.tribus.interfaces.UserDao;
9   import hu.elte.tribus.model.User;
10  
11  import org.acegisecurity.GrantedAuthority;
12  import org.acegisecurity.GrantedAuthorityImpl;
13  import org.acegisecurity.userdetails.UserDetails;
14  import org.acegisecurity.userdetails.UserDetailsService;
15  import org.acegisecurity.userdetails.UsernameNotFoundException;
16  import org.springframework.dao.DataAccessException;
17  
18  /***
19   * @author kocka
20   * 
21   */
22  public class UserDetailServiceImpl implements UserDetailsService, Serializable {
23  
24  	/***
25  	 * 
26  	 */
27  	private static final long serialVersionUID = 4843571652792394776L;
28  
29  	private UserDao userDao;
30  
31  	private final static GrantedAuthority ADMIN_AUTH = new GrantedAuthorityImpl("ROLE_ADMIN");
32  	private final static GrantedAuthority USER_AUTH = new GrantedAuthorityImpl("ROLE_USER");
33  	
34  	private class UserDetailsImpl implements UserDetails {
35  
36  		private User user;
37  
38  		public GrantedAuthority[] getAuthorities() {
39  			if(user.isAdmin()) {
40  				return new GrantedAuthority[]{USER_AUTH, ADMIN_AUTH};
41  			} else {
42  				return new GrantedAuthority[]{USER_AUTH};
43  			}
44  		}
45  
46  		public String getPassword() {
47  			return user.getPasswd();
48  		}
49  
50  		public String getUsername() {
51  			return user.getUsername();
52  		}
53  
54  		public boolean isAccountNonExpired() {
55  			return true;
56  		}
57  
58  		public boolean isAccountNonLocked() {
59  			return user.getStatus() != User.ENUM_STATUS_REG_DISABLED;
60  		}
61  
62  		public boolean isCredentialsNonExpired() {
63  			return true;
64  		}
65  
66  		public boolean isEnabled() {
67  			return user.getStatus() == User.ENUM_STATUS_REG_ACCEPTED;
68  		}
69  
70  		public UserDetailsImpl(User user) {
71  			super();
72  			this.user = user;
73  		}
74  
75  	}
76  
77  	public UserDetailServiceImpl(UserDao userDao) {
78  		super();
79  		this.userDao = userDao;
80  	}
81  
82  	/*
83  	 * (non-Javadoc)
84  	 * 
85  	 * @see org.acegisecurity.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
86  	 */
87  	public UserDetails loadUserByUsername(String userName)
88  			throws UsernameNotFoundException, DataAccessException {
89  		User user = userDao.getUser(userName);
90  		if(user == null) {
91  			throw new UsernameNotFoundException("User not found");
92  		}
93  		return new UserDetailsImpl(user);
94  	}
95  
96  }