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

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

pred-finalna

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