Merge pull request #563 from Licoy/main

封装OAuth2授权回调页面、修复独立日志数据库查询令牌日志时错误问题
This commit is contained in:
Calcium-Ion 2024-11-12 16:27:46 +08:00 committed by GitHub
commit 0b0bcbab80
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 3025 additions and 3456 deletions

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"one-api/common"
"os"
"strings"
"time"
@ -39,7 +40,15 @@ const (
)
func GetLogByKey(key string) (logs []*Log, err error) {
if os.Getenv("LOG_SQL_DSN") != "" {
var tk Token
if err = DB.Model(&Token{}).Where("`key`=?", strings.TrimPrefix(key, "sk-")).First(&tk).Error; err != nil {
return nil, err
}
err = LOG_DB.Model(&Log{}).Where("token_id=?", tk.Id).Find(&logs).Error
} else {
err = LOG_DB.Joins("left join tokens on tokens.id = logs.token_id").Where("tokens.key = ?", strings.TrimPrefix(key, "sk-")).Find(&logs).Error
}
return logs, err
}

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,6 @@ import Setting from './pages/Setting';
import EditUser from './pages/User/EditUser';
import { getLogo, getSystemName } from './helpers';
import PasswordResetForm from './components/PasswordResetForm';
import GitHubOAuth from './components/GitHubOAuth';
import PasswordResetConfirm from './components/PasswordResetConfirm';
import { UserContext } from './context/User';
import Channel from './pages/Channel';
@ -26,7 +25,7 @@ import Midjourney from './pages/Midjourney';
import Pricing from './pages/Pricing/index.js';
import Task from "./pages/Task/index.js";
import Playground from './components/Playground.js';
import LinuxDoOAuth from './components/LinuxDoOAuth.js';
import OAuth2Callback from "./components/OAuth2Callback.js";
const Home = lazy(() => import('./pages/Home'));
const Detail = lazy(() => import('./pages/Detail'));
@ -178,7 +177,7 @@ function App() {
path='/oauth/github'
element={
<Suspense fallback={<Loading></Loading>}>
<GitHubOAuth />
<OAuth2Callback type='github'></OAuth2Callback>
</Suspense>
}
/>
@ -186,7 +185,7 @@ function App() {
path='/oauth/linuxdo'
element={
<Suspense fallback={<Loading></Loading>}>
<LinuxDoOAuth />
<OAuth2Callback type='linuxdo'></OAuth2Callback>
</Suspense>
}
/>

View File

@ -1,61 +0,0 @@
import React, { useContext, useEffect, useState } from 'react';
import { Dimmer, Loader, Segment } from 'semantic-ui-react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { API, showError, showSuccess, updateAPI } from '../helpers';
import { UserContext } from '../context/User';
import { setUserData } from '../helpers/data.js';
const GitHubOAuth = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [userState, userDispatch] = useContext(UserContext);
const [prompt, setPrompt] = useState('处理中...');
const [processing, setProcessing] = useState(true);
let navigate = useNavigate();
const sendCode = async (code, state, count) => {
const res = await API.get(`/api/oauth/github?code=${code}&state=${state}`);
const { success, message, data } = res.data;
if (success) {
if (message === 'bind') {
showSuccess('绑定成功!');
navigate('/setting');
} else {
userDispatch({ type: 'login', payload: data });
localStorage.setItem('user', JSON.stringify(data));
setUserData(data);
updateAPI()
showSuccess('登录成功!');
navigate('/token');
}
} else {
showError(message);
if (count === 0) {
setPrompt(`操作失败,重定向至登录界面中...`);
navigate('/setting'); // in case this is failed to bind GitHub
return;
}
count++;
setPrompt(`出现错误,第 ${count} 次重试中...`);
await new Promise((resolve) => setTimeout(resolve, count * 2000));
await sendCode(code, state, count);
}
};
useEffect(() => {
let code = searchParams.get('code');
let state = searchParams.get('state');
sendCode(code, state, 0).then();
}, []);
return (
<Segment style={{ minHeight: '300px' }}>
<Dimmer active inverted>
<Loader size='large'>{prompt}</Loader>
</Dimmer>
</Segment>
);
};
export default GitHubOAuth;

View File

@ -1,61 +0,0 @@
import React, { useContext, useEffect, useState } from 'react';
import { Dimmer, Loader, Segment } from 'semantic-ui-react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { API, showError, showSuccess, updateAPI } from '../helpers';
import { UserContext } from '../context/User';
import { setUserData } from '../helpers/data.js';
const LinuxDoOAuth = () => {
const [searchParams, setSearchParams] = useSearchParams();
const [userState, userDispatch] = useContext(UserContext);
const [prompt, setPrompt] = useState('处理中...');
const [processing, setProcessing] = useState(true);
let navigate = useNavigate();
const sendCode = async (code, state, count) => {
const res = await API.get(`/api/oauth/linuxdo?code=${code}&state=${state}`);
const { success, message, data } = res.data;
if (success) {
if (message === 'bind') {
showSuccess('绑定成功!');
navigate('/setting');
} else {
userDispatch({ type: 'login', payload: data });
localStorage.setItem('user', JSON.stringify(data));
setUserData(data);
updateAPI()
showSuccess('登录成功!');
navigate('/token');
}
} else {
showError(message);
if (count === 0) {
setPrompt(`操作失败,重定向至登录界面中...`);
navigate('/setting'); // in case this is failed to bind GitHub
return;
}
count++;
setPrompt(`出现错误,第 ${count} 次重试中...`);
await new Promise((resolve) => setTimeout(resolve, count * 2000));
await sendCode(code, state, count);
}
};
useEffect(() => {
let code = searchParams.get('code');
let state = searchParams.get('state');
sendCode(code, state, 0).then();
}, []);
return (
<Segment style={{ minHeight: '300px' }}>
<Dimmer active inverted>
<Loader size='large'>{prompt}</Loader>
</Dimmer>
</Segment>
);
};
export default LinuxDoOAuth;

View File

@ -0,0 +1,61 @@
import React, { useContext, useEffect, useState } from 'react';
import { Dimmer, Loader, Segment } from 'semantic-ui-react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { API, showError, showSuccess, updateAPI } from '../helpers';
import { UserContext } from '../context/User';
import { setUserData } from '../helpers/data.js';
const OAuth2Callback = (props) => {
const [searchParams, setSearchParams] = useSearchParams();
const [userState, userDispatch] = useContext(UserContext);
const [prompt, setPrompt] = useState('处理中...');
const [processing, setProcessing] = useState(true);
let navigate = useNavigate();
const sendCode = async (code, state, count) => {
const res = await API.get(`/api/oauth/${props.type}?code=${code}&state=${state}`);
const { success, message, data } = res.data;
if (success) {
if (message === 'bind') {
showSuccess('绑定成功!');
navigate('/setting');
} else {
userDispatch({ type: 'login', payload: data });
localStorage.setItem('user', JSON.stringify(data));
setUserData(data);
updateAPI()
showSuccess('登录成功!');
navigate('/token');
}
} else {
showError(message);
if (count === 0) {
setPrompt(`操作失败,重定向至登录界面中...`);
navigate('/setting'); // in case this is failed to bind GitHub
return;
}
count++;
setPrompt(`出现错误,第 ${count} 次重试中...`);
await new Promise((resolve) => setTimeout(resolve, count * 2000));
await sendCode(code, state, count);
}
};
useEffect(() => {
let code = searchParams.get('code');
let state = searchParams.get('state');
sendCode(code, state, 0).then();
}, []);
return (
<Segment style={{ minHeight: '300px' }}>
<Dimmer active inverted>
<Loader size='large'>{prompt}</Loader>
</Dimmer>
</Segment>
);
};
export default OAuth2Callback;

View File

@ -90,7 +90,7 @@ const OperationSetting = () => {
try {
setLoading(true);
await getOptions();
showSuccess('刷新成功');
// showSuccess('刷新成功');
} catch (error) {
showError('刷新失败');
} finally {

View File

@ -1,5 +1,5 @@
import React, { useContext, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import React, {useContext, useEffect, useState} from 'react';
import {useNavigate} from 'react-router-dom';
import {
API,
copy,
@ -9,8 +9,8 @@ import {
showSuccess,
} from '../helpers';
import Turnstile from 'react-turnstile';
import { UserContext } from '../context/User';
import { onGitHubOAuthClicked, onLinuxDOOAuthClicked } from './utils';
import {UserContext} from '../context/User';
import {onGitHubOAuthClicked, onLinuxDOOAuthClicked} from './utils';
import {
Avatar,
Banner,
@ -101,12 +101,12 @@ const PersonalSetting = () => {
}, [disableButton, countdown]);
const handleInputChange = (name, value) => {
setInputs((inputs) => ({ ...inputs, [name]: value }));
setInputs((inputs) => ({...inputs, [name]: value}));
};
const generateAccessToken = async () => {
const res = await API.get('/api/user/token');
const { success, message, data } = res.data;
const {success, message, data} = res.data;
if (success) {
setSystemToken(data);
await copy(data);
@ -118,7 +118,7 @@ const PersonalSetting = () => {
const getAffLink = async () => {
const res = await API.get('/api/user/aff');
const { success, message, data } = res.data;
const {success, message, data} = res.data;
if (success) {
let link = `${window.location.origin}/register?aff=${data}`;
setAffLink(link);
@ -129,9 +129,9 @@ const PersonalSetting = () => {
const getUserData = async () => {
let res = await API.get(`/api/user/self`);
const { success, message, data } = res.data;
const {success, message, data} = res.data;
if (success) {
userDispatch({ type: 'login', payload: data });
userDispatch({type: 'login', payload: data});
} else {
showError(message);
}
@ -139,7 +139,7 @@ const PersonalSetting = () => {
const loadModels = async () => {
let res = await API.get(`/api/user/models`);
const { success, message, data } = res.data;
const {success, message, data} = res.data;
if (success) {
setModels(data);
console.log(data);
@ -167,12 +167,12 @@ const PersonalSetting = () => {
}
const res = await API.delete('/api/user/self');
const { success, message } = res.data;
const {success, message} = res.data;
if (success) {
showSuccess('账户已删除!');
await API.get('/api/user/logout');
userDispatch({ type: 'logout' });
userDispatch({type: 'logout'});
localStorage.removeItem('user');
navigate('/login');
} else {
@ -185,7 +185,7 @@ const PersonalSetting = () => {
const res = await API.get(
`/api/oauth/wechat/bind?code=${inputs.wechat_verification_code}`,
);
const { success, message } = res.data;
const {success, message} = res.data;
if (success) {
showSuccess('微信账户绑定成功!');
setShowWeChatBindModal(false);
@ -202,7 +202,7 @@ const PersonalSetting = () => {
const res = await API.put(`/api/user/self`, {
password: inputs.set_new_password,
});
const { success, message } = res.data;
const {success, message} = res.data;
if (success) {
showSuccess('密码修改成功!');
setShowWeChatBindModal(false);
@ -220,7 +220,7 @@ const PersonalSetting = () => {
const res = await API.post(`/api/user/aff_transfer`, {
quota: transferAmount,
});
const { success, message } = res.data;
const {success, message} = res.data;
if (success) {
showSuccess(message);
setOpenTransfer(false);
@ -244,7 +244,7 @@ const PersonalSetting = () => {
const res = await API.get(
`/api/verification?email=${inputs.email}&turnstile=${turnstileToken}`,
);
const { success, message } = res.data;
const {success, message} = res.data;
if (success) {
showSuccess('验证码发送成功,请检查邮箱!');
} else {
@ -262,7 +262,7 @@ const PersonalSetting = () => {
const res = await API.get(
`/api/oauth/email/bind?email=${inputs.email}&code=${inputs.email_verification_code}`,
);
const { success, message } = res.data;
const {success, message} = res.data;
if (success) {
showSuccess('邮箱账户绑定成功!');
setShowEmailBindModal(false);
@ -290,7 +290,7 @@ const PersonalSetting = () => {
showSuccess('已复制:' + text);
} else {
// setSearchKeyword(text);
Modal.error({ title: '无法复制到剪贴板,请手动复制', content: text });
Modal.error({title: '无法复制到剪贴板,请手动复制', content: text});
}
};
@ -307,15 +307,15 @@ const PersonalSetting = () => {
size={'small'}
centered={true}
>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Typography.Text>{`可用额度${renderQuotaWithPrompt(userState?.user?.aff_quota)}`}</Typography.Text>
<Input
style={{ marginTop: 5 }}
style={{marginTop: 5}}
value={userState?.user?.aff_quota}
disabled={true}
></Input>
</div>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Typography.Text>
{`划转额度${renderQuotaWithPrompt(transferAmount)} 最低` +
renderQuota(getQuotaPerUnit())}
@ -323,7 +323,7 @@ const PersonalSetting = () => {
<div>
<InputNumber
min={0}
style={{ marginTop: 5 }}
style={{marginTop: 5}}
value={transferAmount}
onChange={(value) => setTransferAmount(value)}
disabled={false}
@ -331,7 +331,7 @@ const PersonalSetting = () => {
</div>
</div>
</Modal>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Card
title={
<Card.Meta
@ -339,7 +339,7 @@ const PersonalSetting = () => {
<Avatar
size='default'
color={stringToColor(getUsername())}
style={{ marginRight: 4 }}
style={{marginRight: 4}}
>
{typeof getUsername() === 'string' &&
getUsername().slice(0, 1)}
@ -378,7 +378,7 @@ const PersonalSetting = () => {
}
>
<Typography.Title heading={6}>可用模型</Typography.Title>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Space wrap>
{models.map((model) => (
<Tag
@ -395,11 +395,12 @@ const PersonalSetting = () => {
</div>
</Card>
<Card
style={{marginTop: 10}}
footer={
<div>
<Typography.Text>邀请链接</Typography.Text>
<Input
style={{ marginTop: 10 }}
style={{marginTop: 10}}
value={affLink}
onClick={handleAffLinkClick}
readOnly
@ -408,17 +409,17 @@ const PersonalSetting = () => {
}
>
<Typography.Title heading={6}>邀请信息</Typography.Title>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Descriptions row>
<Descriptions.Item itemKey='待使用收益'>
<span style={{ color: 'rgba(var(--semi-red-5), 1)' }}>
<span style={{color: 'rgba(var(--semi-red-5), 1)'}}>
{renderQuota(userState?.user?.aff_quota)}
</span>
<Button
type={'secondary'}
onClick={() => setOpenTransfer(true)}
size={'small'}
style={{ marginLeft: 10 }}
style={{marginLeft: 10}}
>
划转
</Button>
@ -432,12 +433,12 @@ const PersonalSetting = () => {
</Descriptions>
</div>
</Card>
<Card>
<Card style={{marginTop: 10}}>
<Typography.Title heading={6}>个人信息</Typography.Title>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Typography.Text strong>邮箱</Typography.Text>
<div
style={{ display: 'flex', justifyContent: 'space-between' }}
style={{display: 'flex', justifyContent: 'space-between'}}
>
<div>
<Input
@ -462,10 +463,10 @@ const PersonalSetting = () => {
</div>
</div>
</div>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Typography.Text strong>微信</Typography.Text>
<div
style={{ display: 'flex', justifyContent: 'space-between' }}
style={{display: 'flex', justifyContent: 'space-between'}}
>
<div>
<Input
@ -489,10 +490,10 @@ const PersonalSetting = () => {
</div>
</div>
</div>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Typography.Text strong>GitHub</Typography.Text>
<div
style={{ display: 'flex', justifyContent: 'space-between' }}
style={{display: 'flex', justifyContent: 'space-between'}}
>
<div>
<Input
@ -519,10 +520,10 @@ const PersonalSetting = () => {
</div>
</div>
</div>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Typography.Text strong>Telegram</Typography.Text>
<div
style={{ display: 'flex', justifyContent: 'space-between' }}
style={{display: 'flex', justifyContent: 'space-between'}}
>
<div>
<Input
@ -550,10 +551,10 @@ const PersonalSetting = () => {
</div>
</div>
</div>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Typography.Text strong>LinuxDO</Typography.Text>
<div
style={{ display: 'flex', justifyContent: 'space-between' }}
style={{display: 'flex', justifyContent: 'space-between'}}
>
<div>
<Input
@ -580,7 +581,7 @@ const PersonalSetting = () => {
</div>
</div>
</div>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Space>
<Button onClick={generateAccessToken}>
生成系统访问令牌
@ -607,7 +608,7 @@ const PersonalSetting = () => {
readOnly
value={systemToken}
onClick={handleSystemTokenClick}
style={{ marginTop: '10px' }}
style={{marginTop: '10px'}}
/>
)}
{status.wechat_login && (
@ -625,8 +626,8 @@ const PersonalSetting = () => {
visible={showWeChatBindModal}
size={'small'}
>
<Image src={status.wechat_qrcode} />
<div style={{ textAlign: 'center' }}>
<Image src={status.wechat_qrcode}/>
<div style={{textAlign: 'center'}}>
<p>
微信扫码关注公众号输入验证码获取验证码三分钟内有效
</p>
@ -676,7 +677,7 @@ const PersonalSetting = () => {
{disableButton ? `重新发送 (${countdown})` : '获取验证码'}
</Button>
</div>
<div style={{ marginTop: 10 }}>
<div style={{marginTop: 10}}>
<Input
fluid
placeholder='验证码'
@ -705,14 +706,14 @@ const PersonalSetting = () => {
centered={true}
onOk={deleteAccount}
>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Banner
type='danger'
description='您正在删除自己的帐户,将清空所有数据且不可恢复'
closeIcon={null}
/>
</div>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Input
placeholder={`输入你的账户名 ${userState?.user?.username} 以确认删除`}
name='self_account_deletion_confirmation'
@ -743,7 +744,7 @@ const PersonalSetting = () => {
centered={true}
onOk={changePassword}
>
<div style={{ marginTop: 20 }}>
<div style={{marginTop: 20}}>
<Input
name='set_new_password'
placeholder='新密码'
@ -753,7 +754,7 @@ const PersonalSetting = () => {
}
/>
<Input
style={{ marginTop: 20 }}
style={{marginTop: 20}}
name='set_new_password_confirmation'
placeholder='确认新密码'
value={inputs.set_new_password_confirmation}