From e7ff6eaf7ffd713d102f596b4e5d906504160ff8 Mon Sep 17 00:00:00 2001
From: Jack <jack.su@pollex.com.tw>
Date: 星期二, 23 十一月 2021 18:34:23 +0800
Subject: [PATCH] [ADD] 客戶註冊的API

---
 pamapi/src/main/java/com/pollex/pam/domain/Customer.java                             |   15 +
 pamapi/src/main/java/com/pollex/pam/repository/OtpTmpRepository.java                 |   15 +
 pamapi/src/main/java/com/pollex/pam/enums/OtpTmpStatusEnum.java                      |    6 
 pamapi/src/main/java/com/pollex/pam/service/dto/CustomerRegisterDTO.java             |   53 +++++
 pamapi/src/main/java/com/pollex/pam/web/rest/AccountResource.java                    |   47 +++-
 pamapi/src/main/java/com/pollex/pam/service/CustomerService.java                     |   47 ++++
 pamapi/src/doc/註冊API/註冊API.txt                                                       |   13 +
 pamapi/src/main/java/com/pollex/pam/enums/CustomerDetailEnum.java                    |    3 
 pamapi/src/main/java/com/pollex/pam/web/rest/OtpResource.java                        |   53 +++-
 pamapi/src/main/java/com/pollex/pam/service/UserService.java                         |  110 +++++-----
 pamapi/src/main/java/com/pollex/pam/service/CustomerAuthService.java                 |   34 +++
 pamapi/src/main/java/com/pollex/pam/service/OtpTmpService.java                       |   39 +++
 pamapi/src/main/java/com/pollex/pam/security/provider/OtpAuthenticationProvider.java |   29 ++
 pamapi/src/main/java/com/pollex/pam/domain/OtpTmp.java                               |   92 +++++++++
 pamapi/src/main/java/com/pollex/pam/service/mapper/CustomerDTOMapper.java            |   17 +
 15 files changed, 480 insertions(+), 93 deletions(-)

diff --git "a/pamapi/src/doc/\350\250\273\345\206\212API/\350\250\273\345\206\212API.txt" "b/pamapi/src/doc/\350\250\273\345\206\212API/\350\250\273\345\206\212API.txt"
new file mode 100644
index 0000000..e5a3ccf
--- /dev/null
+++ "b/pamapi/src/doc/\350\250\273\345\206\212API/\350\250\273\345\206\212API.txt"
@@ -0,0 +1,13 @@
+post : 
+http://localhost:8080/api/otp/register
+
+request body: 
+
+{
+    "phone": "0973000003",
+    "email":"email@pollex.com.tw",
+    "indexKey": "3485a742",
+    "otpCode": "123",
+    "name":"Jack",
+    "contactType":"SMS" // "SMS"嚗tp������"EMAIL":Otp�email
+}
\ No newline at end of file
diff --git a/pamapi/src/main/java/com/pollex/pam/domain/Customer.java b/pamapi/src/main/java/com/pollex/pam/domain/Customer.java
index 225fba6..580dea9 100644
--- a/pamapi/src/main/java/com/pollex/pam/domain/Customer.java
+++ b/pamapi/src/main/java/com/pollex/pam/domain/Customer.java
@@ -5,6 +5,8 @@
 
 import javax.persistence.Column;
 import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
 import javax.persistence.GeneratedValue;
 import javax.persistence.GenerationType;
 import javax.persistence.Id;
@@ -14,6 +16,7 @@
 import org.springframework.data.annotation.LastModifiedDate;
 
 import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.pollex.pam.enums.OtpLoginTypeEnum;
 
 @Entity
 @Table(name = "customer")
@@ -37,6 +40,10 @@
 	
 	@Column(name = "email")
     private String email;
+	
+	@Enumerated(value = EnumType.STRING)
+	@Column(name = "contact_type")
+    private OtpLoginTypeEnum contactType;
 	
 	@CreatedDate
     @Column(name = "created_date", updatable = false)
@@ -95,6 +102,14 @@
 	public void setLastModifiedDate(Instant lastModifiedDate) {
 		this.lastModifiedDate = lastModifiedDate;
 	}
+
+	public OtpLoginTypeEnum getContactType() {
+		return contactType;
+	}
+
+	public void setContactType(OtpLoginTypeEnum contactType) {
+		this.contactType = contactType;
+	}
     
     
 
diff --git a/pamapi/src/main/java/com/pollex/pam/domain/OtpTmp.java b/pamapi/src/main/java/com/pollex/pam/domain/OtpTmp.java
new file mode 100644
index 0000000..4007d37
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/domain/OtpTmp.java
@@ -0,0 +1,92 @@
+package com.pollex.pam.domain;
+
+import java.io.Serializable;
+import java.time.Instant;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+
+import org.springframework.data.annotation.CreatedDate;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.pollex.pam.enums.OtpLoginTypeEnum;
+import com.pollex.pam.enums.OtpTmpStatusEnum;
+
+@Entity
+@Table(name = "otp_tmp")
+public class OtpTmp implements Serializable{
+	
+	
+	/**
+	 * 
+	 */
+	private static final long serialVersionUID = 1L;
+
+	@Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+	
+	@Column(name = "account")
+    private String account;
+	
+	@Column(name = "index_key")
+    private String indexKey;
+	
+	@Enumerated(value = EnumType.STRING)
+	@Column(name = "status")
+    private OtpTmpStatusEnum status;
+	
+	@CreatedDate
+    @Column(name = "created_date", updatable = false)
+    @JsonIgnore
+    private Instant createdDate = Instant.now();
+
+	public Long getId() {
+		return id;
+	}
+
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	public String getIndexKey() {
+		return indexKey;
+	}
+
+	public void setIndexKey(String indexKey) {
+		this.indexKey = indexKey;
+	}
+
+	public OtpTmpStatusEnum getStatus() {
+		return status;
+	}
+
+	public void setStatus(OtpTmpStatusEnum status) {
+		this.status = status;
+	}
+
+	public Instant getCreatedDate() {
+		return createdDate;
+	}
+
+	public void setCreatedDate(Instant createdDate) {
+		this.createdDate = createdDate;
+	}
+
+	public String getAccount() {
+		return account;
+	}
+
+	public void setAccount(String account) {
+		this.account = account;
+	}
+	
+	
+	
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/enums/CustomerDetailEnum.java b/pamapi/src/main/java/com/pollex/pam/enums/CustomerDetailEnum.java
index 692c87a..f1ccc21 100644
--- a/pamapi/src/main/java/com/pollex/pam/enums/CustomerDetailEnum.java
+++ b/pamapi/src/main/java/com/pollex/pam/enums/CustomerDetailEnum.java
@@ -3,7 +3,8 @@
 public enum CustomerDetailEnum {
     ID("CustomerId"),
     NAME("CustomerName"),
-    ACCOUNT("CustomerAccount");
+    ACCOUNT("CustomerAccount"),
+    CONTACT_TYPE("ContactType");
 
     private final String value;
 
diff --git a/pamapi/src/main/java/com/pollex/pam/enums/OtpTmpStatusEnum.java b/pamapi/src/main/java/com/pollex/pam/enums/OtpTmpStatusEnum.java
new file mode 100644
index 0000000..b48d88e
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/enums/OtpTmpStatusEnum.java
@@ -0,0 +1,6 @@
+package com.pollex.pam.enums;
+
+public enum OtpTmpStatusEnum {
+	UNVERIFIED,
+    VERRIFIED
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/repository/OtpTmpRepository.java b/pamapi/src/main/java/com/pollex/pam/repository/OtpTmpRepository.java
new file mode 100644
index 0000000..7b49c10
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/repository/OtpTmpRepository.java
@@ -0,0 +1,15 @@
+package com.pollex.pam.repository;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import com.pollex.pam.domain.OtpTmp;
+
+@Repository
+public interface OtpTmpRepository extends JpaRepository<OtpTmp, Long>{
+
+	OtpTmp findByAccountAndIndexKey(String account, String indexKey);
+
+	OtpTmp findByAccount(String account);
+
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/security/provider/OtpAuthenticationProvider.java b/pamapi/src/main/java/com/pollex/pam/security/provider/OtpAuthenticationProvider.java
index 6fadbba..43138ce 100644
--- a/pamapi/src/main/java/com/pollex/pam/security/provider/OtpAuthenticationProvider.java
+++ b/pamapi/src/main/java/com/pollex/pam/security/provider/OtpAuthenticationProvider.java
@@ -2,9 +2,13 @@
 
 import com.pollex.pam.config.ApplicationProperties;
 import com.pollex.pam.domain.Customer;
+import com.pollex.pam.domain.OtpTmp;
 import com.pollex.pam.enums.CustomerDetailEnum;
+import com.pollex.pam.enums.OtpLoginTypeEnum;
+import com.pollex.pam.enums.OtpTmpStatusEnum;
 import com.pollex.pam.repository.CustomerRepository;
 import com.pollex.pam.security.token.OtpAuthenticationToken;
+import com.pollex.pam.service.OtpTmpService;
 import com.pollex.pam.service.OtpWebService;
 import com.pollex.pam.service.dto.OtpResponseDTO;
 import com.pollex.pam.web.rest.vm.OtpAccount;
@@ -38,6 +42,9 @@
 
     @Autowired
     CustomerRepository customerRepository;
+    
+    @Autowired
+    OtpTmpService otpTmpService;
 
     public Authentication authenticate(OtpAuthenticationToken otpAuthenticationToken) throws AuthenticationException {
         OtpAccount otpAccount = otpAuthenticationToken.getPrincipal();
@@ -46,13 +53,15 @@
         String otpCode = otpAuthenticationToken.getCredentials();
 
         if(applicationProperty.isMockLogin()){
-            return getCustomerToken(account, otpCode);
+        	setVerrifiedOtpTmp(account, indexKey);
+            return getCustomerToken(account, otpCode, indexKey);
         }
 
         try {
             OtpResponseDTO otpResponseDTO = otpWebService.verifyOTP(indexKey, otpCode);
             if(otpResponseDTO.isSuccess()) {
-                return getCustomerToken(account, otpCode);
+            	setVerrifiedOtpTmp(account, indexKey);
+                return getCustomerToken(account, otpCode, indexKey);
             }
         } catch (Exception e) {
             log.error("Exception: ", e);
@@ -62,9 +71,18 @@
         throw new AuthenticationCredentialsNotFoundException("");
     }
 
-    private UsernamePasswordAuthenticationToken getCustomerToken(String account, String otpCode) {
-        // todo �摮�DB��撅祆迤撣貊鞊∴����畾essage����垢��脰�酉���
-        Customer customer = customerRepository.findOneByEmailEqualsOrPhoneEquals(account, account).orElseThrow(() -> new UsernameNotFoundException("this customer is not in db, account = " + account));
+    private void setVerrifiedOtpTmp(String account, String indexKey) {
+    	OtpTmp otpTmp = otpTmpService.findByAccountAndIndexKey(account, indexKey);
+    	otpTmp.setStatus(OtpTmpStatusEnum.VERRIFIED);
+    	otpTmpService.save(otpTmp);
+	}
+
+	private UsernamePasswordAuthenticationToken getCustomerToken(String account
+    		, String otpCode, String indexKey) {
+    	
+    	
+    	// todo �摮�DB��撅祆迤撣貊鞊∴����畾essage����垢��脰�酉���
+        Customer customer = customerRepository.findOneByEmailEqualsOrPhoneEquals(account, account).orElseThrow(() -> new UsernameNotFoundException("this customer is not in register, account = " + account));
 
         List<GrantedAuthority> grantedAuths = Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"));
         UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(account, otpCode, grantedAuths);
@@ -73,6 +91,7 @@
         details.put(CustomerDetailEnum.ID.getValue(), customer.getId().toString());
         details.put(CustomerDetailEnum.NAME.getValue(), customer.getName());
         details.put(CustomerDetailEnum.ACCOUNT.getValue(), account);
+//        details.put(CustomerDetailEnum.CONTACT_TYPE.getValue(), customer.getContactType());
         authenticationToken.setDetails(details);
 
         return authenticationToken;
diff --git a/pamapi/src/main/java/com/pollex/pam/service/CustomerAuthService.java b/pamapi/src/main/java/com/pollex/pam/service/CustomerAuthService.java
new file mode 100644
index 0000000..6960ee6
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/service/CustomerAuthService.java
@@ -0,0 +1,34 @@
+package com.pollex.pam.service;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.stereotype.Service;
+
+import com.pollex.pam.security.jwt.TokenProvider;
+import com.pollex.pam.security.token.OtpAuthenticationToken;
+import com.pollex.pam.web.rest.vm.OtpAccount;
+
+@Service
+public class CustomerAuthService {
+	
+	@Autowired
+    AuthenticationManagerBuilder authenticationManagerBuilder;
+
+    @Autowired
+    TokenProvider tokenProvider;
+	
+	public String authorize(String account, String indexKey, String otpCode) {
+		OtpAccount otpAccount = new OtpAccount(account, indexKey);
+        OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(
+            otpAccount,
+            otpCode
+        );
+
+        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
+        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
+        String jwt = tokenProvider.createToken(authentication, false);
+        return jwt;
+	}
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/service/CustomerService.java b/pamapi/src/main/java/com/pollex/pam/service/CustomerService.java
new file mode 100644
index 0000000..30561b9
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/service/CustomerService.java
@@ -0,0 +1,47 @@
+package com.pollex.pam.service;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.userdetails.UsernameNotFoundException;
+import org.springframework.stereotype.Service;
+
+import com.pollex.pam.domain.Customer;
+import com.pollex.pam.domain.OtpTmp;
+import com.pollex.pam.enums.OtpLoginTypeEnum;
+import com.pollex.pam.enums.OtpTmpStatusEnum;
+import com.pollex.pam.repository.CustomerRepository;
+import com.pollex.pam.service.dto.CustomerRegisterDTO;
+import com.pollex.pam.service.mapper.CustomerDTOMapper;
+
+@Service
+public class CustomerService {
+	
+	@Autowired
+	CustomerRepository customerRepository;
+	
+	@Autowired
+    CustomerDTOMapper customerDTOMapper;
+	
+	@Autowired
+	CustomerAuthService customerAuthService;
+	
+	@Autowired
+	OtpTmpService otpTmpService;
+	
+	public Customer save(Customer customer) {
+		return customerRepository.save(customer);
+	}
+	
+	public String registerCustomer(CustomerRegisterDTO registDTO) {
+		String account = registDTO.getContactType() == OtpLoginTypeEnum.EMAIL?registDTO.getEmail():registDTO.getPhone();
+		OtpTmp otpTmp = otpTmpService.findByAccountAndIndexKey(account, registDTO.getIndexKey());
+    	if(otpTmp.getStatus() == OtpTmpStatusEnum.VERRIFIED) {
+    		Customer customer = customerDTOMapper.toCustomer(registDTO);
+        	save(customer);
+        	String jwt = customerAuthService.authorize(account, registDTO.getIndexKey(), registDTO.getOtpCode());
+        	return jwt;
+    	}else {
+    		throw new UsernameNotFoundException("Otp record not found");
+    	}
+		
+	}
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/service/OtpTmpService.java b/pamapi/src/main/java/com/pollex/pam/service/OtpTmpService.java
new file mode 100644
index 0000000..0d718fd
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/service/OtpTmpService.java
@@ -0,0 +1,39 @@
+package com.pollex.pam.service;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import com.pollex.pam.domain.OtpTmp;
+import com.pollex.pam.enums.OtpLoginTypeEnum;
+import com.pollex.pam.enums.OtpTmpStatusEnum;
+import com.pollex.pam.repository.OtpTmpRepository;
+
+@Service
+public class OtpTmpService {
+	
+	@Autowired
+	OtpTmpRepository otpTmpRepository;
+	
+	public OtpTmp createOtpTmp(String account, String indexKey) {
+		OtpTmp oldTmp = otpTmpRepository.findByAccount(account);
+		if(oldTmp==null) {
+			OtpTmp otpTmp = new OtpTmp();
+	    	otpTmp.setIndexKey(indexKey);
+	    	otpTmp.setAccount(account);
+	    	otpTmp.setStatus(OtpTmpStatusEnum.UNVERIFIED);
+	    	return otpTmpRepository.save(otpTmp);
+		}else {
+			oldTmp.setIndexKey(indexKey);
+			oldTmp.setStatus(OtpTmpStatusEnum.UNVERIFIED);
+			return otpTmpRepository.save(oldTmp);
+		}
+	}
+
+	public OtpTmp findByAccountAndIndexKey(String account, String indexKey) {
+		return otpTmpRepository.findByAccountAndIndexKey(account, indexKey);
+	}
+
+	public OtpTmp save(OtpTmp otpTmp) {
+		return otpTmpRepository.save(otpTmp);
+	}
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/service/UserService.java b/pamapi/src/main/java/com/pollex/pam/service/UserService.java
index fe9b32b..3bfa0ad 100644
--- a/pamapi/src/main/java/com/pollex/pam/service/UserService.java
+++ b/pamapi/src/main/java/com/pollex/pam/service/UserService.java
@@ -1,18 +1,13 @@
 package com.pollex.pam.service;
 
-import com.pollex.pam.config.Constants;
-import com.pollex.pam.domain.Authority;
-import com.pollex.pam.domain.User;
-import com.pollex.pam.repository.AuthorityRepository;
-import com.pollex.pam.repository.UserRepository;
-import com.pollex.pam.security.AuthoritiesConstants;
-import com.pollex.pam.security.SecurityUtils;
-import com.pollex.pam.service.dto.AdminUserDTO;
-import com.pollex.pam.service.dto.UserDTO;
 import java.time.Instant;
 import java.time.temporal.ChronoUnit;
-import java.util.*;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
 import java.util.stream.Collectors;
+
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.cache.CacheManager;
@@ -22,6 +17,16 @@
 import org.springframework.security.crypto.password.PasswordEncoder;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+
+import com.pollex.pam.config.Constants;
+import com.pollex.pam.domain.Authority;
+import com.pollex.pam.domain.User;
+import com.pollex.pam.repository.AuthorityRepository;
+import com.pollex.pam.repository.UserRepository;
+import com.pollex.pam.security.SecurityUtils;
+import com.pollex.pam.service.dto.AdminUserDTO;
+import com.pollex.pam.service.dto.UserDTO;
+
 import tech.jhipster.security.RandomUtil;
 
 /**
@@ -40,6 +45,7 @@
     private final AuthorityRepository authorityRepository;
 
     private final CacheManager cacheManager;
+    
 
     public UserService(
         UserRepository userRepository,
@@ -93,47 +99,47 @@
             });
     }
 
-    public User registerUser(AdminUserDTO userDTO, String password) {
-        userRepository
-            .findOneByLogin(userDTO.getLogin().toLowerCase())
-            .ifPresent(existingUser -> {
-                boolean removed = removeNonActivatedUser(existingUser);
-                if (!removed) {
-                    throw new UsernameAlreadyUsedException();
-                }
-            });
-        userRepository
-            .findOneByEmailIgnoreCase(userDTO.getEmail())
-            .ifPresent(existingUser -> {
-                boolean removed = removeNonActivatedUser(existingUser);
-                if (!removed) {
-                    throw new EmailAlreadyUsedException();
-                }
-            });
-        User newUser = new User();
-        String encryptedPassword = passwordEncoder.encode(password);
-        newUser.setLogin(userDTO.getLogin().toLowerCase());
-        // new user gets initially a generated password
-        newUser.setPassword(encryptedPassword);
-        newUser.setFirstName(userDTO.getFirstName());
-        newUser.setLastName(userDTO.getLastName());
-        if (userDTO.getEmail() != null) {
-            newUser.setEmail(userDTO.getEmail().toLowerCase());
-        }
-        newUser.setImageUrl(userDTO.getImageUrl());
-        newUser.setLangKey(userDTO.getLangKey());
-        // new user is not active
-        newUser.setActivated(false);
-        // new user gets registration key
-        newUser.setActivationKey(RandomUtil.generateActivationKey());
-        Set<Authority> authorities = new HashSet<>();
-        authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
-        newUser.setAuthorities(authorities);
-        userRepository.save(newUser);
-        this.clearUserCaches(newUser);
-        log.debug("Created Information for User: {}", newUser);
-        return newUser;
-    }
+//    public User registerUser(AdminUserDTO userDTO, String password) {
+//        userRepository
+//            .findOneByLogin(userDTO.getLogin().toLowerCase())
+//            .ifPresent(existingUser -> {
+//                boolean removed = removeNonActivatedUser(existingUser);
+//                if (!removed) {
+//                    throw new UsernameAlreadyUsedException();
+//                }
+//            });
+//        userRepository
+//            .findOneByEmailIgnoreCase(userDTO.getEmail())
+//            .ifPresent(existingUser -> {
+//                boolean removed = removeNonActivatedUser(existingUser);
+//                if (!removed) {
+//                    throw new EmailAlreadyUsedException();
+//                }
+//            });
+//        User newUser = new User();
+//        String encryptedPassword = passwordEncoder.encode(password);
+//        newUser.setLogin(userDTO.getLogin().toLowerCase());
+//        // new user gets initially a generated password
+//        newUser.setPassword(encryptedPassword);
+//        newUser.setFirstName(userDTO.getFirstName());
+//        newUser.setLastName(userDTO.getLastName());
+//        if (userDTO.getEmail() != null) {
+//            newUser.setEmail(userDTO.getEmail().toLowerCase());
+//        }
+//        newUser.setImageUrl(userDTO.getImageUrl());
+//        newUser.setLangKey(userDTO.getLangKey());
+//        // new user is not active
+//        newUser.setActivated(false);
+//        // new user gets registration key
+//        newUser.setActivationKey(RandomUtil.generateActivationKey());
+//        Set<Authority> authorities = new HashSet<>();
+//        authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
+//        newUser.setAuthorities(authorities);
+//        userRepository.save(newUser);
+//        this.clearUserCaches(newUser);
+//        log.debug("Created Information for User: {}", newUser);
+//        return newUser;
+//    }
 
     private boolean removeNonActivatedUser(User existingUser) {
         if (existingUser.isActivated()) {
@@ -322,4 +328,6 @@
             Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE)).evict(user.getEmail());
         }
     }
+    
+    
 }
diff --git a/pamapi/src/main/java/com/pollex/pam/service/dto/CustomerRegisterDTO.java b/pamapi/src/main/java/com/pollex/pam/service/dto/CustomerRegisterDTO.java
new file mode 100644
index 0000000..058cc56
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/service/dto/CustomerRegisterDTO.java
@@ -0,0 +1,53 @@
+package com.pollex.pam.service.dto;
+
+import com.pollex.pam.enums.OtpLoginTypeEnum;
+
+public class CustomerRegisterDTO {
+	
+    private String name;
+    private String phone;
+    private String email;
+    private OtpLoginTypeEnum contactType;
+    private String indexKey;
+    private String otpCode;
+    
+	public String getName() {
+		return name;
+	}
+	public void setName(String name) {
+		this.name = name;
+	}
+	public String getPhone() {
+		return phone;
+	}
+	public void setPhone(String phone) {
+		this.phone = phone;
+	}
+	public String getEmail() {
+		return email;
+	}
+	public void setEmail(String email) {
+		this.email = email;
+	}
+	public OtpLoginTypeEnum getContactType() {
+		return contactType;
+	}
+	public void setContactType(OtpLoginTypeEnum contactType) {
+		this.contactType = contactType;
+	}
+	public String getIndexKey() {
+		return indexKey;
+	}
+	public void setIndexKey(String indexKey) {
+		this.indexKey = indexKey;
+	}
+	public String getOtpCode() {
+		return otpCode;
+	}
+	public void setOtpCode(String otpCode) {
+		this.otpCode = otpCode;
+	}
+    
+    
+	
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/service/mapper/CustomerDTOMapper.java b/pamapi/src/main/java/com/pollex/pam/service/mapper/CustomerDTOMapper.java
new file mode 100644
index 0000000..326eac2
--- /dev/null
+++ b/pamapi/src/main/java/com/pollex/pam/service/mapper/CustomerDTOMapper.java
@@ -0,0 +1,17 @@
+package com.pollex.pam.service.mapper;
+
+import org.springframework.beans.BeanUtils;
+import org.springframework.stereotype.Service;
+
+import com.pollex.pam.domain.Customer;
+import com.pollex.pam.service.dto.CustomerRegisterDTO;
+
+@Service
+public class CustomerDTOMapper {
+	
+	public Customer toCustomer(CustomerRegisterDTO source) {
+		Customer target = new Customer();
+		BeanUtils.copyProperties(source, target);
+		return target;
+	}
+}
diff --git a/pamapi/src/main/java/com/pollex/pam/web/rest/AccountResource.java b/pamapi/src/main/java/com/pollex/pam/web/rest/AccountResource.java
index fbb1b24..a4a87ae 100644
--- a/pamapi/src/main/java/com/pollex/pam/web/rest/AccountResource.java
+++ b/pamapi/src/main/java/com/pollex/pam/web/rest/AccountResource.java
@@ -3,10 +3,15 @@
 import com.pollex.pam.domain.User;
 import com.pollex.pam.repository.UserRepository;
 import com.pollex.pam.security.SecurityUtils;
+import com.pollex.pam.security.jwt.JWTFilter;
+import com.pollex.pam.service.CustomerAuthService;
+import com.pollex.pam.service.CustomerService;
 import com.pollex.pam.service.MailService;
 import com.pollex.pam.service.UserService;
 import com.pollex.pam.service.dto.AdminUserDTO;
+import com.pollex.pam.service.dto.CustomerRegisterDTO;
 import com.pollex.pam.service.dto.PasswordChangeDTO;
+import com.pollex.pam.web.rest.UserJWTController.JWTToken;
 import com.pollex.pam.web.rest.errors.*;
 import com.pollex.pam.web.rest.vm.KeyAndPasswordVM;
 import com.pollex.pam.web.rest.vm.ManagedUserVM;
@@ -16,7 +21,10 @@
 import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 
 /**
@@ -40,6 +48,9 @@
     private final UserService userService;
 
     private final MailService mailService;
+    
+    @Autowired
+    CustomerService customerService;
 
     public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) {
         this.userRepository = userRepository;
@@ -47,23 +58,25 @@
         this.mailService = mailService;
     }
 
-    /**
-     * {@code POST  /register} : register the user.
-     *
-     * @param managedUserVM the managed user View Model.
-     * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
-     * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
-     * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used.
-     */
-    @PostMapping("/register")
-    @ResponseStatus(HttpStatus.CREATED)
-    public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
-        if (isPasswordLengthInvalid(managedUserVM.getPassword())) {
-            throw new InvalidPasswordException();
-        }
-        User user = userService.registerUser(managedUserVM, managedUserVM.getPassword());
-        mailService.sendActivationEmail(user);
-    }
+//    /**
+//     * {@code POST  /register} : register the user.
+//     *
+//     * @param managedUserVM the managed user View Model.
+//     * @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
+//     * @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
+//     * @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used.
+//     */
+//    @PostMapping("/register")
+//    @ResponseStatus(HttpStatus.CREATED)
+//    public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
+//        if (isPasswordLengthInvalid(managedUserVM.getPassword())) {
+//            throw new InvalidPasswordException();
+//        }
+//        User user = userService.registerUser(managedUserVM, managedUserVM.getPassword());
+//        mailService.sendActivationEmail(user);
+//    }
+    
+    
 
     /**
      * {@code GET  /activate} : activate the registered user.
diff --git a/pamapi/src/main/java/com/pollex/pam/web/rest/OtpResource.java b/pamapi/src/main/java/com/pollex/pam/web/rest/OtpResource.java
index 6308dac..d2ba706 100644
--- a/pamapi/src/main/java/com/pollex/pam/web/rest/OtpResource.java
+++ b/pamapi/src/main/java/com/pollex/pam/web/rest/OtpResource.java
@@ -5,7 +5,11 @@
 import com.pollex.pam.security.jwt.JWTFilter;
 import com.pollex.pam.security.jwt.TokenProvider;
 import com.pollex.pam.security.token.OtpAuthenticationToken;
+import com.pollex.pam.service.CustomerAuthService;
+import com.pollex.pam.service.CustomerService;
+import com.pollex.pam.service.OtpTmpService;
 import com.pollex.pam.service.OtpWebService;
+import com.pollex.pam.service.dto.CustomerRegisterDTO;
 import com.pollex.pam.service.dto.OtpResponseDTO;
 import com.pollex.pam.web.rest.vm.*;
 import org.slf4j.Logger;
@@ -40,22 +44,33 @@
 
     @Autowired
     TokenProvider tokenProvider;
+    
+    @Autowired
+    CustomerAuthService customerAuthService;
+    
+    @Autowired
+    OtpTmpService otpTmpService;
+    
+    @Autowired
+    CustomerService customerService;
 
     @PostMapping("/sendOtp")
     public ResponseEntity<Object> sendOtp(@RequestBody OtpLoginVM login) {
-        try {
+    	OtpResponseDTO otpResponse;
+    	try {
             if(applicationProperty.isMockLogin()) {
-                return new ResponseEntity<>(getMockSendOtpResponse(), HttpStatus.OK);
-            }
-
-            if(login.getLoginType() == OtpLoginTypeEnum.SMS) {
-                return new ResponseEntity<>(otpWebService.sendByPhone(login.getAccount()), HttpStatus.OK);
+            	otpResponse = getMockSendOtpResponse();
+            }else if(login.getLoginType() == OtpLoginTypeEnum.SMS) {
+            	otpResponse = otpWebService.sendByPhone(login.getAccount());
             }
             else if(login.getLoginType() == OtpLoginTypeEnum.EMAIL) {
-                return new ResponseEntity<>(otpWebService.sendByEmail(login.getAccount()), HttpStatus.OK);
+            	otpResponse = otpWebService.sendByEmail(login.getAccount());
+            }else {
+            	return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("can not support this login type, loginType = " + login.getLoginType().name());
             }
-
-            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("can not support this login type, loginType = " + login.getLoginType().name());
+            otpTmpService.createOtpTmp(login.getAccount(), otpResponse.getIndexKey());
+            return new ResponseEntity<>(otpResponse, HttpStatus.OK);
+            
         } catch (ServiceException | RemoteException e) {
             return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("connecting otp web service error");
         }
@@ -63,22 +78,22 @@
 
     @PostMapping("/verify")
     public ResponseEntity<UserJWTController.JWTToken> verifyOtp(@RequestBody VerifyOtpVM verifyOtpParam) {
-        OtpAccount otpAccount = new OtpAccount(verifyOtpParam.getAccount(), verifyOtpParam.getIndexKey());
-        OtpAuthenticationToken authenticationToken = new OtpAuthenticationToken(
-            otpAccount,
-            verifyOtpParam.getOtpCode()
-        );
-
-        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
-        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
-        String jwt = tokenProvider.createToken(authentication, false);
+        String jwt = customerAuthService.authorize(verifyOtpParam.getAccount(), verifyOtpParam.getIndexKey(), verifyOtpParam.getOtpCode());
         HttpHeaders httpHeaders = new HttpHeaders();
         httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer" + jwt);
         return new ResponseEntity<>(new UserJWTController.JWTToken(jwt), httpHeaders, HttpStatus.OK);
     }
-
+ 
     private OtpResponseDTO getMockSendOtpResponse() {
         String indexKey = UUID.randomUUID().toString().substring(0, 8);
         return new OtpResponseDTO(new String[]{indexKey, "0", "", ""});
     }
+    
+    @PostMapping("/register")
+    public ResponseEntity<UserJWTController.JWTToken> registerAccount(@RequestBody CustomerRegisterDTO registDTO) {
+    	String jwt = customerService.registerCustomer(registDTO);
+    	HttpHeaders httpHeaders = new HttpHeaders();
+        httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer" + jwt);
+        return new ResponseEntity<>(new UserJWTController.JWTToken(jwt), httpHeaders, HttpStatus.OK);
+    }
 }

--
Gitblit v1.8.0