package com.rongyichuang.user.service;
|
|
import com.rongyichuang.user.entity.User;
|
import com.rongyichuang.user.repository.UserRepository;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.stereotype.Service;
|
import org.springframework.transaction.annotation.Transactional;
|
|
import java.util.Optional;
|
|
/**
|
* 用户服务类
|
*/
|
@Service
|
@Transactional
|
public class UserService {
|
|
@Autowired
|
private UserRepository userRepository;
|
|
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
|
|
/**
|
* 根据手机号查找或创建用户
|
* 如果用户存在,更新姓名和密码(如果提供了密码)
|
* 如果用户不存在,创建新用户
|
*
|
* @param phone 手机号
|
* @param name 姓名
|
* @param password 密码(可以为null,表示不更新密码)
|
* @return 用户实体
|
*/
|
public User findOrCreateUserByPhone(String phone, String name, String password) {
|
Optional<User> existingUser = userRepository.findByPhone(phone);
|
|
if (existingUser.isPresent()) {
|
// 用户存在,更新姓名和密码(如果提供了密码)
|
User user = existingUser.get();
|
user.setName(name);
|
if (password != null && !password.trim().isEmpty()) {
|
user.setPassword(passwordEncoder.encode(password));
|
}
|
return userRepository.save(user);
|
} else {
|
// 用户不存在,创建新用户
|
User newUser = new User();
|
newUser.setName(name);
|
newUser.setPhone(phone);
|
if (password != null && !password.trim().isEmpty()) {
|
newUser.setPassword(passwordEncoder.encode(password));
|
} else {
|
// 如果没有提供密码,设置一个默认密码
|
newUser.setPassword(passwordEncoder.encode("123456"));
|
}
|
return userRepository.save(newUser);
|
}
|
}
|
|
/**
|
* 根据手机号查找用户
|
*/
|
public Optional<User> findByPhone(String phone) {
|
return userRepository.findByPhone(phone);
|
}
|
|
/**
|
* 保存用户
|
*/
|
public User save(User user) {
|
return userRepository.save(user);
|
}
|
|
/**
|
* 根据ID查找用户
|
*/
|
public Optional<User> findById(Long id) {
|
return userRepository.findById(id);
|
}
|
}
|