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
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package ru.scamburger.Soundger.controllers;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.scamburger.Soundger.dto.UserCredentialsRequestDto;
import ru.scamburger.Soundger.service.RegisterService;

@RestController
@RequestMapping("/api")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/api/user

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок

public class RegisterServiceController {

private final RegisterService registerService;

public RegisterServiceController(RegisterService registerService) {
this.registerService = registerService;
}

@PostMapping("/register")
@Transactional
public ResponseEntity<String> register(@RequestBody UserCredentialsRequestDto userDto) {
if (registerService.doRegister(userDto.getUsername(), userDto.getPassword())) {
return new ResponseEntity<>("User create", HttpStatus.OK);
} else {
return new ResponseEntity<>("Username exist on server", HttpStatus.CONFLICT);
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

при удачной регистрации нужно вернуть в ответе новоиспеченного юзера (в json)

нужна будет новая dto, т.к. нельзя отдавай сущность из базы as-is (как есть), потому что там может быть секретная инфа (по типу пароля, например)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ладно

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bubuntoid
Пока у нас нету у User'a никаких полей кроме логина и пароля и id
DTO с какими данными мне возвращать

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давай логин, айди и токен


}
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
package ru.scamburger.Soundger.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.scamburger.Soundger.dto.AuthTokenResponseDto;
import ru.scamburger.Soundger.dto.UserCredentialsRequestDto;
import ru.scamburger.Soundger.exception.UnauthorizedException;
import ru.scamburger.Soundger.service.AuthService;
import ru.scamburger.Soundger.annotation.Authorized;
import ru.scamburger.Soundger.entity.User;
import ru.scamburger.Soundger.service.RegisterService;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
Expand All @@ -30,41 +38,29 @@ public User deleteUser() {
return new User();
}

//Контролер для теста создания Юзера
@GetMapping("/addUser")
@Transactional
public String addUser() {
User user=new User();
user.setUsername("root");
user.setPassword("xfk1ZvguvewaSSNvTqqOCNjv0gEZuym3m21JnHNK9YBFTsGg15ri5xWd1oOPVVtY");
entityManager.merge(user);
return "I hate java";
}

@GetMapping("/addauthtoken")
public String testAuth(){
public String testAuth() {
try {
authService.authorize("root","root");
authService.authorize("root", "root");
} catch (UnauthorizedException e) {
e.getStackTrace();
return "Unauthorized";
e.getStackTrace();
return "Unauthorized";
}
return "token added";
}

@GetMapping("/testfindauth")
public String findAuthToken(){
if(!authService.isAuthorized("342af481-e953-44c3-974f-8151717b06c1")){
public String findAuthToken() {
if (!authService.isAuthorized("342af481-e953-44c3-974f-8151717b06c1")) {
return "false account not expired";
}
else {
} else {
return "true or exception,account expired";
}
}

@GetMapping("/logout")
@Authorized
public String logout(){
public String logout() {
try {
authService.logout();
} catch (UnauthorizedException e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package ru.scamburger.Soundger.service;

public interface RegisterService {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UserService

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок

boolean doRegister(String username, String password);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

возвращаемый тип должен быть User

метод предлагаю переименовать в registerUser()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package ru.scamburger.Soundger.service;

import org.jasypt.util.password.PasswordEncryptor;
import org.springframework.stereotype.Service;
import ru.scamburger.Soundger.dao.AuthTokenDao;
import ru.scamburger.Soundger.entity.AuthToken;
import ru.scamburger.Soundger.entity.User;

import java.util.Date;
import java.util.UUID;

@Service
public class RegisterServiceImpl implements RegisterService {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

переименовать в след за UserService

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ок


private final int tokenLifetimeInMilliseconds = 1000 * 60 * 60 * 24;
private final PasswordEncryptor passwordEncryptor;
private final AuthTokenDao authTokenDao;

public RegisterServiceImpl(AuthTokenDao authTokenDao, PasswordEncryptor passwordEncryptor) {
this.authTokenDao = authTokenDao;
this.passwordEncryptor = passwordEncryptor;
}

@Override
public boolean doRegister(String username, String password) {
AuthToken authToken = new AuthToken();
authToken.setToken(UUID.randomUUID().toString());
authToken.setExpiredAt(new Date(new Date().getTime() + tokenLifetimeInMilliseconds));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

токен не нужен, т.к. юзер еще не авторизировался

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

он null должен быть в целом, тут по сути вообще никаких действий с этой сущностью (AuthToken) не должно быть

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мб в данном случае сделать как везде?
Когда регаешься на сайте у тебя также происходит первоначальная авторизация
Бесит такой момент когда зарегался а потом тебе ещё надо авторизироваться

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

окей, тогда не забудь в новое дто добавить соответствующее поле authToken или просто token

User user = new User();
user.setUsername(username);
user.setPassword(passwordEncryptor.encryptPassword(password));
authToken.setUser(user);
try {
authTokenDao.saveAuthToken(authToken);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

почему сохраняется authToken а не user?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Верхний тред чекни

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это то понятно, но стремно выходит, что логически ты должен сохранить юзера, а вызывается метод на сохранение токена, давай сделаем userDao.saveUser, он уже в свою очередь токен за собой подтянет (точно так же как saveAuthToken подтягивает юзера)

return true;
} catch (Exception e) {
throw e;
}
}
}