View Javadoc
1   package com.rest;
2   
3   /*
4    * #%L
5    * Gateway
6    * %%
7    * Copyright (C) 2015 Powered by Sergey
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   * 
13   *      http://www.apache.org/licenses/LICENSE-2.0
14   * 
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  
24  import com.dto.*;
25  import com.entity.AuthorityEntity;
26  import com.entity.UserEntity;
27  import com.repository.IAuthorityRepository;
28  import com.repository.IUserRepository;
29  import com.utils.BundleMessageReader;
30  import org.modelmapper.ModelMapper;
31  import org.springframework.beans.factory.annotation.Autowired;
32  import org.springframework.beans.factory.annotation.Value;
33  import org.springframework.http.HttpStatus;
34  import org.springframework.http.ResponseEntity;
35  import org.springframework.mail.javamail.JavaMailSender;
36  import org.springframework.security.crypto.password.StandardPasswordEncoder;
37  import org.springframework.stereotype.Component;
38  import org.springframework.transaction.annotation.Transactional;
39  import org.springframework.web.bind.annotation.*;
40  import org.thymeleaf.spring3.SpringTemplateEngine;
41  import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
42  
43  import javax.validation.Valid;
44  import javax.validation.Validator;
45  import java.security.Principal;
46  import java.util.UUID;
47  
48  ;
49  
50  /**
51   * Created by aautushk on 8/30/2015.
52   */
53  
54  
55  @Component
56  @RestController
57  @RequestMapping("/gateway")
58  public class UserRest {
59      @Autowired
60  	public IUserRepository userRepository;
61  
62      @Autowired
63      public IAuthorityRepository authorityRepository;
64  
65      private BundleMessageReader bundleMessageReader = new BundleMessageReader();
66  
67      @Autowired
68      public Validator validator;
69  
70      @Autowired
71      public JavaMailSender mailSender;
72  
73      @Autowired
74      public ClassLoaderTemplateResolver emailTemplateResolver;
75  
76      @Autowired
77      public SpringTemplateEngine thymeleaf;
78  
79      @Value("${mailserver.sendFrom}")
80      public String mailSendFrom;
81  
82      @Value("${gatewayHost}")
83      public String gatewayHost;
84  
85      @Value("${gatewayPort}")
86      public String gatewayPort;
87  
88      @Value("${server.contextPath}")
89      public String contextPath;
90  
91      public EmailSender emailSender;
92  
93      private ModelMapper modelMapper = new ModelMapper(); //read more at http://modelmapper.org/user-manual/
94  
95      private StandardPasswordEncoder standardPasswordEncoder = new StandardPasswordEncoder("53cr3t");
96  
97      private UserResponseDto convertToResponseDto(UserEntity user) {
98          UserResponseDto userDro = modelMapper.map(user, UserResponseDto.class);
99          return userDro;
100     }
101 
102     @RequestMapping(value = "/createUser", method = RequestMethod.POST)
103     @Transactional
104     public ResponseEntity createUser(@Valid @RequestBody UserRequestDto userRequestDto){
105         UserEntity user = userRepository.findByUsername(userRequestDto.getUsername());
106         if(user != null){
107             throw new RuntimeException(bundleMessageReader.getMessage("UserAlreadyRegistered"));
108         }
109 
110         String encodedPassword = standardPasswordEncoder.encode(userRequestDto.getPassword());
111         userRequestDto.setPassword(encodedPassword);
112 
113         user = modelMapper.map(userRequestDto, UserEntity.class);
114         user.setEnabled(false);
115 
116         UUID emailVerificationToken = UUID.randomUUID();
117         user.setEmailVerificationToken(emailVerificationToken.toString());
118 
119         userRepository.save(user);
120 
121         AuthorityEntity authorityEntity = new AuthorityEntity();
122         authorityEntity.setUsername(user.getUsername());
123         authorityEntity.setAuthority("SYSTEM_USER");
124 
125         authorityRepository.save(authorityEntity); // initial role is assigned to the new user (needed by spring security)
126 
127         if(emailSender == null){// this check needed for unit testing perposes
128             emailSender = new EmailSender(mailSender, emailTemplateResolver, thymeleaf, user.getUsername(), mailSendFrom);
129         }
130 
131         String requestBaseUrl = this.gatewayHost + ':' + this.gatewayPort + this.contextPath;
132         emailSender.sendVerificationTokenEmail(emailVerificationToken.toString(), requestBaseUrl);
133 
134         return new ResponseEntity(HttpStatus.OK);
135     }
136 
137     @RequestMapping(value = "/activateUser", method = RequestMethod.PUT)
138     @Transactional
139     public ResponseEntity activateUser(@RequestParam String emailVerificationToken) {
140         UserEntity user = userRepository.findByEmailVerificationToken(emailVerificationToken);
141         if(user == null){
142             throw new RuntimeException(bundleMessageReader.getMessage("NotValidEmailVerificationToken"));
143         }
144         user.setEnabled(true);
145         userRepository.save(user);
146         return new ResponseEntity(HttpStatus.OK);
147     }
148 
149     @RequestMapping(value = "/changePassword", method = RequestMethod.PUT)
150     @Transactional
151     public ResponseEntity changePassword(@Valid @RequestBody UserPasswordRequestDto userPasswordRequestDto, Principal user) {
152         String username =  user.getName();
153 
154         UserEntity userFromDB = userRepository.findByUsername(username);
155 
156         if(!standardPasswordEncoder.matches(userPasswordRequestDto.getCurrentPassword(), userFromDB.getPassword())){
157             throw new RuntimeException(bundleMessageReader.getMessage("WrongCurrentPassword"));
158         }
159 
160         String encodedNewPassword = standardPasswordEncoder.encode(userPasswordRequestDto.getNewPassword());
161         userFromDB.setPassword(encodedNewPassword);
162 
163         userRepository.save(userFromDB);
164 
165         return new ResponseEntity(HttpStatus.OK);
166     }
167 
168     @RequestMapping(value = "/initiateResetPassword", method = RequestMethod.PUT)
169     @Transactional
170     public ResponseEntity initiateResetPassword(@Valid @RequestBody InitiateResetPasswordRequestDto initiateResetPasswordRequestDto) {
171         UserEntity user = userRepository.findByUsername(initiateResetPasswordRequestDto.getEmail());
172 
173         if(user == null){
174             throw new RuntimeException(bundleMessageReader.getMessage("NoUserFound"));
175         }
176 
177         UUID resetPasswordToken = UUID.randomUUID();
178         user.setResetPasswordToken(resetPasswordToken.toString());
179 
180         userRepository.save(user);
181 
182         if(emailSender == null){// this check needed for unit testing perposes
183             emailSender = new EmailSender(mailSender, emailTemplateResolver, thymeleaf, user.getUsername(), mailSendFrom);
184         }
185 
186         String requestBaseUrl = this.gatewayHost + ':' + this.gatewayPort + this.contextPath;
187         emailSender.sendReserPasswordEmail(resetPasswordToken.toString(), requestBaseUrl);
188 
189         return new ResponseEntity(HttpStatus.OK);
190     }
191 
192     @RequestMapping(value = "/resetPassword", method = RequestMethod.PUT)
193     @Transactional
194     public ResponseEntity resetPassword(@Valid @RequestBody ResetPasswordRequestDto resetPasswordDto, @RequestParam String resetPasswordToken) {
195         UserEntity user = userRepository.findByResetPasswordToken(resetPasswordToken);
196 
197         if(user == null){
198             throw new RuntimeException(bundleMessageReader.getMessage("NotValidResetPasswordToken"));
199         }
200 
201         String encodedNewPassword = standardPasswordEncoder.encode(resetPasswordDto.getNewPassword());
202         user.setPassword(encodedNewPassword);
203 
204         userRepository.save(user);
205 
206         return new ResponseEntity(HttpStatus.OK);
207     }
208 }