Skip to content

Commit

Permalink
Backend fetches GitHub and Twitter username (#201)
Browse files Browse the repository at this point in the history
* fetch github and twiter username from backend

* send notify message to builder topic for join and exit team
  • Loading branch information
yuanmomo authored Mar 10, 2024
1 parent 55f03fb commit 16220cd
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 26 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package com.dl.officialsite.common.utils;

import com.dl.officialsite.login.model.SessionUserInfo;
import com.dl.officialsite.oauth2.config.OAuthSessionKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.Optional;

@Slf4j
public abstract class HttpSessionUtils {
Expand Down Expand Up @@ -58,5 +60,13 @@ public static void clearLogin(HttpSession session) {
session.removeAttribute(MEMBER_ATTRIBUTE_KEY);
}

public static void setOAuthUserName(HttpSession session, OAuthSessionKey sessionKey, String githubName) {
session.setAttribute(sessionKey.toString(), githubName);
}

public static String getOAuthUserName(HttpSession session, OAuthSessionKey sessionKey) {
return Optional.ofNullable(session.getAttribute(sessionKey.toString()))
.map(Object::toString)
.orElse(null);
}
}
28 changes: 17 additions & 11 deletions src/main/java/com/dl/officialsite/member/MemberController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import com.dl.officialsite.bot.event.EventNotify;
import com.dl.officialsite.bot.event.NotifyMessageFactory;
import com.dl.officialsite.common.base.BaseResponse;
import com.dl.officialsite.common.utils.HttpSessionUtils;
import com.dl.officialsite.oauth2.config.OAuthSessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -27,6 +29,7 @@
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
Expand Down Expand Up @@ -125,12 +128,12 @@ public Predicate toPredicate(Root<Member> root, CriteriaQuery<?> criteriaQuery,
}

@PostMapping("/create")
public BaseResponse createMember(@Valid @RequestBody Member member, @RequestParam String address) {
public BaseResponse createMember(@Valid @RequestBody Member member, @RequestParam String address, HttpServletRequest request) {
member.setGithubId(HttpSessionUtils.getOAuthUserName(request.getSession(), OAuthSessionKey.GITHUB_USER_NAME));
member.setTweetId(HttpSessionUtils.getOAuthUserName(request.getSession(), OAuthSessionKey.TWITTER_USER_NAME));

this.setOAuthUserName(request.getSession(), member);

if (member.getGithubId() != null && member.getGithubId().equals("")) {
member.setGithubId(null);
}
MemberVo _member = memberService.save(member);

applicationContext.publishEvent(new EventNotify(Member.class, BotEnum.TELEGRAM, ChannelEnum.GENERAL,
Expand All @@ -140,17 +143,17 @@ public BaseResponse createMember(@Valid @RequestBody Member member, @RequestPara


@PutMapping("/update")
public BaseResponse updateMemberByAddress(@RequestParam String address, @RequestBody MemberVo member) {
public BaseResponse updateMemberByAddress(@RequestParam String address, @RequestBody MemberVo member, HttpServletRequest request) {
Optional<Member> memberData = memberRepository.findByAddress(address);

if (memberData.isPresent()) {
Member _member = memberData.get();
if (member.getGithubId() != null) {
_member.setGithubId(member.getGithubId());
}
if (member.getTweetId() != null) {
_member.setTweetId(member.getTweetId());
}

Optional.ofNullable(HttpSessionUtils.getOAuthUserName(request.getSession(), OAuthSessionKey.GITHUB_USER_NAME))
.ifPresent(githubUserName -> _member.setGithubId(githubUserName));
Optional.ofNullable(HttpSessionUtils.getOAuthUserName(request.getSession(), OAuthSessionKey.TWITTER_USER_NAME))
.ifPresent(twitterUserName -> _member.setTweetId(twitterUserName));

if (member.getWechatId() != null) {
_member.setWechatId(member.getWechatId());
}
Expand Down Expand Up @@ -211,4 +214,7 @@ private Long getMemberId(HttpSession session) {
return memberId;
}

private void setOAuthUserName(HttpSession session, Member member) {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
*
*/


package com.dl.officialsite.oauth2.config;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;

@Getter
@ToString
@AllArgsConstructor
public enum OAuthSessionKey {
GITHUB_USER_NAME("GITHUB_USER_NAME"),
TWITTER_USER_NAME("TWITTER_USER_NAME")
;

private String sessionKey;


}
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,31 @@
import com.dl.officialsite.common.base.BaseResponse;
import com.dl.officialsite.common.utils.HttpSessionUtils;
import com.dl.officialsite.common.utils.UserSecurityUtils;
import com.dl.officialsite.oauth2.config.RegistrationConfig;
import com.dl.officialsite.oauth2.config.OAuthConfig;
import com.dl.officialsite.oauth2.handler.bind.IOAuthBindHandler;
import com.dl.officialsite.oauth2.config.OAuthSessionKey;
import com.dl.officialsite.oauth2.config.RegistrationConfig;
import com.dl.officialsite.oauth2.handler.bind.OAuthBindHandlers;
import com.dl.officialsite.oauth2.handler.userinfo.IUserInfoRetrieveHandler;
import com.dl.officialsite.oauth2.handler.userinfo.UserInfoRetrieveHandlers;
import com.dl.officialsite.oauth2.manager.OAuthUsernameManager;
import com.dl.officialsite.oauth2.model.bo.AccessTokenResponse;
import com.dl.officialsite.oauth2.model.bo.user.IUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.manager.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.keygen.Base64StringKeyGenerator;
import org.springframework.security.crypto.keygen.StringKeyGenerator;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
Expand Down Expand Up @@ -136,6 +138,7 @@ public BaseResponse<String> receiveAuthorizationCode(
@PathVariable String registrationId,
@RequestParam("code") String code,
@RequestParam("state") String state,
HttpServletRequest request,
HttpServletResponse response,
HttpSession httpSession
) throws Exception{
Expand Down Expand Up @@ -164,15 +167,15 @@ public BaseResponse<String> receiveAuthorizationCode(
}
String accessToken = accessTokenResponse.getAccessToken();
log.info("access token received: {}", accessToken);
return BaseResponse.successWithData(accessToken);
/**
* 3. Get user info via access_token
*/
// IUserInfoRetrieveHandler retrieveHandler = this.userInfoRetrieveHandlers.get(registrationId);
// Assert.notNull(retrieveHandler, "retrieveHandler not found:"+registrationId);
// IUserInfo userInfo = retrieveHandler.retrieve(registration.getUserInfoUri(), accessToken);
// log.info("user info {}", userInfo.getUsername());
// Assert.notNull(userInfo, "failed to find userInfo");
IUserInfoRetrieveHandler retrieveHandler = this.userInfoRetrieveHandlers.get(registrationId);
Assert.notNull(retrieveHandler, "retrieveHandler not found:"+registrationId);
IUserInfo userInfo = retrieveHandler.retrieve(registration.getUserInfoUri(), accessToken);
log.info("user info {}", userInfo.getUsername());
Assert.notNull(userInfo, "failed to find userInfo");
HttpSessionUtils.setOAuthUserName(request.getSession(), OAuthSessionKey.GITHUB_USER_NAME, userInfo.getUsername());
/**
* 4. Bind userInfo
*/
Expand All @@ -184,6 +187,7 @@ public BaseResponse<String> receiveAuthorizationCode(
//
// response.addCookie(new Cookie("oauth_"+registrationId, userInfo.getUsername()));
// return BaseResponse.successWithData(userInfo.getUsername());
return BaseResponse.successWithData(accessToken);
}

@GetMapping("username/{registrationId}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@


import com.dl.officialsite.common.base.BaseResponse;
import com.dl.officialsite.common.utils.HttpSessionUtils;
import com.dl.officialsite.common.utils.UserSecurityUtils;
import com.dl.officialsite.oauth2.config.OAuthConfig;
import com.dl.officialsite.oauth2.config.OAuthSessionKey;
import com.dl.officialsite.oauth2.config.RegistrationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -20,6 +22,7 @@
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
Expand Down Expand Up @@ -74,9 +77,11 @@ private String generateAuthorizeUrl(boolean test) {
public BaseResponse getTwitter(
@RequestParam("oauth_token") String oauthToken,
@RequestParam("oauth_verifier") String oauthVerifier,
@RequestParam(value = "secret", required = false) String secret
@RequestParam(value = "secret", required = false) String secret,
HttpServletRequest request
) {
String twitterUserName = fetchProfile(oauthToken, oauthVerifier, secret);
HttpSessionUtils.setOAuthUserName(request.getSession(), OAuthSessionKey.TWITTER_USER_NAME, twitterUserName);
return BaseResponse.successWithData(twitterUserName);
}

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/dl/officialsite/team/TeamService.java
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ public void join(TeamMemberJoinVO teamMember) {
log.info("发送邮件给管理员:{},接收地址{}", email, mailAddress);
emailService.memberJoinTeam(mailAddress, subject, content);
applicationContext.publishEvent(new EventNotify(Member.class, BotEnum.TELEGRAM,
ChannelEnum.GENERAL,
ChannelEnum.BUILDER,
NotifyMessageFactory.joinTeamMessage(member1.getNickName(), team.getTeamName())));
} else {
throw new BizException(CodeEnums.TEAM_ADMIN_NOT_EXIST.getCode(),
Expand Down Expand Up @@ -220,7 +220,7 @@ public void join(TeamMemberJoinVO teamMember) {
log.info("发送邮件给管理员:{},接收地址{}", email, mailAddress);
emailService.memberJoinTeam(mailAddress, subject, content);
applicationContext.publishEvent(new EventNotify(Member.class, BotEnum.TELEGRAM,
ChannelEnum.GENERAL,
ChannelEnum.BUILDER,
NotifyMessageFactory.joinTeamMessage(member1.getNickName(), team.getTeamName())));
} else {
throw new BizException(CodeEnums.TEAM_ADMIN_NOT_EXIST.getCode(),
Expand Down Expand Up @@ -274,7 +274,7 @@ public void exit(TeamMemberJoinVO teamMember, String address) {
String text = member1.getNickName() + "成员退出";
emailService.sendMail(member.get().getEmail(), subject, text);
applicationContext.publishEvent(new EventNotify(Member.class, BotEnum.TELEGRAM,
ChannelEnum.GENERAL,
ChannelEnum.BUILDER,
NotifyMessageFactory.exitTeamMessage(member1.getNickName(), team.getTeamName())));
} else {
throw new BizException(CodeEnums.NOT_AUTHORITY_FOR_EXIT.getCode(),
Expand Down

0 comments on commit 16220cd

Please sign in to comment.