提交 6eb13e72 authored 作者: Whispa's avatar Whispa

commit commit

上级 4f5450b7
......@@ -11,7 +11,6 @@ import com.example.afrishop_v3.models.TbCfCoupon;
import com.example.afrishop_v3.models.TbCfToicoupon;
import com.example.afrishop_v3.models.TbCfUserInfo;
import com.example.afrishop_v3.payload.request.LoginRequest;
import com.example.afrishop_v3.payload.response.MessageResponse;
import com.example.afrishop_v3.repository.NetworkRepository;
import com.example.afrishop_v3.repository.TbCfCouponRepository;
import com.example.afrishop_v3.repository.TbCfToicouponRepository;
......@@ -20,7 +19,6 @@ import com.example.afrishop_v3.security.jwt.JwtUtils;
import com.example.afrishop_v3.security.services.UserDetailsImpl;
import com.example.afrishop_v3.util.IdUtil;
import org.hashids.Hashids;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
......@@ -30,6 +28,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
......@@ -48,6 +48,7 @@ public class AuthController extends Controller {
private final TbCfCouponRepository couponRepository;
private final TbCfToicouponRepository toicouponRepository;
private final NetworkRepository networkRepository;
private final EntityManager entityManager;
private final PasswordEncoder encoder;
......@@ -55,12 +56,13 @@ public class AuthController extends Controller {
private final JwtUtils jwtUtils;
public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TbCfCouponRepository couponRepository, TbCfToicouponRepository toicouponRepository, NetworkRepository networkRepository, PasswordEncoder encoder, DomainProperties domainProperties, JwtUtils jwtUtils) {
public AuthController(AuthenticationManager authenticationManager, UserRepository userRepository, TbCfCouponRepository couponRepository, TbCfToicouponRepository toicouponRepository, NetworkRepository networkRepository, EntityManager entityManager, PasswordEncoder encoder, DomainProperties domainProperties, JwtUtils jwtUtils) {
this.authenticationManager = authenticationManager;
this.userRepository = userRepository;
this.couponRepository = couponRepository;
this.toicouponRepository = toicouponRepository;
this.networkRepository = networkRepository;
this.entityManager = entityManager;
this.encoder = encoder;
this.domainProperties = domainProperties;
this.jwtUtils = jwtUtils;
......@@ -69,16 +71,33 @@ public class AuthController extends Controller {
@PostMapping("/signin")
public Result authenticateUser(@RequestBody LoginRequest loginRequest) {
Optional<TbCfUserInfo> byAccount = userRepository.findByFirebaseUid(loginRequest.getAccount());
if( !byAccount.isPresent() ){
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(),"User not found");
Result<Object> notFound = new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(), "User not found");
if (!byAccount.isPresent()) {
boolean b = userRepository.existsByAccount(loginRequest.getAccount());
if (b) {
Optional<TbCfUserInfo> firstByAccount = userRepository.findFirstByAccount(loginRequest.getAccount());
if (firstByAccount.isPresent()) {
TbCfUserInfo userInfo = firstByAccount.get();
userInfo.setFirebaseUid(loginRequest.getAccount());
try {
userRepository.save(userInfo);
} catch (Exception e) {
return notFound;
}
byAccount = Optional.of(userInfo);
} else return notFound;
} else
return notFound;
}
Authentication authentication;
try {
authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getAccount(), loginRequest.getPassword()));
}catch (BadCredentialsException e){
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Invalid username or password");
} catch (BadCredentialsException e) {
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Invalid username or password");
}
SecurityContextHolder.getContext().setAuthentication(authentication);
......@@ -93,22 +112,23 @@ public class AuthController extends Controller {
userInfo.setToken(jwt);
if( loginRequest.getFcm() != null ){
if (loginRequest.getFcm() != null) {
userInfo.setFcm(loginRequest.getFcm());
}
userInfo.setLastLoginTime(new Date());
userRepository.save(userInfo);
if( userInfo.hasFcm() ){
sendNotification(userInfo.getFcm(),"Welcome ",userInfo.display() + ", Welcome and start shopping !!!");
if (userInfo.hasFcm()) {
sendNotification(userInfo.getFcm(), "Welcome ", userInfo.display() + ", Welcome and start shopping !!!");
}
return new Result<>(userInfo);
}
@PostMapping("/signup")
public Result<?> registerUser( @RequestBody TbCfUserInfo signUpRequest) {
public Result<?> registerUser(@RequestBody TbCfUserInfo signUpRequest) {
try {
// boolean byAccount = userRepository.existsByAccount(signUpRequest.getEmail());
// if ( byAccount ) {
......@@ -122,41 +142,42 @@ public class AuthController extends Controller {
email = email == null ? "" : email.trim();
if( email.isEmpty() ){
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Email is empty");
if (email.isEmpty()) {
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Email is empty");
}
if( !isEmailValid(email) ){
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Invalid email");
if (!isEmailValid(email)) {
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Invalid email");
}
if( password == null || password.isEmpty() ){
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Password is Empty");
if (password == null || password.isEmpty()) {
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Password is Empty");
}
if( !isPasswordValid(password) ){
if (!isPasswordValid(password)) {
String string = "Password is not strong";
if( !isPasswordValidDigit(password) ){
if (!isPasswordValidDigit(password)) {
string += ", a digit must occur at least once";
}
if( !isPasswordValidUpperCase(password) ){
if (!isPasswordValidUpperCase(password)) {
string += ", an upper case letter must occur at least once";
}
if( !isPasswordValidLength(password) ){
if (!isPasswordValidLength(password)) {
string += ", at least eight characters though";
}
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(),string);
return new Result<>(ResultCodeEnum.VALIDATE_ERROR.getCode(), string);
}
boolean byEmail = userRepository.existsByFirebaseUid(email);
boolean byEmail2 = userRepository.existsByAccount(email);
if ( byEmail ) {
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(),"Error: Email is already in use!");
if (byEmail || byEmail2) {
return new Result(ResultCodeEnum.VALIDATE_ERROR.getCode(), "Error: Email is already in use!");
}
......@@ -182,18 +203,14 @@ public class AuthController extends Controller {
fixCoupon(signUpRequest);
return authenticateUser(new LoginRequest(userInfo.getFirebaseUid(),password,userInfo.getFcm()));
}
catch (Exception e){
return authenticateUser(new LoginRequest(userInfo.getFirebaseUid(), password, userInfo.getFcm()));
} catch (Exception e) {
System.out.println(e.getMessage());
return new Result<>(ResultCodeEnum.SERVICE_ERROR.getCode(),e.getMessage());
return new Result<>(ResultCodeEnum.SERVICE_ERROR.getCode(), e.getMessage());
}
}
@PostMapping(value = "/register/user")
public Result checkFirebase(@RequestBody TbCfUserInfo user) throws ParseException {
//Data to be userInfoVo
......@@ -214,9 +231,12 @@ public class AuthController extends Controller {
if (isTokenValid) {
//Query to find user from database by firebase uid
Optional<TbCfUserInfo> optional = userRepository.findByFirebaseUid(user.getFirebaseUid());
if ( !optional.isPresent() ) {
if (user.getEmail() != null && !user.getEmail().isEmpty() && userRepository.existsByAccount(user.getEmail())) {
optional = userRepository.findFirstByAccount(user.getEmail());
}
if (!optional.isPresent()) {
String userid = IdUtil.createIdbyUUID();
......@@ -228,13 +248,12 @@ public class AuthController extends Controller {
user = userRepository.save(user);
//赠送用户优惠券
fixCoupon(user);
} else {
TbCfUserInfo userInfo = optional.get();
if( user.hasFcm() ){
if (user.hasFcm()) {
userInfo.setFcm(user.getFcm());
}
......@@ -245,20 +264,24 @@ public class AuthController extends Controller {
boolean b = property.equals(userInfo.getAvatar()) || userInfo.getAvatar() == null || userInfo.getAvatar().isEmpty();
if( user.getAvatar() != null && b){
if (user.getAvatar() != null && b) {
userInfo.setAvatar(user.getAvatar());
}
boolean b1 = userInfo.getNick() == null || userInfo.getNick().isEmpty();
if( user.getNick() != null && b1){
if (user.getNick() != null && b1) {
userInfo.setNick(user.getNick());
}
if( user.getEmail() != null ){
if (user.getEmail() != null) {
userInfo.setEmail(user.getEmail());
}
if( user.getPhone() != null ){
if (user.getUserType() != null) {
userInfo.setUserType(user.getUserType());
}
if (user.getPhone() != null) {
userInfo.setPhone(user.getPhone());
}
......@@ -267,13 +290,11 @@ public class AuthController extends Controller {
}
// generate token codes has been moved downwards from if condition of checking if user doesn't exist in database, because even if
// user exist we have to generate token also
if( user.getPassword() == null ){
if (user.getPassword() == null) {
user.setPassword(encoder.encode(user.getFirebaseUid()));// Assign user from database to the user we have to return back to request
}
fixCode(user);
//addToNetwork(user);
......@@ -282,18 +303,18 @@ public class AuthController extends Controller {
userRepository.save(user);
//注册成功 创建token
return authenticateUser(new LoginRequest(user.getFirebaseUid(),user.getFirebaseUid()));
return authenticateUser(new LoginRequest(user.getFirebaseUid(), user.getFirebaseUid()));
} else {
return new Result<>(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(),ResultCodeEnum.ILLEGAL_ARGUMENT.getDesc());
return new Result<>(ResultCodeEnum.ILLEGAL_ARGUMENT.getCode(), ResultCodeEnum.ILLEGAL_ARGUMENT.getDesc());
}
}
private void fixCoupon(TbCfUserInfo user){
try{
private void fixCoupon(TbCfUserInfo user) {
try {
List<TbCfCoupon> couponVailList = couponRepository.findAllByCouponVaild(1);
//获取当前时间的时分秒
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");//设置日期格式
......@@ -314,13 +335,24 @@ public class AuthController extends Controller {
toi.setEndTime(endDate);
toicouponRepository.save(toi);
}
}catch (Exception e){
} catch (Exception e) {
}
}
private void fixCode(TbCfUserInfo user) {
if( user.getCode() == null ) {
Query nativeQuery = entityManager.createNativeQuery("select b.code as data FROM user_info b where b.external_id=:user limit 1");
nativeQuery.setParameter("user", user.getUserId());
if (nativeQuery.getSingleResult() != null) {
user.setCode((String) nativeQuery.getSingleResult());
}
}
private void fixCode(TbCfUserInfo user){
if( user.getCode() == null){
if (user.getCode() == null) {
Hashids hashids = new Hashids("big_afr_dev", 6);
Long codeCount = user.getCodeCount();
......@@ -331,7 +363,7 @@ public class AuthController extends Controller {
long range = Math.abs((long) (Math.random() * (Max - Min)) + Min);
long id = Math.addExact(currentTime, range);
if( codeCount == null){
if (codeCount == null) {
id = userRepository.count() + id;
}
......@@ -339,11 +371,11 @@ public class AuthController extends Controller {
}
}
private void addToNetwork(TbCfUserInfo user){
private void addToNetwork(TbCfUserInfo user) {
Network top = networkRepository.findTopByOrderByIdDesc();
if( top != null && !user.invited() ) {
if (!networkRepository.existsByUserInfo_UserIdAndNetworkInfo_UserId(top.getNetworkId(), user.getUserId())){
if (top != null && !user.invited()) {
if (!networkRepository.existsByUserInfo_UserIdAndNetworkInfo_UserId(top.getNetworkId(), user.getUserId())) {
Network network = new Network();
network.setUserInfo(top.getNetworkInfo());
network.setNetworkInfo(user);
......@@ -355,7 +387,7 @@ public class AuthController extends Controller {
}
private void fillUserNecessayInfo(TbCfUserInfo tbCfUserInfoVo) {
if( tbCfUserInfoVo.getAvatar() == null) tbCfUserInfoVo.setAvatar(domainProperties.getProperty("user.avatar"));
if (tbCfUserInfoVo.getAvatar() == null) tbCfUserInfoVo.setAvatar(domainProperties.getProperty("user.avatar"));
tbCfUserInfoVo.setUserNo(IdUtil.createIdByDate());
tbCfUserInfoVo.setPhoneFlag(StateConstant.INVALID);
tbCfUserInfoVo.setLoginCount(0);
......@@ -364,7 +396,8 @@ public class AuthController extends Controller {
tbCfUserInfoVo.setInvitedCount(0);
tbCfUserInfoVo.setEnableFlag(StateConstant.VALID);
//目前有验证码的都是邮箱类型
tbCfUserInfoVo.setUserType(UserTypeEnum.FACEBOOK.getCode());
if (tbCfUserInfoVo.getUserType() == null)
tbCfUserInfoVo.setUserType(UserTypeEnum.UN_KNOW.getCode());
tbCfUserInfoVo.setEmailFlag(StateConstant.INVALID);
}
}
server.servlet.context-path=/zion
spring.jpa.hibernate.ddl-auto=update
server.port = 7001
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:159.138.48.71}:3306/chinafrica_ref?useUnicode=true&connectionCollation=utf8mb4_general_ci&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
server.port = 7000
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:47.106.242.175}:3306/afrishop_test?useUnicode=true&connectionCollation=utf8mb4_general_ci&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=Diaoyunnuli.8
spring.datasource.password=diaoyun666
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.datasource.connectionInitSql: SET NAMES 'utf8mb4'
#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论