验证中...
Languages: Java
Categories: Web开发技术
Latest update 2019-07-10 23:31
UserService.java
Raw Copy
package dgut.sai.yxgame.account.service;
import dgut.sai.yxgame.account.dao.PasswordResetTokenRepository;
import dgut.sai.yxgame.account.dao.RoleRepository;
import dgut.sai.yxgame.account.dao.UserRepository;
import dgut.sai.yxgame.account.dao.VerificationTokenRepository;
import dgut.sai.yxgame.account.dto.UserDto;
import dgut.sai.yxgame.account.error.UserAlreadyExistException;
import dgut.sai.yxgame.account.model.PasswordResetToken;
import dgut.sai.yxgame.account.model.User;
import dgut.sai.yxgame.account.model.VerificationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
@Service("userService")
@Transactional
public class UserService implements IUserService {
private final UserRepository repository;
private final VerificationTokenRepository tokenRepository;
private final PasswordResetTokenRepository passwordTokenRepository;
private final PasswordEncoder passwordEncoder;
private final RoleRepository roleRepository;
// @Autowired
// private SessionRegistry sessionRegistry;
private static final String TOKEN_INVALID = "invalidToken";
private static final String TOKEN_EXPIRED = "expired";
private static final String TOKEN_VALID = "valid";
private static final String QR_PREFIX = "https://chart.googleapis.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=";
private static final String APP_NAME = "SpringRegistration";
@Autowired
public UserService(UserRepository repository, VerificationTokenRepository tokenRepository, PasswordResetTokenRepository passwordTokenRepository, PasswordEncoder passwordEncoder, RoleRepository roleRepository) {
this.repository = repository;
this.tokenRepository = tokenRepository;
this.passwordTokenRepository = passwordTokenRepository;
this.passwordEncoder = passwordEncoder;
this.roleRepository = roleRepository;
}
// 用户邮箱注册账号
@Override
public User registerNewUserAccount(final UserDto accountDto) {
if (emailExist(accountDto.getEmail())) {
throw new UserAlreadyExistException("邮箱已存在: " + accountDto.getEmail());
}
final User user = new User();
if (!StringUtils.isEmpty(accountDto.getInviteCode())) {
if (!inviteCodeExist(accountDto.getInviteCode())) {
throw new UserAlreadyExistException("邀请码不存在: " + accountDto.getInviteCode());
} else {
user.setReferee(repository.findByInviteCode(accountDto.getInviteCode()));
user.getReferee().getChildren().add(user);
}
}
user.setRegTime(new Date());// 注册时间
user.setFirstName(accountDto.getFirstName());
user.setLastName(accountDto.getLastName());
user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
user.setEmail(accountDto.getEmail());
// user.setUsing2FA(accountDto.isUsing2FA());
user.setRoles(Collections.singletonList(roleRepository.findByName("ROLE_USER")));
return repository.save(user);
}
// 社区账号登录时,更新或增加用户信息
@Override
public void updateSocialLoginUser(String openid, String socialType, LinkedHashMap<String, Object> details) {
// 判断是否已存在社区账号
List<User> socialuser = repository.findByWeixinOrSteamOrQq(openid, openid, openid);
if (socialuser.size() == 0) {
// 首次登录,创建本地账号
User newuser = new User();
// 第三方登录的新用户的注册时间与激活时间
newuser.setRegTime(new Date());
newuser.setActiveTime(new Date());
switch (socialType) {
case "weixin":
newuser.setWeixin(openid);
newuser.setRoles(Arrays.asList(roleRepository.findByName("ROLE_USER"),
roleRepository.findByName("ROLE_WEIXIN")));
// newuser.setHeadimg(details.get("headimgurl").toString());
// newuser.setNickname(details.get("nickname").toString());
break;
case "qq":
newuser.setQq(openid);
newuser.setRoles(
Arrays.asList(roleRepository.findByName("ROLE_USER"), roleRepository.findByName("ROLE_QQ")));
// figureurl_qq_1 大小为40×40像素的QQ头像URL。
newuser.setHeadimg(details.get("figureurl_qq_1")==null?null:details.get("figureurl_qq_1").toString().replace("http:",""));
newuser.setNickname(details.get("nickname").toString());
break;
case "steam":
newuser.setSteam(openid);
newuser.setRoles(
Arrays.asList(roleRepository.findByName("ROLE_USER"), roleRepository.findByName("ROLE_STEAM")));
newuser.setHeadimg(details.get("avatarfull")==null?null:details.get("avatarfull").toString().replace("http:",""));
newuser.setNickname(details.get("personaname").toString());
break;
case "weibo":
break;
}
newuser.setSecret("dgut.sai");
newuser.setPassword(passwordEncoder.encode("dgut.sai"));
// user.setPassword(passwordEncoder.encode(accountDto.getPassword()));
newuser.setEnabled(true);
repository.save(newuser);
} else if (socialuser.size() == 1) {
// 已经登录过的社区账号,以后每次登录就在本地数据中更新他们的呢称和头像(URL,可直接请求)
switch (socialType) {
case "weixin":
// socialuser.get(0).setHeadimg(details.get("headimgurl").toString());
// socialuser.get(0).setNickname(details.get("nickname").toString());
break;
case "steam":
socialuser.get(0).setHeadimg(details.get("avatar")==null?null:details.get("avatar").toString().replace("http:",""));
socialuser.get(0).setNickname(details.get("personaname").toString());
break;
case "qq":
socialuser.get(0).setHeadimg(details.get("figureurl_qq_1")==null?null:details.get("figureurl_qq_1").toString().replace("http:",""));
socialuser.get(0).setNickname(details.get("nickname").toString());
break;
}
repository.save(socialuser.get(0));
}
}
@Override
public User getUser(final String verificationToken) {
final VerificationToken token = tokenRepository.findByToken(verificationToken);
if (token != null) {
return token.getUser();
}
return null;
}
@Override
public VerificationToken getVerificationTokenByEmail(final String email){
User user = findUserByEmail(email);
if(user == null || user.isEnabled())
return null;
return tokenRepository.findByUser(user);
}
@Override
public VerificationToken getVerificationToken(final String VerificationToken) {
return tokenRepository.findByToken(VerificationToken);
}
@Override
public void saveRegisteredUser(final User user) {
repository.save(user);
}
@Override
public void deleteUser(final User user) {
final VerificationToken verificationToken = tokenRepository.findByUser(user);
if (verificationToken != null) {
tokenRepository.delete(verificationToken);
}
final PasswordResetToken passwordToken = passwordTokenRepository.findByUser(user);
if (passwordToken != null) {
passwordTokenRepository.delete(passwordToken);
}
repository.delete(user);
}
@Override
public void createVerificationTokenForUser(final User user, final String token) {
final VerificationToken myToken = new VerificationToken(token, user);
tokenRepository.save(myToken);
}
@Override
public VerificationToken generateNewVerificationToken(final String existingVerificationToken) {
VerificationToken vToken = tokenRepository.findByToken(existingVerificationToken);
vToken.updateToken(UUID.randomUUID().toString());
vToken = tokenRepository.save(vToken);
return vToken;
}
@Override
public void createPasswordResetTokenForUser(final User user, final String token) {
final PasswordResetToken myToken = new PasswordResetToken(token, user);
passwordTokenRepository.save(myToken);
}
@Override
public User findUserByEmail(final String email) {
return repository.findByEmail(email);
}
@Override
public PasswordResetToken getPasswordResetToken(final String token) {
return passwordTokenRepository.findByToken(token);
}
@Override
public User getUserByPasswordResetToken(final String token) {
return passwordTokenRepository.findByToken(token).getUser();
}
@Override
public User getUserByID(final long id) {
return repository.findOne(id);
}
@Override
public void changeUserPassword(final User user, final String password) {
user.setPassword(passwordEncoder.encode(password));
repository.save(user);
}
@Override
public boolean checkIfValidOldPassword(final User user, final String oldPassword) {
return passwordEncoder.matches(oldPassword, user.getPassword());
}
@Override
public String validateVerificationToken(String token) {
final VerificationToken verificationToken = tokenRepository.findByToken(token);
if (verificationToken == null) {
return TOKEN_INVALID;
}
final User user = verificationToken.getUser();
final Calendar cal = Calendar.getInstance();
if ((verificationToken.getExpiryDate().getTime() - cal.getTime().getTime()) <= 0) {
tokenRepository.delete(verificationToken);
return TOKEN_EXPIRED;
}
user.setEnabled(true);
tokenRepository.delete(verificationToken); // 新用户激活token校验一次后删除。 modify by sai on 2018-6-24
repository.save(user);
return TOKEN_VALID;
}
@Override
public String generateQRUrl(User user) throws UnsupportedEncodingException {
return QR_PREFIX + URLEncoder.encode(String.format("otpauth://totp/%s:%s?secret=%s&issuer=%s", APP_NAME, user.getEmail(), user.getSecret(), APP_NAME), "UTF-8");
}
@Override
public User updateUser2FA(boolean use2FA) {
final Authentication curAuth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = (User) curAuth.getPrincipal();
currentUser.setUsing2FA(use2FA);
currentUser = repository.save(currentUser);
final Authentication auth = new UsernamePasswordAuthenticationToken(currentUser, currentUser.getPassword(), curAuth.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
return currentUser;
}
private boolean emailExist(final String email) {
return repository.findByEmail(email) != null;
}
private boolean inviteCodeExist(final String code) {
return repository.findByInviteCode(code) != null;
}
// 新用户激活成功后,推荐人增加的游善点数
@Value("${yxCoinBonus.referee}")
private Integer refereeBonus = 5;
/**
* 推荐人增加游善点数
*
* @param user 用户
*/
@Override
public void refereeManager(User user) {
Optional.ofNullable(user.getReferee())
.ifPresent(referee -> {
referee.setYxCoin(referee.getYxCoin() + refereeBonus);
repository.save(referee);
});
}
@Override
public Optional<List<User>> findUser(String allKey) {
return Optional.ofNullable(repository.findByEmailOrWeixinOrSteamOrQq(allKey, allKey, allKey, allKey));
}
/**
* 记录用户登录时间
*
* @param user 用户
*/
@Override
public void setLastLoginTime(User user) {
user.setLastLoginTime(new Date());
repository.save(user);
}
// 刷新用户的签到标记
@Override
public void refreshAttendance() {
System.err.println(new Date() + "刷新签到表");
repository.refreshAttendance();
}
// 统计在线人线
// @Override
// public List<String> getUsersFromSessionRegistry() {
// return sessionRegistry.getAllPrincipals().stream().filter((u) -> !sessionRegistry.getAllSessions(u, false).isEmpty()).map(Object::toString).collect(Collectors.toList());
// }
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search

183227_9af5e6a8_1826025 111910_4d91f001_1826025