Учебный проект по созданию базового функционала в springboot.
Внимание! в resources/certs/ лежат ключи *.pem. В настоящем проекте они должны быть добавлены в .gitignore!
Сущность - обычно подразумевается класс, отражающий таблицу из БД.
DTO - data transfer object. Паттерн, подразумевающий создание классов, инкапсулирующих в себя поля, которые необходимо получить, создать, обновить (create, read, update)
Mapper - класс, задающий правила автоматического преобразования сущности в DTO и обратно. Использует библиотеку mapstruct.
- Создание 100 юзеров при запуске приложения.
Необходимо:
- model:
User- структура для записи в БД - repository:
UserRepository- содержит CRUD для записи в БД - dto:
UserDTO,UserCreateDTO- указывают, какие поля необходимо заполнить для выполнения create, read, update. - mapper:
UserMapper- инкапсулирует код преобразования сущности в DTO и обратно. - component: опционально. Класс
DataInitializerPropertiesнужен для получения переменных из переменных окружения.DataInitializerProperties.getCount()Переменная из application.yml, позволет гибко задавать кол-во юзеров для генерации во время запуска приложения. - component:
DataInitializer- использует faker для создания юзеров.
- model:
- Частичное обновление PUT вместо PATCH - необязательно заполнять все поля для обновления сущности. При передаче поля со значением null - оно будет подставлено. Если же поле не передается, оно будет проигнорировано.
Необходимо:
- install dependency:
implementation("org.openapitools:jackson-databind-nullable:0.2.6") - create
UserUpdateDTOwithJsonNullablefields. - create config
JacksonConfigand write rules for mapping (UserMapper, etc). - create
JsonNullableMapperand added him toUserMapper. - create simple controllers
UserControllerfor updateUsermodel using API. - create service
UserServicefor encapsulation of business logic by separating it from http requests.
- install dependency:
- Подключен JPA Audit - автоматическая запись времени создания и обновления записи в БД.
Необходимо:
- set
@EnableJpaAuditingin classApplication. - modify
UserDTO. - modify
Usermodel, added fieldscreatedAtandupdatedAtwith@CreatedDateand@LastModifiedDate. - set @EntityListeners(AuditingEntityListener.class) on
Usermodel.
- set
- Перехват ошибок с помощью Advice.
Необходимо:
- create handler
GlobalExceptionHandler. - create exception
ResourceNotFoundException. - use this exception in controllers or service.
- create handler
- Поиск юзера по емайлу.
Необходимо:
- add
emailfield with@EmailinUsermodel. - add
findByEmailmethod inUserRepository. - add
getUserByEmailmethod inUserService. - add email in all user DTO's.
- add new controller.
- add
- Фильтрация и пагинация.
By default?page=1
Пример: http://localhost:8080/api/users?emailCont=is&&updatedAtGt=2024-03-23 20:18:56
Необходимо:
- update
getUsersinUserService. - update
getUsersinUserController. - add
JpaSpecificationExecutor<User>inUserRepository. - implements filter in
UserSpecification. - create
UserParamsDTOas filter params.
- update
- Авторизация.
Необходимо:
- install dependency.
- update
Usermodel, implementsUserDetails. - create
CustomUserDetailsServiceas CRUD for users. - add
passwordEncoderbean for hashing password inEncodersConfig. - create
SecurityConfigwhere usingpasswordEncoderandCustomUserDetailsService. - create
JWTUtilsfor generic jwt token. - create rsa keys and
RsaKeyProperties. Dont pushprivate.pemto git! This for only example.
# datafaker/src/main/resources/certs openssl genpkey -out private.pem -algorithm RSA -pkeyopt rsa_keygen_bits:2048 &&\ openssl rsa -in private.pem -pubout -out public.pem
- create
AuthRequestDTO - create
AuthenticationController. - add security filter for urls in
SecurityConfig. - create
UserUtilswithgetCurrentUsermethod for get authenticated user. - add
passwordDigestinUserCreateDTO. - add
encryptPasswordmethod inUserMapper. - check generate token.
curl -X POST -H "content-type:application/json" -d '{"username":"admin@admin.ru", "password": "123"}' http://localhost:8080/api/login
- check get users with token.
curl -H "content-type:application/json" -H "authorization:bearer <token>" http://localhost:8080/api/users
- install dependency.
Other commands (before create authentication):
Get all users
curl http://localhost:8080/api/usersGet user by id
curl http://localhost:8080/api/users/1Create User
curl -X POST -H "content-type:application/json" -d '{"firstName":"Bob", "lastName":"Marley"}' http://localhost:8080/api/usersPartial update user (JsonNullable)
curl -X PUT -H 'content-type:application/json' -d '{"lastName":"Hello"}' http://localhost:8080/api/users/1Full update user
curl -X PUT -H 'content-type:application/json' -d '{"firstName":"NewFirstName", "lastName":"NewLastName"}' http://localhost:8080/api/users/1