mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-21 22:41:05 +08:00
feat: add GitHub OAuth login
This commit is contained in:
13
README.md
13
README.md
@@ -20,6 +20,7 @@ OpenIsle 基于 Spring Boot 构建,提供社区后台常见的注册、登录
|
||||
* **用户体系**:注册、登录,密码使用 BCrypt 加密
|
||||
* **JWT 认证**:登录后获得 Token,接口通过 `Authorization: Bearer` 认证
|
||||
* **Google 登录**:支持使用 Google OAuth 登录
|
||||
* **GitHub 登录**:支持使用 GitHub OAuth 登录
|
||||
* **邮件通知**:抽象 `EmailSender`,默认实现基于 Resend
|
||||
* **角色权限**:内置 `ADMIN` 与 `USER`,管理员接口以 `/api/admin/**` 提供
|
||||
* **文章与评论**:支持分类、评论及多级回复
|
||||
@@ -43,10 +44,13 @@ OpenIsle 基于 Spring Boot 构建,提供社区后台常见的注册、登录
|
||||
- `MYSQL_USER`:数据库用户名
|
||||
- `MYSQL_PASSWORD`:数据库密码
|
||||
- `RESEND_API_KEY`:Resend 邮件服务 API Key
|
||||
- `COS_BASE_URL`:腾讯云 COS 访问域名
|
||||
- `GOOGLE_CLIENT_ID`:Google OAuth 客户端 ID
|
||||
- `VUE_APP_GOOGLE_CLIENT_ID`:前端 Google OAuth 客户端 ID
|
||||
- `JWT_SECRET`:JWT 签名密钥
|
||||
- `COS_BASE_URL`:腾讯云 COS 访问域名
|
||||
- `GOOGLE_CLIENT_ID`:Google OAuth 客户端 ID
|
||||
- `VUE_APP_GOOGLE_CLIENT_ID`:前端 Google OAuth 客户端 ID
|
||||
- `GITHUB_CLIENT_ID`:GitHub OAuth 客户端 ID
|
||||
- `GITHUB_CLIENT_SECRET`:GitHub OAuth 客户端密钥
|
||||
- `VUE_APP_GITHUB_CLIENT_ID`:前端 GitHub OAuth 客户端 ID
|
||||
- `JWT_SECRET`:JWT 签名密钥
|
||||
- `JWT_EXPIRATION`:JWT 过期时间(毫秒)
|
||||
- `PASSWORD_STRENGTH`:密码强度(LOW、MEDIUM、HIGH)
|
||||
- `CAPTCHA_ENABLED`:是否启用验证码(true/false)
|
||||
@@ -68,6 +72,7 @@ mvn spring-boot:run
|
||||
- `POST /api/auth/register`:注册新用户
|
||||
- `POST /api/auth/login`:登录并获取 Token
|
||||
- `POST /api/auth/google`:Google 登录并获取 Token
|
||||
- `POST /api/auth/github`:GitHub 登录并获取 Token
|
||||
- `GET /api/config`:查看验证码开关配置
|
||||
- 需要认证的接口示例:`GET /api/hello`(需 `Authorization` 头)
|
||||
- 管理员接口示例:`GET /api/admin/hello`
|
||||
|
||||
301
open-isle-cli/src/assets/icons/github.svg
Normal file
301
open-isle-cli/src/assets/icons/github.svg
Normal file
File diff suppressed because one or more lines are too long
@@ -18,6 +18,7 @@ export const API_PORT = 8081
|
||||
// export const API_BASE_URL = API_PORT ? `${API_DOMAIN}:${API_PORT}` : API_DOMAIN
|
||||
export const API_BASE_URL = "";
|
||||
export const GOOGLE_CLIENT_ID = '777830451304-nt8afkkap18gui4f9entcha99unal744.apps.googleusercontent.com'
|
||||
export const GITHUB_CLIENT_ID = ''
|
||||
export const toast = useToast()
|
||||
|
||||
initTheme()
|
||||
|
||||
@@ -11,6 +11,7 @@ import NewPostPageView from '../views/NewPostPageView.vue'
|
||||
import SettingsPageView from '../views/SettingsPageView.vue'
|
||||
import ProfileView from '../views/ProfileView.vue'
|
||||
import NotFoundPageView from '../views/NotFoundPageView.vue'
|
||||
import GithubCallbackPageView from '../views/GithubCallbackPageView.vue'
|
||||
|
||||
const routes = [
|
||||
{
|
||||
@@ -68,6 +69,11 @@ const routes = [
|
||||
name: 'users',
|
||||
component: ProfileView
|
||||
},
|
||||
{
|
||||
path: '/github-callback',
|
||||
name: 'github-callback',
|
||||
component: GithubCallbackPageView
|
||||
},
|
||||
{
|
||||
path: '/404',
|
||||
name: 'not-found',
|
||||
|
||||
41
open-isle-cli/src/utils/github.js
Normal file
41
open-isle-cli/src/utils/github.js
Normal file
@@ -0,0 +1,41 @@
|
||||
import { API_BASE_URL, GITHUB_CLIENT_ID, toast } from '../main'
|
||||
import { setToken, loadCurrentUser } from './auth'
|
||||
|
||||
export function githubAuthorize(state = '') {
|
||||
if (!GITHUB_CLIENT_ID) {
|
||||
toast.error('GitHub 登录不可用')
|
||||
return
|
||||
}
|
||||
const redirectUri = `${window.location.origin}/github-callback`
|
||||
const url = `https://github.com/login/oauth/authorize?client_id=${GITHUB_CLIENT_ID}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=user:email&state=${state}`
|
||||
window.location.href = url
|
||||
}
|
||||
|
||||
export async function githubExchange(code, state, reason) {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/github`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, redirectUri: `${window.location.origin}/github-callback`, reason, state })
|
||||
})
|
||||
const data = await res.json()
|
||||
if (res.ok && data.token) {
|
||||
setToken(data.token)
|
||||
await loadCurrentUser()
|
||||
toast.success('登录成功')
|
||||
return true
|
||||
} else if (data.reason_code === 'NOT_APPROVED') {
|
||||
toast.info('当前为注册审核模式,请填写注册理由')
|
||||
sessionStorage.setItem('github_code', code)
|
||||
return 'NEED_REASON'
|
||||
} else if (data.reason_code === 'IS_APPROVING') {
|
||||
toast.info('您的注册理由正在审批中')
|
||||
return true
|
||||
} else {
|
||||
toast.error(data.error || '登录失败')
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error('登录失败')
|
||||
}
|
||||
return false
|
||||
}
|
||||
32
open-isle-cli/src/views/GithubCallbackPageView.vue
Normal file
32
open-isle-cli/src/views/GithubCallbackPageView.vue
Normal file
@@ -0,0 +1,32 @@
|
||||
<template>
|
||||
<div class="loading">GitHub 登录中...</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { githubExchange } from '../utils/github'
|
||||
|
||||
export default {
|
||||
name: 'GithubCallbackPageView',
|
||||
async mounted() {
|
||||
const url = new URL(window.location.href)
|
||||
const code = url.searchParams.get('code')
|
||||
const state = url.searchParams.get('state')
|
||||
const result = await githubExchange(code, state, '')
|
||||
if (result === 'NEED_REASON') {
|
||||
this.$router.push('/signup-reason?github=1')
|
||||
} else {
|
||||
this.$router.push('/')
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.loading {
|
||||
height: calc(100vh - var(--header-height));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 20px;
|
||||
}
|
||||
</style>
|
||||
@@ -34,6 +34,10 @@
|
||||
<img class="login-page-button-icon" src="../assets/icons/google.svg" alt="Google Logo" />
|
||||
<div class="login-page-button-text">Google 登录</div>
|
||||
</div>
|
||||
<div class="login-page-button" @click="loginWithGithub">
|
||||
<img class="login-page-button-icon" src="../assets/icons/github.svg" alt="GitHub Logo" />
|
||||
<div class="login-page-button-text">GitHub 登录</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -42,6 +46,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 BaseInput from '../components/BaseInput.vue'
|
||||
export default {
|
||||
name: 'LoginPageView',
|
||||
@@ -89,6 +94,9 @@ export default {
|
||||
}, () => {
|
||||
this.$router.push('/signup-reason?google=1')
|
||||
})
|
||||
},
|
||||
loginWithGithub() {
|
||||
githubAuthorize()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,10 @@
|
||||
<img class="signup-page-button-icon" src="../assets/icons/google.svg" alt="Google Logo" />
|
||||
<div class="signup-page-button-text">Google 注册</div>
|
||||
</div>
|
||||
<div class="signup-page-button" @click="signupWithGithub">
|
||||
<img class="signup-page-button-icon" src="../assets/icons/github.svg" alt="GitHub Logo" />
|
||||
<div class="signup-page-button-text">GitHub 注册</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -83,6 +87,7 @@
|
||||
<script>
|
||||
import { API_BASE_URL, toast } from '../main'
|
||||
import { googleSignIn, googleGetIdToken } from '../utils/google'
|
||||
import { githubAuthorize } from '../utils/github'
|
||||
import BaseInput from '../components/BaseInput.vue'
|
||||
export default {
|
||||
name: 'SignupPageView',
|
||||
@@ -211,6 +216,9 @@ export default {
|
||||
this.$router.push('/signup-reason?google=1')
|
||||
})
|
||||
}
|
||||
},
|
||||
signupWithGithub() {
|
||||
githubAuthorize()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import BaseInput from '../components/BaseInput.vue'
|
||||
import { API_BASE_URL, toast } from '../main'
|
||||
import { googleAuthWithToken } from '../utils/google'
|
||||
import { githubExchange } from '../utils/github'
|
||||
|
||||
export default {
|
||||
name: 'SignupReasonPageView',
|
||||
@@ -29,17 +30,25 @@ export default {
|
||||
reason: '',
|
||||
error: '',
|
||||
isGoogle: false,
|
||||
isGithub: false,
|
||||
isWaitingForRegister: false,
|
||||
googleToken: ''
|
||||
googleToken: '',
|
||||
githubCode: ''
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.isGoogle = this.$route.query.google === '1'
|
||||
this.isGithub = this.$route.query.github === '1'
|
||||
if (this.isGoogle) {
|
||||
this.googleToken = sessionStorage.getItem('google_id_token') || ''
|
||||
if (!this.googleToken) {
|
||||
this.$router.push('/signup')
|
||||
}
|
||||
} else if (this.isGithub) {
|
||||
this.githubCode = sessionStorage.getItem('github_code') || ''
|
||||
if (!this.githubCode) {
|
||||
this.$router.push('/signup')
|
||||
}
|
||||
} else if (!sessionStorage.getItem('signup_username')) {
|
||||
this.$router.push('/signup')
|
||||
}
|
||||
@@ -65,6 +74,23 @@ export default {
|
||||
sessionStorage.removeItem('google_id_token')
|
||||
return
|
||||
}
|
||||
if (this.isGithub) {
|
||||
this.isWaitingForRegister = true
|
||||
const code = this.githubCode || sessionStorage.getItem('github_code')
|
||||
if (!code) {
|
||||
toast.error('GitHub 登录失败')
|
||||
return
|
||||
}
|
||||
const result = await githubExchange(code, '', this.reason)
|
||||
this.isWaitingForRegister = false
|
||||
sessionStorage.removeItem('github_code')
|
||||
if (result) {
|
||||
this.$router.push('/')
|
||||
} else {
|
||||
this.error = 'GitHub 登录失败'
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
this.isWaitingForRegister = true
|
||||
const res = await fetch(`${API_BASE_URL}/api/auth/register`, {
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.openisle.service.JwtService;
|
||||
import com.openisle.service.UserService;
|
||||
import com.openisle.service.CaptchaService;
|
||||
import com.openisle.service.GoogleAuthService;
|
||||
import com.openisle.service.GithubAuthService;
|
||||
import com.openisle.service.RegisterModeService;
|
||||
import com.openisle.service.NotificationService;
|
||||
import com.openisle.model.RegisterMode;
|
||||
@@ -27,6 +28,7 @@ public class AuthController {
|
||||
private final EmailSender emailService;
|
||||
private final CaptchaService captchaService;
|
||||
private final GoogleAuthService googleAuthService;
|
||||
private final GithubAuthService githubAuthService;
|
||||
private final RegisterModeService registerModeService;
|
||||
private final NotificationService notificationService;
|
||||
private final UserRepository userRepository;
|
||||
@@ -125,6 +127,37 @@ public class AuthController {
|
||||
));
|
||||
}
|
||||
|
||||
@PostMapping("/github")
|
||||
public ResponseEntity<?> loginWithGithub(@RequestBody GithubLoginRequest req) {
|
||||
Optional<User> user = githubAuthService.authenticate(req.getCode(), req.getReason(), 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 (req.reason != null && !req.reason.isEmpty()) {
|
||||
notificationService.createRegisterRequestNotifications(user.get(), req.getReason());
|
||||
}
|
||||
if (user.get().getRegisterReason() != null && !user.get().getRegisterReason().isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(Map.of(
|
||||
"error", "Account awaiting approval",
|
||||
"reason_code", "IS_APPROVING"
|
||||
));
|
||||
}
|
||||
return ResponseEntity.badRequest().body(Map.of(
|
||||
"error", "Account awaiting approval",
|
||||
"reason_code", "NOT_APPROVED"
|
||||
));
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(Map.of("token", jwtService.generateToken(user.get().getUsername())));
|
||||
}
|
||||
return ResponseEntity.badRequest().body(Map.of(
|
||||
"error", "Invalid github code",
|
||||
"reason_code", "INVALID_CREDENTIALS"
|
||||
));
|
||||
}
|
||||
|
||||
@GetMapping("/check")
|
||||
public ResponseEntity<?> checkToken() {
|
||||
return ResponseEntity.ok(Map.of("valid", true));
|
||||
@@ -152,6 +185,13 @@ public class AuthController {
|
||||
private String reason;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class GithubLoginRequest {
|
||||
private String code;
|
||||
private String redirectUri;
|
||||
private String reason;
|
||||
}
|
||||
|
||||
@Data
|
||||
private static class VerifyRequest {
|
||||
private String username;
|
||||
|
||||
111
src/main/java/com/openisle/service/GithubAuthService.java
Normal file
111
src/main/java/com/openisle/service/GithubAuthService.java
Normal file
@@ -0,0 +1,111 @@
|
||||
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.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GithubAuthService {
|
||||
private final UserRepository userRepository;
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
@Value("${github.client-id:}")
|
||||
private String clientId;
|
||||
|
||||
@Value("${github.client-secret:}")
|
||||
private String clientSecret;
|
||||
|
||||
public Optional<User> authenticate(String code, String reason, com.openisle.model.RegisterMode mode, String redirectUri) {
|
||||
try {
|
||||
String tokenUrl = "https://github.com/login/oauth/access_token";
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
|
||||
HttpEntity<String> request = new HttpEntity<>(
|
||||
"client_id=" + clientId +
|
||||
"&client_secret=" + clientSecret +
|
||||
"&code=" + code +
|
||||
(redirectUri != null ? "&redirect_uri=" + redirectUri : ""),
|
||||
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.github.com/user", HttpMethod.GET, entity, JsonNode.class);
|
||||
if (!userRes.getStatusCode().is2xxSuccessful() || userRes.getBody() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JsonNode userNode = userRes.getBody();
|
||||
String username = userNode.hasNonNull("login") ? userNode.get("login").asText() : null;
|
||||
String email = null;
|
||||
if (userNode.hasNonNull("email")) {
|
||||
email = userNode.get("email").asText();
|
||||
}
|
||||
if (email == null || email.isEmpty()) {
|
||||
ResponseEntity<JsonNode> emailsRes = restTemplate.exchange(
|
||||
"https://api.github.com/user/emails", HttpMethod.GET, entity, JsonNode.class);
|
||||
if (emailsRes.getStatusCode().is2xxSuccessful() && emailsRes.getBody() != null && emailsRes.getBody().isArray()) {
|
||||
for (JsonNode n : emailsRes.getBody()) {
|
||||
if (n.has("primary") && n.get("primary").asBoolean()) {
|
||||
email = n.get("email").asText();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (email == null) {
|
||||
email = username + "@users.noreply.github.com";
|
||||
}
|
||||
return Optional.of(processUser(email, username, reason, mode));
|
||||
} catch (Exception e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private User processUser(String email, String username, String reason, 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);
|
||||
}
|
||||
if (!user.isApproved() && reason != null && !reason.isEmpty()) {
|
||||
user.setRegisterReason(reason);
|
||||
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.setRegisterReason(reason);
|
||||
user.setApproved(mode == com.openisle.model.RegisterMode.DIRECT);
|
||||
user.setAvatar("https://github.com/" + finalUsername + ".png");
|
||||
return userRepository.save(user);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,9 @@ cos.bucket-name=${COS_BUCKET_NAME:}
|
||||
|
||||
# Google OAuth configuration
|
||||
google.client-id=${GOOGLE_CLIENT_ID:}
|
||||
# GitHub OAuth configuration
|
||||
github.client-id=${GITHUB_CLIENT_ID:}
|
||||
github.client-secret=${GITHUB_CLIENT_SECRET:}
|
||||
# OpenAI configuration
|
||||
openai.api-key=${OPENAI_API_KEY:}
|
||||
openai.model=${OPENAI_MODEL:gpt-4o}
|
||||
|
||||
Reference in New Issue
Block a user