mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-23 06:30:48 +08:00
Merge pull request #222 from nagisa77/codex/add-discord-login-support
Add Discord OAuth support
This commit is contained in:
@@ -21,6 +21,7 @@ OpenIsle 基于 Spring Boot 构建,提供社区后台常见的注册、登录
|
||||
* **JWT 认证**:登录后获得 Token,接口通过 `Authorization: Bearer` 认证
|
||||
* **Google 登录**:支持使用 Google OAuth 登录
|
||||
* **GitHub 登录**:支持使用 GitHub OAuth 登录
|
||||
* **Discord 登录**:支持使用 Discord OAuth 登录
|
||||
* **邮件通知**:抽象 `EmailSender`,默认实现基于 Resend
|
||||
* **角色权限**:内置 `ADMIN` 与 `USER`,管理员接口以 `/api/admin/**` 提供
|
||||
* **文章与评论**:支持分类、评论及多级回复
|
||||
@@ -50,6 +51,9 @@ OpenIsle 基于 Spring Boot 构建,提供社区后台常见的注册、登录
|
||||
- `GITHUB_CLIENT_ID`:GitHub OAuth 客户端 ID
|
||||
- `GITHUB_CLIENT_SECRET`:GitHub OAuth 客户端密钥
|
||||
- `VUE_APP_GITHUB_CLIENT_ID`:前端 GitHub OAuth 客户端 ID
|
||||
- `DISCORD_CLIENT_ID`:Discord OAuth 客户端 ID
|
||||
- `DISCORD_CLIENT_SECRET`:Discord OAuth 客户端密钥
|
||||
- `VUE_APP_DISCORD_CLIENT_ID`:前端 Discord OAuth 客户端 ID
|
||||
- `TWITTER_CLIENT_ID`:Twitter OAuth 客户端 ID
|
||||
- `TWITTER_CLIENT_SECRET`:Twitter OAuth 客户端密钥
|
||||
- `VUE_APP_TWITTER_CLIENT_ID`:前端 Twitter OAuth 客户端 ID
|
||||
@@ -76,6 +80,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/discord`:Discord 登录并获取 Token
|
||||
- `POST /api/auth/twitter`:Twitter 登录并获取 Token
|
||||
- `GET /api/config`:查看验证码开关配置
|
||||
- 需要认证的接口示例:`GET /api/hello`(需 `Authorization` 头)
|
||||
|
||||
1
open-isle-cli/src/assets/icons/discord.svg
Normal file
1
open-isle-cli/src/assets/icons/discord.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Discord</title><path d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
@@ -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 DISCORD_CLIENT_ID = ''
|
||||
export const TWITTER_CLIENT_ID = 'ZTRTU05KSk9KTTJrTTdrVC1tc1E6MTpjaQ'
|
||||
export const toast = useToast()
|
||||
|
||||
|
||||
@@ -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 DiscordCallbackPageView from '../views/DiscordCallbackPageView.vue'
|
||||
import TwitterCallbackPageView from '../views/TwitterCallbackPageView.vue'
|
||||
|
||||
const routes = [
|
||||
@@ -75,6 +76,11 @@ const routes = [
|
||||
name: 'github-callback',
|
||||
component: GithubCallbackPageView
|
||||
},
|
||||
{
|
||||
path: '/discord-callback',
|
||||
name: 'discord-callback',
|
||||
component: DiscordCallbackPageView
|
||||
},
|
||||
{
|
||||
path: '/twitter-callback',
|
||||
name: 'twitter-callback',
|
||||
|
||||
59
open-isle-cli/src/utils/discord.js
Normal file
59
open-isle-cli/src/utils/discord.js
Normal file
@@ -0,0 +1,59 @@
|
||||
import { API_BASE_URL, DISCORD_CLIENT_ID, toast } from '../main'
|
||||
import { setToken, loadCurrentUser } from './auth'
|
||||
|
||||
export function discordAuthorize(state = '') {
|
||||
if (!DISCORD_CLIENT_ID) {
|
||||
toast.error('Discord 登录不可用')
|
||||
return
|
||||
}
|
||||
const redirectUri = `${window.location.origin}/discord-callback`
|
||||
const url = `https://discord.com/api/oauth2/authorize?client_id=${DISCORD_CLIENT_ID}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=identify%20email&state=${state}`
|
||||
window.location.href = url
|
||||
}
|
||||
|
||||
export async function discordExchange(code, state, reason) {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/discord`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, redirectUri: `${window.location.origin}/discord-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: '登录失败'
|
||||
}
|
||||
}
|
||||
}
|
||||
47
open-isle-cli/src/views/DiscordCallbackPageView.vue
Normal file
47
open-isle-cli/src/views/DiscordCallbackPageView.vue
Normal file
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<div class="discord-callback-page">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
<div class="discord-callback-page-text">Magic is happening...</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { discordExchange } from '../utils/discord'
|
||||
import { hatch } from 'ldrs'
|
||||
|
||||
hatch.register()
|
||||
|
||||
export default {
|
||||
name: 'DiscordCallbackPageView',
|
||||
async mounted() {
|
||||
const url = new URL(window.location.href)
|
||||
const code = url.searchParams.get('code')
|
||||
const state = url.searchParams.get('state')
|
||||
const result = await discordExchange(code, state, '')
|
||||
|
||||
if (result.needReason) {
|
||||
this.$router.push('/signup-reason?token=' + result.token)
|
||||
} else {
|
||||
this.$router.push('/')
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.discord-callback-page {
|
||||
background-color: var(--background-color);
|
||||
height: calc(100vh - var(--header-height));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.discord-callback-page-text {
|
||||
margin-top: 25px;
|
||||
font-size: 16px;
|
||||
color: var(--primary-color);
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
@@ -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="loginWithDiscord">
|
||||
<img class="login-page-button-icon" src="../assets/icons/discord.svg" alt="Discord Logo" />
|
||||
<div class="login-page-button-text">Discord 登录</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>
|
||||
@@ -51,6 +55,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 { discordAuthorize } from '../utils/discord'
|
||||
import { twitterAuthorize } from '../utils/twitter'
|
||||
import BaseInput from '../components/BaseInput.vue'
|
||||
export default {
|
||||
@@ -107,6 +112,9 @@ export default {
|
||||
loginWithGithub() {
|
||||
githubAuthorize()
|
||||
},
|
||||
loginWithDiscord() {
|
||||
discordAuthorize()
|
||||
},
|
||||
loginWithTwitter() {
|
||||
twitterAuthorize()
|
||||
}
|
||||
|
||||
@@ -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="signupWithDiscord">
|
||||
<img class="signup-page-button-icon" src="../assets/icons/discord.svg" alt="Discord Logo" />
|
||||
<div class="signup-page-button-text">Discord 注册</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>
|
||||
@@ -92,6 +96,7 @@
|
||||
import { API_BASE_URL, toast } from '../main'
|
||||
import { googleSignIn } from '../utils/google'
|
||||
import { githubAuthorize } from '../utils/github'
|
||||
import { discordAuthorize } from '../utils/discord'
|
||||
import { twitterAuthorize } from '../utils/twitter'
|
||||
import BaseInput from '../components/BaseInput.vue'
|
||||
export default {
|
||||
@@ -214,6 +219,9 @@ export default {
|
||||
signupWithGithub() {
|
||||
githubAuthorize()
|
||||
},
|
||||
signupWithDiscord() {
|
||||
discordAuthorize()
|
||||
}
|
||||
signupWithTwitter() {
|
||||
twitterAuthorize()
|
||||
}
|
||||
|
||||
@@ -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.DiscordAuthService;
|
||||
import com.openisle.service.TwitterAuthService;
|
||||
import com.openisle.service.RegisterModeService;
|
||||
import com.openisle.service.NotificationService;
|
||||
@@ -31,6 +32,7 @@ public class AuthController {
|
||||
private final CaptchaService captchaService;
|
||||
private final GoogleAuthService googleAuthService;
|
||||
private final GithubAuthService githubAuthService;
|
||||
private final DiscordAuthService discordAuthService;
|
||||
private final TwitterAuthService twitterAuthService;
|
||||
private final RegisterModeService registerModeService;
|
||||
private final NotificationService notificationService;
|
||||
@@ -199,6 +201,36 @@ public class AuthController {
|
||||
));
|
||||
}
|
||||
|
||||
@PostMapping("/discord")
|
||||
public ResponseEntity<?> loginWithDiscord(@RequestBody DiscordLoginRequest req) {
|
||||
Optional<User> user = discordAuthService.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 discord code",
|
||||
"reason_code", "INVALID_CREDENTIALS"
|
||||
));
|
||||
}
|
||||
|
||||
@PostMapping("/twitter")
|
||||
public ResponseEntity<?> loginWithTwitter(@RequestBody TwitterLoginRequest req) {
|
||||
Optional<User> user = twitterAuthService.authenticate(req.getCode(), registerModeService.getRegisterMode(), req.getRedirectUri());
|
||||
@@ -260,6 +292,12 @@ public class AuthController {
|
||||
private String redirectUri;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class DiscordLoginRequest {
|
||||
private String code;
|
||||
private String redirectUri;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class TwitterLoginRequest {
|
||||
private String code;
|
||||
|
||||
107
src/main/java/com/openisle/service/DiscordAuthService.java
Normal file
107
src/main/java/com/openisle/service/DiscordAuthService.java
Normal file
@@ -0,0 +1,107 @@
|
||||
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.util.LinkedMultiValueMap;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DiscordAuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
@Value("${discord.client-id:}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${discord.client-secret:}")
|
||||
private String clientSecret;
|
||||
|
||||
public Optional<User> authenticate(String code, com.openisle.model.RegisterMode mode, String redirectUri) {
|
||||
try {
|
||||
String tokenUrl = "https://discord.com/api/oauth2/token";
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
|
||||
|
||||
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
|
||||
body.add("client_id", clientId);
|
||||
body.add("client_secret", clientSecret);
|
||||
body.add("grant_type", "authorization_code");
|
||||
body.add("code", code);
|
||||
if (redirectUri != null) {
|
||||
body.add("redirect_uri", redirectUri);
|
||||
}
|
||||
body.add("scope", "identify email");
|
||||
|
||||
HttpEntity<MultiValueMap<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://discord.com/api/users/@me", HttpMethod.GET, entity, JsonNode.class);
|
||||
if (!userRes.getStatusCode().is2xxSuccessful() || userRes.getBody() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JsonNode userNode = userRes.getBody();
|
||||
String email = userNode.hasNonNull("email") ? userNode.get("email").asText() : null;
|
||||
String username = userNode.hasNonNull("username") ? userNode.get("username").asText() : null;
|
||||
String id = userNode.hasNonNull("id") ? userNode.get("id").asText() : null;
|
||||
String avatar = null;
|
||||
if (userNode.hasNonNull("avatar") && id != null) {
|
||||
avatar = "https://cdn.discordapp.com/avatars/" + id + "/" + userNode.get("avatar").asText() + ".png";
|
||||
}
|
||||
if (email == null) {
|
||||
email = (username != null ? username : id) + "@users.noreply.discord.com";
|
||||
}
|
||||
return Optional.of(processUser(email, username, avatar, mode));
|
||||
} catch (Exception e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private User processUser(String email, String username, String avatar, 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);
|
||||
if (avatar != null) {
|
||||
user.setAvatar(avatar);
|
||||
} else {
|
||||
user.setAvatar("https://cdn.discordapp.com/embed/avatars/0.png");
|
||||
}
|
||||
return userRepository.save(user);
|
||||
}
|
||||
}
|
||||
@@ -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:}
|
||||
# Discord OAuth configuration
|
||||
discord.client-id=${DISCORD_CLIENT_ID:}
|
||||
discord.client-secret=${DISCORD_CLIENT_SECRET:}
|
||||
# Twitter OAuth configuration
|
||||
twitter.client-id=${TWITTER_CLIENT_ID:}
|
||||
twitter.client-secret=${TWITTER_CLIENT_SECRET:}
|
||||
|
||||
Reference in New Issue
Block a user