new auth, hot entries

This commit is contained in:
_Bastler 2021-10-05 14:39:49 +02:00
parent e9e9a22719
commit 4a2b8b08bb
13 changed files with 279 additions and 107 deletions

View File

@ -142,6 +142,7 @@ public class CommentManager {
*
* @param username the username
* @param comment the comment
* @param ignore the ignore
*/
public void applyMetadata(String username, Comment comment, List<String> ignore) {
@ -193,6 +194,7 @@ public class CommentManager {
*
* @param username the username
* @param entries the entries
* @param ignore the ignore
*/
public void applyMetadata(String username, List<Comment> entries, List<String> ignore) {
for (Comment comment : entries) {

View File

@ -63,6 +63,19 @@ public class EntryManager {
return entryRepository.findAllByRanking(date, gravity, PageRequest.of(page, size));
}
/**
* Fetch by comments.
*
* @param date the date
* @param gravity the gravity
* @param page the page
* @param size the size
* @return the page
*/
public Page<RankedEntry> fetchByComments(Instant date, double gravity, int page, int size) {
return entryRepository.findAllByComments(date, gravity, PageRequest.of(page, size));
}
/**
* Fetch by date.
*
@ -116,7 +129,9 @@ public class EntryManager {
* Apply metadata.
*
* @param username the username
* @param karma the karma
* @param entry the entry
* @param ignore the ignore
*/
public void applyMetadata(String username, long karma, Entry entry, List<String> ignore) {
@ -170,7 +185,9 @@ public class EntryManager {
* Apply metadata.
*
* @param username the username
* @param karma the karma
* @param entries the entries
* @param ignore the ignore
*/
public void applyMetadata(String username, long karma, List<Entry> entries,
List<String> ignore) {

View File

@ -15,7 +15,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticatio
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@ -32,6 +31,7 @@ import de.bstly.board.model.QEntry;
import de.bstly.board.model.QLocalUser;
import de.bstly.board.repository.EntryRepository;
import de.bstly.board.repository.LocalUserRepository;
import de.bstly.board.security.LocalUserDetails;
/**
* The Class UserManager.
@ -43,22 +43,19 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
@Autowired
private LocalUserRepository localUserRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private EntryManager entryManager;
@Autowired
private EntryRepository entryRepository;
private QLocalUser qLocalUser = QLocalUser.localUser;
private QEntry qEntry = QEntry.entry;
@Value("${admin.password:}")
private String adminPassword;
@Value("${bstly.board.ranking.gravity:1.2}")
private double GRAVITY;
/*
* @see org.springframework.security.core.userdetails.UserDetailsService#
@ -76,6 +73,9 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
* @see org.springframework.security.core.userdetails.UserDetailsService#
* loadUserByUsername(java.lang.String)
*/
/*
* @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
*/
/*
* @see
* de.bstly.board.businesslogic.LocalUserManager#loadUserByUsername(java.lang.
@ -102,7 +102,20 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
passwordHash = "";
}
return new User(username, passwordHash, authorities);
LocalUserDetails userDetails = new LocalUserDetails(username, passwordHash, authorities);
userDetails.setGravity(GRAVITY);
if (localUser.getSettings().containsKey("gravity")) {
try {
userDetails.setGravity(Double.parseDouble(localUser.getSettings().get("gravity")));
} catch (Exception e) {
}
}
userDetails.setKarma(getKarma(username));
return userDetails;
}
/*
@ -121,6 +134,9 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
* @see org.springframework.beans.factory.SmartInitializingSingleton#
* afterSingletonsInstantiated()
*/
/*
* @see org.springframework.beans.factory.SmartInitializingSingleton#afterSingletonsInstantiated()
*/
/*
*
* @see org.springframework.beans.factory.SmartInitializingSingleton#
@ -245,9 +261,10 @@ public class UserManager implements UserDetailsService, SmartInitializingSinglet
}
/**
* Gets the karma.
*
* @param username
* @return
* @param username the username
* @return the karma
*/
public long getKarma(String username) {
long karma = 0;

View File

@ -7,6 +7,7 @@ import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
@ -17,6 +18,8 @@ import org.springframework.web.bind.annotation.RestController;
import com.google.common.collect.Lists;
import de.bstly.board.controller.support.EntityResponseStatusException;
import de.bstly.board.security.LocalUserDetails;
/**
* The Class AuthenticationController.
@ -25,22 +28,24 @@ import com.google.common.collect.Lists;
@RequestMapping("/auth")
public class AuthenticationController extends BaseController {
private static String authorizationRequestBaseUri = "oauth2/authorization";
@Autowired
private ClientRegistrationRepository clientRegistrationRepository;
/**
* Me.
*
* @return the authentication
* @return the object
*/
@GetMapping
public Authentication me() {
public Object me() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth;
if (auth != null && auth.getPrincipal() instanceof LocalUserDetails) {
return (LocalUserDetails) auth.getPrincipal();
}
throw new EntityResponseStatusException(HttpStatus.UNAUTHORIZED);
}
/**
@ -74,10 +79,8 @@ public class AuthenticationController extends BaseController {
*/
protected static class Client {
private String id;
private String loginUrl;
/**

View File

@ -9,14 +9,13 @@ import org.springframework.security.core.context.SecurityContextHolder;
import de.bstly.board.businesslogic.UserManager;
import de.bstly.board.model.LocalUser;
import de.bstly.board.security.LocalUserDetails;
/**
* The Class BaseController.
*/
public class BaseController {
@Autowired
private UserManager localUserManager;
@ -36,8 +35,20 @@ public class BaseController {
* @return the current username
*/
protected String getCurrentUsername() {
LocalUserDetails localUserDetails = getLocalUserDetails();
return localUserDetails != null ? localUserDetails.getUsername() : null;
}
/**
* Gets the local user details.
*
* @return the local user details
*/
protected LocalUserDetails getLocalUserDetails() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return auth != null ? auth.getName() : null;
return (auth != null && auth.getPrincipal() instanceof LocalUserDetails)
? (LocalUserDetails) auth.getPrincipal()
: null;
}
/**

View File

@ -48,6 +48,7 @@ public class BookmarksController extends BaseController {
*
* @param pageParameter the page parameter
* @param sizeParameter the size parameter
* @param ignoreParameter the ignore parameter
* @return the entries
*/
@PreAuthorize("isAuthenticated()")

View File

@ -41,19 +41,14 @@ public class CommentController extends BaseController {
@Autowired
private CommentManager commentManager;
@Autowired
private CommentValidator commentValidator;
@Autowired
private VoteManager voteManager;
@Value("${bstly.board.size:30}")
private int SIZE;
@Value("${bstly.board.ranking.gravity:1.2}")
private double GRAVITY;
/**
* Fetch by rank.
*
@ -63,6 +58,7 @@ public class CommentController extends BaseController {
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param gravityParameter the gravity parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@ -89,6 +85,7 @@ public class CommentController extends BaseController {
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param descParameter the desc parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@ -118,6 +115,7 @@ public class CommentController extends BaseController {
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param ascParameter the asc parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@ -155,6 +153,7 @@ public class CommentController extends BaseController {
* Gets the comment.
*
* @param id the id
* @param ignoreParameter the ignore parameter
* @return the comment
*/
@PreAuthorize("isAuthenticated()")
@ -176,6 +175,7 @@ public class CommentController extends BaseController {
* Creates the comment.
*
* @param comment the comment
* @param ignoreParameter the ignore parameter
* @return the comment
*/
@PreAuthorize("isAuthenticated()")

View File

@ -56,9 +56,6 @@ public class EntryController extends BaseController {
@Value("${bstly.board.size:30}")
private int SIZE;
@Value("${bstly.board.ranking.gravity:1.2}")
private double GRAVITY;
/**
* Fetch by ranking.
*
@ -66,6 +63,7 @@ public class EntryController extends BaseController {
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param gravityParameter the gravity parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@ -81,8 +79,48 @@ public class EntryController extends BaseController {
}
Page<RankedEntry> entries = entryManager.fetchByRanking(dateParameter.orElse(Instant.now()),
gravityParameter.orElse(GRAVITY), pageParameter.orElse(0),
sizeParameter.orElse(SIZE));
gravityParameter.orElse(getLocalUserDetails().getGravity()),
pageParameter.orElse(0), sizeParameter.orElse(SIZE));
Page<Entry> transformed = new PageImpl<Entry>(
entries.getContent().stream().map(rankedEntry -> {
Entry entry = Entry.fromRankedEntry(rankedEntry);
entry.getMetadata().put("points", rankedEntry.getPoints());
return entry;
}).collect(Collectors.toList()), entries.getPageable(), entries.getTotalElements());
List<String> ignore = ignoreParameter.orElse(Lists.newArrayList());
entryManager.applyMetadata(getCurrentUsername(), userManager.getKarma(getCurrentUsername()),
transformed.getContent(), ignore);
return transformed;
}
/**
* Fetch by ranking.
*
* @param pageParameter the page parameter
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param gravityParameter the gravity parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@GetMapping("/comments")
public Page<Entry> fetchByComments(@RequestParam("page") Optional<Integer> pageParameter,
@RequestParam("size") Optional<Integer> sizeParameter,
@RequestParam("date") Optional<Instant> dateParameter,
@RequestParam("gravity") Optional<Double> gravityParameter,
@RequestParam("ignore") Optional<List<String>> ignoreParameter) {
if (sizeParameter.isPresent() && sizeParameter.get() > 100) {
sizeParameter = Optional.of(100);
}
Page<RankedEntry> entries = entryManager.fetchByComments(
dateParameter.orElse(Instant.now()),
gravityParameter.orElse(getLocalUserDetails().getGravity()),
pageParameter.orElse(0), sizeParameter.orElse(SIZE));
Page<Entry> transformed = new PageImpl<Entry>(
entries.getContent().stream().map(rankedEntry -> Entry.fromRankedEntry(rankedEntry))
@ -101,6 +139,7 @@ public class EntryController extends BaseController {
* @param pageParameter the page parameter
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@ -130,6 +169,7 @@ public class EntryController extends BaseController {
* @param sizeParameter the size parameter
* @param dateParameter the date parameter
* @param ascParameter the asc parameter
* @param ignoreParameter the ignore parameter
* @return the page
*/
@PreAuthorize("isAuthenticated()")
@ -158,6 +198,7 @@ public class EntryController extends BaseController {
* Gets the entry.
*
* @param id the id
* @param ignoreParameter the ignore parameter
* @return the entry
*/
@PreAuthorize("isAuthenticated()")
@ -181,6 +222,7 @@ public class EntryController extends BaseController {
* Creates the entry.
*
* @param entry the entry
* @param ignoreParameter the ignore parameter
* @return the entry
*/
@PreAuthorize("isAuthenticated()")

View File

@ -275,7 +275,6 @@ public class Entry {
entry.setTitle(rankedEntry.getTitle());
entry.setText(rankedEntry.getText());
entry.setRanking(rankedEntry.getRanking());
entry.getMetadata().put("points", rankedEntry.getPoints());
return entry;
}

View File

@ -16,7 +16,6 @@ import org.springframework.stereotype.Repository;
import de.bstly.board.model.Entry;
import de.bstly.board.model.RankedEntry;
/**
* The Interface EntryRepository.
*/
@ -24,19 +23,21 @@ import de.bstly.board.model.RankedEntry;
public interface EntryRepository
extends JpaRepository<Entry, Long>, QuerydslPredicateExecutor<Entry> {
static final String UPVOTES_QUERY = "SELECT upvote.target,COUNT(upvote.id) AS count FROM votes as upvote WHERE upvote.type = 0 AND upvote.target_type = 1 GROUP BY upvote.target";
static final String DOWNVOTES_QUERY = "SELECT downvote.target,COUNT(downvote.id) AS count FROM votes as downvote WHERE downvote.type = 1 AND downvote.target_type = 1 GROUP BY downvote.target";
static final String COMMENTS_QUERY = "SELECT comment.target,COUNT(comment.id) AS count FROM comments as comment GROUP BY comment.target";
static final String CALCULATION_QUERY = "SELECT entry.*, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) as points, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) / POW(TIMESTAMPDIFF(HOUR, entry.created, :before)+2,:gravity) AS ranking FROM entries AS entry LEFT JOIN ("
static final String RANK_CALCULATION_QUERY = "SELECT entry.*, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) as points, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) / POW(TIMESTAMPDIFF(HOUR, entry.created, :before)+2,:gravity) AS ranking FROM entries AS entry LEFT JOIN ("
+ UPVOTES_QUERY
+ ") AS upvote ON upvote.target = entry.id LEFT JOIN ("
+ DOWNVOTES_QUERY
+ ") AS downvote ON downvote.target = entry.id WHERE entry.created < :before AND entry.entry_status = 'NORMAL' ORDER BY ranking DESC, entry.created DESC";
static final String COMMENT_CALCULATION_QUERY = "SELECT entry.*, IFNULL(comment.count,0) as comments, IFNULL(comment.count,0) / POW(TIMESTAMPDIFF(HOUR, entry.created, :before)+2,:gravity) AS ranking FROM entries AS entry LEFT JOIN ("
+ COMMENTS_QUERY
+ ") AS comment ON comment.target = entry.id WHERE entry.created < :before AND entry.entry_status = 'NORMAL' ORDER BY ranking DESC, entry.created DESC";
static final String ARCHIVE_CALCULATION_QUERY = "SELECT entry.*, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) as points, (IFNULL(upvote.count,0) - IFNULL(downvote.count,0)) / POW(TIMESTAMPDIFF(HOUR, entry.created, :before)+2,:gravity) AS ranking FROM entries AS entry LEFT JOIN ("
+ UPVOTES_QUERY
@ -44,12 +45,10 @@ public interface EntryRepository
+ DOWNVOTES_QUERY
+ ") AS downvote ON downvote.target = entry.id WHERE entry.created < :before ORDER BY ranking DESC, entry.created DESC";
static final String ADDITIONAL_QUERY = "SELECT entry.*, calculation.ranking, calculation.points FROM entries AS entry LEFT JOIN ("
+ CALCULATION_QUERY
+ RANK_CALCULATION_QUERY
+ ") as calculation on calculation.id = entry.id WHERE entry.created < :before ORDER BY calculation.ranking DESC, entry.created DESC";
static final String COUNT_QUERY = "SELECT count(*) FROM entries as entry WHERE entry.created < :before";
/**
@ -60,10 +59,22 @@ public interface EntryRepository
* @param pageable the pageable
* @return the page
*/
@Query(value = CALCULATION_QUERY, countQuery = COUNT_QUERY, nativeQuery = true)
@Query(value = RANK_CALCULATION_QUERY, countQuery = COUNT_QUERY, nativeQuery = true)
Page<RankedEntry> findAllByRanking(@Param("before") Instant before,
@Param("gravity") double gravity, Pageable pageable);
/**
* Find all by comments.
*
* @param before the before
* @param gravity the gravity
* @param pageable the pageable
* @return the page
*/
@Query(value = COMMENT_CALCULATION_QUERY, countQuery = COUNT_QUERY, nativeQuery = true)
Page<RankedEntry> findAllByComments(@Param("before") Instant before,
@Param("gravity") double gravity, Pageable pageable);
/**
* Find all by ranking archive.
*

View File

@ -0,0 +1,72 @@
/**
*
*/
package de.bstly.board.security;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
/**
* The Class LocalUserDetails.
*/
public class LocalUserDetails extends User {
/**
* default serialVersionUID
*/
private static final long serialVersionUID = 1L;
private double gravity;
private long karma;
/**
* Instantiates a new local user details.
*
* @param username the username
* @param password the password
* @param authorities the authorities
*/
public LocalUserDetails(String username, String password,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
/**
* Gets the gravity.
*
* @return the gravity
*/
public double getGravity() {
return gravity;
}
/**
* Sets the gravity.
*
* @param gravity the new gravity
*/
public void setGravity(double gravity) {
this.gravity = gravity;
}
/**
* Gets the karma.
*
* @return the karma
*/
public long getKarma() {
return karma;
}
/**
* Sets the karma.
*
* @param karma the new karma
*/
public void setKarma(long karma) {
this.karma = karma;
}
}

View File

@ -14,9 +14,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
@ -26,7 +25,6 @@ import com.google.common.collect.Lists;
import de.bstly.board.businesslogic.UserManager;
import de.bstly.board.model.LocalUser;
/**
* The Class OAuth2AuthenticationSuccessHandler.
*/
@ -34,34 +32,33 @@ import de.bstly.board.model.LocalUser;
public class OAuth2AuthenticationSuccessHandler
extends SavedRequestAwareAuthenticationSuccessHandler {
@Autowired
private UserManager localUserManager;
private RememberMeServices rememberMeServices;
/*
* @see org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.Authentication)
*/
/*
* @see org.springframework.security.web.authentication.
* SavedRequestAwareAuthenticationSuccessHandler#onAuthenticationSuccess(javax.
* servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
* org.springframework.security.core.Authentication)
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
LocalUser localUser = localUserManager.getByAuth(authentication);
UserDetails userDetails = localUserManager.loadUserByUsername(localUser.getUsername());
List<GrantedAuthority> authorities = Lists.newArrayList();
authorities.addAll(authentication.getAuthorities());
if (localUser.getRoles() != null) {
for (String role : localUser.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role));
}
}
User user = new User(localUser.getUsername(), "", authorities);
authorities.addAll(userDetails.getAuthorities());
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(
user, null, authorities);
userDetails, null, authorities);
SecurityContextHolder.getContext().setAuthentication(newAuthentication);