diff options
author | Vitaly Takmazov | 2019-04-29 14:06:24 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2019-04-29 14:06:24 +0300 |
commit | c3a9365645ec94d5b7c9778ab32c93e5eb4be5f6 (patch) | |
tree | d853fc7df61fdc18a20a52c93291853796e9a60f | |
parent | 409ef92da23f4b650340197e7383ba8b528999e4 (diff) |
UserUtils -> @Visitor
19 files changed, 190 insertions, 211 deletions
diff --git a/src/main/java/com/juick/server/api/Messages.java b/src/main/java/com/juick/server/api/Messages.java index 402d2162..3ac272f2 100644 --- a/src/main/java/com/juick/server/api/Messages.java +++ b/src/main/java/com/juick/server/api/Messages.java @@ -25,11 +25,10 @@ import com.juick.server.www.WebApp; import com.juick.service.component.MessageReadEvent; import com.juick.model.CommandResult; import com.juick.server.util.HttpBadRequestException; -import com.juick.server.util.HttpNotFoundException; -import com.juick.server.util.UserUtils; import com.juick.service.MessagesService; import com.juick.service.TagService; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.Pair; import org.springframework.beans.factory.annotation.Value; @@ -78,8 +77,8 @@ public class Messages { @GetMapping("/api/home") public ResponseEntity<List<com.juick.Message>> getHome( + @Visitor User visitor, @RequestParam(defaultValue = "0") int before_mid) { - User visitor = UserUtils.getCurrentUser(); if (!visitor.isAnonymous()) { int vuid = visitor.getUid(); List<Integer> mids = messagesService.getMyFeed(vuid, before_mid, true); @@ -92,6 +91,7 @@ public class Messages { @GetMapping("/api/messages") public ResponseEntity<List<com.juick.Message>> getMessages( + @Visitor User visitor, @RequestParam(required = false) String uname, @RequestParam(name = "before_mid", defaultValue = "0") Integer before, @RequestParam(required = false, defaultValue = "0") Integer daysback, @@ -101,8 +101,6 @@ public class Messages { @RequestParam(required = false, defaultValue = "0") Integer page, @RequestParam(required = false) String media, @RequestParam(required = false) String tag) { - - User visitor = UserUtils.getCurrentUser(); List<Integer> mids; if (!StringUtils.isEmpty(uname)) { User user = userService.getUserByName(uname); @@ -151,8 +149,9 @@ public class Messages { return ResponseEntity.ok(msgs); } @DeleteMapping("/api/messages") - public CommandResult deleteMessage(@RequestParam int mid, @RequestParam(required = false, defaultValue = "0") int rid) { - User visitor = UserUtils.getCurrentUser(); + public CommandResult deleteMessage( + @Visitor User visitor, + @RequestParam int mid, @RequestParam(required = false, defaultValue = "0") int rid) { if (rid > 0) { if (messagesService.deleteReply(visitor.getUid(), mid, rid)) { return CommandResult.fromString("Reply deleted"); @@ -163,17 +162,20 @@ public class Messages { } throw new HttpBadRequestException(); } + @GetMapping("/api/messages/discussions") public List<Message> getDiscussions( - @RequestParam(required = false, defaultValue = "0") Long to) { - List<Message> msgs = messagesService.getMessages(UserUtils.getCurrentUser(), messagesService.getDiscussions(UserUtils.getCurrentUser().getUid(), to)); + @Visitor User visitor, + @RequestParam(required = false, defaultValue = "0") Long to) { + List<Message> msgs = messagesService.getMessages(visitor, + messagesService.getDiscussions(visitor.getUid(), to)); msgs.forEach(m -> m.getUser().setAvatar(webApp.getAvatarUrl(m.getUser()))); return msgs; } @GetMapping("/api/thread") public ResponseEntity<List<com.juick.Message>> getThread( + @Visitor User visitor, @RequestParam(defaultValue = "0") int mid) { - User visitor = UserUtils.getCurrentUser(); Optional<Message> message = messagesService.getMessage(mid); if (message.isPresent()) { Message msg = message.get(); @@ -199,8 +201,9 @@ public class Messages { return NOT_FOUND; } @GetMapping(value = "/api/thread/mark_read/{mid}-{rid}.gif", produces = MediaType.IMAGE_GIF_VALUE) - public byte[] markThreadRead(@PathVariable int mid, @PathVariable int rid) throws IOException { - User visitor = UserUtils.getCurrentUser(); + public byte[] markThreadRead( + @Visitor User visitor, + @PathVariable int mid, @PathVariable int rid) throws IOException { if (!visitor.isAnonymous()) { messagesService.setLastReadComment(visitor, mid, rid); Message msg = messagesService.getMessage(mid).orElseThrow(IllegalStateException::new); diff --git a/src/main/java/com/juick/server/api/Notifications.java b/src/main/java/com/juick/server/api/Notifications.java index 6829653c..f2c2d712 100644 --- a/src/main/java/com/juick/server/api/Notifications.java +++ b/src/main/java/com/juick/server/api/Notifications.java @@ -17,18 +17,19 @@ package com.juick.server.api; +import com.juick.ExternalToken; import com.juick.Message; import com.juick.Status; -import com.juick.ExternalToken; import com.juick.User; import com.juick.model.AnonymousUser; import com.juick.server.util.HttpBadRequestException; -import com.juick.server.util.UserUtils; import com.juick.service.MessagesService; import com.juick.service.PushQueriesService; import com.juick.service.SubscriptionService; import com.juick.service.TelegramService; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; +import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -41,7 +42,6 @@ import springfox.documentation.annotations.ApiIgnore; import javax.inject.Inject; import java.io.IOException; -import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; @@ -62,6 +62,8 @@ public class Notifications { private UserService userService; @Inject private TelegramService telegramService; + @Value("${api_user:juick}") + private String serviceUser; private User collectTokens(Integer uid) { @@ -84,11 +86,11 @@ public class Notifications { @ApiIgnore @RequestMapping(value = "/api/notifications", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<List<User>> doGet( + @Visitor User visitor, @RequestParam(required = false, defaultValue = "0") int uid, @RequestParam(required = false, defaultValue = "0") int mid, @RequestParam(required = false, defaultValue = "0") int rid) { - User visitor = UserUtils.getCurrentUser(); - if (!(visitor.getName().equals("juick"))) { + if (!(visitor.getName().equals(serviceUser))) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null); } if (uid > 0 && mid == 0) { @@ -119,9 +121,9 @@ public class Notifications { @ApiIgnore @RequestMapping(value = "/api/notifications", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<Status> doDelete( + @Visitor User visitor, @RequestBody List<ExternalToken> list) { - User visitor = UserUtils.getCurrentUser(); - if (!visitor.getName().equals("juick")) { + if (!visitor.getName().equals(serviceUser)) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null); } list.forEach(t -> { @@ -145,9 +147,9 @@ public class Notifications { @ApiIgnore @RequestMapping(value = "/api/notifications/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity<Status> doDeleteTokens( + @Visitor User visitor, @RequestBody List<ExternalToken> list) { - User visitor = UserUtils.getCurrentUser(); - if (!visitor.getName().equals("juick")) { + if (!visitor.getName().equals(serviceUser)) { return ResponseEntity.status(HttpStatus.FORBIDDEN).body(null); } list.forEach(t -> { @@ -172,8 +174,8 @@ public class Notifications { @ApiIgnore @RequestMapping(value = "/api/notifications", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Status doPut( + @Visitor User visitor, @RequestBody List<ExternalToken> list) throws IOException { - User visitor = UserUtils.getCurrentUser(); list.forEach(t -> { switch (t.getType()) { case "gcm": @@ -195,8 +197,8 @@ public class Notifications { @Deprecated @RequestMapping(value = "/api/android/register", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Status doAndroidRegister( + @Visitor User visitor, @RequestParam(name = "regid") String regId) { - User visitor = UserUtils.getCurrentUser(); pushQueriesService.addGCMToken(visitor.getUid(), regId); return Status.OK; } @@ -204,9 +206,8 @@ public class Notifications { @Deprecated @RequestMapping(value = "/api/winphone/register", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public Status doWinphoneRegister( - Principal principal, + @Visitor User visitor, @RequestParam(name = "url") String regId) { - User visitor = UserUtils.getCurrentUser(); pushQueriesService.addMPNSToken(visitor.getUid(), regId); return Status.OK; } diff --git a/src/main/java/com/juick/server/api/PM.java b/src/main/java/com/juick/server/api/PM.java index 06dc9733..b65841c0 100644 --- a/src/main/java/com/juick/server/api/PM.java +++ b/src/main/java/com/juick/server/api/PM.java @@ -20,13 +20,16 @@ package com.juick.server.api; import com.juick.Chat; import com.juick.Message; import com.juick.User; -import com.juick.server.www.WebApp; -import com.juick.service.component.MessageEvent; import com.juick.model.AnonymousUser; import com.juick.model.PrivateChats; -import com.juick.server.util.*; +import com.juick.server.util.HttpBadRequestException; +import com.juick.server.util.HttpForbiddenException; +import com.juick.server.util.WebUtils; +import com.juick.server.www.WebApp; import com.juick.service.PMQueriesService; import com.juick.service.UserService; +import com.juick.service.component.MessageEvent; +import com.juick.service.security.annotation.Visitor; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; @@ -54,8 +57,8 @@ public class PM { @RequestMapping(value = "/api/pm", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public List<com.juick.Message> doGetPM( + @Visitor User visitor, @RequestParam(required = false) String uname) { - User visitor = UserUtils.getCurrentUser(); int uid = 0; if (uname != null && uname.matches("^[a-zA-Z0-9\\-]{2,16}$")) { uid = userService.getUIDbyName(uname); @@ -72,9 +75,9 @@ public class PM { @RequestMapping(value = "/api/pm", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public com.juick.Message doPostPM( + @Visitor User visitor, @RequestParam String uname, @RequestParam String body) { - User visitor = UserUtils.getCurrentUser(); User userTo = AnonymousUser.INSTANCE; if (WebUtils.isUserName(uname)) { userTo = userService.getUserByName(uname); @@ -102,8 +105,8 @@ public class PM { } @RequestMapping(value = "/api/groups_pms", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public PrivateChats doGetGroupsPMs( + @Visitor User visitor, @RequestParam(defaultValue = "5") int cnt) { - User visitor = UserUtils.getCurrentUser(); // TODO: ignore cnt param for now but make sure paging param will not be cnt List<Chat> lastconv = pmQueriesService.getLastChats(visitor); diff --git a/src/main/java/com/juick/server/api/Post.java b/src/main/java/com/juick/server/api/Post.java index b575cef8..10e19faf 100644 --- a/src/main/java/com/juick/server/api/Post.java +++ b/src/main/java/com/juick/server/api/Post.java @@ -21,12 +21,16 @@ import com.juick.Message; import com.juick.Reaction; import com.juick.Status; import com.juick.User; -import com.juick.server.CommandsManager; import com.juick.model.CommandResult; -import com.juick.server.util.*; +import com.juick.server.CommandsManager; +import com.juick.server.util.HttpBadRequestException; +import com.juick.server.util.HttpForbiddenException; +import com.juick.server.util.HttpNotFoundException; +import com.juick.server.util.HttpUtils; import com.juick.service.MessagesService; import com.juick.service.SubscriptionService; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -66,10 +70,10 @@ public class Post { @RequestMapping(value = "/api/post", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseStatus(value = HttpStatus.OK) public CommandResult doPostMessage( + @Visitor User visitor, @RequestParam(required = false, defaultValue = StringUtils.EMPTY) String body, @RequestParam(required = false) String img, @RequestParam(required = false) MultipartFile attach) throws Exception { - User visitor = UserUtils.getCurrentUser(); body = body.replace("\r", StringUtils.EMPTY); URI attachmentFName = HttpUtils.receiveMultiPartFile(attach, tmpDir); @@ -97,13 +101,13 @@ public class Post { @RequestMapping(value = "/api/comment", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public CommandResult doPostComment( + @Visitor User visitor, @RequestParam(defaultValue = "0") int mid, @RequestParam(defaultValue = "0") int rid, @RequestParam(required = false, defaultValue = StringUtils.EMPTY) final String body, @RequestParam(required = false) String img, @RequestParam(required = false) MultipartFile attach) throws Exception { - User visitor = UserUtils.getCurrentUser(); if (mid == 0) { throw new HttpBadRequestException(); } @@ -149,8 +153,7 @@ public class Post { @PostMapping("/api/like") @ResponseStatus(value = HttpStatus.OK) - public Status doPostRecomm(@RequestParam Integer mid) throws Exception { - com.juick.User visitor = UserUtils.getCurrentUser(); + public Status doPostRecomm(@Visitor User visitor, @RequestParam Integer mid) throws Exception { Optional<com.juick.Message> message = messagesService.getMessage(mid); if (!message.isPresent()) { throw new HttpNotFoundException(); @@ -166,8 +169,8 @@ public class Post { @PostMapping("/api/subscribe") @ResponseStatus(value = HttpStatus.OK) - public Status doPostSubscribe(@RequestParam Integer mid) throws Exception { - com.juick.User visitor = UserUtils.getCurrentUser(); + public Status doPostSubscribe(@Visitor User visitor, + @RequestParam Integer mid) throws Exception { Optional<com.juick.Message> message = messagesService.getMessage(mid); if (!message.isPresent()) { throw new HttpNotFoundException(); @@ -189,11 +192,12 @@ public class Post { @PostMapping("/api/react") @ResponseStatus(value = HttpStatus.OK) - public Status doPostReact(@RequestParam Integer mid,@RequestParam @NotNull int reactionId, - @RequestParam (required = false, defaultValue = "1") int count) { + public Status doPostReact( + @Visitor User visitor, + @RequestParam Integer mid, @RequestParam @NotNull int reactionId, + @RequestParam(required = false, defaultValue = "1") int count) { logger.info("got reaction with type: {}", reactionId); - com.juick.User visitor = UserUtils.getCurrentUser(); Optional<com.juick.Message> message = messagesService.getMessage(mid); if (!message.isPresent()) { throw new HttpNotFoundException(); @@ -211,10 +215,10 @@ public class Post { } @PostMapping("/api/update") - public CommandResult updateMessage(@RequestParam Integer mid, - @RequestParam(required = false, defaultValue = "0") Integer rid, - @RequestParam String body) { - User visitor = UserUtils.getCurrentUser(); + public CommandResult updateMessage(@Visitor User visitor, + @RequestParam Integer mid, + @RequestParam(required = false, defaultValue = "0") Integer rid, + @RequestParam String body) { User author = rid == 0 ? messagesService.getMessageAuthor(mid) : messagesService.getReply(mid, rid).getUser(); if (visitor.equals(author)) { if (messagesService.updateMessage(mid, rid, body)) { diff --git a/src/main/java/com/juick/server/api/Service.java b/src/main/java/com/juick/server/api/Service.java index 27316d91..791e09ce 100644 --- a/src/main/java/com/juick/server/api/Service.java +++ b/src/main/java/com/juick/server/api/Service.java @@ -1,14 +1,13 @@ package com.juick.server.api; -import com.juick.Message; import com.juick.User; import com.juick.server.CommandsManager; import com.juick.server.EmailManager; import com.juick.server.ServerManager; import com.juick.server.util.HttpForbiddenException; -import com.juick.server.util.UserUtils; import com.juick.service.EmailService; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; @@ -64,8 +63,8 @@ public class Service { @ApiIgnore @PostMapping("/api/mail") @ResponseStatus(value = HttpStatus.OK) - public void processMail(InputStream data) throws Exception { - if (UserUtils.getCurrentUser().getName().equals(serviceUser)) { + public void processMail(@Visitor User current, InputStream data) throws Exception { + if (current.getName().equals(serviceUser)) { MimeMessage msg = new MimeMessage(session, data); String[] returnPaths = msg.getHeader("Return-Path"); if (returnPaths != null) { @@ -90,7 +89,7 @@ public class Service { body[0] = IOUtils.toString(a.getInputStream(), StandardCharsets.UTF_8); logger.info("got text: {}", body[0]); } catch (IOException e) { - logger.info("attachment error: {}", e); + logger.info("attachment error", e); } }); } @@ -145,8 +144,7 @@ public class Service { .forEach(session -> serverManager.getSessions().remove(session)); } @GetMapping("/api/events") - public SseEmitter handle() throws IOException { - User visitor = UserUtils.getCurrentUser(); + public SseEmitter handle(@Visitor User visitor) throws IOException { logger.info("{} connected", visitor.getName()); if (!visitor.isAnonymous()) { userService.updateLastSeen(visitor); diff --git a/src/main/java/com/juick/server/api/Tags.java b/src/main/java/com/juick/server/api/Tags.java index 7a8e572a..35f2bc66 100644 --- a/src/main/java/com/juick/server/api/Tags.java +++ b/src/main/java/com/juick/server/api/Tags.java @@ -19,8 +19,8 @@ package com.juick.server.api; import com.juick.User; import com.juick.model.TagStats; -import com.juick.server.util.UserUtils; import com.juick.service.TagService; +import com.juick.service.security.annotation.Visitor; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -40,9 +40,9 @@ public class Tags { @RequestMapping(value = "/api/tags", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public List<TagStats> tags( + @Visitor User visitor, @RequestParam(required = false, defaultValue = "0") int user_id ) { - User visitor = UserUtils.getCurrentUser(); if (user_id == 0) { user_id = visitor.getUid(); } diff --git a/src/main/java/com/juick/server/api/Users.java b/src/main/java/com/juick/server/api/Users.java index 33b3704b..1a046ad8 100644 --- a/src/main/java/com/juick/server/api/Users.java +++ b/src/main/java/com/juick/server/api/Users.java @@ -22,10 +22,11 @@ import com.juick.model.AnonymousUser; import com.juick.model.ApplicationStatus; import com.juick.server.util.HttpNotFoundException; import com.juick.server.util.HttpUtils; -import com.juick.server.util.UserUtils; import com.juick.server.util.WebUtils; import com.juick.server.www.WebApp; import com.juick.service.*; +import com.juick.service.security.annotation.Visitor; +import com.juick.service.security.entities.JuickUser; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; @@ -61,12 +62,13 @@ public class Users { private String tmpDir; @RequestMapping(value = "/api/auth", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) - public String getAuthToken() { - return userService.getHashByUID(UserUtils.getCurrentUser().getUid()); + public String getAuthToken(@Visitor User visitor) { + return userService.getHashByUID(visitor.getUid()); } @RequestMapping(value = "/api/users", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public List<User> doGetUsers( + @Visitor User visitor, @RequestParam(value = "uname", required = false) List<String> unames) { List<com.juick.User> users = new ArrayList<>(); @@ -79,8 +81,7 @@ public class Users { users.forEach(u -> u.setAvatar(webApp.getAvatarUrl(u))); if (!users.isEmpty()) return users; - if (!UserUtils.getCurrentUser().isAnonymous()) { - User visitor = UserUtils.getCurrentUser(); + if (!visitor.isAnonymous()) { visitor.setAvatar(webApp.getAvatarUrl(visitor)); return Collections.singletonList(visitor); } @@ -89,12 +90,11 @@ public class Users { } @GetMapping("/api/me") - public SecureUser getMe() { - User visitor = UserUtils.getCurrentUser(); + public SecureUser getMe(@Visitor User visitor) { SecureUser me = new SecureUser(); me.setUid(visitor.getUid()); me.setName(visitor.getName()); - me.setAuthHash(getAuthToken()); + me.setAuthHash(getAuthToken(visitor)); List<Integer> unread = messagesService.getUnread(visitor); me.setUnread(unread); me.setUnreadCount(unread.size()); @@ -104,8 +104,8 @@ public class Users { return (SecureUser)userService.getUserInfo(me); } @PostMapping("/api/me/upload") - public void updateInfo(@RequestParam MultipartFile avatar) throws IOException { - User visitor = UserUtils.getCurrentUser(); + public void updateInfo(@Visitor User visitor, + @RequestParam MultipartFile avatar) throws IOException { String avatarTmpPath = HttpUtils.receiveMultiPartFile(avatar, tmpDir).getHost(); if (StringUtils.isNotEmpty(avatarTmpPath)) { imagesService.saveAvatar(avatarTmpPath, visitor.getUid()); @@ -114,8 +114,8 @@ public class Users { @RequestMapping(value = "/api/users/read", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public List<User> doGetUserRead( + @Visitor User visitor, @RequestParam String uname) { - User visitor = UserUtils.getCurrentUser(); int uid = 0; if (uname == null) { uid = visitor.getUid(); @@ -138,8 +138,8 @@ public class Users { @RequestMapping(value = "/api/users/readers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public List<User> doGetUserReaders( + @Visitor User visitor, @RequestParam String uname) { - User visitor = UserUtils.getCurrentUser(); int uid = 0; if (uname == null) { uid = visitor.getUid(); @@ -161,11 +161,11 @@ public class Users { } @GetMapping("/api/info/{uname}") - public User getUserInfo(@PathVariable String uname) { + public User getUserInfo(@Visitor User visitor, @PathVariable String uname) { User user = userService.getUserByName(uname); if (!user.isBanned()) { - user.setRead(doGetUserRead(uname)); - user.setReaders(doGetUserReaders(uname)); + user.setRead(doGetUserRead(visitor, uname)); + user.setReaders(doGetUserReaders(visitor, uname)); user.setAvatar(webApp.getAvatarUrl(user)); return userService.getUserInfo(user); } diff --git a/src/main/java/com/juick/server/api/activity/Profile.java b/src/main/java/com/juick/server/api/activity/Profile.java index 701b1949..a7ba65a5 100644 --- a/src/main/java/com/juick/server/api/activity/Profile.java +++ b/src/main/java/com/juick/server/api/activity/Profile.java @@ -25,11 +25,14 @@ import com.juick.server.api.activity.model.objects.OrderedCollectionPage; import com.juick.server.api.activity.model.objects.Person; import com.juick.server.util.HttpBadRequestException; import com.juick.server.util.HttpNotFoundException; -import com.juick.server.util.UserUtils; import com.juick.server.www.WebApp; import com.juick.service.MessagesService; import com.juick.service.UserService; -import com.juick.service.activities.*; +import com.juick.service.activities.AnnounceEvent; +import com.juick.service.activities.FollowEvent; +import com.juick.service.activities.UndoAnnounceEvent; +import com.juick.service.activities.UndoFollowEvent; +import com.juick.service.security.annotation.Visitor; import com.overzealous.remark.Remark; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -43,20 +46,15 @@ import org.springframework.http.ResponseEntity; 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.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import javax.inject.Inject; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -132,15 +130,15 @@ public class Profile { } @GetMapping(value = "/u/{userName}/blog", produces = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE}) - public OrderedCollectionPage getOutboxPage(@PathVariable String userName, + public OrderedCollectionPage getOutboxPage(@Visitor User visitor, @PathVariable String userName, @RequestParam(required = false, defaultValue = "0") int before) { - User visitor = UserUtils.getCurrentUser(); User user = userService.getUserByName(userName); if (!user.isAnonymous() && !user.isBanned()) { UriComponentsBuilder uri = UriComponentsBuilder.fromUriString(baseUri); String personUri = uri.path(String.format("/u/%s", userName)).toUriString(); List<Integer> mids = messagesService.getUserBlog(user.getUid(), 0, before); - List<Note> notes = messagesService.getMessages(visitor, mids).stream().map(activityPubManager::makeNote).collect(Collectors.toList()); + List<Note> notes = messagesService.getMessages(visitor, mids) + .stream().map(activityPubManager::makeNote).collect(Collectors.toList()); OrderedCollectionPage page = new OrderedCollectionPage(); page.setPartOf(uri.replacePath(String.format("/u/%s/blog/toc", userName)).toUriString()); page.setFirst(uri.replacePath(String.format("/u/%s/blog", userName)).toUriString()); @@ -260,12 +258,15 @@ public class Profile { } @PostMapping(value = "/api/inbox", consumes = {Context.LD_JSON_MEDIA_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE}) - public ResponseEntity<CommandResult> processInbox(InputStream inboxData) throws Exception { + public ResponseEntity<CommandResult> processInbox( + @Visitor User visitor, + InputStream inboxData) throws Exception { String inbox = IOUtils.toString(inboxData, StandardCharsets.UTF_8); logger.info("Inbox: {}", inbox); Activity activity = jsonMapper.readValue(inbox, Activity.class); - User visitor = UserUtils.getCurrentUser(); - if ((StringUtils.isNotEmpty(visitor.getUri().toString()) && visitor.getUri().equals(URI.create(activity.getActor()))) || !visitor.isAnonymous()) { + if ((StringUtils.isNotEmpty(visitor.getUri().toString()) + && visitor.getUri().equals(URI.create(activity.getActor()))) + || !visitor.isAnonymous()) { if (activity instanceof Follow) { Follow followRequest = (Follow) activity; applicationEventPublisher.publishEvent( diff --git a/src/main/java/com/juick/server/api/rss/Feeds.java b/src/main/java/com/juick/server/api/rss/Feeds.java index d6e0587c..5a5d42eb 100644 --- a/src/main/java/com/juick/server/api/rss/Feeds.java +++ b/src/main/java/com/juick/server/api/rss/Feeds.java @@ -19,9 +19,9 @@ package com.juick.server.api.rss; import com.juick.User; import com.juick.server.util.HttpNotFoundException; -import com.juick.server.util.UserUtils; import com.juick.service.MessagesService; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -43,25 +43,27 @@ public class Feeds { private UserService userService; @GetMapping("/rss/{userName}/blog") - public ModelAndView getBlog(@PathVariable String userName) { + public ModelAndView getBlog(@Visitor User visitor, @PathVariable String userName) { User user = userService.getUserByName(userName); if (!user.isAnonymous() && !user.isBanned()) { List<Integer> mids = messagesService.getUserBlog(user.getUid(), 0, 0); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("messagesView"); modelAndView.addObject("user", user); - modelAndView.addObject("messages", messagesService.getMessages(UserUtils.getCurrentUser(), mids)); + modelAndView.addObject("messages", messagesService.getMessages(visitor, mids)); return modelAndView; } throw new HttpNotFoundException(); } @GetMapping("/rss/") - public ModelAndView getLast(@RequestParam(value = "hours", required = false, defaultValue = "0") Integer hours) { + public ModelAndView getLast( + @Visitor User visitor, + @RequestParam(value = "hours", required = false, defaultValue = "0") Integer hours) { List<Integer> mids = messagesService.getLastMessages(hours); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("messagesView"); - modelAndView.addObject("messages", messagesService.getMessages(UserUtils.getCurrentUser(),mids)); + modelAndView.addObject("messages", messagesService.getMessages(visitor, mids)); return modelAndView; } @GetMapping("/rss/comments") diff --git a/src/main/java/com/juick/server/util/UserUtils.java b/src/main/java/com/juick/server/util/UserUtils.java deleted file mode 100644 index 1adc85ab..00000000 --- a/src/main/java/com/juick/server/util/UserUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2008-2017, Juick - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -package com.juick.server.util; - -import com.juick.User; -import com.juick.model.AnonymousUser; -import com.juick.service.security.entities.JuickUser; -import javax.annotation.Nonnull; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; - -/** - * Created by aalexeev on 11/14/16. - */ -public class UserUtils { - private UserUtils() { - throw new IllegalStateException(); - } - - public static Authentication getAuthentication() { - return SecurityContextHolder.getContext().getAuthentication(); - } - - public static Object getPrincipal(final Authentication authentication) { - return authentication == null ? null : authentication.getPrincipal(); - } - - @Nonnull - public static User getCurrentUser() { - Object principal = getPrincipal(getAuthentication()); - - if (principal instanceof JuickUser) - return ((JuickUser) principal).getUser(); - - if (principal instanceof User) - return (User) principal; - - return AnonymousUser.INSTANCE; - } -} diff --git a/src/main/java/com/juick/server/www/controllers/Help.java b/src/main/java/com/juick/server/www/controllers/Help.java index 12abee80..909e8acb 100644 --- a/src/main/java/com/juick/server/www/controllers/Help.java +++ b/src/main/java/com/juick/server/www/controllers/Help.java @@ -17,11 +17,12 @@ package com.juick.server.www.controllers; +import com.juick.User; import com.juick.server.util.HttpNotFoundException; -import com.juick.server.util.UserUtils; +import com.juick.server.www.HelpService; import com.juick.server.www.WebApp; import com.juick.service.MessagesService; -import com.juick.server.www.HelpService; +import com.juick.service.security.annotation.Visitor; import org.commonmark.parser.Parser; import org.commonmark.renderer.html.HtmlRenderer; import org.springframework.stereotype.Controller; @@ -30,8 +31,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import javax.inject.Inject; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Locale; import java.util.Objects; @@ -53,12 +52,12 @@ public class Help { @GetMapping({"/help/", "/help", "/help/{langOrPage}", "/help/{lang}/{page}"}) public String showHelp( + @Visitor User visitor, Locale locale, @PathVariable(required = false, name = "lang") String lang, @PathVariable(required = false, name = "page") String page, @PathVariable(required = false, name = "langOrPage") String langOrPage, - Model model) throws IOException, URISyntaxException { - com.juick.User visitor = UserUtils.getCurrentUser(); + Model model) { visitor.setAvatar(webApp.getAvatarWebPath(visitor)); String navigation = null; diff --git a/src/main/java/com/juick/server/www/controllers/Login.java b/src/main/java/com/juick/server/www/controllers/Login.java index d933934e..9fca57e7 100644 --- a/src/main/java/com/juick/server/www/controllers/Login.java +++ b/src/main/java/com/juick/server/www/controllers/Login.java @@ -16,8 +16,9 @@ */ package com.juick.server.www.controllers; -import com.juick.server.util.UserUtils; +import com.juick.User; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; @@ -34,17 +35,17 @@ public class Login { private UserService userService; @GetMapping("/login") - public String getloginForm(@RequestParam(required = false, defaultValue = "true") boolean redirect) { - com.juick.User visitor = UserUtils.getCurrentUser(); - + public String getloginForm( + @Visitor User visitor, + @RequestParam(required = false, defaultValue = "true") boolean redirect) { if (!visitor.isAnonymous()) { return redirect ? "redirect:/" : "redirect:/login/success"; } return "views/login"; } @GetMapping("/login/success") - public String getSuccessLogin(ModelMap model) { - model.addAttribute("hash", userService.getHashByUID(UserUtils.getCurrentUser().getUid())); + public String getSuccessLogin(@Visitor User visitor, ModelMap model) { + model.addAttribute("hash", userService.getHashByUID(visitor.getUid())); return "views/login_success"; } } diff --git a/src/main/java/com/juick/server/www/controllers/MessagesWWW.java b/src/main/java/com/juick/server/www/controllers/MessagesWWW.java index e1c1bed8..501c0d82 100644 --- a/src/main/java/com/juick/server/www/controllers/MessagesWWW.java +++ b/src/main/java/com/juick/server/www/controllers/MessagesWWW.java @@ -18,14 +18,15 @@ package com.juick.server.www.controllers; import com.juick.Message; import com.juick.Tag; +import com.juick.User; import com.juick.formatters.PlainTextFormatter; import com.juick.server.Utils; import com.juick.server.util.HttpForbiddenException; import com.juick.server.util.HttpNotFoundException; -import com.juick.server.util.UserUtils; import com.juick.server.util.WebUtils; import com.juick.server.www.WebApp; import com.juick.service.*; +import com.juick.service.security.annotation.Visitor; import com.juick.util.MessageUtils; import org.apache.commons.codec.CharEncoding; import org.apache.commons.lang3.StringUtils; @@ -92,6 +93,7 @@ public class MessagesWWW { @GetMapping("/") protected String doGet( + @Visitor User visitor, @RequestParam(required = false) String tag, @RequestParam(name = "show", required = false) String paramShow, @RequestParam(name = "search", required = false) String paramSearch, @@ -103,8 +105,6 @@ public class MessagesWWW { if (tag != null) { return "redirect:/tag/" + URLEncoder.encode(tag, StandardCharsets.UTF_8); } - com.juick.User visitor = UserUtils.getCurrentUser(); - visitor.setAvatar(webApp.getAvatarWebPath(visitor)); if (paramSearch != null && paramSearch.length() > 64) { @@ -199,6 +199,7 @@ public class MessagesWWW { @GetMapping(path = "/{uname}/", headers = "Connection!=Upgrade") protected String doGetBlog( + @Visitor User visitor, @RequestParam(required = false, name = "show") String paramShow, @RequestParam(required = false, name = "tag") String paramTagStr, @RequestParam(required = false, name = "search") String paramSearch, @@ -208,7 +209,6 @@ public class MessagesWWW { @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, ModelMap model) throws IOException { com.juick.User user = userService.getUserByName(uname); - com.juick.User visitor = UserUtils.getCurrentUser(); if (user.isBanned() || user.isAnonymous()) { throw new HttpNotFoundException(); } @@ -317,9 +317,10 @@ public class MessagesWWW { } @GetMapping("/{uname}/tags") - protected String doGetTags(@PathVariable String uname, ModelMap model) { + protected String doGetTags( + @Visitor User visitor, + @PathVariable String uname, ModelMap model) { com.juick.User user = userService.getUserByName(uname); - com.juick.User visitor = UserUtils.getCurrentUser(); if (visitor.isBanned()) { throw new HttpNotFoundException(); } @@ -336,9 +337,10 @@ public class MessagesWWW { } @GetMapping("/{uname}/friends") - protected String doGetFriends(@PathVariable String uname, ModelMap model) { + protected String doGetFriends( + @Visitor User visitor, + @PathVariable String uname, ModelMap model) { com.juick.User user = userService.getUserByName(uname); - com.juick.User visitor = UserUtils.getCurrentUser(); if (visitor.isBanned()) { throw new HttpNotFoundException(); } @@ -353,9 +355,10 @@ public class MessagesWWW { } @GetMapping("/{uname}/readers") - protected String doGetReaders(@PathVariable String uname, ModelMap model) throws IOException { + protected String doGetReaders( + @Visitor User visitor, + @PathVariable String uname, ModelMap model) throws IOException { com.juick.User user = userService.getUserByName(uname); - com.juick.User visitor = UserUtils.getCurrentUser(); visitor.setAvatar(webApp.getAvatarWebPath(visitor)); model.addAttribute("title", "Читатели " + user.getName()); model.addAttribute("headers", "<meta name=\"robots\" content=\"noindex\"/>"); @@ -367,9 +370,10 @@ public class MessagesWWW { } @GetMapping("/{uname}/bl") - protected String doGetBL(@PathVariable String uname, ModelMap model) throws IOException { + protected String doGetBL( + @Visitor User visitor, + @PathVariable String uname, ModelMap model) throws IOException { com.juick.User user = userService.getUserByName(uname); - com.juick.User visitor = UserUtils.getCurrentUser(); if (visitor.getUid() != user.getUid()) { throw new HttpForbiddenException(); } @@ -383,12 +387,13 @@ public class MessagesWWW { return "views/users"; } @GetMapping("/tag/{tagName}") - protected String tagAction(HttpServletRequest request, - @PathVariable String tagName, - @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, - @RequestParam(required = false, defaultValue = "0") int before, - ModelMap model) throws IOException { - com.juick.User visitor = UserUtils.getCurrentUser(); + protected String tagAction( + @Visitor User visitor, + HttpServletRequest request, + @PathVariable String tagName, + @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, + @RequestParam(required = false, defaultValue = "0") int before, + ModelMap model) throws IOException { visitor.setAvatar(webApp.getAvatarWebPath(visitor)); String paramTagStr = StringEscapeUtils.unescapeHtml4(tagName); com.juick.Tag paramTag = tagService.getTag(paramTagStr, false); @@ -457,8 +462,7 @@ public class MessagesWWW { return "views/index"; } @GetMapping("/pm/inbox") - protected String doGetInbox(ModelMap model) { - com.juick.User visitor = UserUtils.getCurrentUser(); + protected String doGetInbox(@Visitor User visitor, ModelMap model) { if (visitor.isAnonymous()) { return "redirect:/login"; } @@ -475,9 +479,10 @@ public class MessagesWWW { } @GetMapping("/pm/sent") - protected String doGetSent(@RequestParam(required = false) String uname, - ModelMap model) { - com.juick.User visitor = UserUtils.getCurrentUser(); + protected String doGetSent( + @Visitor User visitor, + @RequestParam(required = false) String uname, + ModelMap model) { if (visitor.isAnonymous()) { return "redirect:/login"; } @@ -497,13 +502,12 @@ public class MessagesWWW { return "views/pm_sent"; } @GetMapping(value = "/{uname}/{mid}", produces = MediaType.TEXT_HTML_VALUE) - protected String threadAction(ModelMap model, - @PathVariable String uname, - @PathVariable int mid, - @CookieValue(name = "sape_cookie", - required = false, defaultValue = StringUtils.EMPTY) String sapeCookie) { - com.juick.User visitor = UserUtils.getCurrentUser(); - + protected String threadAction( + @Visitor User visitor, + ModelMap model, + @PathVariable String uname, + @PathVariable int mid, + @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie) { if (!messagesService.canViewThread(mid, visitor.getUid())) { throw new HttpForbiddenException(); } @@ -603,8 +607,9 @@ public class MessagesWWW { } @GetMapping("/post") - protected String postAction(@RequestParam(required = false) String body, ModelMap model) { - com.juick.User visitor = UserUtils.getCurrentUser(); + protected String postAction( + @Visitor User visitor, + @RequestParam(required = false) String body, ModelMap model) { fillUserModel(model, visitor, visitor); visitor.setAvatar(webApp.getAvatarWebPath(visitor)); model.addAttribute("title", "Написать"); diff --git a/src/main/java/com/juick/server/www/controllers/Settings.java b/src/main/java/com/juick/server/www/controllers/Settings.java index d5a21d09..370c2154 100644 --- a/src/main/java/com/juick/server/www/controllers/Settings.java +++ b/src/main/java/com/juick/server/www/controllers/Settings.java @@ -20,9 +20,9 @@ import com.juick.User; import com.juick.model.NotifyOpts; import com.juick.server.util.HttpBadRequestException; import com.juick.server.util.HttpUtils; -import com.juick.server.util.UserUtils; import com.juick.server.www.WebApp; import com.juick.service.*; +import com.juick.service.security.annotation.Visitor; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -79,8 +79,10 @@ public class Settings { private WebApp webApp; @GetMapping("/settings") - protected String doGet(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException { - com.juick.User visitor = UserUtils.getCurrentUser(); + protected String doGet( + @Visitor User visitor, + HttpServletRequest request, + HttpServletResponse response, ModelMap model) throws IOException { if (visitor.isAnonymous()) { response.sendRedirect("/login"); } @@ -119,11 +121,12 @@ public class Settings { } @PostMapping("/settings") - protected String doPost(HttpServletRequest request, HttpServletResponse response, - @RequestParam(required = false) MultipartFile avatar, - ModelMap model) + protected String doPost( + @Visitor User visitor, + HttpServletRequest request, HttpServletResponse response, + @RequestParam(required = false) MultipartFile avatar, + ModelMap model) throws IOException { - com.juick.User visitor = UserUtils.getCurrentUser(); if (visitor.isAnonymous()) { throw new HttpBadRequestException(); } @@ -261,9 +264,10 @@ public class Settings { return "views/settings_result"; } @PostMapping("/settings/unsubscribe") - public String unsubscribeOneClick(@RequestParam(name = "List-Unsubscribe") String unsubscribe, - ModelMap model) { - User user = UserUtils.getCurrentUser(); + public String unsubscribeOneClick( + @Visitor User user, + @RequestParam(name = "List-Unsubscribe") String unsubscribe, + ModelMap model) { if (!user.isAnonymous()) { if (unsubscribe.equals("One-Click")) { emailService.setNotificationsEmail(user.getUid(), StringUtils.EMPTY); diff --git a/src/main/java/com/juick/server/www/controllers/SignUp.java b/src/main/java/com/juick/server/www/controllers/SignUp.java index 30223952..8793478a 100644 --- a/src/main/java/com/juick/server/www/controllers/SignUp.java +++ b/src/main/java/com/juick/server/www/controllers/SignUp.java @@ -16,13 +16,14 @@ */ package com.juick.server.www.controllers; +import com.juick.User; import com.juick.server.util.HttpBadRequestException; import com.juick.server.util.HttpForbiddenException; -import com.juick.server.util.UserUtils; import com.juick.server.www.WebApp; import com.juick.service.CrosspostService; import com.juick.service.EmailService; import com.juick.service.UserService; +import com.juick.service.security.annotation.Visitor; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; @@ -51,9 +52,9 @@ public class SignUp { @GetMapping("/signup") - protected String doGet(@RequestParam String type, @RequestParam String hash, ModelMap model) { - com.juick.User visitor = UserUtils.getCurrentUser(); - + protected String doGet( + @Visitor User visitor, + @RequestParam String type, @RequestParam String hash, ModelMap model) { if (hash.length() > 36 || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) { throw new HttpBadRequestException(); @@ -91,6 +92,7 @@ public class SignUp { @PostMapping("/signup") protected String doPost( + @Visitor User visitor, HttpServletResponse response, @RequestParam String type, @RequestParam String hash, @@ -98,7 +100,6 @@ public class SignUp { @RequestParam(required = false) String username, @RequestParam(required = false) String password, ModelMap modelMap) { - com.juick.User visitor = UserUtils.getCurrentUser(); int uid = 0; if (hash.length() > 36 || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) { diff --git a/src/main/java/com/juick/server/www/controllers/SocialLogin.java b/src/main/java/com/juick/server/www/controllers/SocialLogin.java index 35d3c1f8..8081c54b 100644 --- a/src/main/java/com/juick/server/www/controllers/SocialLogin.java +++ b/src/main/java/com/juick/server/www/controllers/SocialLogin.java @@ -25,14 +25,14 @@ import com.github.scribejava.core.model.*; import com.github.scribejava.core.oauth.OAuth10aService; import com.github.scribejava.core.oauth.OAuth20Service; import com.juick.model.facebook.User; +import com.juick.model.vk.UsersResponse; import com.juick.server.Utils; import com.juick.server.util.HttpBadRequestException; -import com.juick.server.util.UserUtils; import com.juick.service.CrosspostService; import com.juick.service.EmailService; import com.juick.service.TelegramService; import com.juick.service.UserService; -import com.juick.model.vk.UsersResponse; +import com.juick.service.security.annotation.Visitor; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.digest.HmacAlgorithms; import org.apache.commons.codec.digest.HmacUtils; @@ -180,7 +180,9 @@ public class SocialLogin { } } @GetMapping("/_twitter") - protected void doTwitterLogin(HttpServletRequest request, HttpServletResponse response) + protected void doTwitterLogin( + @Visitor com.juick.User user, + HttpServletRequest request, HttpServletResponse response) throws IOException, ExecutionException, InterruptedException { String hash = StringUtils.EMPTY, request_token = StringUtils.EMPTY, request_token_secret = StringUtils.EMPTY; String verifier = request.getParameter("oauth_verifier"); @@ -196,7 +198,6 @@ public class SocialLogin { request_token_secret = cookie.getValue(); } } - com.juick.User user = UserUtils.getCurrentUser(); OAuth10aService oAuthService = twitterBuilder .apiSecret(twitterConsumerSecret) .callback("https://juick.com/_twitter") diff --git a/src/main/java/com/juick/service/security/HTTPSignatureAuthenticationFilter.java b/src/main/java/com/juick/service/security/HTTPSignatureAuthenticationFilter.java index 44d97207..158841b4 100644 --- a/src/main/java/com/juick/service/security/HTTPSignatureAuthenticationFilter.java +++ b/src/main/java/com/juick/service/security/HTTPSignatureAuthenticationFilter.java @@ -3,12 +3,11 @@ package com.juick.service.security; import com.juick.User; import com.juick.server.SignatureManager; import com.juick.service.UserService; -import org.apache.commons.io.IOUtils; +import com.juick.service.security.entities.JuickUser; import org.apache.commons.lang3.StringUtils; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; @@ -18,7 +17,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; import java.util.stream.Collectors; @@ -51,7 +49,8 @@ public class HTTPSignatureAuthenticationFilter extends OncePerRequestFilter { Authentication authentication = new UsernamePasswordAuthenticationToken(userWithPassword.getName(), userWithPassword.getCredentials()); SecurityContextHolder.getContext().setAuthentication(authentication); } else { - Authentication authentication = new AnonymousAuthenticationToken(userUri, user, Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))); + Authentication authentication = new AnonymousAuthenticationToken(userUri, + new JuickUser(user), JuickUser.ANONYMOUS_AUTHORITY); SecurityContextHolder.getContext().setAuthentication(authentication); } } diff --git a/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java b/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java index 2fd5a2a7..0a80a28c 100644 --- a/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java +++ b/src/main/java/com/juick/service/security/HashParamAuthenticationFilter.java @@ -18,8 +18,8 @@ package com.juick.service.security; import com.juick.User; -import com.juick.service.security.entities.JuickUser; import com.juick.service.UserService; +import com.juick.service.security.entities.JuickUser; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.RememberMeAuthenticationToken; import org.springframework.security.core.Authentication; diff --git a/src/main/java/com/juick/service/security/annotation/Visitor.java b/src/main/java/com/juick/service/security/annotation/Visitor.java new file mode 100644 index 00000000..14d7cc87 --- /dev/null +++ b/src/main/java/com/juick/service/security/annotation/Visitor.java @@ -0,0 +1,12 @@ +package com.juick.service.security.annotation; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; + +import java.lang.annotation.*; + +@Target({ ElementType.PARAMETER, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@AuthenticationPrincipal(errorOnInvalidType = true, expression = "user") +public @interface Visitor { +} |