diff --git a/src/main/java/net/vesseldoc/server/ServerApplication.java b/src/main/java/net/vesseldoc/server/ServerApplication.java deleted file mode 100644 index de33563..0000000 --- a/src/main/java/net/vesseldoc/server/ServerApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.vesseldoc.server; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ServerApplication { - - public static void main(String[] args) { - SpringApplication.run(ServerApplication.class, args); - } - -} diff --git a/src/main/java/net/vesseldoc/server/config/JwtAuthenticationEntryPoint.java b/src/main/java/net/vesseldoc/server/config/JwtAuthenticationEntryPoint.java deleted file mode 100644 index 11c3961..0000000 --- a/src/main/java/net/vesseldoc/server/config/JwtAuthenticationEntryPoint.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.vesseldoc.server.config; - -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.Serializable; - -@Component -public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable { - - private static final long serialVersionUID = -7858869558953243875L; - - @Override - public void commence(HttpServletRequest request, HttpServletResponse response, - AuthenticationException authException) throws IOException { - - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/config/JwtRequestFilter.java b/src/main/java/net/vesseldoc/server/config/JwtRequestFilter.java deleted file mode 100644 index 2e95dad..0000000 --- a/src/main/java/net/vesseldoc/server/config/JwtRequestFilter.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.vesseldoc.server.config; - -import net.vesseldoc.server.service.JwtUserDetailsService; -import io.jsonwebtoken.ExpiredJwtException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -@Component -public class JwtRequestFilter extends OncePerRequestFilter { - - @Autowired - private JwtUserDetailsService jwtUserDetailsService; - - @Autowired - private JwtTokenUtil jwtTokenUtil; - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws ServletException, IOException { - - final String requestTokenHeader = request.getHeader("Authorization"); - - String username = null; - String jwtToken = null; - // JWT Token is in the form "Bearer token". Remove Bearer word and get - // only the Token - if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) { - jwtToken = requestTokenHeader.substring(7); - try { - username = jwtTokenUtil.getUsernameFromToken(jwtToken); - } catch (IllegalArgumentException e) { - System.out.println("Unable to get JWT Token"); - } catch (ExpiredJwtException e) { - System.out.println("JWT Token has expired"); - } - } else { - logger.warn("JWT Token does not begin with Bearer String"); - } - - // Once we get the token validate it. - if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { - - UserDetails userDetails = this.jwtUserDetailsService.loadUserByUsername(username); - - // if token is valid configure Spring Security to manually set - // authentication - if (jwtTokenUtil.validateToken(jwtToken, userDetails)) { - - UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( - userDetails, null, userDetails.getAuthorities()); - usernamePasswordAuthenticationToken - .setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - // After setting the Authentication in the context, we specify - // that the current user is authenticated. So it passes the - // Spring Security Configurations successfully. - SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); - } - } - chain.doFilter(request, response); - } - -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/config/JwtTokenUtil.java b/src/main/java/net/vesseldoc/server/config/JwtTokenUtil.java deleted file mode 100644 index 8938408..0000000 --- a/src/main/java/net/vesseldoc/server/config/JwtTokenUtil.java +++ /dev/null @@ -1,75 +0,0 @@ -package net.vesseldoc.server.config; - -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Component; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -@Component -public class JwtTokenUtil implements Serializable { - - private static final long serialVersionUID = -2550185165626007488L; - - public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; - - @Value("${jwt.secret}") - private String secret; - - //retrieve username from jwt token - public String getUsernameFromToken(String token) { - return getClaimFromToken(token, Claims::getSubject); - } - - //retrieve expiration date from jwt token - public Date getExpirationDateFromToken(String token) { - return getClaimFromToken(token, Claims::getExpiration); - } - - public T getClaimFromToken(String token, Function claimsResolver) { - final Claims claims = getAllClaimsFromToken(token); - return claimsResolver.apply(claims); - } - - //for retrieveing any information from token we will need the secret key - private Claims getAllClaimsFromToken(String token) { - return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); - } - - //check if the token has expired - private Boolean isTokenExpired(String token) { - final Date expiration = getExpirationDateFromToken(token); - return expiration.before(new Date()); - } - - //generate token for user - public String generateToken(UserDetails userDetails) { - Map claims = new HashMap<>(); - return doGenerateToken(claims, userDetails.getUsername()); - } - - //while creating the token - - //1. Define claims of the token, like Issuer, Expiration, Subject, and the ID - //2. Sign the JWT using the HS512 algorithm and secret key. - //3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1) - // compaction of the JWT to a URL-safe string - private String doGenerateToken(Map claims, String subject) { - - return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) - .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000)) - .signWith(SignatureAlgorithm.HS512, secret).compact(); - } - - //validate token - public Boolean validateToken(String token, UserDetails userDetails) { - final String username = getUsernameFromToken(token); - return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/config/WebSecurityConfig.java b/src/main/java/net/vesseldoc/server/config/WebSecurityConfig.java deleted file mode 100644 index 75d61f1..0000000 --- a/src/main/java/net/vesseldoc/server/config/WebSecurityConfig.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.vesseldoc.server.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - -@Configuration -@EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; - - @Autowired - private UserDetailsService jwtUserDetailsService; - - @Autowired - private JwtRequestFilter jwtRequestFilter; - - @Autowired - public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - // configure AuthenticationManager so that it knows from where to load - // user for matching credentials - // Use BCryptPasswordEncoder - auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder()); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Override - protected void configure(HttpSecurity httpSecurity) throws Exception { - // We don't need CSRF for this example - httpSecurity.csrf().disable() - // dont authenticate this particular request - .authorizeRequests().antMatchers("/authenticate", "/register").permitAll(). - // all other requests need to be authenticated - anyRequest().authenticated().and(). - // make sure we use stateless session; session won't be used to - // store user's state. - exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() - .sessionCreationPolicy(SessionCreationPolicy.STATELESS); - - // Add a filter to validate the tokens with every request - httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/controller/FormController.java b/src/main/java/net/vesseldoc/server/controller/FormController.java deleted file mode 100644 index 155fcad..0000000 --- a/src/main/java/net/vesseldoc/server/controller/FormController.java +++ /dev/null @@ -1,122 +0,0 @@ -package net.vesseldoc.server.controller; - -import net.vesseldoc.server.model.DAOUser; -import net.vesseldoc.server.service.FileService; -import net.vesseldoc.server.service.FormService; -import net.vesseldoc.server.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.http.HttpHeaders; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.util.List; - -@RestController -public class FormController { - - @Autowired - private UserService userService; - - @Autowired - private FormService formService; - - @Autowired - private FileService fileService; - - /** - * Creates a new empty form which is attached to a user and a Form structure. - * - * @param structureId ID of the form structure this form is based on. - * @return Form ID. - */ - @PostMapping(value = "/newForm") - public String newForm(@RequestParam("structure_id") long structureId) { - long userId = userService.getCurrentUser().getId(); - return formService.save(userId, structureId).toString(); - } - - /** - * Request to get a list of forms including info abouth them. - * - * @return Form list as json. - */ - @GetMapping(value = "/form/list") - public ResponseEntity>> getFormList() { - DAOUser user = userService.getCurrentUser(); - if (userService.currentUserHasHighAuthority()) { - return formService.getAllForms(); - } else { - return formService.getAllFormsByUser(user.getId()); - } - } - - /** - * Request to list all forms that is not signed. - * - * @return Form list as json. - */ - @GetMapping(value = "/form/list/notsigned") - public ResponseEntity>> getCurrentUsersForms() { - DAOUser user = userService.getCurrentUser(); - if (userService.currentUserHasHighAuthority()) { - return formService.getAllUnsigned(); - } else { - return formService.getAllUnsignedByUser(user.getId()); - } - } - - /** - * Request to get form content. - * - * @param formId form id. - * @return Form content as bytearray. - * @throws IOException if the file dont exist. - */ - @GetMapping(value = "/form/get/{formId:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}") - @ResponseBody - public ResponseEntity getFormFile(@PathVariable String formId) throws IOException { - ByteArrayResource file = new ByteArrayResource(fileService.getForm(formId)); - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; formId=\"" + formId + "\"") - .body(file); - } - - /** - * Request to upload form to a specified form id. - * - * @param file form content as bytearray. - * @param formId form id. - * @return Response to tell if the upload was successful. - * @throws IOException if the file cant be stored. - */ - @PostMapping(value = "/form/set") - public ResponseEntity uploadFormFile(@RequestParam("file") MultipartFile file, @RequestParam("id") String formId) throws IOException { - return fileService.storeForm(file, formId); - } - - /** - * Request for signing a form. - * User needs high authority to do this. - * - * @param formId form id. - * @return Response to tell if the signing was successful. - */ - @PostMapping(value = "/form/set/sign") - public ResponseEntity signForm(@RequestParam("form_id") String formId) { - return formService.signForm(formId); - } - - /** - * Request to check signed status of a specified form id. - * - * @param formId form id. - * @return Response to with status. True if it is signed, false if not. - */ - @GetMapping(value = "/form/get/signed/{formId:[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}}") - public ResponseEntity getSignedStatus(@PathVariable String formId) { - return ResponseEntity.ok(formService.isSigned(formId)); - } -} diff --git a/src/main/java/net/vesseldoc/server/controller/FormStructureController.java b/src/main/java/net/vesseldoc/server/controller/FormStructureController.java deleted file mode 100644 index 04542e1..0000000 --- a/src/main/java/net/vesseldoc/server/controller/FormStructureController.java +++ /dev/null @@ -1,52 +0,0 @@ -package net.vesseldoc.server.controller; - -import net.vesseldoc.server.service.FormStructureService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.util.List; - -@RestController -public class FormStructureController { - - @Autowired - private FormStructureService formStructureService; - - /** - * Request to get a list of all form structures. - * - * @return List of form structures as json. - */ - @GetMapping(value = "/structure/list") - public List> getAllInfo() { - return formStructureService.getAllInfo(); - } - - /** - * Request to get form structure content. - * - * @param structureId form structure id. - * @return Form structure content as bytearray. - */ - @GetMapping(value = "/structure/get/{structureId:[0-9]+}") - public byte[] getContent(@PathVariable long structureId) { - return formStructureService.getContent(structureId); - } - - /** - * Request to upload new form structure. - * Can only be done by a user with high authority. - * - * @param title form structure title. - * @param file form structure content as multipartfile. - * @return Form structure id. - * @throws IOException if data couldn't be stored. - */ - @PostMapping(value = "/structure/set") - public long uploadStructure(@RequestParam("title") String title, @RequestParam("content") MultipartFile file) throws IOException { - return formStructureService.saveStructure(title, file); - } - -} diff --git a/src/main/java/net/vesseldoc/server/controller/JwtAuthenticationController.java b/src/main/java/net/vesseldoc/server/controller/JwtAuthenticationController.java deleted file mode 100644 index 172e569..0000000 --- a/src/main/java/net/vesseldoc/server/controller/JwtAuthenticationController.java +++ /dev/null @@ -1,83 +0,0 @@ -package net.vesseldoc.server.controller; - -import net.vesseldoc.server.config.JwtTokenUtil; -import net.vesseldoc.server.model.JwtRequest; -import net.vesseldoc.server.model.JwtResponse; -import net.vesseldoc.server.model.UserDTO; -import net.vesseldoc.server.service.JwtUserDetailsService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.DisabledException; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.web.bind.annotation.*; - -@RestController -@CrossOrigin -public class JwtAuthenticationController { - - @Autowired - private AuthenticationManager authenticationManager; - - @Autowired - private JwtTokenUtil jwtTokenUtil; - - @Autowired - private JwtUserDetailsService userDetailsService; - - /** - * Request to log in and return a bearer token. - * - * @param authenticationRequest JwtRequest, which requires a username and a password. - * @return Response with bearer token. - * @throws Exception if username and password dont match. - */ - @RequestMapping(value = "/authenticate", method = RequestMethod.POST) - public ResponseEntity createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception { - - authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword()); - - final UserDetails userDetails = userDetailsService - .loadUserByUsername(authenticationRequest.getUsername()); - - final String token = jwtTokenUtil.generateToken(userDetails); - - return ResponseEntity.ok(new JwtResponse(token)); - } - - /** - * Request to register new user. - * - * @param user UserDTO, which requires a username and a password. - * @return Response with user information if it was successful. - * @throws Exception if user already exist or if username or password is empty. - */ - @RequestMapping(value = "/register", method = RequestMethod.POST) - public ResponseEntity saveUser(@RequestBody UserDTO user) throws Exception { - if (user.getUsername() == "" || user.getPassword() == "") { - return new ResponseEntity("username/password cannot be empty.", HttpStatus.BAD_REQUEST); - } - return ResponseEntity.ok(userDetailsService.save(user)); - } - - /** - * Authenticates with an authentication manager that have a set of checks. - * If one of these checks is triggered, then it returns a exception instead. - * - * @param username username. - * @param password password. - * @throws Exception if one of the checks is triggered. - */ - private void authenticate(String username, String password) throws Exception { - try { - authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); - } catch (DisabledException e) { - throw new Exception("USER_DISABLED", e); - } catch (BadCredentialsException e) { - throw new Exception("INVALID_CREDENTIALS", e); - } - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/controller/UserController.java b/src/main/java/net/vesseldoc/server/controller/UserController.java deleted file mode 100644 index 962f2db..0000000 --- a/src/main/java/net/vesseldoc/server/controller/UserController.java +++ /dev/null @@ -1,89 +0,0 @@ -package net.vesseldoc.server.controller; - -import net.vesseldoc.server.model.DAOUser; -import net.vesseldoc.server.service.UserService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -public class UserController { - - @Autowired - private UserService userService; - - /** - * Request to get details of the user that is currently logged in. - * - * @return user details as json. - */ - @GetMapping(value = "/user/get/details") - public DAOUser getUserDetails() { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - return userService.getUserDetails(auth.getName()); - } - - /** - * Request to get list of users including information about them. - * - * @return user list as json. - */ - @GetMapping(value = "/user/get/list") - public List getUserList() { - return userService.getAllUsers(); - } - - /** - * Request to change password. - * If username is specified, then it is required to have a high authority role. - * If no username is specified then the possword to the current logged in user is going to be changed. - * - * @param currentPassword current password. - * @param newPassword new password. - * @param username username. - * @return Response to tell if the password change was successful. - */ - @PostMapping(value = "/user/set/password") - public ResponseEntity changePassword(@RequestParam("current_password") String currentPassword, - @RequestParam("new_password") String newPassword, - @RequestParam(value = "username", required = false) String username) { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (username == null || username.equals("")) { - username = auth.getName(); - } - - return userService.changePassword(username, currentPassword, newPassword); - } - - /** - * Request to change role of a specified user. - * Can only be done by a user with high authority. - * - * @param username username. - * @param role role as string eg. 'ADMIN' or 'WORKER'. - * @return Response to tell iw the change was successful. - */ - @PostMapping(value = "/user/set/role") - public ResponseEntity setUserRole(@RequestParam("username") String username, - @RequestParam("role") String role) { - return userService.changeUserRole(username, role); - } - - /** - * Request to deactivate user. - * - * @param username username. - * @return Response to tell if the deactivation was successful. - */ - @PostMapping(value = "/user/set/deactivate") - public ResponseEntity deactivateUser(@RequestParam("username") String username) { - return userService.deactivateUser(username); - } -} diff --git a/src/main/java/net/vesseldoc/server/model/DAOUser.java b/src/main/java/net/vesseldoc/server/model/DAOUser.java deleted file mode 100644 index 8699353..0000000 --- a/src/main/java/net/vesseldoc/server/model/DAOUser.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.vesseldoc.server.model; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import javax.persistence.*; - -@Entity -@Table(name = "user") -public class DAOUser { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - - @Column - private String username; - - @Column - @JsonIgnore - private String password; - - @Column(name = "role_id") - private long roleId; - - private boolean active; - - public long getId() { - return id; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public long getRoleId() { - return roleId; - } - - public void setRoleId(long roleId) { - this.roleId = roleId; - } - - public boolean isActive() { - return active; - } - - public void setActive(boolean active) { - this.active = active; - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/model/Form.java b/src/main/java/net/vesseldoc/server/model/Form.java deleted file mode 100644 index 03c92de..0000000 --- a/src/main/java/net/vesseldoc/server/model/Form.java +++ /dev/null @@ -1,86 +0,0 @@ -package net.vesseldoc.server.model; - -import org.hibernate.annotations.CreationTimestamp; -import org.hibernate.annotations.GenericGenerator; - -import javax.persistence.*; -import java.util.Date; -import java.util.UUID; - -/** - * This is the Form object. - * If a new Form object is created, then hibernate will make sure it is placed in the connected databasse. - */ -@Entity -@Table(name = "form") -public class Form { - - /** - * https://thoughts-on-java.org/generate-uuids-primary-keys-hibernate/ - */ - @Id - @GeneratedValue(generator = "UUID") - @GenericGenerator( - name = "UUID", - strategy = "org.hibernate.id.UUIDGenerator" - ) - @Column(name = "id", updatable = false, nullable = false) - private UUID id; - - @Column(name = "user_id") - private long user_id; - - @Column(name = "form_structure_id") - private long form_structure_id; - - @CreationTimestamp - @Column(name = "creation_date") - @Temporal(TemporalType.TIMESTAMP) - private Date creationDate; - - @Column(name = "signed") - private boolean signed; - - @Column(name = "signed_user_id") - private long signedUserId; - - public UUID getId() { - return id; - } - - public Date getCreationDate() { - return creationDate; - } - - public long getUser_id() { - return user_id; - } - - public void setUser_id(long user_id) { - this.user_id = user_id; - } - - public long getForm_structure_id() { - return form_structure_id; - } - - public void setForm_structure_id(long form_structure_id) { - this.form_structure_id = form_structure_id; - } - - public boolean isSigned() { - return signed; - } - - public void setSigned(boolean signed) { - this.signed = signed; - } - - public long getSignedUserId() { - return signedUserId; - } - - public void setSignedUserId(long signedUserId) { - this.signedUserId = signedUserId; - } -} diff --git a/src/main/java/net/vesseldoc/server/model/FormStructure.java b/src/main/java/net/vesseldoc/server/model/FormStructure.java deleted file mode 100644 index 4fc19f9..0000000 --- a/src/main/java/net/vesseldoc/server/model/FormStructure.java +++ /dev/null @@ -1,41 +0,0 @@ -package net.vesseldoc.server.model; - -import javax.persistence.*; -import java.sql.Blob; - -@Entity -@Table(name = "form_structure") -public class FormStructure { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private long id; - - @Column(name = "title") - private String title; - - @Lob - @Column(name = "content", columnDefinition = "MEDIUMBLOB") - private byte[] content; - - public long getId() { - return id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public byte[] getContent() { - return content; - } - - public void setContent(byte[] content) { - this.content = content; - } -} diff --git a/src/main/java/net/vesseldoc/server/model/JwtRequest.java b/src/main/java/net/vesseldoc/server/model/JwtRequest.java deleted file mode 100644 index e3a2857..0000000 --- a/src/main/java/net/vesseldoc/server/model/JwtRequest.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.vesseldoc.server.model; - -import java.io.Serializable; - -public class JwtRequest implements Serializable { - - private static final long serialVersionUID = 5926468583005150707L; - - private String username; - private String password; - - //need default constructor for JSON Parsing - public JwtRequest() { - } - - public JwtRequest(String username, String password) { - this.setUsername(username); - this.setPassword(password); - } - - public String getUsername() { - return this.username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return this.password; - } - - public void setPassword(String password) { - this.password = password; - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/model/JwtResponse.java b/src/main/java/net/vesseldoc/server/model/JwtResponse.java deleted file mode 100644 index 1ae4679..0000000 --- a/src/main/java/net/vesseldoc/server/model/JwtResponse.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.vesseldoc.server.model; - -import java.io.Serializable; - -public class JwtResponse implements Serializable { - - private static final long serialVersionUID = -8091879091924046844L; - private final String jwttoken; - - public JwtResponse(String jwttoken) { - this.jwttoken = jwttoken; - } - - public String getToken() { - return this.jwttoken; - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/model/Role.java b/src/main/java/net/vesseldoc/server/model/Role.java deleted file mode 100644 index 10a3374..0000000 --- a/src/main/java/net/vesseldoc/server/model/Role.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.vesseldoc.server.model; - -import javax.persistence.*; - -@Entity -@Table(name = "role") -public class Role { - - @Id - private long id; - @Column - private String name; - - public long getId() { - return id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/src/main/java/net/vesseldoc/server/model/UserDTO.java b/src/main/java/net/vesseldoc/server/model/UserDTO.java deleted file mode 100644 index 72fba4f..0000000 --- a/src/main/java/net/vesseldoc/server/model/UserDTO.java +++ /dev/null @@ -1,22 +0,0 @@ -package net.vesseldoc.server.model; - -public class UserDTO { - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/repository/FormRepository.java b/src/main/java/net/vesseldoc/server/repository/FormRepository.java deleted file mode 100644 index 0cad0e3..0000000 --- a/src/main/java/net/vesseldoc/server/repository/FormRepository.java +++ /dev/null @@ -1,36 +0,0 @@ -package net.vesseldoc.server.repository; - -import net.vesseldoc.server.model.Form; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import java.util.List; -import java.util.UUID; - -/** - * FormRepository is used to connect directly with the database about Form related data, if needed. - */ -@Repository -public interface FormRepository extends JpaRepository { - - /** - * Gets the last form created by the given user. - * - * @param userId User ID - * @return Form ID of the last created form by given user. - */ - @Query(value = "SELECT id FROM form f1 WHERE f1.user_id=:userId " + - "AND f1.creation_date = (" + - "SELECT MAX(creation_date) FROM form f2 WHERE f2.user_id = f1.user_id" + - ")", nativeQuery = true) - byte[] getLatestFormId(long userId); - - @Query(value = "SELECT * FROM form WHERE user_id=:userId", nativeQuery = true) - List
getAllByUserId(long userId); - - @Query(value = "SELECT * FROM form", nativeQuery = true) - List getAll(); - - Form getById(UUID id); -} diff --git a/src/main/java/net/vesseldoc/server/repository/FormStructureRepository.java b/src/main/java/net/vesseldoc/server/repository/FormStructureRepository.java deleted file mode 100644 index 6183922..0000000 --- a/src/main/java/net/vesseldoc/server/repository/FormStructureRepository.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.vesseldoc.server.repository; - -import net.vesseldoc.server.model.FormStructure; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface FormStructureRepository extends JpaRepository { - - @Query(value = "SELECT * FROM form_structure", nativeQuery = true) - List getAll(); - - @Query(value = "SELECT content FROM form_structure WHERE id=:id", nativeQuery = true) - byte[] getContentById(long id); - - @Query(value = "SELECT MAX(id) FROM form_structure", nativeQuery = true) - long getLast(); -} diff --git a/src/main/java/net/vesseldoc/server/repository/RoleRepository.java b/src/main/java/net/vesseldoc/server/repository/RoleRepository.java deleted file mode 100644 index 2b8f24c..0000000 --- a/src/main/java/net/vesseldoc/server/repository/RoleRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.vesseldoc.server.repository; - -import net.vesseldoc.server.model.Role; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -@Repository -public interface RoleRepository extends CrudRepository { - - Role getRoleById(long id); - - Role getRoleByName(String name); -} diff --git a/src/main/java/net/vesseldoc/server/repository/UserRepository.java b/src/main/java/net/vesseldoc/server/repository/UserRepository.java deleted file mode 100644 index bc9ad52..0000000 --- a/src/main/java/net/vesseldoc/server/repository/UserRepository.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.vesseldoc.server.repository; - -import net.vesseldoc.server.model.DAOUser; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.CrudRepository; -import org.springframework.stereotype.Repository; - -import java.util.List; - -@Repository -public interface UserRepository extends CrudRepository { - - DAOUser findByUsername(String username); - - @Query(value = "SELECT * FROM user u WHERE username=:username AND active=1", nativeQuery = true) - DAOUser getUserDetails(String username); - - @Query(value = "SELECT * FROM user WHERE active=1", nativeQuery = true) - List getUserList(); - - DAOUser getDAOUserById(long userId); - -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/service/FileService.java b/src/main/java/net/vesseldoc/server/service/FileService.java deleted file mode 100644 index c8ada8a..0000000 --- a/src/main/java/net/vesseldoc/server/service/FileService.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.vesseldoc.server.service; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.text.SimpleDateFormat; - -@Service -public class FileService { - - @Autowired - private FormService formService; - - private String dir = "/var/vesseldoc/forms/"; - - /** - * Gets form file by a specified form id. - * - * @param uuid form id. - * @return file as bytearray. - * @throws IOException if file isn't found. - */ - public byte[] getForm(String uuid) throws IOException { - String date = new SimpleDateFormat("yyyyMMdd").format(formService.getForm(uuid).getCreationDate()); - File file = new File(dir + date + "/" + uuid); - return Files.readAllBytes(file.toPath()); - } - - /** - * Store a form file. - * - * @param file file as multipartfile. - * @param uuid form id. - * @return Response to give feedback if the file was successfully stored or not. - * @throws IOException if file couldn't be stored. - */ - public ResponseEntity storeForm(MultipartFile file, String uuid) throws IOException { - ResponseEntity response; - if (formService.isSigned(uuid)) { - response = ResponseEntity.status(HttpStatus.CONFLICT).body("Cannot update form when its already signed."); - } else { - String date = new SimpleDateFormat("yyyyMMdd").format(formService.getForm(uuid).getCreationDate()); - File path = new File(dir + date); - if (!path.exists()) { - path.mkdirs(); - } - Files.copy(file.getInputStream(), Paths.get(dir + date + "/" + uuid), StandardCopyOption.REPLACE_EXISTING); - response = ResponseEntity.ok("Form successfully saved!"); - } - - return response; - } - - /** - * Checks if there exist a file with to the given form id. - * - * @param uuid form id. - * @return true if it exists, false if not. - */ - public boolean formExists(String uuid) { - String date = new SimpleDateFormat("yyyyMMdd").format(formService.getForm(uuid).getCreationDate()); - File path = new File(dir + date); - return path.exists(); - } -} diff --git a/src/main/java/net/vesseldoc/server/service/FormService.java b/src/main/java/net/vesseldoc/server/service/FormService.java deleted file mode 100644 index 7a4741f..0000000 --- a/src/main/java/net/vesseldoc/server/service/FormService.java +++ /dev/null @@ -1,185 +0,0 @@ -package net.vesseldoc.server.service; - -import net.vesseldoc.server.model.Form; -import net.vesseldoc.server.repository.FormRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -import java.nio.ByteBuffer; -import java.util.*; - -@Service -public class FormService { - - @Autowired - private FormRepository formRepository; - - @Autowired - private UserService userService; - - @Autowired - private FileService fileService; - - @Autowired - private FormStructureService formStructureService; - - /** - * This creates a new form object, sends the information to the database and returns and ID. - * - * @param userId User ID - * @param structureId Form structure ID - * @return Form ID of the newly created form - */ - public UUID save(long userId, long structureId) { - Form form = new Form(); - form.setUser_id(userId); - form.setForm_structure_id(structureId); - - formRepository.save(form); - return getLatestFormByUser(userId); - } - - /** - * Gets the latest created Form ID by the given user. - * - * @param userId User ID - * @return Form ID - */ - public UUID getLatestFormByUser(long userId) { - byte[] uuidAsBytes = formRepository.getLatestFormId(userId); - ByteBuffer b = ByteBuffer.wrap(uuidAsBytes); - UUID uuid = new UUID(b.getLong(), b.getLong()); - return uuid; - } - - - /** - * Gets a list of all forms including structure title, form creator and name of user who signed it. - * - * @return form list. - */ - public ResponseEntity>> getAllForms() { - List dbContent = formRepository.getAll(); - List> list = new ArrayList>(); - Iterator it = dbContent.iterator(); - while (it.hasNext()) { - Form fs = it.next(); - String structureName = formStructureService.getFormStructure(fs.getForm_structure_id()).getTitle(); - String formOwnerUsername = userService.getUserDetails(fs.getUser_id()).getUsername(); - String signedUsername = userService.getUserDetails(fs.getSignedUserId()).getUsername(); - list.add(Arrays.asList(structureName, formOwnerUsername, signedUsername, fs)); - } - return ResponseEntity.ok(list); - } - - /** - * Gets a list of all unsigned forms. - * - * @return list of unsigned forms. - */ - public ResponseEntity>> getAllUnsigned() { - List dbContent = formRepository.getAll(); - List> list = new ArrayList>(); - Iterator it = dbContent.iterator(); - while (it.hasNext()) { - Form fs = it.next(); - if (!fs.isSigned()) { - String structureName = formStructureService.getFormStructure(fs.getForm_structure_id()).getTitle(); - String formOwnerUsername = userService.getUserDetails(fs.getUser_id()).getUsername(); - String signedUsername = userService.getUserDetails(fs.getSignedUserId()).getUsername(); - list.add(Arrays.asList(structureName, formOwnerUsername, signedUsername, fs)); - } - } - return ResponseEntity.ok(list); - } - - /** - * Gets a list of forms by a specified user. - * - * @param userId user id. - * @return lsit of forms. - */ - public ResponseEntity>> getAllFormsByUser(long userId) { - List dbContent = formRepository.getAllByUserId(userId); - List> list = new ArrayList>(); - Iterator it = dbContent.iterator(); - while (it.hasNext()) { - Form fs = it.next(); - String structureName = formStructureService.getFormStructure(fs.getForm_structure_id()).getTitle(); - String formOwnerUsername = userService.getUserDetails(fs.getUser_id()).getUsername(); - String signedUsername = userService.getUserDetails(fs.getSignedUserId()).getUsername(); - list.add(Arrays.asList(structureName, formOwnerUsername, signedUsername, fs)); - } - return ResponseEntity.ok(list); - - } - - /** - * Gets a list of unsigned for by a specified user. - * - * @param userId user id. - * @return list of forms. - */ - public ResponseEntity>> getAllUnsignedByUser(long userId) { - List dbContent = formRepository.getAllByUserId(userId); - List> list = new ArrayList>(); - Iterator it = dbContent.iterator(); - while (it.hasNext()) { - Form fs = it.next(); - if (!fs.isSigned()) { - String structureName = formStructureService.getFormStructure(fs.getForm_structure_id()).getTitle(); - String structureOwner = userService.getUserDetails(fs.getUser_id()).getUsername(); - list.add(Arrays.asList(structureName, structureOwner, fs)); - } - } - return ResponseEntity.ok(list); - } - - /** - * Gets a form object by a specified form id. - * - * @param uuid form id. - * @return form object. - */ - public Form getForm(String uuid) { - return formRepository.getById(UUID.fromString(uuid)); - } - - /** - * Signs a form. - * Current user needs high authority to sign. - * - * @param formId form id. - * @return Response to tell if the form was successfully signed or not. - */ - public ResponseEntity signForm(String formId) { - ResponseEntity response; - Form form = getForm(formId); - - if (!userService.getUserRole(userService.getCurrentUser().getUsername()).equals("ADMIN")) { - response = ResponseEntity.status(HttpStatus.FORBIDDEN).body("You are not permitted to do this!"); - } else if (form.isSigned()) { - response = ResponseEntity.status(HttpStatus.CONFLICT).body("Form is already signed."); - } else if (!fileService.formExists(formId)) { - response = ResponseEntity.status(HttpStatus.CONFLICT).body("Form is not filled yet."); - } else { - form.setSigned(true); - form.setSignedUserId(userService.getCurrentUser().getId()); - formRepository.save(form); - response = ResponseEntity.ok("Successfully signed the form!"); - } - return response; - } - - /** - * Checks if a form is signed. - * - * @param formId form id. - * @return true if signed, false if not signed. - */ - public boolean isSigned(String formId) { - return getForm(formId).isSigned(); - } -} diff --git a/src/main/java/net/vesseldoc/server/service/FormStructureService.java b/src/main/java/net/vesseldoc/server/service/FormStructureService.java deleted file mode 100644 index a0021be..0000000 --- a/src/main/java/net/vesseldoc/server/service/FormStructureService.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.vesseldoc.server.service; - -import net.vesseldoc.server.model.FormStructure; -import net.vesseldoc.server.repository.FormStructureRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -@Service -public class FormStructureService { - - @Autowired - private FormStructureRepository formStructureRepository; - - /** - * Gets a list of all form structures. - * - * @return list of form structures. - */ - public List> getAllInfo() { - List dbContent = formStructureRepository.getAll(); - List> list = new ArrayList>(); - Iterator it = dbContent.iterator(); - while (it.hasNext()) { - FormStructure fs = it.next(); - list.add(Arrays.asList(fs.getId(), fs.getTitle())); - } - return list; - } - - /** - * Gets content of a given form structure id. - * - * @param id form structure id: - * @return form structure content as bytearray. - */ - public byte[] getContent(long id) { - return formStructureRepository.getContentById(id); - } - - /** - * Saves a form structure and returns its id. - * - * @param title form structure title. - * @param file form structure content as multipartfile. - * @return form structure id. - * @throws IOException if file cant be saved. - */ - public long saveStructure(String title, MultipartFile file) throws IOException { - byte[] bytes = file.getBytes(); - FormStructure structure = new FormStructure(); - structure.setTitle(title); - structure.setContent(bytes); - - return formStructureRepository.save(structure).getId(); - } - - /** - * Gets form structure with info from database. - * - * @param id form structure id. - * @return form structure object. - */ - public FormStructure getFormStructure(long id) { - return formStructureRepository.getOne(id); - } -} diff --git a/src/main/java/net/vesseldoc/server/service/JwtUserDetailsService.java b/src/main/java/net/vesseldoc/server/service/JwtUserDetailsService.java deleted file mode 100644 index ac1d036..0000000 --- a/src/main/java/net/vesseldoc/server/service/JwtUserDetailsService.java +++ /dev/null @@ -1,61 +0,0 @@ -package net.vesseldoc.server.service; - -import net.vesseldoc.server.model.DAOUser; -import net.vesseldoc.server.model.Role; -import net.vesseldoc.server.model.UserDTO; -import net.vesseldoc.server.repository.RoleRepository; -import net.vesseldoc.server.repository.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; - -@Service -public class JwtUserDetailsService implements UserDetailsService { - - @Autowired - private UserRepository userRepository; - - @Autowired - private PasswordEncoder bcryptEncoder; - - @Autowired - private RoleRepository roleRepository; - - /** - * Loads user by username - * - * @return details of user. - */ - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - DAOUser user = userRepository.findByUsername(username); - if (user == null) { - throw new UsernameNotFoundException("User not found with username: " + username); - } else if (!user.isActive()) { - throw new UsernameNotFoundException("User with username " + username + " is deactivated."); - } - return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), - new ArrayList<>()); - } - - /** - * Saves the user - * - * @param user user - * @return user saved - */ - public DAOUser save(UserDTO user) { - DAOUser newUser = new DAOUser(); - newUser.setUsername(user.getUsername()); - newUser.setPassword(bcryptEncoder.encode(user.getPassword())); - newUser.setRoleId(roleRepository.getRoleByName("WORKER").getId()); - newUser.setActive(true); - - return userRepository.save(newUser); - } -} \ No newline at end of file diff --git a/src/main/java/net/vesseldoc/server/service/UserService.java b/src/main/java/net/vesseldoc/server/service/UserService.java deleted file mode 100644 index 8200a4b..0000000 --- a/src/main/java/net/vesseldoc/server/service/UserService.java +++ /dev/null @@ -1,173 +0,0 @@ -package net.vesseldoc.server.service; - -import net.vesseldoc.server.model.DAOUser; -import net.vesseldoc.server.repository.RoleRepository; -import net.vesseldoc.server.repository.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.crypto.bcrypt.BCrypt; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class UserService { - - @Autowired - private UserRepository repository; - - @Autowired - private RoleRepository roleRepository; - - @Autowired - private PasswordEncoder encoder; - - @Autowired - public UserService(UserRepository repository) { - this.repository = repository; - } - - - /** - * Get User object from database. - * - * @return user object. - */ - public DAOUser getUserDetails(String username) { - return repository.getUserDetails(username); - } - - public DAOUser getUserDetails(long id) { - return repository.getDAOUserById(id); - } - - /** - * Gets the User ID for the user that is currently logged in. - * - * @return user ID for current user that is logged in. - */ - public DAOUser getCurrentUser() { - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - return getUserDetails(auth.getName()); - } - - /** - * Checks if the user who is currently logged in has a role that has high authority. - * - * @return true if user is high authority. - */ - public boolean currentUserHasHighAuthority() { - DAOUser user = getCurrentUser(); - - if (getUserRole(user.getUsername()).equals("ADMIN")) { - return true; - } else if (getUserRole(user.getUsername()).equals("CAPTAIN")) { - return true; - } else { - return false; - } - } - - /** - * Lists all users in the database. - * - * @return all users. - */ - public List getAllUsers() { - return repository.getUserList(); - } - - /** - * Changes password for specified user if old password matches. - * - * @param username username of the user that sre having it's password changed. - * @param oldPassword existing password - * @param newPassword new password. - * @return response to tell if it was successfull or not. - */ - public ResponseEntity changePassword(String username, String oldPassword, String newPassword) { - DAOUser user = repository.getUserDetails(username); - - if (!currentUserHasHighAuthority() || !getCurrentUser().getUsername().equals(username)) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).body("You dont have permission to change this users password!"); - } else if (!BCrypt.checkpw(oldPassword, user.getPassword()) && !currentUserHasHighAuthority()) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Old password didn't match!"); - } else if (newPassword.equals(oldPassword)) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Can't change to the same password."); - } else { - user.setPassword(encoder.encode(newPassword)); - repository.save(user); - return ResponseEntity.ok("Successfully changed password!"); - } - - } - - /** - * Gets rolename of given user. - * - * @param username username. - * @return name of role. - */ - public String getUserRole(String username) { - return getRoleName(repository.getUserDetails(username).getRoleId()); - } - - public String getRoleName(long roleId) { - return roleRepository.getRoleById(roleId).getName(); - } - - /** - * Changes role of given user. - * Can only be changed by an user with high authority. - * An user cannot change its own role. - * - * @param username username. - * @param role new role. - * @return Response to tell if the change was successful. - */ - public ResponseEntity changeUserRole(String username, String role) { - ResponseEntity response; - Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - if (!currentUserHasHighAuthority()) { - response = ResponseEntity.status(HttpStatus.FORBIDDEN).body("You need admin permission to do that!"); - } else if (auth.getName().equals(username)) { - response = ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Cannot change own role."); - } else if (roleRepository.getRoleByName(role) == null) { - response = ResponseEntity.status(HttpStatus.CONFLICT).body("Role dont exist!"); - } else if (repository.findByUsername(username) == null) { - response = ResponseEntity.status(HttpStatus.CONFLICT).body("User dont exist!"); - } else if (repository.findByUsername(username).getRoleId() == roleRepository.getRoleByName(role).getId()) { - response = ResponseEntity.status(HttpStatus.CONFLICT).body("User already have that role!"); - } else { - DAOUser user = repository.findByUsername(username); - user.setRoleId(roleRepository.getRoleByName(role).getId()); - repository.save(user); - response = ResponseEntity.ok("Successfully changed users role!"); - } - return response; - } - - /** - * Deactivates given user. - * Can only be done by an user with high authority. - * - * @param username username. - * @return Response to tell if the deactivation was successful. - */ - public ResponseEntity deactivateUser(String username) { - if (!currentUserHasHighAuthority()) { - return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Current user is not allowed to do that."); - } else if (getUserDetails(username) == null) { - return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Given user does not exist."); - } else { - DAOUser user = getUserDetails(username); - user.setActive(false); - repository.save(user); - return ResponseEntity.ok("Successfully deactivated user."); - } - } -} diff --git a/src/main/resources/application.properties.template b/src/main/resources/application.properties.template deleted file mode 100644 index d33e162..0000000 --- a/src/main/resources/application.properties.template +++ /dev/null @@ -1,7 +0,0 @@ -jwt.secret=javainuse -spring.datasource.url=jdbc:mysql:// -spring.datasource.username= -spring.datasource.password= -spring.datasource.platform=mysql -spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl -spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl \ No newline at end of file diff --git a/src/test/java/net/vesseldoc/server/ServerApplicationTest.java b/src/test/java/net/vesseldoc/server/ServerApplicationTest.java deleted file mode 100644 index 7d21285..0000000 --- a/src/test/java/net/vesseldoc/server/ServerApplicationTest.java +++ /dev/null @@ -1,360 +0,0 @@ -package net.vesseldoc.server; - -import io.jsonwebtoken.lang.Assert; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.UUID; - -import static java.nio.charset.StandardCharsets.UTF_8; - -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) -public class ServerApplicationTest { - - @LocalServerPort - private int port; - - static String token; - static String formId; - static String structureId; - - @Test - @Order(1) - void testLogin() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/authenticate"); - - String boundary = UUID.randomUUID().toString(); - c = (HttpURLConnection) url.openConnection(); - - String username = "test1"; - String password = "test1"; - /* - String userpass = username + ":" + password; - String basicAuth = "Basic :" + new String(Base64.getEncoder().encode(userpass.getBytes())); - c.setRequestProperty("Authorization", basicAuth); - - */ - - c.setDoOutput(true); - c.setRequestMethod("POST"); - c.setRequestProperty("Content-Type", "application/json;charset=UTF-8;boundary=----WebKitFormBoundary" + boundary); - - DataOutputStream request = new DataOutputStream(c.getOutputStream()); - - request.writeBytes("{\n" + - "\"username\" : \"" + username + "\",\n" + - "\"password\" : \"" + password + "\"\n" + - "}"); - - request.flush(); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), UTF_8)); - String response = br.readLine(); - System.out.println("Response: " + response); - - String[] splitted = response.split("\""); - token = splitted[3]; - System.out.println("Token : " + token); - - boolean match = token.matches("^[a-zA-Z0-9._-]+$"); - Assert.isTrue(match, "Did not return token."); - } else { - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), UTF_8)); - String response = br.readLine(); - System.out.println("Bad response: " + response); - } - - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(2) - void testAddNewForm() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/newForm?structure_id=1"); - - String boundary = UUID.randomUUID().toString(); - c = (HttpURLConnection) url.openConnection(); - - System.out.println("Adding new form with token: " + token); - - c.setDoOutput(true); - c.setRequestMethod("POST"); - c.setRequestProperty("Content-Type", "multipart/form-data;charset=UTF-8;boundary=----WebKitFormBoundary" + boundary); - c.setRequestProperty("Authorization", "Bearer " + token); - - DataOutputStream request = new DataOutputStream(c.getOutputStream()); - - request.writeBytes("------WebKitFormBoundary" + boundary + "\r\n"); - request.writeBytes("Content-Disposition: form-data; name=\"structure_id\"\r\n"); - request.writeBytes("Content-Type: text/plain\r\n\r\n"); - request.writeBytes(1 + "\r\n"); - - request.writeBytes("------WebKitFormBoundary" + boundary + "--\r\n"); - request.flush(); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), UTF_8)); - String response = br.readLine(); - System.out.println("Response: " + response); - boolean match = response.matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); - formId = response; - Assert.isTrue(match, "Did not return form id."); - } else { - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), UTF_8)); - String response = br.readLine(); - System.out.println("Bad response: " + response); - } - - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(3) - void testListUsersForms() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/getUsersForms"); - c = (HttpURLConnection) url.openConnection(); - c.setRequestMethod("GET"); - c.setRequestProperty("Authorization", "Bearer " + token); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), UTF_8)); - String response = br.readLine(); - System.out.println("Response: " + response); - - //boolean match = response.matches("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"); - //Assert.isTrue(match, "Did not return form id."); - } else { - BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), UTF_8)); - String response = br.readLine(); - System.out.println("Bad response: " + response); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(4) - void testGetNonexistenFile() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/form/get/" + formId); - c = (HttpURLConnection) url.openConnection(); - c.setRequestMethod("GET"); - c.setRequestProperty("Authorization", "Bearer " + token); - boolean match = c.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR; - Assert.isTrue(match, - "Should have gotten a 403 FORBIDDEN response"); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(5) - void testFormFileUpload() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/form/set/"); - String boundary = UUID.randomUUID().toString(); - c = (HttpURLConnection) url.openConnection(); - c.setDoOutput(true); - c.setRequestMethod("POST"); - c.setRequestProperty("Authorization", "Bearer " + token); - c.setRequestProperty("Content-Type", "multipart/form-data;charset=UTF-8;boundary=----WebKitFormBoundary" + boundary); - DataOutputStream request = new DataOutputStream(c.getOutputStream()); - - // ID - request.writeBytes("------WebKitFormBoundary" + boundary + "\r\n"); - request.writeBytes("Content-Disposition: form-data; name=\"id\"\r\n"); - request.writeBytes("Content-Type: text/plain\r\n\r\n"); - request.writeBytes(formId + "\r\n"); - - // File - request.writeBytes("------WebKitFormBoundary" + boundary + "\r\n"); - request.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"binary\"\r\n"); - request.writeBytes("Content-Type: application/octet-stream\r\n\r\n"); - request.write("Can we pretend that this is a file?".getBytes(UTF_8)); - request.writeBytes("\r\n"); - request.writeBytes("------WebKitFormBoundary" + boundary + "--\r\n"); - request.flush(); - boolean match = c.getResponseCode() == HttpURLConnection.HTTP_OK; - Assert.isTrue(match, "Something went wrong with the upload."); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(6) - void testGetExistentFile() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/form/get/" + formId); - c = (HttpURLConnection) url.openConnection(); - c.setRequestMethod("GET"); - c.setRequestProperty("Authorization", "Bearer " + token); - boolean match = c.getResponseCode() == HttpURLConnection.HTTP_OK; - Assert.isTrue(match, - "Should have gotten a 200 OK response"); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(c.getInputStream(), StandardCharsets.UTF_8)); - String response = bufferedReader.readLine(); - boolean match2 = response.matches("Can we pretend that this is a file\\?"); - Assert.isTrue(match2, "File didn't match"); - System.out.println("Response: " + response); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(7) - void testUploadStructure() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/structure/set"); - c = (HttpURLConnection) url.openConnection(); - c.setDoOutput(true); - c.setRequestMethod("POST"); - c.setRequestProperty("Authorization", "Bearer " + token); - String boundary = UUID.randomUUID().toString(); - c.setRequestProperty("Content-Type", "multipart/form-data;charset=UTF-8;boundary=----WebKitFormBoundary" + boundary); - DataOutputStream request = new DataOutputStream(c.getOutputStream()); - - // Title - request.writeBytes("------WebKitFormBoundary" + boundary + "\r\n"); - request.writeBytes("Content-Disposition: form-data; name=\"title\"\r\n"); - request.writeBytes("Content-Type: text/plain\r\n\r\n"); - request.writeBytes("Test structure 1" + "\r\n"); - - // File - request.writeBytes("------WebKitFormBoundary" + boundary + "\r\n"); - request.writeBytes("Content-Disposition: form-data; name=\"content\"; filename=\"binary\"\r\n"); - request.writeBytes("Content-Type: application/octet-stream\r\n\r\n"); - request.write(("{ \n" + - "'1' : 'Label 1',\n" + - "'2' : 'Label 2' \n" + - "}").getBytes(UTF_8)); - request.writeBytes("\r\n"); - request.writeBytes("------WebKitFormBoundary" + boundary + "--\r\n"); - request.flush(); - - boolean match = c.getResponseCode() == HttpURLConnection.HTTP_OK; - Assert.isTrue(match, - "Should have gotten a 200 OK response"); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(c.getInputStream(), StandardCharsets.UTF_8)); - String response = bufferedReader.readLine(); - System.out.println("Response: " + response); - structureId = response; - } - - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(8) - void testGetStructureList() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/structure/list"); - c = (HttpURLConnection) url.openConnection(); - c.setRequestMethod("GET"); - c.setRequestProperty("Authorization", "Bearer " + token); - boolean match = c.getResponseCode() == HttpURLConnection.HTTP_OK; - Assert.isTrue(match, - "Should have gotten a 200 OK response"); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(c.getInputStream(), StandardCharsets.UTF_8)); - String response = bufferedReader.readLine(); - System.out.println("Response: " + response); - - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } - - @Test - @Order(9) - void testGetStructureContent() { - HttpURLConnection c = null; - - try { - URL url = new URL("http://localhost:" + port + "/structure/get/" + structureId); - c = (HttpURLConnection) url.openConnection(); - c.setRequestMethod("GET"); - c.setRequestProperty("Authorization", "Bearer " + token); - boolean match = c.getResponseCode() == HttpURLConnection.HTTP_OK; - Assert.isTrue(match, - "Should have gotten a 200 OK response"); - - if (c.getResponseCode() == HttpURLConnection.HTTP_OK) { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(c.getInputStream(), StandardCharsets.UTF_8)); - System.out.println("Response: "); - while (bufferedReader.ready()) { - System.out.println(bufferedReader.readLine()); - } - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (c != null) c.disconnect(); - } - } -}