source: backend/GlobeGuru-backend/src/main/java/AccountHandler.java@ cd64b06

Last change on this file since cd64b06 was 53bad7e, checked in by Kristijan <kristijanzafirovski26@…>, 6 days ago

dodadeno informacii za broj na lugje

  • Property mode set to 100644
File size: 9.1 KB
Line 
1import com.fasterxml.jackson.databind.ObjectMapper;
2import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
3import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
4import com.google.api.client.http.HttpTransport;
5import com.google.api.client.http.javanet.NetHttpTransport;
6import com.google.api.client.json.JsonFactory;
7import com.google.api.client.json.jackson2.JacksonFactory;
8import com.sun.net.httpserver.HttpExchange;
9import com.sun.net.httpserver.HttpHandler;
10
11import java.io.IOException;
12import java.security.GeneralSecurityException;
13import java.sql.SQLException;
14import java.util.*;
15import java.util.concurrent.ConcurrentHashMap;
16
17public class AccountHandler implements HttpHandler {
18 private static final Map<String, String> sessions = new ConcurrentHashMap<>();
19 private static final String CLIENT_ID = "376204422797-s8f05nn6drmec1cko2h4kg1nk24abgc9.apps.googleusercontent.com";
20
21 @Override
22 public void handle(HttpExchange exchange) throws IOException {
23 String path = exchange.getRequestURI().getPath();
24 String method = exchange.getRequestMethod();
25
26 if ("POST".equalsIgnoreCase(method)) {
27 switch (path) {
28 case "/account/register":
29 handleRegister(exchange);
30 break;
31 case "/account/login":
32 handleLogin(exchange);
33 break;
34 case "/account/logout":
35 handleLogout(exchange);
36 break;
37 case "/account/delete":
38 handleDeleteAccount(exchange);
39 break;
40 default:
41 Server.sendResponse(exchange, 404, "Endpoint not found");
42 }
43 } else if ("GET".equalsIgnoreCase(method) && path.equalsIgnoreCase("/account/session")) {
44 handleSession(exchange);
45 } else {
46 Server.sendResponse(exchange, 405, "Method not allowed");
47 }
48 }
49
50 private void handleSession(HttpExchange exchange) throws IOException {
51 String sessionId = getSessionId(exchange);
52 ObjectMapper mapper = new ObjectMapper();
53 Map<String, Object> response = new HashMap<>();
54 if (sessionId != null && sessions.containsKey(sessionId)) {
55 response.put("loggedIn", true);
56 response.put("user", sessions.get(sessionId));
57 try {
58 response.put("isAdmin", DatabaseUtil.isAdmin(sessions.get(sessionId)));
59 } catch (SQLException e) {
60 e.printStackTrace();
61 response.put("isAdmin", false);
62 }
63 } else {
64 response.put("loggedIn", false);
65 }
66
67 String jsonResponse = mapper.writeValueAsString(response);
68 Server.sendResponse(exchange, 200, jsonResponse);
69 }
70
71 private String getSessionId(HttpExchange exchange) {
72 List<String> cookies = exchange.getRequestHeaders().get("Cookie");
73 if (cookies != null) {
74 for (String cookie : cookies) {
75 if (cookie.contains("sessionId=")) {
76 return cookie.replaceAll("g_state=\\{\"i_l\":0\\}; sessionId=", "");
77 }
78 }
79 }
80 return null;
81 }
82
83
84 private void handleRegister(HttpExchange exchange) throws IOException {
85 String requestBody = new String(exchange.getRequestBody().readAllBytes());
86 ObjectMapper mapper = new ObjectMapper();
87 Map<String, String> formData = mapper.readValue(requestBody, Map.class);
88 String username = formData.get("username");
89 String email = formData.get("email");
90 String password = formData.get("password");
91
92 try {
93 if (DatabaseUtil.registerUser(username, email, password)) {
94 Server.sendResponse(exchange, 200, "{\"message\": \"Registration successful!\"}");
95 } else {
96 Server.sendResponse(exchange, 400, "{\"message\": \"Registration failed! User may already exist.\"}");
97 }
98 } catch (SQLException e) {
99 e.printStackTrace();
100 Server.sendResponse(exchange, 500, "{\"message\": \"Internal server error\"}");
101 }
102 }
103
104 private void handleLogin(HttpExchange exchange) throws IOException {
105 String requestBody = new String(exchange.getRequestBody().readAllBytes());
106 ObjectMapper mapper = new ObjectMapper();
107 Map<String, String> formData = mapper.readValue(requestBody, Map.class);
108
109 if (formData.containsKey("id_token")) {
110 handleGoogleSignIn(exchange, formData.get("id_token"));
111 } else {
112 handleFormLogin(exchange, formData.get("email"), formData.get("password"));
113 }
114 }
115
116 private void handleGoogleSignIn(HttpExchange exchange, String idTokenString) throws IOException {
117 HttpTransport transport = new NetHttpTransport();
118 JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
119
120 GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
121 .setAudience(Collections.singletonList(CLIENT_ID)).build();
122
123 try {
124 GoogleIdToken idToken = verifier.verify(idTokenString);
125 if (idToken != null) {
126 GoogleIdToken.Payload payload = idToken.getPayload();
127 String email = payload.getEmail();
128 if (DatabaseUtil.userExists(email)) {
129 System.out.println("User exists, logging in");
130 handleFormLogin(exchange, email, null);
131 } else {
132 System.out.println("User does not exist, creating new user");
133 String name = (String) payload.get("name");
134 DatabaseUtil.registerUser(name, email, null); // Password is null for Google login
135 String response = createSession(email);
136 Server.sendResponse(exchange, 200, response);
137 }
138 } else {
139 String response = "{\"message\": \"Invalid ID token\"}";
140 System.out.println(response);
141 Server.sendResponse(exchange, 401, response);
142 }
143 } catch (SQLException e) {
144 e.printStackTrace();
145 String response = "{\"message\": \"Database error\"}";
146 System.out.println(response);
147 Server.sendResponse(exchange, 500, response);
148 } catch (GeneralSecurityException e) {
149 throw new RuntimeException(e);
150 }
151 }
152
153 private void handleFormLogin(HttpExchange exchange, String email, String password) throws IOException {
154 try {
155 if (DatabaseUtil.userExists(email)) {
156 if (DatabaseUtil.authenticateUser(email, password)) {
157 String response = createSession(email);
158 Server.sendResponse(exchange, 200, response);
159 } else {
160 String response = "{\"message\": \"Invalid password\"}";
161 System.out.println(response);
162 Server.sendResponse(exchange, 401, response);
163 }
164 } else {
165 String response = "{\"message\": \"User does not exist\"}";
166 System.out.println(response);
167 Server.sendResponse(exchange, 404, response);
168 }
169 } catch (SQLException e) {
170 e.printStackTrace();
171 String response = "{\"message\": \"Database error: " + e.getMessage() + "\"}";
172 System.out.println(response);
173 Server.sendResponse(exchange, 500, response);
174 }
175 }
176
177 private void handleLogout(HttpExchange exchange) throws IOException {
178 String sessionId = getSessionId(exchange);
179 if (sessionId != null && sessions.containsKey(sessionId)) {
180 sessions.remove(sessionId);
181 Server.sendResponse(exchange, 200, "{\"message\": \"Logout successful\"}");
182 } else {
183 Server.sendResponse(exchange, 401, "{\"message\": \"Not logged in\"}");
184 }
185 }
186
187 private void handleDeleteAccount(HttpExchange exchange) throws IOException {
188 String userIdStr = new String(exchange.getRequestBody().readAllBytes()).replaceAll("\"", "");
189 int userId = Integer.parseInt(userIdStr);
190 Map<String, Object> response = new HashMap<>();
191 try {
192 boolean success = DatabaseUtil.deleteUser(userId);
193 response.put("success", success);
194 if (!success) {
195 response.put("message", "User not found");
196 }
197 } catch (SQLException e) {
198 e.printStackTrace();
199 response.put("success", false);
200 response.put("message", "Database error: " + e.getMessage());
201 }
202
203 String jsonResponse = new ObjectMapper().writeValueAsString(response);
204 Server.sendResponse(exchange, 200, jsonResponse);
205 }
206
207
208 private String createSession(String email) throws SQLException {
209 String sessionId = UUID.randomUUID().toString();
210 sessions.put(sessionId, email);
211 boolean isAdmin = DatabaseUtil.isAdmin(email);
212 return "{\"message\": \"" + email + " logged in!\", \"sessionId\": \"" + sessionId + "\", \"isAdmin\": " + isAdmin + "}";
213 }
214
215}
Note: See TracBrowser for help on using the repository browser.