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
21 changes: 21 additions & 0 deletions Docker-compose/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
services:
app:
image: 'twitter-box:latest'
container_name: app
depends_on:
- db
ports:
- '4000:4000'
environment:
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/mypostgresuser
- SPRING_DATASOURCE_USERNAME=mypostgresuser
- SPRING_DATASOURCE_PASSWORD=mypostgrespassword
- SPRING_JPA_HIBERNATE_DDL_AUTO=update

db:
image: 'postgres:latest'
container_name: db
environment:
- POSTGRES_USER=mypostgresuser
- POSTGRES_DATABASE=mypostgresuser
- POSTGRES_PASSWORD=mypostgrespassword
30 changes: 24 additions & 6 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.1.4'
id 'io.spring.dependency-management' version '1.1.3'
id 'org.springframework.boot' version '3.4.2'
id 'io.spring.dependency-management' version '1.1.7'
}

group = 'com.booleanuk'
version = '0.0.1'
sourceCompatibility = '17'
version = '0.0.2'

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

configurations {
compileOnly {
Expand All @@ -20,14 +25,27 @@ repositories {

dependencies {
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.6'
implementation 'io.jsonwebtoken:jjwt-impl:0.12.6'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.6'

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

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

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

tasks.named('test') {
useJUnitPlatform()
}
}
32 changes: 32 additions & 0 deletions src/main/java/com/booleanuk/api/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.booleanuk.api;

import com.booleanuk.api.model.ERole;
import com.booleanuk.api.model.Role;
import com.booleanuk.api.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/controller/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.booleanuk.api.controller;

import com.booleanuk.api.model.ERole;
import com.booleanuk.api.model.Role;
import com.booleanuk.api.model.User;
import com.booleanuk.api.payload.request.LoginRequest;
import com.booleanuk.api.payload.request.SignupRequest;
import com.booleanuk.api.payload.response.JwtResponse;
import com.booleanuk.api.payload.response.MessageResponse;
import com.booleanuk.api.repository.RoleRepository;
import com.booleanuk.api.repository.UserRepository;
import com.booleanuk.api.security.jwt.JwtUtils;
import com.booleanuk.api.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")));
}
}
128 changes: 128 additions & 0 deletions src/main/java/com/booleanuk/api/controller/FollowerController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
package com.booleanuk.api.controller;

import com.booleanuk.api.model.*;
import com.booleanuk.api.payload.response.*;
import com.booleanuk.api.repository.FollowerRepository;
import com.booleanuk.api.repository.UserRepository;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
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("followers")
public class FollowerController {
@Autowired
private FollowerRepository followerRepository;

@Autowired
private UserRepository userRepository;

@GetMapping
public ResponseEntity<FollowerListResponse> getAllFollows() {
FollowerListResponse followerListResponse = new FollowerListResponse();
followerListResponse.set(this.followerRepository.findAll());
return ResponseEntity.ok(followerListResponse);
}

@PostMapping("/{u1}/follow/{u2}")
public ResponseEntity<Response<?>> follow(@RequestBody Follower follower, @PathVariable("u1") int u1, @PathVariable("u2") int u2) {
User user = this.userRepository.findById(u1).orElse(null);
User isfollowed = this.userRepository.findById(u2).orElse(null);

try {
if(user == null || isfollowed == null){
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}

for(Follower aFollower : this.followerRepository.findAll()){
if(aFollower.getIsFollowing().equals(user) && aFollower.getIsFollowed().equals(isfollowed)){
ErrorResponse error = new ErrorResponse();
error.set("Bad request");
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
}

follower.setIsFollowing(user);
follower.setIsFollowed(isfollowed);

FollowerResponse followerResponse = new FollowerResponse();
followerResponse.set(this.followerRepository.save(follower));

return new ResponseEntity<>(followerResponse, HttpStatus.CREATED);

} catch (Exception e) {
ErrorResponse error = new ErrorResponse();
error.set("Bad request");
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}
}





@DeleteMapping("/{u1}/unfollow/{u2}")
public ResponseEntity<Response<?>> unfollow(@PathVariable("u1") int u1, @PathVariable("u2") int u2) {
User user = this.userRepository.findById(u1).orElse(null);
User isfollowed = this.userRepository.findById(u2).orElse(null);

try {
if(user == null || isfollowed == null){
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}

for(Follower aFollower : this.followerRepository.findAll()){
if(aFollower.getIsFollowing().equals(user) && aFollower.getIsFollowed().equals(isfollowed)){
this.followerRepository.delete(aFollower);
FollowerResponse followerResponse = new FollowerResponse();
followerResponse.set(aFollower);
return ResponseEntity.ok(followerResponse);
}
}

ErrorResponse error = new ErrorResponse();
error.set("Bad request, user with ID" + u1 + "do not follow user with ID" + u2);
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);

} catch (Exception e) {
ErrorResponse error = new ErrorResponse();
error.set("Bad request");
return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
}

}

@GetMapping("{id}")
public ResponseEntity<?> getAllFollowsForSpecificUser(@PathVariable int id) {
User user = this.userRepository.findById(id).orElse(null);
if(user == null){
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}

FollowerListResponse followerListResponse = new FollowerListResponse();
followerListResponse.set(this.followerRepository.findAllIsFollowingByIsFollowed(user));
return ResponseEntity.ok(followerListResponse);
}

@GetMapping("follows/{id}")
public ResponseEntity<?> getAllFollowingForSpecificUser(@PathVariable int id) {
User user = this.userRepository.findById(id).orElse(null);
if(user == null){
ErrorResponse error = new ErrorResponse();
error.set("not found");
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}

FollowerListResponse followerListResponse = new FollowerListResponse();
followerListResponse.set(this.followerRepository.findAllIsFollowedByIsFollowing(user));
return ResponseEntity.ok(followerListResponse);
}
}
Loading