Merge pull request #221 from nagisa77/codex/add-x-twitter-login-support

Add Twitter OAuth login
This commit is contained in:
Tim
2025-07-16 16:21:15 +08:00
committed by GitHub
11 changed files with 258 additions and 0 deletions

View File

@@ -50,6 +50,9 @@ OpenIsle 基于 Spring Boot 构建,提供社区后台常见的注册、登录
- `GITHUB_CLIENT_ID`GitHub OAuth 客户端 ID
- `GITHUB_CLIENT_SECRET`GitHub OAuth 客户端密钥
- `VUE_APP_GITHUB_CLIENT_ID`:前端 GitHub OAuth 客户端 ID
- `TWITTER_CLIENT_ID`Twitter OAuth 客户端 ID
- `TWITTER_CLIENT_SECRET`Twitter OAuth 客户端密钥
- `VUE_APP_TWITTER_CLIENT_ID`:前端 Twitter OAuth 客户端 ID
- `JWT_SECRET`JWT 签名密钥
- `JWT_EXPIRATION`JWT 过期时间(毫秒)
- `PASSWORD_STRENGTH`密码强度LOW、MEDIUM、HIGH
@@ -73,6 +76,7 @@ mvn spring-boot:run
- `POST /api/auth/login`:登录并获取 Token
- `POST /api/auth/google`Google 登录并获取 Token
- `POST /api/auth/github`GitHub 登录并获取 Token
- `POST /api/auth/twitter`Twitter 登录并获取 Token
- `GET /api/config`:查看验证码开关配置
- 需要认证的接口示例:`GET /api/hello`(需 `Authorization` 头)
- 管理员接口示例:`GET /api/admin/hello`

View File

@@ -0,0 +1,4 @@
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<title>Twitter icon</title>
<path d="M23.954 4.569c-.885.389-1.83.654-2.825.775 1.014-.611 1.794-1.574 2.163-2.723-.949.555-2.005.959-3.127 1.184-.897-.959-2.173-1.559-3.591-1.559-2.717 0-4.92 2.203-4.92 4.917 0 .39.045.765.127 1.124-4.083-.205-7.697-2.159-10.126-5.134-.422.722-.666 1.561-.666 2.475 0 1.709.87 3.214 2.188 4.096-.807-.026-1.566-.248-2.229-.616v.061c0 2.385 1.693 4.374 3.946 4.827-.413.111-.849.171-1.296.171-.314 0-.615-.03-.916-.086.631 1.953 2.445 3.376 4.6 3.416-1.68 1.318-3.808 2.105-6.102 2.105-.39 0-.779-.023-1.17-.069 2.189 1.394 4.768 2.209 7.548 2.209 9.051 0 14.001-7.496 14.001-13.986 0-.21 0-.42-.015-.63.961-.689 1.8-1.56 2.46-2.548l-.047-.02z"/>
</svg>

After

Width:  |  Height:  |  Size: 764 B

View File

@@ -19,6 +19,7 @@ export const API_PORT = 8081
export const API_BASE_URL = "";
export const GOOGLE_CLIENT_ID = '777830451304-nt8afkkap18gui4f9entcha99unal744.apps.googleusercontent.com'
export const GITHUB_CLIENT_ID = 'Ov23liVkO1NPAX5JyWxJ'
export const TWITTER_CLIENT_ID = 'YOUR_TWITTER_CLIENT_ID'
export const toast = useToast()
initTheme()

View File

@@ -12,6 +12,7 @@ import SettingsPageView from '../views/SettingsPageView.vue'
import ProfileView from '../views/ProfileView.vue'
import NotFoundPageView from '../views/NotFoundPageView.vue'
import GithubCallbackPageView from '../views/GithubCallbackPageView.vue'
import TwitterCallbackPageView from '../views/TwitterCallbackPageView.vue'
const routes = [
{
@@ -74,6 +75,11 @@ const routes = [
name: 'github-callback',
component: GithubCallbackPageView
},
{
path: '/twitter-callback',
name: 'twitter-callback',
component: TwitterCallbackPageView
},
{
path: '/404',
name: 'not-found',

View File

@@ -0,0 +1,41 @@
import { API_BASE_URL, TWITTER_CLIENT_ID, toast } from '../main'
import { setToken, loadCurrentUser } from './auth'
export function twitterAuthorize(state = '') {
if (!TWITTER_CLIENT_ID) {
toast.error('Twitter 登录不可用')
return
}
const redirectUri = `${window.location.origin}/twitter-callback`
const url = `https://twitter.com/i/oauth2/authorize?response_type=code&client_id=${TWITTER_CLIENT_ID}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=tweet.read%20users.read&state=${state}`
window.location.href = url
}
export async function twitterExchange(code, state, reason) {
try {
const res = await fetch(`${API_BASE_URL}/api/auth/twitter`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code, redirectUri: `${window.location.origin}/twitter-callback`, reason, state })
})
const data = await res.json()
if (res.ok && data.token) {
setToken(data.token)
await loadCurrentUser()
toast.success('登录成功')
return { success: true, needReason: false }
} else if (data.reason_code === 'NOT_APPROVED') {
toast.info('当前为注册审核模式,请填写注册理由')
return { success: false, needReason: true, token: data.token }
} else if (data.reason_code === 'IS_APPROVING') {
toast.info('您的注册理由正在审批中')
return { success: true, needReason: false }
} else {
toast.error(data.error || '登录失败')
return { success: false, needReason: false, error: data.error || '登录失败' }
}
} catch (e) {
toast.error('登录失败')
return { success: false, needReason: false, error: '登录失败' }
}
}

View File

@@ -38,6 +38,10 @@
<img class="login-page-button-icon" src="../assets/icons/github.svg" alt="GitHub Logo" />
<div class="login-page-button-text">GitHub 登录</div>
</div>
<div class="login-page-button" @click="loginWithTwitter">
<img class="login-page-button-icon" src="../assets/icons/twitter.svg" alt="Twitter Logo" />
<div class="login-page-button-text">Twitter 登录</div>
</div>
</div>
</div>
</template>
@@ -47,6 +51,7 @@ import { API_BASE_URL, toast } from '../main'
import { setToken, loadCurrentUser } from '../utils/auth'
import { googleSignIn } from '../utils/google'
import { githubAuthorize } from '../utils/github'
import { twitterAuthorize } from '../utils/twitter'
import BaseInput from '../components/BaseInput.vue'
export default {
name: 'LoginPageView',
@@ -101,6 +106,9 @@ export default {
},
loginWithGithub() {
githubAuthorize()
},
loginWithTwitter() {
twitterAuthorize()
}
}
}

View File

@@ -80,6 +80,10 @@
<img class="signup-page-button-icon" src="../assets/icons/github.svg" alt="GitHub Logo" />
<div class="signup-page-button-text">GitHub 注册</div>
</div>
<div class="signup-page-button" @click="signupWithTwitter">
<img class="signup-page-button-icon" src="../assets/icons/twitter.svg" alt="Twitter Logo" />
<div class="signup-page-button-text">Twitter 注册</div>
</div>
</div>
</div>
</template>
@@ -88,6 +92,7 @@
import { API_BASE_URL, toast } from '../main'
import { googleSignIn } from '../utils/google'
import { githubAuthorize } from '../utils/github'
import { twitterAuthorize } from '../utils/twitter'
import BaseInput from '../components/BaseInput.vue'
export default {
name: 'SignupPageView',
@@ -208,6 +213,9 @@ export default {
},
signupWithGithub() {
githubAuthorize()
},
signupWithTwitter() {
twitterAuthorize()
}
}
}

View File

@@ -0,0 +1,46 @@
<template>
<div class="twitter-callback-page">
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
<div class="twitter-callback-page-text">Magic is happening...</div>
</div>
</template>
<script>
import { twitterExchange } from '../utils/twitter'
import { hatch } from 'ldrs'
hatch.register()
export default {
name: 'TwitterCallbackPageView',
async mounted() {
const url = new URL(window.location.href)
const code = url.searchParams.get('code')
const state = url.searchParams.get('state')
const result = await twitterExchange(code, state, '')
if (result.needReason) {
this.$router.push('/signup-reason?token=' + result.token)
} else {
this.$router.push('/')
}
}
}
</script>
<style scoped>
.twitter-callback-page {
background-color: var(--background-color);
height: calc(100vh - var(--header-height));
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.twitter-callback-page-text {
margin-top: 25px;
font-size: 16px;
color: var(--primary-color);
font-weight: bold;
}
</style>

View File

@@ -7,6 +7,7 @@ import com.openisle.service.UserService;
import com.openisle.service.CaptchaService;
import com.openisle.service.GoogleAuthService;
import com.openisle.service.GithubAuthService;
import com.openisle.service.TwitterAuthService;
import com.openisle.service.RegisterModeService;
import com.openisle.service.NotificationService;
import com.openisle.model.RegisterMode;
@@ -30,6 +31,7 @@ public class AuthController {
private final CaptchaService captchaService;
private final GoogleAuthService googleAuthService;
private final GithubAuthService githubAuthService;
private final TwitterAuthService twitterAuthService;
private final RegisterModeService registerModeService;
private final NotificationService notificationService;
private final UserRepository userRepository;
@@ -197,6 +199,36 @@ public class AuthController {
));
}
@PostMapping("/twitter")
public ResponseEntity<?> loginWithTwitter(@RequestBody TwitterLoginRequest req) {
Optional<User> user = twitterAuthService.authenticate(req.getCode(), registerModeService.getRegisterMode(), req.getRedirectUri());
if (user.isPresent()) {
if (RegisterMode.DIRECT.equals(registerModeService.getRegisterMode())) {
return ResponseEntity.ok(Map.of("token", jwtService.generateToken(user.get().getUsername())));
}
if (!user.get().isApproved()) {
if (user.get().getRegisterReason() != null && !user.get().getRegisterReason().isEmpty()) {
return ResponseEntity.badRequest().body(Map.of(
"error", "Account awaiting approval",
"reason_code", "IS_APPROVING",
"token", jwtService.generateReasonToken(user.get().getUsername())
));
}
return ResponseEntity.badRequest().body(Map.of(
"error", "Account awaiting approval",
"reason_code", "NOT_APPROVED",
"token", jwtService.generateReasonToken(user.get().getUsername())
));
}
return ResponseEntity.ok(Map.of("token", jwtService.generateToken(user.get().getUsername())));
}
return ResponseEntity.badRequest().body(Map.of(
"error", "Invalid twitter code",
"reason_code", "INVALID_CREDENTIALS"
));
}
@GetMapping("/check")
public ResponseEntity<?> checkToken() {
return ResponseEntity.ok(Map.of("valid", true));
@@ -228,6 +260,12 @@ public class AuthController {
private String redirectUri;
}
@Data
private static class TwitterLoginRequest {
private String code;
private String redirectUri;
}
@Data
private static class VerifyRequest {
private String username;

View File

@@ -0,0 +1,99 @@
package com.openisle.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.openisle.model.Role;
import com.openisle.model.User;
import com.openisle.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.*;
@Service
@RequiredArgsConstructor
public class TwitterAuthService {
private final UserRepository userRepository;
private final RestTemplate restTemplate = new RestTemplate();
@Value("${twitter.client-id:}")
private String clientId;
@Value("${twitter.client-secret:}")
private String clientSecret;
public Optional<User> authenticate(String code, com.openisle.model.RegisterMode mode, String redirectUri) {
try {
String tokenUrl = "https://api.twitter.com/2/oauth2/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> body = new HashMap<>();
body.put("client_id", clientId);
body.put("client_secret", clientSecret);
body.put("code", code);
body.put("grant_type", "authorization_code");
if (redirectUri != null) {
body.put("redirect_uri", redirectUri);
}
HttpEntity<Map<String, String>> request = new HttpEntity<>(body, headers);
ResponseEntity<JsonNode> tokenRes = restTemplate.postForEntity(tokenUrl, request, JsonNode.class);
if (!tokenRes.getStatusCode().is2xxSuccessful() || tokenRes.getBody() == null || !tokenRes.getBody().has("access_token")) {
return Optional.empty();
}
String accessToken = tokenRes.getBody().get("access_token").asText();
HttpHeaders authHeaders = new HttpHeaders();
authHeaders.setBearerAuth(accessToken);
HttpEntity<Void> entity = new HttpEntity<>(authHeaders);
ResponseEntity<JsonNode> userRes = restTemplate.exchange(
"https://api.twitter.com/2/users/me", HttpMethod.GET, entity, JsonNode.class);
if (!userRes.getStatusCode().is2xxSuccessful() || userRes.getBody() == null) {
return Optional.empty();
}
JsonNode userNode = userRes.getBody();
String username = userNode.hasNonNull("username") ? userNode.get("username").asText() : null;
String email = null;
if (userNode.hasNonNull("email")) {
email = userNode.get("email").asText();
}
if (email == null) {
email = username + "@twitter.com";
}
return Optional.of(processUser(email, username, mode));
} catch (Exception e) {
return Optional.empty();
}
}
private User processUser(String email, String username, com.openisle.model.RegisterMode mode) {
Optional<User> existing = userRepository.findByEmail(email);
if (existing.isPresent()) {
User user = existing.get();
if (!user.isVerified()) {
user.setVerified(true);
user.setVerificationCode(null);
userRepository.save(user);
}
return user;
}
String baseUsername = username != null ? username : email.split("@")[0];
String finalUsername = baseUsername;
int suffix = 1;
while (userRepository.findByUsername(finalUsername).isPresent()) {
finalUsername = baseUsername + suffix++;
}
User user = new User();
user.setUsername(finalUsername);
user.setEmail(email);
user.setPassword("");
user.setRole(Role.USER);
user.setVerified(true);
user.setApproved(mode == com.openisle.model.RegisterMode.DIRECT);
user.setAvatar("https://twitter.com/" + finalUsername + "/profile_image");
return userRepository.save(user);
}
}

View File

@@ -53,6 +53,9 @@ google.client-id=${GOOGLE_CLIENT_ID:}
# GitHub OAuth configuration
github.client-id=${GITHUB_CLIENT_ID:}
github.client-secret=${GITHUB_CLIENT_SECRET:}
# Twitter OAuth configuration
twitter.client-id=${TWITTER_CLIENT_ID:}
twitter.client-secret=${TWITTER_CLIENT_SECRET:}
# OpenAI configuration
openai.api-key=${OPENAI_API_KEY:}
openai.model=${OPENAI_MODEL:gpt-4o}