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 @@ -36,3 +36,5 @@ out/

### VS Code ###
.vscode/

*.yml
23 changes: 16 additions & 7 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.1'
id 'org.springframework.boot' version '3.5.4'
id 'io.spring.dependency-management' version '1.1.5'
}

Expand All @@ -18,12 +18,21 @@ repositories {
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.postgresql:postgresql'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
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('test') {
Expand Down
2 changes: 1 addition & 1 deletion docs/extensions.html

Large diffs are not rendered by default.

35 changes: 35 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,35 @@
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.existsByName(ERole.ROLE_USER)){
this.roleRepository.save(new Role(ERole.ROLE_USER));
}
if (!this.roleRepository.existsByName(ERole.ROLE_ADMIN)){
this.roleRepository.save(new Role(ERole.ROLE_ADMIN));
}
if (!this.roleRepository.existsByName(ERole.ROLE_MODERATOR)){
this.roleRepository.save(new Role(ERole.ROLE_MODERATOR));
}
}

}

101 changes: 101 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,101 @@
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.RoleRepository;
import com.booleanuk.api.cinema.repository.UserRepository;
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_USER).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 "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
roles.add(modRole);
break;
default:
Role userRole = roleRepository.findByName(ERole.ROLE_USER).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
roles.add(userRole);
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,102 @@
package com.booleanuk.api.cinema.controllers;

import com.booleanuk.api.cinema.models.*;
import com.booleanuk.api.cinema.payload.response.*;
import com.booleanuk.api.cinema.repository.RoleRepository;
import com.booleanuk.api.cinema.repository.ScreeningRepository;
import com.booleanuk.api.cinema.repository.UserRepository;
import com.booleanuk.api.cinema.repository.TicketRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("customers")
public class CustomerController {
@Autowired
private UserRepository customerRepository;
@Autowired
private RoleRepository roleRepository;

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

public record PostUser(String name, String email, String phone) {}

@PostMapping
public ResponseEntity<Response<?>> createUser(@RequestBody PostUser request) {
CustomerResponse customerResponse = new CustomerResponse();
Role userRole = roleRepository.findByName(ERole.ROLE_USER).orElseThrow(() -> new RuntimeException("Error: Role is not found"));
User customer = new User(request.name(), request.email(), request.phone(), "password", userRole);
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<?>> getUserById(@PathVariable int id) {
User 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<?>> updateUser(@PathVariable int id, @RequestBody PostUser customer) {
User 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.setUsername(customer.name());
customerToUpdate.setEmail(customer.email());
customerToUpdate.setPhone(customer.phone());
customerToUpdate.setUpdatedAt(OffsetDateTime.now());

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<?>> deleteUser(@PathVariable int id) {
User 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