Skip to content

Commit ea36348

Browse files
committed
dashboard: ready to merge, authentication
1 parent 18e44b5 commit ea36348

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

45 files changed

+1173
-345
lines changed

.DS_Store

0 Bytes
Binary file not shown.

client-mapl-dashboard/pom.xml

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,6 @@
3232
<lombok-mapstruct-binding.version>0.2.0</lombok-mapstruct-binding.version>
3333
</properties>
3434
<dependencies>
35-
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
36-
<dependency>
37-
<groupId>com.google.guava</groupId>
38-
<artifactId>guava</artifactId>
39-
<version>33.1.0-jre</version>
40-
</dependency>
4135

4236
<!--cloud -->
4337
<!-- <dependency>-->
@@ -106,12 +100,12 @@
106100
<artifactId>guava</artifactId>
107101
<version>31.0.1-jre</version>
108102
</dependency>
109-
<dependency>
110-
<groupId>org.springframework.boot</groupId>
111-
<artifactId>spring-boot-docker-compose</artifactId>
112-
<scope>runtime</scope>
113-
<optional>true</optional>
114-
</dependency>
103+
<!-- <dependency>-->
104+
<!-- <groupId>org.springframework.boot</groupId>-->
105+
<!-- <artifactId>spring-boot-docker-compose</artifactId>-->
106+
<!-- <scope>runtime</scope>-->
107+
<!-- <optional>true</optional>-->
108+
<!-- </dependency>-->
115109

116110
<dependency>
117111
<groupId>org.springframework.boot</groupId>

client-mapl-dashboard/src/main/java/app/mapl/BootstrapData.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import app.mapl.repositories.RoleEntityRepository;
1111
import app.mapl.repositories.UsersRepository;
1212
import app.mapl.repositories.WeblinksRepository;
13-
import app.mapl.util.ReadWriteFile;
13+
import app.mapl.util.FileReadWrite;
1414
import app.mapl.util.constants.Datum;
1515
import app.mapl.util.config.logger.CliLogger;
1616
import lombok.RequiredArgsConstructor;
@@ -148,8 +148,8 @@ void printBookmarks() {
148148
void writeUserData() throws IOException {
149149
for (User u : users) {
150150
System.out.println("|__________| WRITING USER TO FILE |_______| /n" + u);
151-
ReadWriteFile.writeUser(u);
152-
ReadWriteFile.writeUsers(users);
151+
FileReadWrite.writeUser(u);
152+
FileReadWrite.writeUsers(users);
153153
}
154154
}
155155

client-mapl-dashboard/src/main/java/app/mapl/FileDataStore.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import app.mapl.models.*;
66
import app.mapl.service.WeblinksService;
77
import app.mapl.util.DownloadSequential;
8-
import app.mapl.util.ReadWriteFile;
8+
import app.mapl.util.FileReadWrite;
99
import lombok.extern.slf4j.Slf4j;
1010
import org.springframework.stereotype.Component;
1111

@@ -18,7 +18,7 @@
1818

1919
@Slf4j
2020
@Component
21-
public class FileDataStore extends ReadWriteFile {
21+
public class FileDataStore extends FileReadWrite {
2222
WeblinksService bookmarks;
2323
FileDataStore(WeblinksService bookmarkservice) {
2424
this.bookmarks = bookmarkservice;
@@ -59,7 +59,7 @@ public static void loadData() throws FileNotFoundException, UnsupportedEncodingE
5959
static List<User> loadUsers() throws FileNotFoundException, UnsupportedEncodingException {
6060
// users[0] = UserManager.getInstance().createUser(500, "user0", "password", "Smith", "Tom", UserType.USER, "[email protected]", "5055087707" ,"http://www.dailytech.net", "1000");
6161
List<String> data = new ArrayList<>();
62-
ReadWriteFile.readFromFilename(data, FILE_IN_USERS);
62+
FileReadWrite.readFromFilename(data, FILE_IN_USERS);
6363
log.info("TEST_USERS::::::: "+FILE_IN_USERS+data.toString());
6464
for (String row : data) {
6565
String[] values = row.split(",");
@@ -85,7 +85,7 @@ static List<User> loadUsers() throws FileNotFoundException, UnsupportedEncodingE
8585
public static List<Weblink> loadWeblinks() throws FileNotFoundException, UnsupportedEncodingException {
8686
// bookmarks[0][0] = BookmarkManager.getInstance().createWeblink(2000, "http://www.javaworld.com/article/2072759/core-java/taming-tiger--part-2.html","http://www.javaworld.com" );
8787
List<String> data = new ArrayList<>();
88-
ReadWriteFile.readFromFilename(data, FILE_IN_WEBLINKS);
88+
FileReadWrite.readFromFilename(data, FILE_IN_WEBLINKS);
8989

9090
for (String row : data) {
9191
String[] values = row.split(",");
@@ -103,7 +103,7 @@ public static List<Weblink> loadWeblinks() throws FileNotFoundException, Unsuppo
103103
public static List<Coin> loadCoins() throws FileNotFoundException, UnsupportedEncodingException {
104104
// Coin coin1 = CoinManager.getInstance().createCoin(5000, CoinMake.TESLA, "Cyber-Truck", 37000.99, 0);
105105
List<String> data =new ArrayList<>();
106-
ReadWriteFile.readFromFilename(data, FILE_IN_COINS);
106+
FileReadWrite.readFromFilename(data, FILE_IN_COINS);
107107
for (String row: data) {
108108
String[] values = row.split(",");
109109
Coin coin = new Coin(Integer.parseInt(values[0]), values[1], values[2], Double.parseDouble(values[3]), Integer.parseInt(values[4]));
@@ -146,7 +146,7 @@ public static void saveLocalUserBookmark(User user, Bookmark bookmark) {
146146
if(!url.endsWith(".pdf")) {
147147
String website = DownloadSequential.downloadFromUrl(((Weblink) bookmark).getUrl());
148148
if(website != null) {
149-
ReadWriteFile.writeWebpage(website, bookmark.getId());
149+
FileReadWrite.writeWebpage(website, bookmark.getId());
150150
}
151151
}
152152
} catch (Exception e) {

client-mapl-dashboard/src/main/java/app/mapl/controllers/UserDashController.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public UserDashController( UsersService usersService ) {
4242
}
4343

4444

45-
@GetMapping("/v1thomas")
45+
@GetMapping("/v1/register")
4646
public String register(Model model) {
4747
UserRequest userAccount = new UserRequest();
4848
model.addAttribute("registerDto", userAccount);
@@ -68,7 +68,7 @@ public String consoleHome(Model model ) throws JsonProcessingException {
6868
model.addAttribute("versionNumber",ver);
6969

7070

71-
List<UserResponse> users = usersService.getUsers();
71+
List<UserResponse> users = usersService.getUsersResponse();
7272
model.addAttribute("users", users);
7373
model.addAttribute("map", map);
7474

client-mapl-dashboard/src/main/java/app/mapl/controllers/UsersController.java

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
import java.util.Map;
3535
import java.util.Optional;
3636

37-
import static app.mapl.util.Utilities.getResponse;
37+
import static app.mapl.models.auth.AuthenticationFilter.getResponse;
3838
import static java.util.Collections.emptyMap;
3939
import static org.springframework.http.HttpStatus.CREATED;
4040
import static org.springframework.http.HttpStatus.OK;
@@ -55,8 +55,8 @@ public class UsersController {
5555

5656
private UsersService usersService;
5757
AuthenticationManager authenticationManager;
58-
public static final String USER_PATH = "/api/users";
59-
public static final String USER_PATH_ID = USER_PATH + "/{userId}";
58+
public static final String USER_PATH = "/api";
59+
public static final String USER_PATH_ID = USER_PATH + "/users/{userId}";
6060

6161
@Autowired
6262
public UsersController( UsersService usersService ) {
@@ -86,12 +86,6 @@ public ResponseEntity<LoginDto> loginUser(@RequestParam String usernameOrEmail,
8686

8787
return new ResponseEntity<>(ldto,HttpStatus.CREATED);
8888
}
89-
@PostMapping("/auth/test")
90-
public ResponseEntity<?> test(@RequestBody UserRequest userRequest ) {
91-
Authentication authenticate = authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(userRequest.getEmail(), userRequest.getPassword()));
92-
return ResponseEntity.ok().body(Map.of("user", authenticate));
93-
}
94-
9589
@Operation(
9690
summary = "Create User REST API registerUser",
9791
description = "Create User REST API is used to save user in a database"
@@ -104,17 +98,24 @@ public ResponseEntity<?> test(@RequestBody UserRequest userRequest ) {
10498
public ResponseEntity<Response> registerUser(@RequestBody @Valid UserRequest user, HttpServletRequest request) {
10599
usersService.createUser(user.getFirstName(), user.getLastName(), user.getEmail(), user.getPassword());
106100
return ResponseEntity.created(getUri()).body( getResponse(request, emptyMap(), "AccountCreated", CREATED));
107-
}
101+
}
108102

109103
@Operation(
110104
summary = "Verify Account REST API",
111105
description = "Verify Account REST API is used to verify a user account"
112106
)
113-
@GetMapping("verify/account")
107+
@GetMapping("/auth/verify/account")
114108
public ResponseEntity<Response> verifyAccount(@RequestParam("key") String key, HttpServletRequest request){
115109
usersService.verifyAccountKey(key);
116110
return ResponseEntity.ok().body( getResponse(request, emptyMap(), "Account Verified.", OK));
117111
}
112+
113+
@PostMapping("/auth/test")
114+
public ResponseEntity<?> test(@RequestBody UserRequest userRequest ) {
115+
Authentication authenticate = authenticationManager.authenticate(UsernamePasswordAuthenticationToken.unauthenticated(userRequest.getEmail(), userRequest.getPassword()));
116+
return ResponseEntity.ok().body(Map.of("user", authenticate));
117+
}
118+
118119
@Operation(
119120
summary = "Save User REST API",
120121
description = "Save User REST API is used to save a user in the database"
@@ -123,7 +124,7 @@ public ResponseEntity<Response> verifyAccount(@RequestParam("key") String key, H
123124
responseCode = "201",
124125
description = "HTTP Status 201 CREATED"
125126
)
126-
@PostMapping(value = "/api/userEntity", consumes = "application/json")
127+
@PostMapping(value = "/users/userEntity", consumes = "application/json")
127128
public ResponseEntity<Response> saveUser(@RequestBody @Valid UserRequest user, HttpServletRequest request){
128129
User savedUser = usersService.createUserRole(
129130
user.getFirstName(),
@@ -144,12 +145,14 @@ private URI getUri() {
144145
responseCode = "200",
145146
description = "HTTP Status 200 SUCCESS"
146147
)
147-
@GetMapping(USER_PATH)
148+
@GetMapping(USER_PATH+"/users")
148149
public ResponseEntity<List<UserResponse>> getUsers() {
149150
List<UserResponse> users = new ArrayList<>();
151+
150152
try {
151-
users = usersService.getUsers();
152-
} catch (Exception e) {
153+
users = usersService.getUsersResponse();
154+
155+
} catch (Exception e) {
153156
System.out.println(e.getMessage());
154157
}
155158
return new ResponseEntity<>(users,
@@ -166,7 +169,7 @@ public ResponseEntity<List<UserResponse>> getUsers() {
166169
)
167170
// http://localhost:8080/api/users/1
168171
@GetMapping(value = USER_PATH_ID)
169-
public ResponseEntity<UserResponse> getUser(@PathVariable("userId") int userId) {
172+
public ResponseEntity<UserDto> getUser(@PathVariable("userId") int userId) {
170173
if(usersService.getUser(userId).isEmpty()) {
171174
throw new ResourceNotFoundException("User " + userId + "not found");
172175
}
@@ -186,16 +189,16 @@ public ResponseEntity<APIResponseDto> getUserById(@PathVariable("id") Long userE
186189
responseCode = "200",
187190
description = "HTTP Status 200 SUCCESS"
188191
)
189-
@GetMapping(value = USER_PATH+ "/email/{email}")
190-
public ResponseEntity<UserResponse> getUserByEmail(@PathVariable("email") String email) {
192+
@GetMapping(value = USER_PATH+ "/users/email/{email}")
193+
public ResponseEntity<UserDto> getUserByEmail(@PathVariable("email") String email) {
191194
if(usersService.getUser(email).isEmpty()) {
192195
throw new ResourceNotFoundException("User " + email + "not found");
193196
}
194197
return new ResponseEntity<>(usersService.getUser(email).get(), OK);
195198
}
196199

197200
/// Non-Register Creation Request
198-
@PostMapping(USER_PATH)
201+
@PostMapping(USER_PATH+"/users")
199202
public ResponseEntity createUser(@RequestBody UserRequest user) {
200203
ResponseEntity<UserResponse> savedUser = usersService.saveUser(user);
201204

@@ -214,7 +217,7 @@ public ResponseEntity createUser(@RequestBody UserRequest user) {
214217
responseCode = "200",
215218
description = "HTTP Status 200 SUCCESS"
216219
)
217-
@PutMapping(value = USER_PATH + "/{userId}", consumes = "application/json") // userId in body
220+
@PutMapping(value = USER_PATH + "/users/{userId}", consumes = "application/json") // userId in body
218221
public ResponseEntity<UserDto> updateUser(@PathVariable("userId") int userId, @RequestBody UserDto userDto) {
219222
Optional<UserDto> updated = usersService.updateUser(userDto);
220223
return updated.map(dto -> new ResponseEntity<>(

client-mapl-dashboard/src/main/java/app/mapl/exception/ApiException.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,15 @@
11
package app.mapl.exception;
22

3+
import jakarta.servlet.http.HttpServletRequest;
4+
import jakarta.servlet.http.HttpServletResponse;
35
import lombok.RequiredArgsConstructor;
6+
import org.springframework.boot.actuate.web.exchanges.HttpExchange.Response;
47
import org.springframework.http.HttpStatus;
58

9+
import java.nio.file.AccessDeniedException;
10+
import java.util.List;
11+
import java.util.Map;
12+
613
public class ApiException extends RuntimeException {
714
private final HttpStatus status;
815
private final String message;
@@ -28,4 +35,14 @@ public HttpStatus getStatus() {
2835
public String getMessage() {
2936
return message;
3037
}
38+
39+
40+
public static void handleErrorResponse(HttpServletRequest request, HttpServletResponse response, Exception exception) {
41+
if (exception instanceof AccessDeniedException) {
42+
response.setStatus(HttpStatus.FORBIDDEN.value());
43+
return;
44+
}
45+
throw new RuntimeException(response.toString());
46+
}
47+
3148
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,44 @@
11
package app.mapl.mapper;
22

3+
import app.mapl.models.auth.CredentialEntity;
4+
import app.mapl.models.auth.RoleEntity;
35
import app.mapl.models.auth.User;
6+
import app.mapl.models.auth.UserRequest;
7+
import app.mapl.models.auth.UserResponse;
48
import app.mapl.models.dto.UserDto;
59
import org.mapstruct.*;
610

11+
import java.util.ArrayList;
12+
import java.util.Collection;
13+
import java.util.Optional;
14+
import java.util.Set;
715

816
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = MappingConstants.ComponentModel.SPRING)
917
public interface UserMapper {
1018
User toUser(UserDto userDto); // REQUEST FROM UI
1119

1220
UserDto toDto(User user); // RESPONSE TO UI
1321

22+
User userRequestToUser(UserRequest userRequest); // REQUEST FROM UI
23+
24+
1425
@BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
1526
User partialUpdate(UserDto userResponse, @MappingTarget User user);
1627

28+
default UserResponse userToUserResponse(User user) {
29+
UserResponse userResponse = new UserResponse();
30+
userResponse.setUserId(user.getUserId());
31+
userResponse.setEmail(user.getEmail());
32+
userResponse.setFirstName(user.getFirstName());
33+
userResponse.setLastName(user.getLastName());
34+
userResponse.setUserType(user.getUserType());
35+
userResponse.setBio(user.getBio());
36+
userResponse.setPhone(user.getPhone());
37+
userResponse.setAuthenticated(user.isAuthenticated());
38+
userResponse.setOrganizationCode(user.getOrganizationCode());
39+
userResponse.setDashboardCode(user.getDashboardCode());
40+
userResponse.setRoles((Set<RoleEntity>) new ArrayList<RoleEntity>((Collection<? extends RoleEntity>) user.getRole()));
41+
return userResponse;
42+
};
43+
1744
}

client-mapl-dashboard/src/main/java/app/mapl/models/auth/AuthenticationFilter.java

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,23 @@
88
import jakarta.servlet.http.HttpServletRequest;
99
import jakarta.servlet.http.HttpServletResponse;
1010
import lombok.extern.slf4j.Slf4j;
11+
import org.springframework.boot.actuate.web.exchanges.HttpExchange.Response;
1112
import org.springframework.http.HttpStatus;
13+
import org.springframework.http.ResponseEntity;
1214
import org.springframework.security.authentication.AuthenticationManager;
1315
import org.springframework.security.authentication.BadCredentialsException;
1416
import org.springframework.security.core.Authentication;
1517
import org.springframework.security.core.AuthenticationException;
1618
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
1719
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
18-
import org.springframework.stereotype.Component;
1920

2021
import java.io.IOException;
22+
import java.util.List;
23+
import java.util.Map;
2124

22-
import static app.mapl.util.Utilities.handleErrorResponse;
25+
import static app.mapl.exception.ApiException.handleErrorResponse;
2326
import static com.fasterxml.jackson.core.JsonParser.Feature.AUTO_CLOSE_SOURCE;
27+
import static java.time.LocalTime.now;
2428
import static org.springframework.boot.actuate.endpoint.web.WebEndpointHttpMethod.POST;
2529
import static org.springframework.security.authentication.UsernamePasswordAuthenticationToken.unauthenticated;
2630

@@ -39,20 +43,19 @@ public AuthenticationFilter(AuthenticationManager authenticationManager, UsersSe
3943
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException , ServletException {
4044

4145
try {
42-
var user = new ObjectMapper().configure(AUTO_CLOSE_SOURCE, true).readValue(request.getInputStream(), UserDto.class); // LoginRequest
46+
var user = new ObjectMapper().configure(AUTO_CLOSE_SOURCE, true).readValue(request.getInputStream(), LoginRequest.class); //
4347
userService.updateLoginAttempt(user.getEmail(), LoginType.LOGIN_ATTEMPT);
4448
var authentication = unauthenticated(user.getEmail(), user.getPassword());
49+
return getAuthenticationManager().authenticate(authentication);
4550
} catch (Exception exception) {
46-
throw new BadCredentialsException("Invalid username or password");
51+
// throw new BadCredentialsException("Invalid username or password");
52+
handleErrorResponse(request, response, new BadCredentialsException("User not found"));
53+
return null; //new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword(), user.getRoles());
54+
} finally {
55+
log.info("Login attempt at {}", now());
56+
return null;
4757
}
48-
UserDto user = userService.updateLoginAttempt(request.getParameter("email"), LoginType.valueOf(request.getParameter("password")));
49-
if (user == null) {
50-
// log.error(exception.getMessage());
51-
handleErrorResponse(request, response, new BadCredentialsException("User not found"));
52-
// throw new BadCredentialsException("User not found");
53-
}
5458

55-
return null; //new UsernamePasswordAuthenticationToken(user.getEmail(), user.getPassword(), user.getRoles());
5659

5760
}
5861

@@ -76,10 +79,16 @@ protected void successfulAuthentication(HttpServletRequest request, HttpServletR
7679
}
7780

7881
private void sendResponse(HttpServletRequest request, HttpServletResponse response, UserDto user) {
82+
jwtService.addCookie(response, user, TokenType.ACCESS_TOKEN);
83+
jwtService.addCookie(response, user, TokenType.REFRESH_TOKEN);
7984
}
8085

81-
private void sendQrCode(HttpServletRequest request, UserDto user) {
86+
private Response sendQrCode(HttpServletRequest request, UserDto user) {
87+
return getResponse(request,Map.of("user", (List<String>) user), "qrCode, please enter", HttpStatus.OK);
8288
}
89+
public static Response getResponse(HttpServletRequest request, Map<String, List<String>> data, String message, HttpStatus status) {
90+
return null; //new Response(status, null);
8391

92+
}
8493

8594
}

0 commit comments

Comments
 (0)