aboutsummaryrefslogtreecommitdiff
path: root/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/AuthController.java
diff options
context:
space:
mode:
Diffstat (limited to 'ufund-api/src/main/java/com/ufund/api/ufundapi/controller/AuthController.java')
-rw-r--r--ufund-api/src/main/java/com/ufund/api/ufundapi/controller/AuthController.java62
1 files changed, 62 insertions, 0 deletions
diff --git a/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/AuthController.java b/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/AuthController.java
new file mode 100644
index 0000000..b46d4ee
--- /dev/null
+++ b/ufund-api/src/main/java/com/ufund/api/ufundapi/controller/AuthController.java
@@ -0,0 +1,62 @@
+package com.ufund.api.ufundapi.controller;
+
+import java.io.IOException;
+import java.util.Map;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.DeleteMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.ufund.api.ufundapi.service.AuthService;
+
+@RestController
+@RequestMapping("auth")
+public class AuthController {
+ private final AuthService authService;
+
+ public AuthController(AuthService authService) {
+ this.authService = authService;
+ }
+
+ /**
+ * Attempts to log in as a user
+ *
+ * @param params A json object in the format {username: string, password: string}
+ * @return An api key and status OK if the authentication was successful,
+ * Status UNAUTHORIZED if the authentication failed and INTERNAL SERVER ERROR otherwise.
+ */
+ @PostMapping("")
+ public ResponseEntity<String> login(@RequestBody Map<String, String> params) {
+ String username = params.get("username");
+ String password = params.get("password");
+ try {
+ String key = authService.login(username, password);
+ return new ResponseEntity<>(key, HttpStatus.OK);
+ } catch (IllegalAccessException e) {
+ return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
+ } catch (IOException ex) {
+ return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
+ }
+ }
+
+ /**
+ * Logs out the current user
+ *
+ * @param key The API sent by the client in the header
+ * @return OK if the user was successfully logged out, INTERNAL_SERVER_ERROR otherwise.
+ */
+ @DeleteMapping("")
+ public ResponseEntity<Object> logout(@RequestHeader("jelly-api-key") String key) {
+ try {
+ authService.logout(key);
+ return new ResponseEntity<>(HttpStatus.OK);
+ } catch (IOException e) {
+ return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
+ }
+ }
+}