新增UserService

新增服务类UserService,这次暂时不建接口了

  1. package net.wendal.nutzbook.service;
  2. import java.util.Date;
  3. import net.wendal.nutzbook.bean.User;
  4. import org.apache.shiro.crypto.hash.Sha256Hash;
  5. import org.nutz.ioc.loader.annotation.IocBean;
  6. import org.nutz.lang.random.R;
  7. import org.nutz.service.IdNameEntityService;
  8. @IocBean(fields="dao")
  9. public class UserService extends IdNameEntityService<User> {
  10. public User add(String name, String password) {
  11. User user = new User();
  12. user.setName(name.trim());
  13. user.setSalt(R.UU16());
  14. user.setPassword(new Sha256Hash(password, user.getSalt()).toHex());
  15. user.setCreateTime(new Date());
  16. user.setUpdateTime(new Date());
  17. return dao().insert(user);
  18. }
  19. public int fetch(String username, String password) {
  20. User user = fetch(username);
  21. if (user == null) {
  22. return -1;
  23. }
  24. String _pass = new Sha256Hash(password, user.getSalt()).toHex();
  25. if(_pass.equalsIgnoreCase(user.getPassword())) {
  26. return user.getId();
  27. }
  28. return -1;
  29. }
  30. public void updatePassword(int userId, String password) {
  31. User user = fetch(userId);
  32. if (user == null) {
  33. return;
  34. }
  35. user.setSalt(R.UU16());
  36. user.setPassword(new Sha256Hash(password, user.getSalt()).toHex());
  37. user.setUpdateTime(new Date());
  38. dao().update(user, "^(password|salt|updateTime)$");
  39. }
  40. }

留意一下IocBean中的fields配置

含义是需要注入父类的dao属性

这里用到了sha256加盐算法,将对应shiro.ini中配置

请不要使用明文存储密码.