fix:修复oauth授权失败问题
This commit is contained in:
1 parent
edf5b4530a
commit
0b3f728570
3 files changed
+262
-11
No files matched your search
@@ -18,6 +18,7 @@ import (
|
||||
"github.com/qianfree/team-api/internal/logic/common"
|
||||
"github.com/qianfree/team-api/internal/middleware"
|
||||
do "github.com/qianfree/team-api/internal/model/do"
|
||||
"github.com/qianfree/team-api/internal/utility/crypto"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/os/gtime"
|
||||
@@ -61,6 +62,34 @@ func getOAuthSetting(ctx context.Context, key string) string {
|
||||
return common.Config().GetOption(ctx, key)
|
||||
}
|
||||
|
||||
// encryptOAuthToken encrypts a token string for secure storage.
|
||||
func encryptOAuthToken(ctx context.Context, token string) string {
|
||||
if token == "" {
|
||||
return ""
|
||||
}
|
||||
encKey := getEncKey(ctx)
|
||||
encrypted, err := crypto.EncryptString(encKey, token)
|
||||
if err != nil {
|
||||
g.Log().Warningf(ctx, "[OAuth] encrypt token failed: %v", err)
|
||||
return token
|
||||
}
|
||||
return encrypted
|
||||
}
|
||||
|
||||
// decryptOAuthToken decrypts a stored token string.
|
||||
func decryptOAuthToken(ctx context.Context, encrypted string) string {
|
||||
if encrypted == "" {
|
||||
return ""
|
||||
}
|
||||
encKey := getEncKey(ctx)
|
||||
decrypted, err := crypto.DecryptString(encKey, encrypted)
|
||||
if err != nil {
|
||||
// 可能是未加密的历史数据,直接返回原值
|
||||
return encrypted
|
||||
}
|
||||
return decrypted
|
||||
}
|
||||
|
||||
// GetOAuthAuthorizeURL 获取 OAuth 授权跳转 URL
|
||||
func (s *sTenant) GetOAuthAuthorizeURL(ctx context.Context, req *v1.OAuthAuthorizeReq) (*v1.OAuthAuthorizeRes, error) {
|
||||
provider, ok := providers[req.Provider]
|
||||
@@ -155,8 +184,8 @@ func (s *sTenant) OAuthCallback(ctx context.Context, req *v1.OAuthCallbackReq) (
|
||||
_, err = dao.TntOauthIdentities.Ctx(ctx).
|
||||
Where("id", identity.Id).
|
||||
Data(do.TntOauthIdentities{
|
||||
AccessToken: oauthToken.AccessToken,
|
||||
RefreshToken: oauthToken.RefreshToken,
|
||||
AccessToken: encryptOAuthToken(ctx, oauthToken.AccessToken),
|
||||
RefreshToken: encryptOAuthToken(ctx, oauthToken.RefreshToken),
|
||||
TokenExpiresAt: gtime.NewFromTime(time.Now().Add(time.Duration(oauthToken.ExpiresIn) * time.Second)),
|
||||
ProviderUsername: userInfo.Username,
|
||||
}).Update()
|
||||
@@ -241,8 +270,8 @@ func (s *sTenant) OAuthCallback(ctx context.Context, req *v1.OAuthCallbackReq) (
|
||||
ProviderUsername: userInfo.Username,
|
||||
Email: userInfo.Email,
|
||||
AvatarUrl: userInfo.AvatarURL,
|
||||
AccessToken: oauthToken.AccessToken,
|
||||
RefreshToken: oauthToken.RefreshToken,
|
||||
AccessToken: encryptOAuthToken(ctx, oauthToken.AccessToken),
|
||||
RefreshToken: encryptOAuthToken(ctx, oauthToken.RefreshToken),
|
||||
TokenExpiresAt: gtime.NewFromTime(time.Now().Add(time.Duration(oauthToken.ExpiresIn) * time.Second)),
|
||||
RawData: string(rawData),
|
||||
}).Insert()
|
||||
@@ -308,6 +337,11 @@ func (s *sTenant) LinkOAuth(ctx context.Context, req *v1.OAuthLinkReq) (*v1.OAut
|
||||
return nil, common.NewBusinessError(10059, "该 OAuth 供应商未启用")
|
||||
}
|
||||
|
||||
enabled := getOAuthSetting(ctx, fmt.Sprintf("oauth_%s_enabled", req.Provider))
|
||||
if enabled != "true" {
|
||||
return nil, common.NewBusinessError(10059, "该 OAuth 供应商未启用")
|
||||
}
|
||||
|
||||
tenantID := middleware.GetTenantID(ctx)
|
||||
userID := middleware.GetUserID(ctx)
|
||||
|
||||
@@ -342,8 +376,8 @@ func (s *sTenant) LinkOAuth(ctx context.Context, req *v1.OAuthLinkReq) (*v1.OAut
|
||||
_, err = dao.TntOauthIdentities.Ctx(ctx).
|
||||
Where("id", existing.Id).
|
||||
Data(do.TntOauthIdentities{
|
||||
AccessToken: oauthToken.AccessToken,
|
||||
RefreshToken: oauthToken.RefreshToken,
|
||||
AccessToken: encryptOAuthToken(ctx, oauthToken.AccessToken),
|
||||
RefreshToken: encryptOAuthToken(ctx, oauthToken.RefreshToken),
|
||||
TokenExpiresAt: gtime.NewFromTime(time.Now().Add(time.Duration(oauthToken.ExpiresIn) * time.Second)),
|
||||
RawData: string(rawData),
|
||||
}).Update()
|
||||
@@ -359,8 +393,8 @@ func (s *sTenant) LinkOAuth(ctx context.Context, req *v1.OAuthLinkReq) (*v1.OAut
|
||||
ProviderUsername: userInfo.Username,
|
||||
Email: userInfo.Email,
|
||||
AvatarUrl: userInfo.AvatarURL,
|
||||
AccessToken: oauthToken.AccessToken,
|
||||
RefreshToken: oauthToken.RefreshToken,
|
||||
AccessToken: encryptOAuthToken(ctx, oauthToken.AccessToken),
|
||||
RefreshToken: encryptOAuthToken(ctx, oauthToken.RefreshToken),
|
||||
TokenExpiresAt: gtime.NewFromTime(time.Now().Add(time.Duration(oauthToken.ExpiresIn) * time.Second)),
|
||||
RawData: string(rawData),
|
||||
}).Insert()
|
||||
@@ -498,6 +532,11 @@ func (p *GitHubProvider) GetUserInfo(ctx context.Context, token string) (*OAuthU
|
||||
name = login
|
||||
}
|
||||
|
||||
// GitHub 用户邮箱私密时 /user 返回空邮箱,需要调用 /user/emails 获取主邮箱
|
||||
if email == "" {
|
||||
email = githubFetchPrimaryEmail(token)
|
||||
}
|
||||
|
||||
return &OAuthUserInfo{
|
||||
ProviderUserID: id,
|
||||
Username: login,
|
||||
@@ -508,6 +547,36 @@ func (p *GitHubProvider) GetUserInfo(ctx context.Context, token string) (*OAuthU
|
||||
}, nil
|
||||
}
|
||||
|
||||
// githubFetchPrimaryEmail fetches the primary verified email from GitHub /user/emails API.
|
||||
func githubFetchPrimaryEmail(token string) string {
|
||||
req, _ := http.NewRequest("GET", "https://api.github.com/user/emails", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var emails []struct {
|
||||
Email string `json:"email"`
|
||||
Primary bool `json:"primary"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&emails); err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, e := range emails {
|
||||
if e.Primary {
|
||||
return e.Email
|
||||
}
|
||||
}
|
||||
if len(emails) > 0 {
|
||||
return emails[0].Email
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// === Google OAuth Provider ===
|
||||
|
||||
type GoogleProvider struct{}
|
||||
@@ -524,7 +593,11 @@ func (p *GoogleProvider) ExchangeToken(ctx context.Context, code string) (*OAuth
|
||||
v.Set("code", code)
|
||||
v.Set("client_id", getOAuthSetting(ctx, "oauth_google_client_id"))
|
||||
v.Set("client_secret", getOAuthSetting(ctx, "oauth_google_client_secret"))
|
||||
v.Set("redirect_uri", getOAuthSetting(ctx, "site_url"))
|
||||
siteURL := getOAuthSetting(ctx, "site_url")
|
||||
if siteURL == "" {
|
||||
siteURL = "http://localhost:3000"
|
||||
}
|
||||
v.Set("redirect_uri", siteURL+"/api/tenant/oauth/google/callback")
|
||||
v.Set("grant_type", "authorization_code")
|
||||
|
||||
resp, err := http.Post("https://oauth2.googleapis.com/token", "application/x-www-form-urlencoded", strings.NewReader(v.Encode()))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted, nextTick } from 'vue'
|
||||
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { useTenantAuthStore } from '@/stores/tenant-auth'
|
||||
import { usePublicSettings } from '@/composables/usePublicSettings'
|
||||
@@ -183,6 +183,23 @@ function clearRamError(field: string) {
|
||||
delete ramErrors[field]
|
||||
if (errorMsg.value) errorMsg.value = ''
|
||||
}
|
||||
|
||||
const hasOAuthProviders = computed(() => {
|
||||
return settings.value['oauth_github_enabled'] || settings.value['oauth_google_enabled']
|
||||
})
|
||||
|
||||
async function handleOAuthLogin(provider: string) {
|
||||
try {
|
||||
const res = await request.get('/tenant/oauth/authorize', { params: { provider } })
|
||||
const { authorize_url } = res.data?.data || {}
|
||||
if (authorize_url) {
|
||||
window.location.href = authorize_url
|
||||
}
|
||||
} catch (e: any) {
|
||||
const apiErr = extractApiError(e)
|
||||
errorMsg.value = apiErr?.message || '第三方登录失败'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -419,6 +436,37 @@ function clearRamError(field: string) {
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- OAuth Login -->
|
||||
<div v-if="hasOAuthProviders" class="mt-6">
|
||||
<div class="relative">
|
||||
<div class="absolute inset-0 flex items-center">
|
||||
<div class="w-full border-t border-gray-200"></div>
|
||||
</div>
|
||||
<div class="relative flex justify-center text-xs">
|
||||
<span class="bg-white px-3 text-gray-400">或使用第三方账号登录</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex gap-3">
|
||||
<button
|
||||
v-if="settings['oauth_github_enabled']"
|
||||
type="button"
|
||||
class="btn btn-secondary flex-1"
|
||||
@click="handleOAuthLogin('github')"
|
||||
>
|
||||
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>
|
||||
GitHub
|
||||
</button>
|
||||
<button
|
||||
v-if="settings['oauth_google_enabled']"
|
||||
type="button"
|
||||
class="btn btn-secondary flex-1"
|
||||
@click="handleOAuthLogin('google')"
|
||||
>
|
||||
<svg class="h-4 w-4" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
|
||||
Google
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="settings.register_enabled" #footer>
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted } from 'vue'
|
||||
import { ref, reactive, computed, onMounted } from 'vue'
|
||||
import Icon from '@/components/common/Icon.vue'
|
||||
import BaseModal from '@/components/common/BaseModal.vue'
|
||||
import request from '@/utils/request'
|
||||
import { usePublicSettings } from '@/composables/usePublicSettings'
|
||||
|
||||
const loading = ref(false)
|
||||
const userInfo = ref<any>(null)
|
||||
const sessions = ref<any[]>([])
|
||||
const { settings } = usePublicSettings()
|
||||
|
||||
// OAuth state
|
||||
const oauthProviders = ref<any[]>([])
|
||||
const oauthLoading = ref(false)
|
||||
const linkProvider = ref('')
|
||||
const linkCode = ref('')
|
||||
const linkLoading = ref(false)
|
||||
const linkError = ref('')
|
||||
|
||||
const editingDisplayName = ref(false)
|
||||
const displayNameForm = reactive({
|
||||
@@ -139,7 +149,88 @@ function parseDeviceInfo(deviceInfo: string): string {
|
||||
onMounted(() => {
|
||||
fetchProfile()
|
||||
fetchSessions()
|
||||
fetchOAuthProviders()
|
||||
})
|
||||
|
||||
async function fetchOAuthProviders() {
|
||||
oauthLoading.value = true
|
||||
try {
|
||||
const res: any = await request.get('/tenant/oauth/providers')
|
||||
oauthProviders.value = res.data?.data?.list || []
|
||||
} catch {
|
||||
oauthProviders.value = []
|
||||
} finally {
|
||||
oauthLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const hasOAuthEnabled = computed(() => {
|
||||
return settings.value['oauth_github_enabled'] || settings.value['oauth_google_enabled']
|
||||
})
|
||||
|
||||
function isProviderLinked(provider: string): boolean {
|
||||
return oauthProviders.value.some((p: any) => p.provider === provider)
|
||||
}
|
||||
|
||||
function getLinkedProvider(provider: string) {
|
||||
return oauthProviders.value.find((p: any) => p.provider === provider)
|
||||
}
|
||||
|
||||
async function handleOAuthLink(provider: string) {
|
||||
linkLoading.value = true
|
||||
linkError.value = ''
|
||||
try {
|
||||
const res: any = await request.get('/tenant/oauth/authorize', { params: { provider } })
|
||||
const { authorize_url, state } = res.data?.data || {}
|
||||
if (authorize_url) {
|
||||
// Open OAuth in popup window
|
||||
const width = 600
|
||||
const height = 700
|
||||
const left = (window.innerWidth - width) / 2
|
||||
const top = (window.innerHeight - height) / 2
|
||||
const popup = window.open(
|
||||
authorize_url,
|
||||
'oauth',
|
||||
`width=${width},height=${height},left=${left},top=${top}`
|
||||
)
|
||||
// Listen for callback message
|
||||
const handleMessage = async (event: MessageEvent) => {
|
||||
if (event.data?.type === 'oauth-callback') {
|
||||
window.removeEventListener('message', handleMessage)
|
||||
if (event.data.code) {
|
||||
try {
|
||||
await request.post('/tenant/oauth/link', {
|
||||
provider,
|
||||
code: event.data.code,
|
||||
})
|
||||
await fetchOAuthProviders()
|
||||
} catch (e: any) {
|
||||
const res = e?.response?.data
|
||||
linkError.value = res?.message || '绑定失败'
|
||||
}
|
||||
}
|
||||
popup?.close()
|
||||
linkLoading.value = false
|
||||
}
|
||||
}
|
||||
window.addEventListener('message', handleMessage)
|
||||
}
|
||||
} catch (e: any) {
|
||||
const res = e?.response?.data
|
||||
linkError.value = res?.message || '绑定失败'
|
||||
} finally {
|
||||
linkLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleOAuthUnlink(provider: string) {
|
||||
try {
|
||||
await request.post('/tenant/oauth/unlink', { provider })
|
||||
await fetchOAuthProviders()
|
||||
} catch {
|
||||
// error toast shown by interceptor
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -259,6 +350,45 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- OAuth Linked Accounts Card -->
|
||||
<div v-if="hasOAuthEnabled" class="card">
|
||||
<div class="card-header">
|
||||
<h2 class="font-semibold text-gray-900">第三方账号</h2>
|
||||
</div>
|
||||
<div class="divide-y divide-gray-100">
|
||||
<div v-if="settings['oauth_github_enabled']" class="px-6 py-4 flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="h-10 w-10 rounded-xl bg-gray-100 flex items-center justify-center">
|
||||
<svg class="h-5 w-5 text-gray-700" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm font-medium text-gray-900">GitHub</p>
|
||||
<p v-if="isProviderLinked('github')" class="text-xs text-gray-500 mt-0.5">已绑定:{{ getLinkedProvider('github')?.provider_username || getLinkedProvider('github')?.provider_user_id }}</p>
|
||||
<p v-else class="text-xs text-gray-500 mt-0.5">未绑定</p>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="isProviderLinked('github')" class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" @click="handleOAuthUnlink('github')">解绑</button>
|
||||
<button v-else class="btn btn-secondary btn-sm" :disabled="linkLoading" @click="handleOAuthLink('github')">绑定</button>
|
||||
</div>
|
||||
<div v-if="settings['oauth_google_enabled']" class="px-6 py-4 flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="h-10 w-10 rounded-xl bg-gray-100 flex items-center justify-center">
|
||||
<svg class="h-5 w-5" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4"/><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-sm font-medium text-gray-900">Google</p>
|
||||
<p v-if="isProviderLinked('google')" class="text-xs text-gray-500 mt-0.5">已绑定:{{ getLinkedProvider('google')?.provider_username || getLinkedProvider('google')?.provider_user_id }}</p>
|
||||
<p v-else class="text-xs text-gray-500 mt-0.5">未绑定</p>
|
||||
</div>
|
||||
</div>
|
||||
<button v-if="isProviderLinked('google')" class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" @click="handleOAuthUnlink('google')">解绑</button>
|
||||
<button v-else class="btn btn-secondary btn-sm" :disabled="linkLoading" @click="handleOAuthLink('google')">绑定</button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="linkError" class="px-6 pb-4 text-xs text-red-500">{{ linkError }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Active Sessions Card -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
|
||||
Reference in new issue
Block a user