1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
package com.ufund.api.ufundapi.controller;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
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 static final Logger LOG = Logger.getLogger(AuthController.class.getName());
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) {
LOG.log(Level.INFO, "POST /auth body={0}", 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 ex) {
LOG.log(Level.WARNING, ex.getLocalizedMessage());
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
} catch (IOException ex) {
LOG.log(Level.SEVERE, ex.getLocalizedMessage());
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) {
LOG.log(Level.INFO, "DELETE /auth key={0}", key);
try {
authService.logout(key);
return new ResponseEntity<>(HttpStatus.OK);
} catch (IOException ex) {
LOG.log(Level.WARNING, ex.getLocalizedMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|