Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Commit

Permalink
Restored dummy login, further improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
spoenemann committed Dec 12, 2019
1 parent 0cf21e3 commit 9315976
Show file tree
Hide file tree
Showing 13 changed files with 176 additions and 177 deletions.
32 changes: 14 additions & 18 deletions server/src/main/java/io/typefox/extreg/LocalRegistryService.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,19 +147,11 @@ public ReviewListJson getReviews(String publisherName, String extensionName) {
var extension = repositories.findExtension(extensionName, publisherName);
if (extension == null)
throw new NotFoundException();
var reviews = repositories.findReviews(extension);
var list = new ReviewListJson();
list.postUrl = createApiUrl(serverUrl, extension.getPublisher().getName(), extension.getName(), "review");
list.reviews = new ArrayList<>(reviews.size());
for (var extReview : reviews) {
var json = new ReviewJson();
json.user = extReview.getUsername();
json.timestamp = extReview.getTimestamp().toString();
json.title = extReview.getTitle();
json.comment = extReview.getComment();
json.rating = extReview.getRating();
list.reviews.add(json);
}
list.reviews = repositories.findReviews(extension)
.map(extReview -> extReview.toReviewJson())
.toList();
return list;
}

Expand All @@ -171,11 +163,11 @@ public void initSearchIndex(ApplicationStartedEvent event) {
logger.info("Initializing search index...");
var allExtensions = repositories.findAllExtensions();
if (!allExtensions.isEmpty()) {
var indexQueries = CollectionUtil.map(allExtensions, extension ->
var indexQueries = allExtensions.map(extension ->
new IndexQueryBuilder()
.withObject(extension.toSearch())
.build()
);
).toList();
searchOperations.bulkIndex(indexQueries);
}
}
Expand Down Expand Up @@ -342,10 +334,9 @@ private void addBundledExtension(String bundled, ExtensionVersion extVersion) {
@Transactional
public ReviewResultJson review(ReviewJson review, String publisherName, String extensionName, String sessionId) {
var session = repositories.findUserSession(sessionId);
if (session == null) {
if (session == null)
return ReviewResultJson.error("Invalid session.");
}
var extension = repositories.findExtension(publisherName, extensionName);
var extension = repositories.findExtension(extensionName, publisherName);
if (extension == null)
throw new NotFoundException();
var extReview = new ExtensionReview();
Expand All @@ -363,14 +354,18 @@ public ReviewResultJson review(ReviewJson review, String publisherName, String e
private double computeAverageRating(Extension extension) {
var reviews = repositories.findReviews(extension);
long sum = 0;
long count = 0;
for (var review : reviews) {
sum += review.getRating();
count++;
}
return (double) sum / reviews.size();
return (double) sum / count;
}

private SearchEntryJson toSearchEntry(ExtensionSearch search) {
var extension = entityManager.find(Extension.class, search.id);
if (extension == null)
return null;
var extVer = extension.getLatest();
var entry = extVer.toSearchEntryJson();
entry.url = createApiUrl(serverUrl, entry.publisher, entry.name);
Expand All @@ -385,7 +380,8 @@ private ExtensionJson toJson(ExtensionVersion extVersion, boolean isLatest) {
json.reviewCount = repositories.countReviews(extension);
json.publisherUrl = createApiUrl(serverUrl, json.publisher);
json.reviewsUrl = createApiUrl(serverUrl, json.publisher, json.name, "reviews");
var allVersions = CollectionUtil.map(repositories.findVersions(extension), extVer -> new SemanticVersion(extVer.getVersion()));
var allVersions = CollectionUtil.map(repositories.findVersions(extension),
extVer -> new SemanticVersion(extVer.getVersion()));
Collections.sort(allVersions, Comparator.reverseOrder());
json.allVersions = new LinkedHashMap<>();
for (var semVer : allVersions) {
Expand Down
13 changes: 7 additions & 6 deletions server/src/main/java/io/typefox/extreg/RegistryAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

Expand Down Expand Up @@ -242,16 +243,16 @@ public ExtensionJson publish(InputStream content) {
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<ReviewResultJson> review(ReviewJson review,
public ResponseEntity<ReviewResultJson> review(@RequestBody(required = false) ReviewJson review,
@PathVariable("publisher") String publisherName,
@PathVariable("extension") String extensionName,
@CookieValue("sessionid") String sessionId) {
@CookieValue(name = "sessionid", required = false) String sessionId) {
ReviewResultJson json;
if (sessionId == null) {
json = ReviewResultJson.error("Not logged in.");
return new ResponseEntity<>(json, getReviewHeaders(), HttpStatus.OK);
}
if (review.rating < 0 || review.rating > 5) {
} else if (review == null) {
json = ReviewResultJson.error("No JSON input.");
} else if (review.rating < 0 || review.rating > 5) {
json = ReviewResultJson.error("The rating must be an integer number between 0 and 5.");
} else {
json = local.review(review, publisherName, extensionName, sessionId);
Expand All @@ -265,7 +266,7 @@ private HttpHeaders getReviewHeaders() {
if (!Strings.isNullOrEmpty(webuiUrl)) {
headers.setAccessControlAllowOrigin(webuiUrl);
headers.setAccessControlAllowCredentials(true);
headers.setAccessControlAllowHeaders(Arrays.asList("content-type"));
headers.setAccessControlAllowHeaders(Arrays.asList("Content-Type"));
}
return headers;
}
Expand Down
177 changes: 99 additions & 78 deletions server/src/main/java/io/typefox/extreg/UserAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import java.net.URISyntaxException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.UUID;

import javax.persistence.EntityManager;
Expand All @@ -23,13 +22,13 @@

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

import io.typefox.extreg.entities.UserData;
import io.typefox.extreg.entities.UserSession;
Expand All @@ -39,8 +38,7 @@
@RestController
public class UserAPI {

private static final String COOKIE_COMMENT = "User session id";
private static final int COOKIE_MAX_AGE = 604_800; // one week in seconds
private static final int COOKIE_MAX_AGE = 7 * 24 * 60 * 60; // one week in seconds

@Autowired
EntityManager entityManager;
Expand All @@ -59,94 +57,117 @@ public class UserAPI {
produces = MediaType.APPLICATION_JSON_VALUE
)
@Transactional
public ResponseEntity<UserJson> userInfo(@CookieValue(name = "sessionid", required = false) String sessionId) {
public ResponseEntity<UserJson> userInfo(@CookieValue(name = "sessionid", required = false) String sessionId,
HttpServletResponse response) {
response.addHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE);
addAccessControlHeaders(response);
if (sessionId == null) {
var json = UserJson.error("Not logged in.");
return new ResponseEntity<>(json, getHeaders(), HttpStatus.OK);
return new ResponseEntity<>(json, HttpStatus.OK);
}
var session = repositories.findUserSession(sessionId);
if (session == null) {
var json = UserJson.error("Invalid session.");
return new ResponseEntity<>(json, getHeaders(), HttpStatus.OK);
return new ResponseEntity<>(json, HttpStatus.OK);
}
//XXX
// updateLastUsed(session);

updateLastUsed(session);
var json = new UserJson();
json.name = session.getUser().getName();
json.name = "test_user";
json.avatarUrl = "https://s.gravatar.com/avatar/9a638e5879d268e59d158a2091723c3c?s=80";
return new ResponseEntity<>(json, getHeaders(), HttpStatus.OK);
//XXX
// .cookie(new NewCookie(sessionCookie, COOKIE_COMMENT, COOKIE_MAX_AGE, false))
response.addCookie(createSessionCookie(session.getId(), COOKIE_MAX_AGE));
return new ResponseEntity<>(json, HttpStatus.OK);
}

@GetMapping("/api/-/user/login")
@Transactional
public RedirectView login(@CookieValue(name = "sessionid", required = false) String sessionId,
HttpServletResponse response) {
var session = sessionId != null ? repositories.findUserSession(sessionId) : null;
if (session == null) {
session = new UserSession();
session.setId(UUID.randomUUID().toString());
session.setUser(getDummyUser());
entityManager.persist(session);
}

updateLastUsed(session);
addAccessControlHeaders(response);
response.addCookie(createSessionCookie(session.getId(), COOKIE_MAX_AGE));
return new RedirectView(getRedirectUrl());
}

private HttpHeaders getHeaders() {
var headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
private UserData getDummyUser() {
var allUsers = repositories.findAllUsers();
if (allUsers.isEmpty()) {
var user = new UserData();
user.setName("test_user");
entityManager.persist(user);
return user;
}
return allUsers.iterator().next();
}

@GetMapping("/api/-/user/logout")
@Transactional
public RedirectView logout(@CookieValue(name = "sessionid", required = false) String sessionId,
HttpServletResponse response) {
if (sessionId != null) {
var session = repositories.findUserSession(sessionId);
if (session != null) {
entityManager.remove(session);
}
response.addCookie(createSessionCookie(sessionId, 0));
}
addAccessControlHeaders(response);
return new RedirectView(getRedirectUrl());
}

private void addAccessControlHeaders(HttpServletResponse response) {
if (!Strings.isNullOrEmpty(webuiUrl)) {
headers.setAccessControlAllowOrigin(webuiUrl);
headers.setAccessControlAllowCredentials(true);
headers.setAccessControlAllowHeaders(Arrays.asList("content-type"));
response.addHeader("Access-Control-Allow-Origin", webuiUrl);
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
}
}

private Cookie createSessionCookie(String sessionId, int maxAge) {
var cookie = new Cookie("sessionid", sessionId);
cookie.setDomain(getDomain());
cookie.setPath(getPath());
cookie.setMaxAge(maxAge);
return cookie;
}

private String getDomain() {
try {
var uri = new URI(serverUrl);
return uri.getHost();
} catch (URISyntaxException exc) {
throw new RuntimeException(exc);
}
return headers;
}

// @GetMapping("/api/-/user/login")
// @Transactional
// public Response login(@CookieValue("sessionid") String sessionCookie) {
// if (sessionCookie != null) {
// var session = entities.findSession(sessionCookie);
// if (session != null) {
// return Response.temporaryRedirect(getRedirectURI())
// .cookie(new NewCookie(sessionCookie, COOKIE_COMMENT, COOKIE_MAX_AGE, false))
// .build();
// }
// }
// var user = entityManager.find(UserData.class, 1l);
// var session = new UserSession();
// session.setId(UUID.randomUUID().toString());
// session.setUser(user);
// updateLastUsed(session);
// entityManager.persist(session);
// return Response.temporaryRedirect(getRedirectURI())
// .cookie(new NewCookie("sessionid", session.getId(),
// "/", getDomain(), COOKIE_COMMENT, COOKIE_MAX_AGE, false))
// .build();
// }

// @GetMapping("/api/-/user/logout")
// @Transactional
// public Response logout(@CookieValue("sessionid") String sessionCookie) {
// if (sessionCookie == null) {
// return Response.temporaryRedirect(getRedirectURI()).build();
// }
// var session = entities.findSession(sessionCookie);
// if (session != null) {
// entityManager.remove(session);
// }
// return Response.temporaryRedirect(getRedirectURI())
// .cookie(new NewCookie(sessionCookie, null, 0, false))
// .build();
// }

// private URI getRedirectURI() {
// try {
// return new URI("/");
// } catch (URISyntaxException exc) {
// throw new WebApplicationException(exc);
// }
// }

// private String getDomain() {
// try {
// var uri = new URI(serverUrl);
// return uri.getHost();
// } catch (URISyntaxException exc) {
// throw new WebApplicationException(exc);
// }
// }

// private void updateLastUsed(UserSession session) {
// session.setLastUsed(LocalDateTime.now(ZoneId.of("UTC")));
// }
private String getPath() {
try {
var uri = new URI(serverUrl);
var path = uri.getRawPath();
if (Strings.isNullOrEmpty(path))
return "/";
return path;
} catch (URISyntaxException exc) {
throw new RuntimeException(exc);
}
}

private String getRedirectUrl() {
if (webuiUrl != null)
return webuiUrl;
return "/";
}

private void updateLastUsed(UserSession session) {
session.setLastUsed(LocalDateTime.now(ZoneId.of("UTC")));
}

}
Loading

0 comments on commit 9315976

Please sign in to comment.