Skip to content
Open
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,5 @@ out/

### VS Code ###
.vscode/
application.yml
*.jar
62 changes: 45 additions & 17 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,33 +1,61 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.4'
id 'io.spring.dependency-management' version '1.1.3'
id 'java'
id 'org.springframework.boot' version '3.5.4'
id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.booleanuk'
version = '0.0.1'
sourceCompatibility = '17'
version = '0.0.1-SNAPSHOT'

java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}

configurations {
compileOnly {
extendsFrom annotationProcessor
}
compileOnly {
extendsFrom annotationProcessor
}
}

repositories {
mavenCentral()
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
implementation 'org.postgresql:postgresql:42.6.0'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'io.jsonwebtoken:jjwt-api:0.12.7'
implementation 'io.jsonwebtoken:jjwt-impl:0.12.7'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.7'

compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'

implementation 'jakarta.validation:jakarta.validation-api:3.1.1'
}

tasks.named('bootBuildImage') {
builder = 'paketobuildpacks/builder-jammy-base:latest'
}

tasks.named('test') {
useJUnitPlatform()
useJUnitPlatform()
}

jar {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest {
attributes 'Main-Class': 'com.booleanuk.api.cinema.Main'
}

from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
9 changes: 9 additions & 0 deletions dockers/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM mcr.microsoft.com/openjdk/jdk:21-ubuntu

WORKDIR /app

COPY java.docker.day.2-0.0.1-SNAPSHOT.jar java.docker.day.2-0.0.1-SNAPSHOT.jar

EXPOSE 4000

ENTRYPOINT [ "java", "-jar", "java.docker.day.2-0.0.1-SNAPSHOT.jar" ]
27 changes: 27 additions & 0 deletions dockers/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
services:
app:
image: 'theater:latest'
container_name: app
depends_on:
- db
ports:
- '4000:4000'
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/ #fill
- SPRING_DATASOURCE_USERNAME= #fill
- SPRING_DATASOURCE_PASSWORD= #fill
- SPRING_JPA_HIBERNATE_DDL_AUTO=update

db:
image: 'postgres:latest'
container_name: db
environment:
- POSTGRES_USER= #fill
- POSTGRES_DATABASE= #fill
- POSTGRES_PASSWORD= #fill
volumes:
- db_data:/var/lib/postgresql/data


volumes:
db_data:
34 changes: 34 additions & 0 deletions src/main/java/com/booleanuk/api/cinema/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.booleanuk.api.cinema;

import com.booleanuk.api.cinema.models.ERole;
import com.booleanuk.api.cinema.models.Role;
import com.booleanuk.api.cinema.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main implements CommandLineRunner {
@Autowired
private RoleRepository roleRepository;

public static void main(String[] args){
SpringApplication.run(Main.class, args);
}

@Override
public void run(String... args) {
if (this.roleRepository.findByName(ERole.ROLE_CUSTOMER).isEmpty()) {
this.roleRepository.save(new Role(ERole.ROLE_CUSTOMER));
}

if (this.roleRepository.findByName(ERole.ROLE_ADMIN).isEmpty()) {
this.roleRepository.save(new Role(ERole.ROLE_ADMIN));
}

if (this.roleRepository.findByName(ERole.ROLE_TICKETMASTER).isEmpty()) {
this.roleRepository.save(new Role(ERole.ROLE_TICKETMASTER));
}
}
}
100 changes: 100 additions & 0 deletions src/main/java/com/booleanuk/api/cinema/controllers/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.booleanuk.api.cinema.controllers;

import com.booleanuk.api.cinema.models.ERole;
import com.booleanuk.api.cinema.models.Role;
import com.booleanuk.api.cinema.models.User;
import com.booleanuk.api.cinema.payload.request.LoginRequest;
import com.booleanuk.api.cinema.payload.request.SignupRequest;
import com.booleanuk.api.cinema.payload.response.JwtResponse;
import com.booleanuk.api.cinema.payload.response.MessageResponse;
import com.booleanuk.api.cinema.repository.*;
import com.booleanuk.api.cinema.security.jwt.JwtUtils;
import com.booleanuk.api.cinema.security.services.UserDetailsImpl;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("auth")
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;

@Autowired
UserRepository userRepository;

@Autowired
RoleRepository roleRepository;

@Autowired
PasswordEncoder encoder;

@Autowired
JwtUtils jwtUtils;

@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
// If using a salt for password use it here
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtUtils.generateJwtToken(authentication);

UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
List<String> roles = userDetails.getAuthorities().stream().map((item) -> item.getAuthority())
.collect(Collectors.toList());
return ResponseEntity
.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles));
}

@PostMapping("/signup")
public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signupRequest) {
if (userRepository.existsByUsername(signupRequest.getUsername())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Username is already taken"));
}
if (userRepository.existsByEmail(signupRequest.getEmail())) {
return ResponseEntity.badRequest().body(new MessageResponse("Error: Email is already in use!"));
}
// Create a new user add salt here if using one
User user = new User(signupRequest.getUsername(), signupRequest.getEmail(), encoder.encode(signupRequest.getPassword()));
Set<String> strRoles = signupRequest.getRole();
Set<Role> roles = new HashSet<>();

if (strRoles == null) {
Role userRole = roleRepository.findByName(ERole.ROLE_CUSTOMER).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
roles.add(userRole);
} else {
strRoles.forEach((role) -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
roles.add(adminRole);
break;
case "ticketmaster":
Role ticketMasterRole = roleRepository.findByName(ERole.ROLE_TICKETMASTER).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
roles.add(ticketMasterRole);
break;
default:
Role customerRole = roleRepository.findByName(ERole.ROLE_CUSTOMER).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
roles.add(customerRole);
break;
}
});
}
user.setRoles(roles);
userRepository.save(user);
return ResponseEntity.ok((new MessageResponse("User registered successfully")));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.booleanuk.api.cinema.controllers;

import com.booleanuk.api.cinema.models.Customer;
import com.booleanuk.api.cinema.repository.CustomerRepository;
import com.booleanuk.api.cinema.payload.response.CustomerListResponse;
import com.booleanuk.api.cinema.payload.response.CustomerResponse;
import com.booleanuk.api.cinema.payload.response.ErrorResponse;
import com.booleanuk.api.cinema.payload.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("customers")
public class CustomerController {
@Autowired
private CustomerRepository customerRepository;

@GetMapping
public ResponseEntity<CustomerListResponse> getAllCustomers() {
CustomerListResponse customerListResponse = new CustomerListResponse();
customerListResponse.set(this.customerRepository.findAll());
return ResponseEntity.ok(customerListResponse);
}

@PostMapping
public ResponseEntity<Response<?>> createCustomer(@RequestBody Customer customer) {
CustomerResponse customerResponse = new CustomerResponse();
try {
customerResponse.set(this.customerRepository.save(customer));
} catch (Exception e) {
ErrorResponse error = new ErrorResponse();
error.set("Bad request");
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(customerResponse, HttpStatus.CREATED);
}

@GetMapping("/{id}")
public ResponseEntity<Response<?>> getCustomerById(@PathVariable int id) {
Customer customer = this.customerRepository.findById(id).orElse(null);
if (customer == null) {
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
CustomerResponse customerResponse = new CustomerResponse();
customerResponse.set(customer);
return ResponseEntity.ok(customerResponse);
}

@PutMapping("/{id}")
public ResponseEntity<Response<?>> updateCustomer(@PathVariable int id, @RequestBody Customer customer) {
Customer customerToUpdate = this.customerRepository.findById(id).orElse(null);
if (customerToUpdate == null) {
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
customerToUpdate.setEmail(customer.getEmail());
customerToUpdate.setName(customer.getName());
customerToUpdate.setPhone(customer.getPhone());

try {
customerToUpdate = this.customerRepository.save(customerToUpdate);
} catch (Exception e) {
ErrorResponse error = new ErrorResponse();
error.set("Bad request");
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
CustomerResponse customerResponse = new CustomerResponse();
customerResponse.set(customerToUpdate);
return new ResponseEntity<>(customerResponse, HttpStatus.CREATED);
}

@DeleteMapping("/{id}")
public ResponseEntity<Response<?>> deleteCustomer(@PathVariable int id) {
Customer customerToDelete = this.customerRepository.findById(id).orElse(null);
if (customerToDelete == null) {
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
this.customerRepository.delete(customerToDelete);
CustomerResponse customerResponse = new CustomerResponse();
customerResponse.set(customerToDelete);
return ResponseEntity.ok(customerResponse);
}
}
Loading