Commit 41e35bae authored by Jie Yuan's avatar Jie Yuan
Browse files

add endpoint /api/auth/api-token and user filter

parent 07ba6851
......@@ -2,6 +2,8 @@ package svmon.endpoints;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
......@@ -10,6 +12,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
......@@ -17,17 +20,27 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import javax.validation.Valid;
import java.net.URI;
import java.security.Principal;
import java.util.Collections;
import java.util.Iterator;
import java.util.OptionalDouble;
import java.util.Random;
import java.util.Optional;
import svmon.model.UserCreatedToken;
import svmon.model.UserInfo;
import svmon.payload.ApiResponse;
import svmon.payload.JwtAuthenticationResponse;
import svmon.payload.LoginRequest;
import svmon.payload.SignUpRequest;
import svmon.payload.UserSummary;
import svmon.repository.UserCreatedTokenJpaRepository;
import svmon.repository.UserInfoJpaRepository;
import svmon.security.JwtTokenProvider;
......@@ -38,17 +51,38 @@ import svmon.security.JwtTokenProvider;
@CrossOrigin(origins={"https://svmon-dev.scc.kit.edu","http://localhost:4200","http://141.52.74.125:4200","https://svmon.eudat.eu"},maxAge=3600)
public class AuthController {
@Autowired
private static final String Optional = null;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
UserInfoJpaRepository userRepository;
private UserInfoJpaRepository userRepository;
@Autowired
private UserCreatedTokenJpaRepository tokenRepo;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
JwtTokenProvider tokenProvider;
@Value("${app.jwtSecret}")
private String jwtSecret;
@Autowired
public void setUserInfoJpaRepository(UserInfoJpaRepository userJpaRepository) {
this.userRepository = userJpaRepository;
}
@Autowired
public void setUserCreatedTokenJpaRepository(UserCreatedTokenJpaRepository userTokenRepository) {
this.tokenRepo = userTokenRepository;
}
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
......@@ -65,6 +99,75 @@ public class AuthController {
String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}
@PostMapping("/api-token")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('USER') ")
@Transactional
@Modifying
public ResponseEntity<?> generateAPIToken(Principal currentUser ) {
if ( currentUser.getName() == null ) {
return null;
}
System.out.print(currentUser.getName() + "....................**..\n");
UserInfo tmp = this.userRepository.findByUsername(currentUser.getName());
Long tmpId = tmp.getId();
UserInfo user = new UserInfo();
String username = this.generateRandomStr(20);
while (userRepository.findByUsername(username) != null) {
username = this.generateRandomStr(20);
}
String pwd = this.generateRandomStr(30);
String email = this.generateRandomStr(10) +"@" +this.generateRandomStr(10);
while ( userRepository.findByEmail(email) != null) {
email = this.generateRandomStr(10) +"@" +this.generateRandomStr(10);
}
user.setAuthService("USERNAME");
user.setEmail(email);
user.setRole("API");
user.setUsername(username);
user.setIsEnabled(true);
user.setPassword(passwordEncoder.encode(pwd));
userRepository.save(user);
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
username,
pwd
)
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = tokenProvider.generateToken(authentication);
UserCreatedToken atoken = tokenRepo.findOne(tmpId);
if ( atoken == null) {
UserCreatedToken newtoken = new UserCreatedToken();
newtoken.setId(tmpId);
newtoken.setToken(jwt);
tokenRepo.save(newtoken);
} else {
Claims claims = Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(atoken.getToken())
.getBody();
String id = claims.getSubject();
userRepository.deleteById(Long.valueOf(id));
System.out.print(id + "ppppppppp\n");
atoken.setToken(jwt);
tokenRepo.saveAndFlush(atoken);
userRepository.flush();
}
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}
@PostMapping("/signup")
@PreAuthorize("hasAuthority('ADMIN')")
......@@ -101,4 +204,15 @@ public class AuthController {
user.getAuthService(),user.getEmail(),user.getRole());
return new ResponseEntity<UserSummary>(userSum, HttpStatus.CREATED);
}
private String generateRandomStr(int length) {
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
......@@ -56,6 +56,7 @@ public class HostNameEndpoint {
* @return
*/
@RequestMapping(value="/{siteId}/add", method=POST)
@PreAuthorize("hasAuthority('ADMIN')")
public @ResponseBody HostName addNewHostName (@PathVariable("siteId") String siteId, @RequestBody HostNameDTO hostNameDTO) {
log.info("Detected endpoint /{siteId}/add for addNewHostName with: "+siteId+" siteId at {}", dateFormat.format(new Date()));
HostName hostName = null;
......@@ -95,6 +96,7 @@ public class HostNameEndpoint {
* @return
*/
@RequestMapping(value="/all", method=DELETE)
@PreAuthorize("hasAuthority('ADMIN')")
public @ResponseBody String deleteAllHostNames() {
String result;
log.info("Detected endpoint /hostnames/all for deleteAllHostNames at {}", dateFormat.format(new Date()));
......@@ -105,6 +107,7 @@ public class HostNameEndpoint {
}
@RequestMapping( value = "/remoteHostNames/update/dpmt/all", method = RequestMethod.PUT)
@PreAuthorize("hasAuthority('ADMIN') ")
public String updateHostNamesFromDPMT() {
String resultMsg;
Integer updatesMade = 0;
......@@ -115,6 +118,7 @@ public class HostNameEndpoint {
}
@RequestMapping( value = "/remoteHostNames/update/all", method = RequestMethod.PUT)
@PreAuthorize("hasAuthority('ADMIN')")
public String checkForUpdates() {
String resultMsg;
log.info("Detected endpoint /remoteHostNames/update/all for checkForUpdates at {}", dateFormat.format(new Date()));
......
......@@ -74,6 +74,7 @@ public class ServiceComponentEndpoint {
* @return
*/
@RequestMapping(value="/{hostNameId}/add", method=POST)
@PreAuthorize("hasAuthority('ADMIN') ")
public @ResponseBody ServiceComponent addNewServiceComponent (@PathVariable("hostNameId") String hostNameID, @RequestBody ServiceComponentDTO servCompDTO) {
log.info("Detected endpoint /{hostNameId}/add for addNewServiceComponent with: "+hostNameID+" hostNameID at {}", dateFormat.format(new Date()));
ServiceComponent servComp = null;
......@@ -149,6 +150,7 @@ public class ServiceComponentEndpoint {
*/
@PostMapping(value = "/jsonreport", consumes = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('API') ")
public ResponseEntity<JsonPakitiReport> createUser( @Valid @RequestBody final JsonPakitiReport report) {
this.servComponentController.saveJsonPakitiReport(report);
......@@ -192,6 +194,7 @@ public class ServiceComponentEndpoint {
/** TODO -- This should be deleted, its just a test endpoint **/
@RequestMapping(value = "/pakiti/report/test",method = RequestMethod.POST)
@PreAuthorize("hasAuthority('ADMIN')")
public String testRegex(@RequestParam Map<String, String> body){
System.out.println("Received test report");
//System.out.println(body.toString());
......@@ -203,6 +206,7 @@ public class ServiceComponentEndpoint {
* @return
*/
@RequestMapping(value="/all", method=GET)
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('USER') ")
public @ResponseBody Iterable<ServiceComponent> getAllServiceComponents() {
log.info("Detected endpoint /serviceComponent/all for getAllServiceComponents at: {}", dateFormat.format(new Date()));
return this.servComponentController.getAllServiceComponents();
......@@ -242,6 +246,7 @@ public class ServiceComponentEndpoint {
* @return
*/
@RequestMapping(value="/all", method=DELETE)
@PreAuthorize("hasAuthority('ADMIN')")
public @ResponseBody String deleteAllServiceComponents() {
log.info("Detected endpoint /serviceComponent/all for deleteAllServiceComponents at: {}", dateFormat.format(new Date()));
return this.servComponentController.deleteAllServiceComponents();
......
......@@ -175,6 +175,7 @@ public class UserRegistrationRestController {
@GetMapping("/me")
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('USER') ")
public ResponseEntity<UserSummary> listMe() {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
......@@ -200,6 +201,7 @@ public class UserRegistrationRestController {
@PutMapping(value="/me", consumes = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('USER') ")
public ResponseEntity<UserInfo> updateMe(@RequestBody UserInfo user) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
......
package svmon.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name = "userToken")
@Data
@NoArgsConstructor
public class UserCreatedToken {
@Id
@Column(name = "userid")
private Long id;
@Column(name = "toeknvalue")
@NotEmpty()
@Length(max=200)
private String token;
}
package svmon.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import svmon.model.UserCreatedToken;
public interface UserCreatedTokenJpaRepository extends JpaRepository<UserCreatedToken, Long> {
}
......@@ -8,6 +8,7 @@ import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.*;
import java.util.Calendar;
import java.util.Date;
......@@ -27,8 +28,10 @@ public class JwtTokenProvider {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
//Date now = new Date();
//Date expiryDate = new Date(now.getTime() + Long.valueOf(jwtExpirationInMs*1000));
//Calendar calendar = Calendar.getInstance();
Date expiryDate = calendarToExpireDate();
return Jwts.builder()
.setSubject(Long.toString(userPrincipal.getId()))
......@@ -64,4 +67,12 @@ public class JwtTokenProvider {
}
return false;
}
private Date calendarToExpireDate() {
Calendar calendar = Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
calendar.set(Calendar.YEAR, year+10);
Date date = calendar.getTime();
return date;
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment