| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346 |
- package com.izouma.nineth.service;
- import cn.binarywang.wx.miniapp.api.WxMaService;
- import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
- import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
- import com.izouma.nineth.config.Constants;
- import com.izouma.nineth.domain.Follow;
- import com.izouma.nineth.domain.User;
- import com.izouma.nineth.dto.PageQuery;
- import com.izouma.nineth.dto.UserDTO;
- import com.izouma.nineth.dto.UserRegister;
- import com.izouma.nineth.enums.AuthStatus;
- import com.izouma.nineth.enums.AuthorityName;
- import com.izouma.nineth.exception.BusinessException;
- import com.izouma.nineth.repo.FollowRepo;
- import com.izouma.nineth.repo.UserRepo;
- import com.izouma.nineth.security.Authority;
- import com.izouma.nineth.security.JwtTokenUtil;
- import com.izouma.nineth.security.JwtUserFactory;
- import com.izouma.nineth.service.sms.SmsService;
- import com.izouma.nineth.service.storage.StorageService;
- import com.izouma.nineth.utils.JpaUtils;
- import com.izouma.nineth.utils.ObjUtils;
- import com.izouma.nineth.utils.SecurityUtils;
- import lombok.AllArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import me.chanjar.weixin.common.error.WxErrorException;
- import me.chanjar.weixin.mp.api.WxMpService;
- import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
- import me.chanjar.weixin.mp.bean.result.WxMpUser;
- import org.apache.commons.lang3.RandomStringUtils;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.beans.BeanUtils;
- import org.springframework.cache.annotation.CacheEvict;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.PageImpl;
- import org.springframework.data.jpa.domain.Specification;
- import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
- import org.springframework.stereotype.Service;
- import javax.persistence.criteria.CriteriaBuilder;
- import javax.persistence.criteria.CriteriaQuery;
- import javax.persistence.criteria.Predicate;
- import javax.persistence.criteria.Root;
- import java.text.SimpleDateFormat;
- import java.util.*;
- import java.util.stream.Collectors;
- @Service
- @Slf4j
- @AllArgsConstructor
- public class UserService {
- private UserRepo userRepo;
- private WxMaService wxMaService;
- private WxMpService wxMpService;
- private SmsService smsService;
- private StorageService storageService;
- private JwtTokenUtil jwtTokenUtil;
- private CaptchaService captchaService;
- private FollowService followService;
- private FollowRepo followRepo;
- // @CacheEvict(value = "user", key = "#user.username")
- public User update(User user) {
- User orig = userRepo.findById(user.getId()).orElseThrow(new BusinessException("无记录"));
- ObjUtils.merge(orig, user);
- orig = userRepo.save(orig);
- userRepo.updateMinterForCollection(orig.getId());
- userRepo.updateOwnerForCollection(orig.getId());
- userRepo.updateMinterForOrder(orig.getId());
- userRepo.updateMinterForAsset(orig.getId());
- return orig;
- }
- // @Cacheable("user")
- public Optional<User> findByUsernameAndDelFalse(String username) {
- return userRepo.findByUsernameAndDelFalse(username);
- }
- public Page<User> all(PageQuery pageQuery) {
- Specification<User> specification = JpaUtils.toSpecification(pageQuery, User.class);
- specification = specification.and((Specification<User>) (root, criteriaQuery, criteriaBuilder) -> {
- List<Predicate> and = new ArrayList<>();
- and.add(criteriaBuilder.notEqual(root.get("id"), 1L));
- if (pageQuery.getQuery().containsKey("hasRole")) {
- String roleName = (String) pageQuery.getQuery().get("hasRole");
- and.add(criteriaBuilder.isMember(Authority.get(AuthorityName.valueOf(roleName)), root.get("authorities")));
- }
- return criteriaBuilder.and(and.toArray(new Predicate[0]));
- });
- return userRepo.findAll(specification, JpaUtils.toPageRequest(pageQuery));
- }
- public User create(UserRegister userRegister) {
- if (StringUtils.isNoneEmpty(userRegister.getPhone()) && userRepo.findByPhoneAndDelFalse(userRegister.getPhone())
- .orElse(null) != null) {
- throw new BusinessException("该手机号已注册");
- }
- User user = new User();
- BeanUtils.copyProperties(userRegister, user);
- user.setAuthStatus(AuthStatus.NOT_AUTH);
- if (StringUtils.isNotBlank(userRegister.getPassword())) {
- user.setPassword(new BCryptPasswordEncoder().encode(userRegister.getPassword()));
- }
- return userRepo.save(user);
- }
- public User phoneRegister(String phone, String code, String password) {
- String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
- User user = create(UserRegister.builder()
- .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
- .username(name)
- .nickname(name)
- .avatar(Constants.DEFAULT_AVATAR)
- .phone(phone)
- .build());
- return user;
- }
- public void del(Long id) {
- User user = userRepo.findById(id).orElseThrow(new BusinessException("用户不存在"));
- user.setDel(true);
- if (StringUtils.isNoneEmpty(user.getOpenId())) {
- user.setOpenId(user.getOpenId() + "###" + RandomStringUtils.randomAlphabetic(8));
- }
- if (StringUtils.isNoneEmpty(user.getPhone())) {
- user.setPhone(user.getPhone() + "###" + RandomStringUtils.randomAlphabetic(8));
- }
- userRepo.save(user);
- }
- public User loginByPhone(String phone, String code) {
- User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("该手机未注册"));
- smsService.verify(phone, code);
- if (user == null) {
- String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
- user = create(UserRegister.builder()
- .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
- .username(name)
- .nickname(name)
- .avatar(Constants.DEFAULT_AVATAR)
- .phone(phone)
- .build());
- }
- return user;
- }
- public User loginByPhonePwd(String phone, String password) {
- User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("账号或密码错误"));
- if (StringUtils.isEmpty(user.getPassword())) {
- throw new BusinessException("账号或密码错误");
- }
- if (StringUtils.isNoneEmpty(user.getPassword()) &&
- new BCryptPasswordEncoder().matches(password, user.getPassword())) {
- throw new BusinessException("账号或密码错误");
- }
- return user;
- }
- public User loginMp(String code) throws WxErrorException {
- WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
- WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(accessToken, null);
- User user = userRepo.findByOpenIdAndDelFalse(wxMpUser.getOpenId()).orElse(null);
- if (user == null) {
- String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
- user = User.builder()
- .username(name)
- .nickname(name)
- .avatar(wxMpUser.getHeadImgUrl())
- .sex(wxMpUser.getSexDesc())
- .country(wxMpUser.getCountry())
- .province(wxMpUser.getProvince())
- .city(wxMpUser.getCity())
- .openId(wxMpUser.getOpenId())
- .language(wxMpUser.getLanguage())
- .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
- .authStatus(AuthStatus.NOT_AUTH)
- .build();
- userRepo.save(user);
- }
- return user;
- }
- public User loginMa(String code) {
- try {
- WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
- String openId = result.getOpenid();
- String sessionKey = result.getSessionKey();
- User userInfo = userRepo.findByOpenIdAndDelFalse(openId).orElse(null);
- ;
- if (userInfo != null) {
- return userInfo;
- }
- String name = "9th_" + RandomStringUtils.randomAlphabetic(8);
- userInfo = User.builder()
- .username(name)
- .nickname(name)
- .openId(openId)
- .avatar(Constants.DEFAULT_AVATAR)
- .authorities(Collections.singleton(Authority.get(AuthorityName.ROLE_USER)))
- .authStatus(AuthStatus.NOT_AUTH)
- .build();
- userInfo = userRepo.save(userInfo);
- return userInfo;
- } catch (WxErrorException e) {
- e.printStackTrace();
- }
- throw new BusinessException("登录失败");
- }
- public User getMaUserInfo(String sessionKey, String rawData, String signature,
- String encryptedData, String iv) {
- // 用户信息校验
- if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
- throw new BusinessException("获取用户信息失败");
- }
- // 解密用户信息
- WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
- User user = userRepo.findByOpenIdAndDelFalse(wxUserInfo.getOpenId()).orElse(null);
- String avatarUrl = Constants.DEFAULT_AVATAR;
- try {
- String path = "image/avatar/" +
- new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) +
- RandomStringUtils.randomAlphabetic(8) +
- ".jpg";
- avatarUrl = storageService.uploadFromUrl(wxUserInfo.getAvatarUrl(), path);
- } catch (Exception e) {
- log.error("获取头像失败", e);
- }
- if (user == null) {
- user = User.builder()
- .username(UUID.randomUUID().toString())
- .nickname(wxUserInfo.getNickName())
- .openId(wxUserInfo.getOpenId())
- .avatar(avatarUrl)
- .sex(wxUserInfo.getGender())
- .country(wxUserInfo.getCountry())
- .province(wxUserInfo.getProvince())
- .city(wxUserInfo.getCity())
- .authorities(Collections.singleton(Authority.builder().name("ROLE_USER").build()))
- .build();
- user = userRepo.save(user);
- } else {
- user.setAvatar(avatarUrl);
- user.setNickname(wxUserInfo.getNickName());
- user.setSex(wxUserInfo.getGender());
- user.setCountry(wxUserInfo.getCountry());
- user.setProvince(wxUserInfo.getProvince());
- user.setCity(wxUserInfo.getCity());
- user = userRepo.save(user);
- }
- return user;
- }
- public String setPassword(Long userId, String password) {
- User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
- user.setPassword(new BCryptPasswordEncoder().encode(password));
- user = userRepo.save(user);
- return jwtTokenUtil.generateToken(JwtUserFactory.create(user));
- }
- public String setPassword(Long userId, String code, String password) {
- User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
- smsService.verify(user.getPhone(), code);
- return setPassword(userId, password);
- }
- public String forgotPassword(String phone, String password, String code) {
- User user = userRepo.findByPhoneAndDelFalse(phone).orElseThrow(new BusinessException("手机号未注册"));
- smsService.verify(user.getPhone(), code);
- return setPassword(user.getId(), password);
- }
- public void bindPhone(Long userId, String phone) {
- User user = userRepo.findByIdAndDelFalse(userId).orElseThrow(new BusinessException("用户不存在"));
- if (StringUtils.isNoneEmpty(user.getPhone())) {
- throw new BusinessException("该账号已绑定手机");
- }
- userRepo.findByPhoneAndDelFalse(phone).ifPresent(user1 -> {
- if (!user1.getId().equals(userId)) {
- throw new BusinessException("该手机号已绑定其他账号");
- }
- });
- user.setPhone(phone);
- userRepo.save(user);
- }
- public UserDTO toDTO(User user) {
- return toDTO(user, true);
- }
- public UserDTO toDTO(User user, boolean join) {
- UserDTO userDTO = new UserDTO();
- BeanUtils.copyProperties(user, userDTO);
- if (join) {
- if (SecurityUtils.getAuthenticatedUser() != null) {
- userDTO.setFollow(followService.isFollow(SecurityUtils.getAuthenticatedUser().getId(), user.getId()));
- }
- }
- return userDTO;
- }
- public List<UserDTO> toDTO(List<User> users) {
- List<Follow> follows = new ArrayList<>();
- if (SecurityUtils.getAuthenticatedUser() != null) {
- follows.addAll(followRepo.findByUserId(SecurityUtils.getAuthenticatedUser().getId()));
- }
- return users.stream().parallel().map(user -> {
- UserDTO dto = toDTO(user, false);
- if (!follows.isEmpty()) {
- dto.setFollow(follows.stream().anyMatch(f -> f.getFollowUserId().equals(user.getId())));
- }
- return dto;
- }).collect(Collectors.toList());
- }
- public Page<UserDTO> toDTO(Page<User> users) {
- List<UserDTO> userDTOS = toDTO(users.getContent());
- return new PageImpl<>(userDTOS, users.getPageable(), users.getTotalElements());
- }
- public void setTradeCode(Long userId, String code, String tradeCode) {
- User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
- smsService.verify(user.getPhone(), code);
- user.setTradeCode(new BCryptPasswordEncoder().encode(tradeCode));
- userRepo.save(user);
- }
- public void verifyTradeCode(Long userId, String tradeCode) {
- User user = userRepo.findById(userId).orElseThrow(new BusinessException("用户不存在"));
- if (!new BCryptPasswordEncoder().matches(tradeCode, user.getTradeCode())) {
- throw new BusinessException("校验失败");
- }
- }
- }
|