Skip to content

Commit

Permalink
optimize config-web
Browse files Browse the repository at this point in the history
  • Loading branch information
colin-lee committed Oct 7, 2015
1 parent 66ac3ed commit 2ded841
Show file tree
Hide file tree
Showing 15 changed files with 998 additions and 20 deletions.
5 changes: 5 additions & 0 deletions config-web/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@
<artifactId>shiro-quartz</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
Expand Down
5 changes: 5 additions & 0 deletions config-web/src/main/java/com/github/autoconf/entity/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Date;
import java.util.Set;

Expand All @@ -13,7 +15,10 @@
public class User {
private static final Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
private Long id;
@NotNull
@Pattern(regexp = "[0-9a-zA-Z_-]+")
private String username;
@NotNull
private String password;
private String salt;
private String roles;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.autoconf.mapper;

import com.github.autoconf.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
Expand All @@ -13,4 +14,7 @@
public interface UserMapper {
@Select("SELECT * FROM user WHERE username=#{username}")
User findByUserName(@Param("username") String username);

@Insert("INSERT user SET username=#{username}, password=#{password}, salt=#{salt}, create_time=NOW()")
void create(User user);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,8 @@ public class UserService {
public User findByUsername(String username) {
return mapper.findByUserName(username);
}

public void create(User user) {
mapper.create(user);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.github.autoconf.shiro;

import com.github.autoconf.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Value;

public class PasswordHelper {
private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

@Value("${shiro.password.algorithmName}")
private String algorithmName = "md5";
@Value("${shiro.password.hashIterations}")
private int hashIterations = 2;

public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
this.randomNumberGenerator = randomNumberGenerator;
}

public void setAlgorithmName(String algorithmName) {
this.algorithmName = algorithmName;
}

public void setHashIterations(int hashIterations) {
this.hashIterations = hashIterations;
}

public void encryptPassword(User user) {

user.setSalt(randomNumberGenerator.nextBytes().toHex());

String newPassword =
new SimpleHash(algorithmName, user.getPassword(), ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();

user.setPassword(newPassword);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
package com.github.autoconf.web;

import com.github.autoconf.entity.User;
import com.github.autoconf.service.UserService;
import com.github.autoconf.shiro.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
Expand All @@ -19,6 +24,11 @@
*/
@Controller
public class UserController {
@Autowired
private PasswordHelper passwordHelper;
@Autowired
private UserService userService;

@RequestMapping("/login")
public String login(Model model) {
if (!model.containsAttribute("user")) {
Expand All @@ -30,6 +40,7 @@ public String login(Model model) {
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginAction(@Valid User user, BindingResult result, RedirectAttributes r) {
if (result.hasErrors()) {
r.addFlashAttribute("message", "用户名或者密码不符合规则");
r.addFlashAttribute("user", user);
return "redirect:/login";
}
Expand All @@ -54,4 +65,33 @@ public String logout(RedirectAttributes r) {
public String unauthorized() {
return "unauthorized";
}

@RequestMapping("/ajax/checkLoginName")
@ResponseBody
public String checkLoginName(@RequestParam String username) {
User u = userService.findByUsername(username);
return u == null ? "true" : "false";
}

//@RequiresRoles("admin")
@RequestMapping("/register")
public String register(Model model) {
if (!model.containsAttribute("user")) {
model.addAttribute("user", new User());
}
return "register";
}

//@RequiresRoles("admin")
@RequestMapping(value = "register", method = RequestMethod.POST)
public String registerAction(@Valid User user, BindingResult result, RedirectAttributes r) {
if (result.hasErrors()) {
r.addFlashAttribute("message", "用户名或者密码不符合规则");
r.addFlashAttribute("user", user);
return "redirect:/register";
}
passwordHelper.encryptPassword(user);
userService.create(user);
return "redirect:/profile/?username=" + user.getUsername();
}
}
2 changes: 2 additions & 0 deletions config-web/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ mysql.url=jdbc:mysql://127.0.0.1:3306/autoconf?useUnicode=true&characterEncoding
mysql.username=root
mysql.password=
guava.cacheSpec=maximumSize=5000,expireAfterAccess=5m,expireAfterWrite=1h,weakValues
shiro.password.algorithmName = md5
shiro.password.hashIterations = 2
1 change: 0 additions & 1 deletion config-web/src/main/resources/logback.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
<logger name="com.opensymphony" level="WARN"/>
<logger name="org.apache" level="WARN"/>

<!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
<logger name="org.hibernate.type.descriptor.sql.BasicBinder" level="TRACE"/>
<logger name="org.hibernate.type.descriptor.sql.BasicExtractor" level="DEBUG"/>
<logger name="org.hibernate.SQL" level="DEBUG"/>
Expand Down
20 changes: 16 additions & 4 deletions config-web/src/main/resources/spring/spring-shiro.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,32 @@
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:util="http://www.springframework.org/schema/util"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"
p:loginUrl="/login"
p:successUrl="/home"
p:unauthorizedUrl="/unauthorized"
p:securityManager-ref="securityManager">
<property name="filters">
<util:map>
<entry key="authc" value-ref="formAuthenticationFilter"/>
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/static/** = anon
/unauthorized = anon
/register = anon
/login = authc
/logout = logout
/admin/** = authc, roles[admin]
/docs/** = authc, perms[document:read]
/** = authc,user
/** = anon
</value>
</property>
</bean>
Expand All @@ -31,7 +39,11 @@
<bean id="lifecycleBeanPostProcessor"
class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<bean id="credentialsMatcher" class="com.github.autoconf.shiro.RetryLimitCredentialsMatcher"/>
<bean class="com.github.autoconf.shiro.PasswordHelper"/>
<bean id="credentialsMatcher" class="com.github.autoconf.shiro.RetryLimitCredentialsMatcher"
p:hashAlgorithmName="${shiro.password.algorithmName}"
p:hashIterations="${shiro.password.hashIterations}"
p:storedCredentialsHexEncoded="true"/>

<bean id="myRealm" class="com.github.autoconf.shiro.UserRealm"
p:credentialsMatcher-ref="credentialsMatcher"
Expand Down
Loading

0 comments on commit 2ded841

Please sign in to comment.