Skip to content

Commit 32d62f2

Browse files
committed
Add tests and fix implementation
Signed-off-by: montesm <[email protected]>
1 parent 787e4bd commit 32d62f2

File tree

6 files changed

+222
-40
lines changed

6 files changed

+222
-40
lines changed

UnityAuth/src/main/java/io/unityfoundation/auth/AuthController.java

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -105,27 +105,30 @@ public HttpResponse<HasPermissionResponse> hasPermission(@Body HasPermissionRequ
105105
}
106106

107107
@Get("/roles")
108-
public HttpResponse<?> getRoles() {
109-
return HttpResponse.ok(roleRepo.findAll());
108+
public HttpResponse<List<RoleDTO>> getRoles() {
109+
return HttpResponse.ok(roleRepo.findAll().stream()
110+
.map(role -> new RoleDTO(role.getId(), role.getName(), role.getDescription()))
111+
.toList());
110112
}
111113

112114
@Get("/tenants")
113-
public HttpResponse<?> getTenants(Authentication authentication) {
115+
public HttpResponse<List<TenantDTO>> getTenants(Authentication authentication) {
114116

115117
String authenticatedUserEmail = authentication.getName();
116118

117-
if(userRepo.existsByEmailAndRoleEqualsUnityAdmin(authenticatedUserEmail)) {
118-
return HttpResponse.ok(tenantRepo.findAll());
119-
}
119+
List<Tenant> tenants = userRepo.existsByEmailAndRoleEqualsUnityAdmin(authenticatedUserEmail) ?
120+
tenantRepo.findAll() : tenantRepo.findAllByUserEmail(authenticatedUserEmail);
120121

121-
return HttpResponse.ok(tenantRepo.findAllByUserEmail(authenticatedUserEmail));
122+
return HttpResponse.ok(tenants.stream()
123+
.map(tenant -> new TenantDTO(tenant.getId(), tenant.getName()))
124+
.toList());
122125
}
123126

124127
@Get("/tenants/{id}/users")
125128
public HttpResponse<List<UserResponse>> getTenantUsers(@PathVariable Long id, Authentication authentication) {
126129

127130
// reject if the declared tenant does not exist
128-
if (tenantRepo.existsById(id)) {
131+
if (!tenantRepo.existsById(id)) {
129132
return HttpResponse.badRequest();
130133
}
131134

@@ -185,25 +188,33 @@ private HttpResponse<HasPermissionResponse> createHasPermissionResponse(boolean
185188
return HttpResponse.ok(new HasPermissionResponse(hasPermission, userEmail, message, permissions));
186189
}
187190

191+
@Serdeable
192+
public record TenantDTO(
193+
Long id,
194+
String name
195+
) {}
196+
197+
@Serdeable
198+
public record RoleDTO(
199+
Long id,
200+
String name,
201+
String description
202+
) {}
203+
188204
@Serdeable
189205
public record HasPermissionResponse(
190206
boolean hasPermission,
191207
@Nullable String userEmail,
192208
@Nullable String errorMessage,
193209
List<String> permissions
194-
) {
195-
196-
}
210+
) {}
197211

198212
@Introspected
199213
public record TenantPermission(
200214
long tenantId,
201215
String permissionName,
202216
PermissionScope permissionScope
203-
204-
) {
205-
206-
}
217+
) {}
207218

208219

209220
public sealed interface UserPermissionsResponse {
@@ -215,8 +226,6 @@ record Failure(String errorMessage) implements UserPermissionsResponse {}
215226

216227
@Serdeable
217228
public record UserPermissionsRequest(@NotNull Long tenantId,
218-
@NotNull Long serviceId) {
219-
220-
}
229+
@NotNull Long serviceId) {}
221230

222231
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package io.unityfoundation.auth;
2+
3+
import jakarta.validation.Constraint;
4+
import jakarta.validation.Payload;
5+
6+
import java.lang.annotation.Documented;
7+
import java.lang.annotation.ElementType;
8+
import java.lang.annotation.Retention;
9+
import java.lang.annotation.Target;
10+
11+
import static java.lang.annotation.RetentionPolicy.RUNTIME;
12+
13+
@Target({ElementType.FIELD})
14+
@Retention(RUNTIME)
15+
@Documented
16+
@Constraint(validatedBy = NullOrNotBlankValidator.class)
17+
public @interface NullOrNotBlank {
18+
String message() default "{javax.validation.constraints.NullOrNotBlank.message}";
19+
Class<?>[] groups() default { };
20+
Class<? extends Payload>[] payload() default {};
21+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package io.unityfoundation.auth;
2+
3+
import jakarta.validation.ConstraintValidator;
4+
import jakarta.validation.ConstraintValidatorContext;
5+
6+
public class NullOrNotBlankValidator implements ConstraintValidator<NullOrNotBlank, String> {
7+
8+
@Override
9+
public boolean isValid(String value, ConstraintValidatorContext context) {
10+
return value == null || !value.trim().isEmpty();
11+
}
12+
}

UnityAuth/src/main/java/io/unityfoundation/auth/UserController.java

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io.micronaut.http.HttpResponse;
44
import io.micronaut.http.HttpStatus;
55
import io.micronaut.http.annotation.*;
6+
import io.micronaut.http.exceptions.HttpStatusException;
67
import io.micronaut.security.annotation.Secured;
78
import io.micronaut.security.authentication.Authentication;
89
import io.micronaut.security.rules.SecurityRule;
@@ -24,22 +25,24 @@ public class UserController {
2425
private final UserRepo userRepo;
2526
private final TenantRepo tenantRepo;
2627
private final RoleRepo roleRepo;
28+
private final PasswordEncoder passwordEncoder;
2729

28-
public UserController(UserRepo userRepo, TenantRepo tenantRepo, RoleRepo roleRepo) {
30+
public UserController(UserRepo userRepo, TenantRepo tenantRepo, RoleRepo roleRepo, PasswordEncoder passwordEncoder) {
2931
this.userRepo = userRepo;
3032
this.tenantRepo = tenantRepo;
3133
this.roleRepo = roleRepo;
34+
this.passwordEncoder = passwordEncoder;
3235
}
3336

3437
@Post
35-
public HttpResponse<?> createUser(@Body AddUserRequest requestDTO,
38+
public HttpResponse<UserResponse> createUser(@Body AddUserRequest requestDTO,
3639
Authentication authentication) {
3740

3841
Long requestTenantId = requestDTO.tenantId();
3942

4043
// reject if the declared tenant does not exist
41-
if (tenantRepo.existsById(requestTenantId)) {
42-
return HttpResponse.notFound("Tenant does not exist");
44+
if (!tenantRepo.existsById(requestTenantId)) {
45+
throw new HttpStatusException(HttpStatus.NOT_FOUND, "Tenant not found");
4346
}
4447

4548
Role unityAdministrator = roleRepo.findByName("Unity Administrator");
@@ -62,7 +65,7 @@ public HttpResponse<?> createUser(@Body AddUserRequest requestDTO,
6265

6366
// reject if new user already exists under a tenant
6467
if (userRepo.existsByEmailAndTenantId(requestDTO.email(), requestTenantId)) {
65-
return HttpResponse.badRequest("User already exists under declared tenant.");
68+
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "User already exists");
6669
}
6770

6871
// if the new user exists, create a new user-role entry
@@ -72,9 +75,9 @@ public HttpResponse<?> createUser(@Body AddUserRequest requestDTO,
7275
if (userOptional.isEmpty()) {
7376
User newUser = new User();
7477
newUser.setEmail(requestDTO.email());
75-
newUser.setPassword(requestDTO.password());
76-
newUser.setFirstName(requestDTO.firstName);
77-
newUser.setLastName(requestDTO.lastName);
78+
newUser.setPassword(passwordEncoder.encode(requestDTO.password()));
79+
newUser.setFirstName(requestDTO.firstName());
80+
newUser.setLastName(requestDTO.lastName());
7881
newUser.setStatus(User.UserStatus.ENABLED);
7982
user = userRepo.save(newUser);
8083
} else {
@@ -91,18 +94,18 @@ public HttpResponse<?> createUser(@Body AddUserRequest requestDTO,
9194
}
9295

9396
@Patch("{id}/roles")
94-
public HttpResponse<?> updateUserRoles(@PathVariable Long id, @Body UpdateUserRolesRequest requestDTO,
97+
public HttpResponse<UserResponse> updateUserRoles(@PathVariable Long id, @Body UpdateUserRolesRequest requestDTO,
9598
Authentication authentication) {
9699
Long requestTenantId = requestDTO.tenantId();
97100

98101
// reject if the declared tenant does not exist
99-
if (tenantRepo.existsById(requestTenantId)) {
100-
return HttpResponse.notFound("Tenant does not exist");
102+
if (!tenantRepo.existsById(requestTenantId)) {
103+
throw new HttpStatusException(HttpStatus.NOT_FOUND, "Tenant not found");
101104
}
102105

103106
Optional<User> userOptional = userRepo.findById(id);
104107
if (userOptional.isEmpty()) {
105-
return HttpResponse.notFound("User not found.");
108+
throw new HttpStatusException(HttpStatus.NOT_FOUND, "User not found");
106109
}
107110

108111
User user = userOptional.get();
@@ -126,7 +129,6 @@ public HttpResponse<?> updateUserRoles(@PathVariable Long id, @Body UpdateUserRo
126129

127130
applyRolesPatch(rolesIntersection, requestTenantId, user.getId());
128131

129-
// return updated user
130132
return HttpResponse.created(new UserResponse(user.getId(),
131133
user.getEmail(),
132134
user.getFirstName(),
@@ -150,17 +152,17 @@ public void applyRolesPatch(List<Long> requestRoles, Long requestTenantId, Long
150152
}
151153

152154
@Patch("{id}")
153-
public HttpResponse<?> selfPatch(@PathVariable Long id, @Body UpdateSelfRequest requestDTO,
155+
public HttpResponse<UserResponse> selfPatch(@PathVariable Long id, @Body UpdateSelfRequest requestDTO,
154156
Authentication authentication) {
155157

156158
Optional<User> userOptional = userRepo.findByEmail(authentication.getName());
157159
if (userOptional.isEmpty()) {
158-
return HttpResponse.notFound("User not found.");
160+
throw new HttpStatusException(HttpStatus.NOT_FOUND, "User not found");
159161
}
160162

161163
User user = userOptional.get();
162164
if (!Objects.equals(user.getId(), id)) {
163-
return HttpResponse.badRequest("User id mismatch.");
165+
throw new HttpStatusException(HttpStatus.BAD_REQUEST, "User id mismatch.");
164166
}
165167

166168
if (requestDTO.firstName != null) {
@@ -170,10 +172,10 @@ public HttpResponse<?> selfPatch(@PathVariable Long id, @Body UpdateSelfRequest
170172
user.setLastName(requestDTO.lastName);
171173
}
172174
if (requestDTO.password != null) {
173-
user.setPassword(requestDTO.password);
175+
user.setPassword(passwordEncoder.encode(requestDTO.password()));
174176
}
175177

176-
User saved = userRepo.save(user);
178+
User saved = userRepo.update(user);
177179
return HttpResponse.ok(new UserResponse(saved.getId(), saved.getEmail(), saved.getFirstName(), saved.getLastName(),
178180
userRepo.getUserRolesByUserId(saved.getId())));
179181
}
@@ -196,8 +198,8 @@ public record AddUserRequest(
196198

197199
@Serdeable
198200
public record UpdateSelfRequest(
199-
@NotBlank String firstName,
200-
@NotBlank String lastName,
201-
@NotBlank String password) {
201+
@NullOrNotBlank String firstName,
202+
@NullOrNotBlank String lastName,
203+
@NullOrNotBlank String password) {
202204
}
203205
}

0 commit comments

Comments
 (0)