Skip to content

Commit

Permalink
Merge pull request #31 from kaizerpwn/feature/auth
Browse files Browse the repository at this point in the history
Authentication code separated to AuthService
  • Loading branch information
kaizerpwn authored Mar 26, 2024
2 parents 53d9541 + 6dd30c5 commit 859b246
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 55 deletions.
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package com.ibrahimokic.ordermanagement.controller.api;

import com.ibrahimokic.ordermanagement.domain.dto.api.LoginRequest;
import com.ibrahimokic.ordermanagement.domain.dto.api.LoginResponse;
import com.ibrahimokic.ordermanagement.domain.entity.User;
import com.ibrahimokic.ordermanagement.domain.dto.UserDto;
import com.ibrahimokic.ordermanagement.mapper.Mapper;
import com.ibrahimokic.ordermanagement.repository.UserRepository;
import com.ibrahimokic.ordermanagement.security.JwtIssuer;
import com.ibrahimokic.ordermanagement.service.AuthService;
import com.ibrahimokic.ordermanagement.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.ArraySchema;
Expand All @@ -15,11 +13,9 @@
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.hibernate.MappingException;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
Expand All @@ -36,9 +32,8 @@
@Tag(name = "User", description = "Operations related to users")
public class UserController {
private final UserService userService;
private final AuthService authService;
private final UserRepository userRepository;
private final Mapper<User, UserDto> userMapper;
private final JwtIssuer jwtIssuer;

@GetMapping
@Operation(summary = "Get all users", description = "Get list of all users")
Expand Down Expand Up @@ -76,32 +71,8 @@ public ResponseEntity<?> getUserById(@PathVariable Long userId) {
@ApiResponse(responseCode = "400", description = "Bad request", content = @Content),
@ApiResponse(responseCode = "500", description = "Internal server error", content = @Content)
})
public ResponseEntity<User> createUser(@RequestBody(required = false) @Valid UserDto userDto, HttpServletResponse response) {
try {
if (userDto == null) {
return ResponseEntity.badRequest().build();
}


User user = userMapper.mapFrom(userDto);
User createdUser = userService.createUser(user);

String accessToken = jwtIssuer.issue(
user.getUserId(),
user.getUsername(),
user.getRole()
);

Cookie cookie = new Cookie("accessToken", accessToken);
cookie.setHttpOnly(true);
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath("/");
response.addCookie(cookie);

return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
} catch (MappingException mappingException) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
public ResponseEntity<User> registerUser(@RequestBody(required = false) @Valid UserDto userDto, HttpServletResponse response) {
return authService.registerUser(userDto, response);
}

@PostMapping("/login")
Expand All @@ -113,28 +84,7 @@ public ResponseEntity<User> createUser(@RequestBody(required = false) @Valid Use
@ApiResponse(responseCode = "500", description = "Internal server error", content = @Content)
})
public ResponseEntity<?> loginUser(@Validated @RequestBody LoginRequest request, HttpServletResponse response) {
User user = userService.loginUser(request);
if (user != null) {
String accessToken = jwtIssuer.issue(
user.getUserId(),
request.getUsername(),
user.getRole()
);

Cookie cookie = new Cookie("accessToken", accessToken);
cookie.setHttpOnly(true);
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath("/");
response.addCookie(cookie);

return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.TEXT_PLAIN)
.body("Successfully logged in");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.contentType(MediaType.TEXT_PLAIN)
.body("Username and password does not match any user in the database");
}
return authService.loginUser(request, response);
}

@PatchMapping("/{userId}")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.ibrahimokic.ordermanagement.service;

import com.ibrahimokic.ordermanagement.domain.dto.UserDto;
import com.ibrahimokic.ordermanagement.domain.dto.api.LoginRequest;
import com.ibrahimokic.ordermanagement.domain.entity.User;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

public interface AuthService {
public ResponseEntity<?> loginUser(@Validated @RequestBody LoginRequest request, HttpServletResponse response);
public ResponseEntity<User> registerUser(@RequestBody(required = false) @Valid UserDto userDto, HttpServletResponse response);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.ibrahimokic.ordermanagement.service.impl;

import com.ibrahimokic.ordermanagement.domain.dto.UserDto;
import com.ibrahimokic.ordermanagement.domain.dto.api.LoginRequest;
import com.ibrahimokic.ordermanagement.domain.entity.User;
import com.ibrahimokic.ordermanagement.mapper.Mapper;
import com.ibrahimokic.ordermanagement.security.JwtIssuer;
import com.ibrahimokic.ordermanagement.service.AuthService;
import com.ibrahimokic.ordermanagement.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.hibernate.MappingException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
private final UserService userService;
private final JwtIssuer jwtIssuer;
private final Mapper<User, UserDto> userMapper;

@Override
public ResponseEntity<?> loginUser(LoginRequest request, HttpServletResponse response) {
User user = userService.loginUser(request);

if (user != null) {
String accessToken = jwtIssuer.issue(
user.getUserId(),
request.getUsername(),
user.getRole()
);

Cookie cookie = new Cookie("accessToken", accessToken);
cookie.setHttpOnly(true);
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath("/");
response.addCookie(cookie);

return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.TEXT_PLAIN)
.body("Successfully logged in");
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.contentType(MediaType.TEXT_PLAIN)
.body("Username and password does not match any user in the database");
}
}

@Override
public ResponseEntity<User> registerUser(UserDto userDto, HttpServletResponse response) {
try {
if (userDto == null) {
return ResponseEntity.badRequest().build();
}


User user = userMapper.mapFrom(userDto);
User createdUser = userService.createUser(user);

String accessToken = jwtIssuer.issue(
user.getUserId(),
user.getUsername(),
user.getRole()
);

Cookie cookie = new Cookie("accessToken", accessToken);
cookie.setHttpOnly(true);
cookie.setMaxAge(24 * 60 * 60);
cookie.setPath("/");
response.addCookie(cookie);

return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
} catch (MappingException mappingException) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}

0 comments on commit 859b246

Please sign in to comment.