From bc23d2d2125d2086847397e85335f29a70668f6b Mon Sep 17 00:00:00 2001 From: Alexander Alexeev Date: Mon, 28 Nov 2016 13:39:04 +0700 Subject: remember-me authorization with test; a statndard DaoAuthentication provider used --- .../security/JuickAuthenticationProvider.java | 50 ------------ .../juick/server/security/entities/JuickUser.java | 2 +- .../main/java/com/juick/service/UserService.java | 4 + .../java/com/juick/service/UserServiceImpl.java | 36 +++++++-- .../service/security/JuickUserDetailsService.java | 34 +++++++++ .../service/security/SimpleRememberMeServices.java | 89 ++++++++++++++++++++++ juick-server/src/main/resources/juick.conf.example | 3 + 7 files changed, 161 insertions(+), 57 deletions(-) delete mode 100644 juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java create mode 100644 juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java create mode 100644 juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java (limited to 'juick-server/src/main') diff --git a/juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java b/juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java deleted file mode 100644 index 87908950..00000000 --- a/juick-server/src/main/java/com/juick/server/security/JuickAuthenticationProvider.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.juick.server.security; - -import com.juick.User; -import com.juick.server.security.entities.JuickUser; -import com.juick.service.UserService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.authentication.AuthenticationProvider; -import org.springframework.security.authentication.LockedException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.AuthenticationException; -import org.springframework.util.Assert; - -import javax.inject.Inject; - -/** - * Created by vitalyster on 25.11.2016. - */ -public class JuickAuthenticationProvider implements AuthenticationProvider { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - private final UserService userService; - - @Inject - public JuickAuthenticationProvider(UserService userService) { - Assert.notNull(userService); - this.userService = userService; - } - - @Override - public Authentication authenticate(Authentication authentication) throws AuthenticationException { - String name = authentication.getName(); - String password = authentication.getCredentials().toString(); - - User user = userService.getFullyUserByName(name); - if (user != null) { - if (user.isBanned()) - throw new LockedException("Username \"" + name + "\" is banned"); - - return new UsernamePasswordAuthenticationToken(name, password, JuickUser.USER_AUTHORITY); - } - return null; - } - - @Override - public boolean supports(Class authentication) { - return authentication.equals(UsernamePasswordAuthenticationToken.class); - } -} diff --git a/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java b/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java index 3e413bf6..f6d27ddf 100644 --- a/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java +++ b/juick-server/src/main/java/com/juick/server/security/entities/JuickUser.java @@ -28,7 +28,7 @@ public class JuickUser implements UserDetails { @Override public String getPassword() { - return null; + return user.getCredentials(); } @Override diff --git a/juick-server/src/main/java/com/juick/service/UserService.java b/juick-server/src/main/java/com/juick/service/UserService.java index 4d7d09c9..3fb2ae12 100644 --- a/juick-server/src/main/java/com/juick/service/UserService.java +++ b/juick-server/src/main/java/com/juick/service/UserService.java @@ -111,4 +111,8 @@ public interface UserService { EmailOpts getEmailOpts(User user); String getEmailHash(User user); + + int deleteLoginForUser(String name); + + int setLoginForUser(int uid, String loginHash); } diff --git a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java index d1e4eff5..a00eab3f 100644 --- a/juick-server/src/main/java/com/juick/service/UserServiceImpl.java +++ b/juick-server/src/main/java/com/juick/service/UserServiceImpl.java @@ -37,6 +37,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { user.setUid(rs.getInt(1)); user.setName(rs.getString(2)); user.setBanned(rs.getBoolean(3)); + user.setLang(rs.getString(4)); return user; } @@ -109,7 +110,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { @Override public Optional getUserByUID(final int uid) { List list = getJdbcTemplate().query( - "SELECT id, nick,banned FROM users WHERE id = ?", new UserMapper(), uid); + "SELECT id, nick, banned, lang FROM users WHERE id = ?", new UserMapper(), uid); return list.isEmpty() ? Optional.empty() : Optional.of(list.get(0)); } @@ -121,7 +122,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { if (StringUtils.isNotBlank(username)) { List list = getJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE nick = ?", new UserMapper(), username); + "SELECT id, nick, banned, lang FROM users WHERE nick = ?", new UserMapper(), username); if (!list.isEmpty()) result = list.get(0); @@ -169,7 +170,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { if (StringUtils.isNotBlank(jid)) { List list = getJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE id = (SELECT user_id FROM jids WHERE jid = ?)", + "SELECT id, nick, banned, lang FROM users WHERE id = (SELECT user_id FROM jids WHERE jid = ?)", new UserMapper(), jid); @@ -186,7 +187,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { return Collections.emptyList(); return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE nick IN (:unames)", + "SELECT id, nick, banned, lang FROM users WHERE nick IN (:unames)", new MapSqlParameterSource("unames", unames), new UserMapper()); } @@ -198,7 +199,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { return Collections.emptyList(); return getNamedParameterJdbcTemplate().query( - "SELECT id, nick, banned FROM users WHERE id IN (:ids)", + "SELECT id, nick, banned, lang FROM users WHERE id IN (:ids)", new MapSqlParameterSource("ids", uids), new UserMapper()); } @@ -273,7 +274,7 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { public com.juick.User getUserByHash(final String hash) { if (StringUtils.isNotBlank(hash)) { List list = getJdbcTemplate().query( - "SELECT logins.user_id, users.nick, users.banned FROM logins " + + "SELECT logins.user_id, users.nick, users.banned, users.lang FROM logins " + "INNER JOIN users ON logins.user_id = users.id WHERE logins.hash = ?", new UserMapper(), hash); @@ -651,4 +652,27 @@ public class UserServiceImpl extends BaseJdbcService implements UserService { user.getUid()); return list.isEmpty() ? "" : list.get(0) + "@mail.juick.com"; } + + @Transactional + @Override + public int deleteLoginForUser(final String name) { + if (StringUtils.isBlank(name)) + return 0; + + return getJdbcTemplate().update( + "delete from logins where user_id in (select id from users where nick = ?)", name); + } + + @Transactional + @Override + public int setLoginForUser(final int uid, final String loginHash) { + if (StringUtils.isEmpty(loginHash)) + return 0; + + return getNamedParameterJdbcTemplate().update( + "INSERT INTO logins (user_id, hash) VALUES(:uid, :hash) ON DUPLICATE KEY UPDATE hash = :hash", + new MapSqlParameterSource() + .addValue("hash", loginHash) + .addValue("uid", uid)); + } } diff --git a/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java b/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java new file mode 100644 index 00000000..d1fd9345 --- /dev/null +++ b/juick-server/src/main/java/com/juick/service/security/JuickUserDetailsService.java @@ -0,0 +1,34 @@ +package com.juick.service.security; + +import com.juick.server.security.entities.JuickUser; +import com.juick.service.UserService; +import org.apache.commons.lang3.StringUtils; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.util.Assert; + +/** + * Created by aalexeev on 11/28/16. + */ +public class JuickUserDetailsService implements UserDetailsService { + private final UserService userService; + + public JuickUserDetailsService(final UserService userService) { + Assert.notNull(userService); + this.userService = userService; + } + + @Override + public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException { + if (StringUtils.isBlank(username)) + throw new UsernameNotFoundException("Invalid user name " + username); + + com.juick.User user = userService.getFullyUserByName(username); + + if (user != null) + return new JuickUser(user); + + throw new UsernameNotFoundException("The username " + username + " is not found"); + } +} diff --git a/juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java b/juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java new file mode 100644 index 00000000..d5d54005 --- /dev/null +++ b/juick-server/src/main/java/com/juick/service/security/SimpleRememberMeServices.java @@ -0,0 +1,89 @@ +package com.juick.service.security; + +import com.juick.User; +import com.juick.server.security.entities.JuickUser; +import com.juick.service.UserService; +import com.juick.util.UserUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.core.env.Environment; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.web.authentication.RememberMeServices; +import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices; +import org.springframework.security.web.authentication.rememberme.InvalidCookieException; +import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationException; +import org.springframework.util.Assert; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Optional; + +/** + * Created by aalexeev on 11/28/16. + */ +public class SimpleRememberMeServices extends AbstractRememberMeServices implements RememberMeServices { + private final UserService userService; + + public SimpleRememberMeServices( + final String key, final UserDetailsService userDetailsService, final UserService userService, final Environment environment) { + super(key, userDetailsService); + + Assert.notNull(userService); + Assert.notNull(environment); + + this.userService = userService; + + setCookieName(environment.getProperty("auth_cookie_name", "hash")); + setCookieDomain(environment.getProperty("web_domain", "juick.com")); + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { + super.logout(request, response, authentication); + userService.deleteLoginForUser(authentication.getName()); + } + + @Override + protected void onLoginSuccess( + HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { + String username = successfulAuthentication.getName(); + + logger.debug("Creating new persistent login for user " + username); + + try { + int uid = userService.getUIDbyName(username); + + Assert.isTrue(uid > 0); + + String hash = UserUtils.generateHash(16); + + userService.setLoginForUser(uid, hash); + + setCookie(new String[]{hash}, getTokenValiditySeconds(), request, response); + } catch (Exception e) { + logger.error("Failed to save cookies ", e); + } + } + + @Override + protected UserDetails processAutoLoginCookie( + String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) + throws RememberMeAuthenticationException, UsernameNotFoundException { + String hash = cookieTokens[0]; + + if (StringUtils.isBlank(hash)) + throw new InvalidCookieException("Cookie is invalid, cookies " + cookieTokens); + + int uid = userService.getUIDbyHash(cookieTokens[0]); + if (uid <= 0) + throw new UsernameNotFoundException("User not found bash hash, cookies" + cookieTokens); + + Optional userOptional = userService.getUserByUID(uid); + + Assert.isTrue(userOptional.isPresent()); + + return new JuickUser(userOptional.get()); + } +} diff --git a/juick-server/src/main/resources/juick.conf.example b/juick-server/src/main/resources/juick.conf.example index c91a42d2..e8ebf5d3 100644 --- a/juick-server/src/main/resources/juick.conf.example +++ b/juick-server/src/main/resources/juick.conf.example @@ -32,6 +32,9 @@ web_domain=juick.com # Authority cookie name (default value - "hash") auth_cookie_name=hash +# Authority remember-me key +auth_remember_me_key=3vHcy3OUDQlkpRDm + ### Template Settings (web page templates) # Show sponsors block -- cgit v1.2.3