Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ipk 167 backend company setup #44

Merged
merged 6 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ services:
- data:/data
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 1234
MONGO_INITDB_ROOT_PASSWORD: pass

mongo-express:
image: mongo-express
Expand All @@ -53,7 +53,7 @@ services:
- mongodb
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: 1234
ME_CONFIG_MONGODB_ADMINPASSWORD: pass
ME_CONFIG_MONGODB_SERVER: mongodb

volumes:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
package com.MeetMate.experiments;
package com.MeetMate._experiments;

public @interface AuthenticationHeader {}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.MeetMate.experiments;
package com.MeetMate._experiments;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.MeetMate.experiments;
package com.MeetMate._experiments;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.MeetMate.experiments;
package com.MeetMate._experiments;

import com.MeetMate.user.User;
import lombok.RequiredArgsConstructor;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.MeetMate.experiments;
package com.MeetMate._experiments;

import com.MeetMate.user.User;
import com.MeetMate.user.UserRepository;
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/com/MeetMate/company/Company.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.MeetMate.company;

import com.MeetMate.enums.BusinessType;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "companies")
@Data
@NoArgsConstructor
public class Company {
private String name;
private String description;
private BusinessType businessType;
private String[] memberEmails;
@Indexed(unique = true)
private String ownerEmail;

public Company(String name, String ownerEmail) {
this.name = name;
this.ownerEmail = ownerEmail;
this.description = "";
this.businessType = null;
}
}
25 changes: 25 additions & 0 deletions src/main/java/com/MeetMate/company/CompanyConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//package com.MeetMate.company;
//
//import org.springframework.boot.CommandLineRunner;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//
//@Configuration
//public class CompanyConfig {
//
// @Bean
// public CommandLineRunner run(CompanyRepository companyRepository) throws Exception {
// return args -> {
// Company company = new Company();
// company.setId(1);
// company.setName("MeetMate");
// company.setDescription("A company that helps you meet your mates");
// company.setMembers(new long[]{1, 2, 3});
// company.setOwnerId(1);
//
// companyRepository.save(company);
// };
// }
//
//
//}
103 changes: 103 additions & 0 deletions src/main/java/com/MeetMate/company/CompanyController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package com.MeetMate.company;

import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.ContextValue;
import org.springframework.graphql.data.method.annotation.MutationMapping;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InaccessibleObjectException;

@RestController
@RequestMapping(path = "api/company")
@RequiredArgsConstructor
public class CompanyController {

private final CompanyService companyService;

@QueryMapping
public Company getCompany(@ContextValue(name = "token") String token) {
token = token.substring(7);
try {
return companyService.getCompany(token);

} catch (Throwable t) {
Class<? extends Throwable> tc = t.getClass();
return null;
// if (tc == EntityNotFoundException.class)
// return ResponseEntity.status(HttpStatus.NOT_FOUND).body("message: " + t.getMessage());
//
// if (tc == IllegalArgumentException.class)
// return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("message: " + t.getMessage());
//
// return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("message: " + t.getMessage());
}
}

@MutationMapping
public ResponseEntity<?> createCompany(
@Argument String companyName,
@Argument String ownerEmail,
@Argument String ownerName,
@Argument String ownerPassword) {
try {
companyService.createCompany(companyName, ownerEmail, ownerName, ownerPassword);
return ResponseEntity.ok().build();

} catch (Throwable t) {
Class<? extends Throwable> tc = t.getClass();
if (tc == InaccessibleObjectException.class)
return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).body("message: " + t.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("message: " + t.getMessage());
}
}

@MutationMapping
public ResponseEntity<?> editCompany(
@ContextValue String token,
@Argument String companyName,
@Argument String description,
@Argument String businessType) {
token = token.substring(7);
try {
companyService.editCompany(token, companyName, description, businessType);
return ResponseEntity.ok().build();
} catch (Throwable t) {
Class<? extends Throwable> tc = t.getClass();

if (tc == EntityNotFoundException.class)
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("message: " + t.getMessage());

if (tc == IllegalArgumentException.class)
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("message: " + t.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("message: " + t.getMessage());
}
}

@MutationMapping
public ResponseEntity<?> deleteCompany(@ContextValue String token) {
token = token.substring(7);
try {
companyService.deleteCompany(token);
return ResponseEntity.ok().build();

} catch (Throwable t) {
Class<? extends Throwable> tc = t.getClass();
if (tc == EntityNotFoundException.class)
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("message: " + t.getMessage());

if (tc == IllegalArgumentException.class)
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("message: " + t.getMessage());

return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("message: " + t.getMessage());
}
}

}
19 changes: 19 additions & 0 deletions src/main/java/com/MeetMate/company/CompanyRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.MeetMate.company;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface CompanyRepository extends MongoRepository<Company, Long> {

Optional<Company> findCompanyByOwnerEmail(String ownerEmail);

// @Modifying
// @Query("{ 'ownerEmail': :#{#ownerEmail} }")
// Company updateByOwnerEmail(String ownerEmail);
}
83 changes: 83 additions & 0 deletions src/main/java/com/MeetMate/company/CompanyService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.MeetMate.company;

import com.MeetMate.enums.BusinessType;
import com.MeetMate.enums.UserRole;
import com.MeetMate.security.JwtService;
import com.MeetMate.user.UserController;
import com.MeetMate.user.UserRepository;
import jakarta.persistence.EntityNotFoundException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

@Service
@RequiredArgsConstructor
public class CompanyService {

private final UserController userController;
private final UserRepository userRepository;
private final CompanyRepository companyRepository;
private final JwtService jwtService;
private final MongoTemplate mongoTemplate;

public Company getCompany(String token) throws IllegalArgumentException {
String ownerEmail = jwtService.extractUserEmail(token);

//Test if user is a company owner
if (userRepository.findUserByEmail(ownerEmail)
.orElseThrow(() -> new EntityNotFoundException("User not found!"))
.getRole() != UserRole.COMPANY_OWNER)
throw new IllegalArgumentException("User is not a company owner");

return companyRepository.findCompanyByOwnerEmail(ownerEmail)
.orElseThrow(() -> new EntityNotFoundException("Company not found"));
}

@Transactional
public void createCompany(String companyName, String ownerEmail, String ownerName, String ownerPassword) {
//Create the company owner
MultiValueMap<String, String> ownerData = new LinkedMultiValueMap<>();
ownerData.add("email", ownerEmail);
ownerData.add("name", ownerName);
ownerData.add("password", ownerPassword);
ownerData.add("role", UserRole.COMPANY_OWNER.toString());

userController.registerNewUser(ownerData);

companyRepository.save(new Company(companyName, ownerEmail));
}

@Transactional
public void editCompany(String token, String companyName, String description, String businessType) {
Company company = getCompany(token);
String ownerEmail = jwtService.extractUserEmail(token);
// if(companyName != null) company.setName(companyName);
// if(description != null) company.setDescription(description);
// if(businessType != null) company.setBusinessType(BusinessType.valueOf(businessType));
// companyRepository.save(company);

Query query = new Query(Criteria.where("ownerEmail").is(ownerEmail));
Update update = new Update();
if (companyName != null) update.set("name", companyName);
if (description != null) update.set("description", description);
if (businessType != null) update.set("businessType", BusinessType.valueOf(businessType));
mongoTemplate.updateFirst(query, update, Company.class);
}

@Transactional
public void deleteCompany(String token) {
Company company = getCompany(token);
try {
userController.deleteUser(token);
} catch (Throwable t) {
return;
}
companyRepository.delete(company);
}
}
5 changes: 5 additions & 0 deletions src/main/java/com/MeetMate/enums/BusinessType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.MeetMate.enums;

public enum BusinessType {

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.MeetMate.roles;
package com.MeetMate.enums;

public enum Role {
public enum UserRole {
ADMIN,
CLIENT,
COMPANY_OWNER,
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/MeetMate/response/GetResponse.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package com.MeetMate.response;

import com.MeetMate.roles.Role;
import com.MeetMate.enums.UserRole;
import java.time.LocalDate;
import lombok.AllArgsConstructor;
import lombok.Builder;
Expand All @@ -15,5 +15,5 @@ public class GetResponse {
String name;
LocalDate created_at;
String email;
Role role;
UserRole role;
}
11 changes: 9 additions & 2 deletions src/main/java/com/MeetMate/security/JwtService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.MeetMate.security;

import com.MeetMate.experiments.Experimentational;
import com.MeetMate._experiments.Experimentational;
import com.MeetMate.enums.UserRole;
import com.MeetMate.user.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
Expand Down Expand Up @@ -53,11 +54,17 @@ public String generateRefreshToken(User user) throws EntityNotFoundException {
.compact();
}

// Claims::getSubject
public String extractUserEmail(String token) {
return extractClaim(token, Claims::getSubject);
}

public long extractCompanyId(String token) {
Claims claims = extractAllClaims(token);
if(claims.get("role").equals(UserRole.COMPANY_OWNER.toString()))
return (long) claims.get("companyId");
throw new IllegalArgumentException("User is not a company owner");
}

@Experimentational
@SuppressWarnings("unchecked")
public <ContentType> ContentType extractClaimGeneric(String claimName, String token) {
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/com/MeetMate/security/RequestHeaderInterceptor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.MeetMate.security;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.graphql.server.WebGraphQlInterceptor;
import org.springframework.graphql.server.WebGraphQlRequest;
import org.springframework.graphql.server.WebGraphQlResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Collections;
//https://stackoverflow.com/questions/77649095/java-21-with-spring-boot-3-2-and-webflux-unable-to-get-headers-from-graphql-requ
@Component
public class RequestHeaderInterceptor implements WebGraphQlInterceptor {

@Override
public Mono<WebGraphQlResponse> intercept(WebGraphQlRequest request, Chain chain) {
String value = request.getHeaders().getFirst("Authorization");
if (value != null) {
request.configureExecutionInput((executionInput, builder) ->
builder.graphQLContext(Collections.singletonMap("token", value)).build());
}
return chain.next(request);
}
}
Loading
Loading