fix: 备份账号 OneDrive 绑定逻辑修改 (#1529)

This commit is contained in:
ssongliu 2023-07-04 16:16:12 +08:00 committed by GitHub
parent f70b0049d9
commit dddd190911
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 131 additions and 12 deletions

View File

@ -98,6 +98,22 @@ func (b *BaseApi) ListBuckets(c *gin.Context) {
helper.SuccessWithData(c, buckets) helper.SuccessWithData(c, buckets)
} }
// @Tags Backup Account
// @Summary Load OneDrive info
// @Description 获取 OneDrive 信息
// @Accept json
// @Success 200 string clientID
// @Security ApiKeyAuth
// @Router /settings/backup/onedrive [get]
func (b *BaseApi) LoadOneDriveInfo(c *gin.Context) {
clientID, err := backupService.LoadOneDriveInfo()
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}
helper.SuccessWithData(c, clientID)
}
// @Tags Backup Account // @Tags Backup Account
// @Summary Delete backup account // @Summary Delete backup account
// @Description 删除备份账号 // @Description 删除备份账号

View File

@ -2,6 +2,7 @@ package service
import ( import (
"context" "context"
"encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -27,6 +28,7 @@ type BackupService struct{}
type IBackupService interface { type IBackupService interface {
List() ([]dto.BackupInfo, error) List() ([]dto.BackupInfo, error)
SearchRecordsWithPage(search dto.RecordSearch) (int64, []dto.BackupRecords, error) SearchRecordsWithPage(search dto.RecordSearch) (int64, []dto.BackupRecords, error)
LoadOneDriveInfo() (string, error)
DownloadRecord(info dto.DownloadRecord) (string, error) DownloadRecord(info dto.DownloadRecord) (string, error)
Create(backupDto dto.BackupOperate) error Create(backupDto dto.BackupOperate) error
GetBuckets(backupDto dto.ForBuckets) ([]interface{}, error) GetBuckets(backupDto dto.ForBuckets) ([]interface{}, error)
@ -88,6 +90,18 @@ func (u *BackupService) SearchRecordsWithPage(search dto.RecordSearch) (int64, [
return total, dtobas, err return total, dtobas, err
} }
func (u *BackupService) LoadOneDriveInfo() (string, error) {
OneDriveID, err := settingRepo.Get(settingRepo.WithByKey("OneDriveID"))
if err != nil {
return "", err
}
idItem, err := base64.StdEncoding.DecodeString(OneDriveID.Value)
if err != nil {
return "", err
}
return string(idItem), err
}
func (u *BackupService) DownloadRecord(info dto.DownloadRecord) (string, error) { func (u *BackupService) DownloadRecord(info dto.DownloadRecord) (string, error) {
if info.Source == "LOCAL" { if info.Source == "LOCAL" {
return info.FileDir + "/" + info.FileName, nil return info.FileDir + "/" + info.FileName, nil
@ -313,8 +327,8 @@ func (u *BackupService) loadAccessToken(backup *model.BackupAccount) error {
} }
data := url.Values{} data := url.Values{}
data.Set("client_id", constant.OneDriveClientID) data.Set("client_id", global.CONF.System.OneDriveID)
data.Set("client_secret", constant.OneDriveClientSecret) data.Set("client_secret", global.CONF.System.OneDriveSc)
data.Set("grant_type", "authorization_code") data.Set("grant_type", "authorization_code")
data.Set("code", varMap["code"].(string)) data.Set("code", varMap["code"].(string))
data.Set("redirect_uri", constant.OneDriveRedirectURI) data.Set("redirect_uri", constant.OneDriveRedirectURI)

View File

@ -21,4 +21,6 @@ type System struct {
IsDemo bool `mapstructure:"is_demo"` IsDemo bool `mapstructure:"is_demo"`
AppRepo string `mapstructure:"app_repo"` AppRepo string `mapstructure:"app_repo"`
ChangeUserInfo bool `mapstructure:"change_user_info"` ChangeUserInfo bool `mapstructure:"change_user_info"`
OneDriveID string `mapstructure:"one_drive_id"`
OneDriveSc string `mapstructure:"one_drive_sc"`
} }

View File

@ -12,7 +12,5 @@ const (
Cos = "COS" Cos = "COS"
Kodo = "KODO" Kodo = "KODO"
OneDriveClientID = "5446cfe3-4c79-47a0-ae25-fc645478e2d9" OneDriveRedirectURI = "http://localhost/login/authorized"
OneDriveClientSecret = "ITh8Q~0UKJNXAvz6HE~pd3DTnGJOgDEEpnDOJbqY"
OneDriveRedirectURI = "http://localhost/login/authorized"
) )

View File

@ -1,6 +1,8 @@
package hook package hook
import ( import (
"encoding/base64"
"github.com/1Panel-dev/1Panel/backend/app/repo" "github.com/1Panel-dev/1Panel/backend/app/repo"
"github.com/1Panel-dev/1Panel/backend/global" "github.com/1Panel-dev/1Panel/backend/global"
"github.com/1Panel-dev/1Panel/backend/utils/cmd" "github.com/1Panel-dev/1Panel/backend/utils/cmd"
@ -26,6 +28,19 @@ func Init() {
} }
global.CONF.System.SSL = sslSetting.Value global.CONF.System.SSL = sslSetting.Value
OneDriveID, err := settingRepo.Get(settingRepo.WithByKey("OneDriveID"))
if err != nil {
global.LOG.Errorf("load onedrive info from setting failed, err: %v", err)
}
idItem, _ := base64.StdEncoding.DecodeString(OneDriveID.Value)
global.CONF.System.OneDriveID = string(idItem)
OneDriveSc, err := settingRepo.Get(settingRepo.WithByKey("OneDriveSc"))
if err != nil {
global.LOG.Errorf("load onedrive info from setting failed, err: %v", err)
}
scItem, _ := base64.StdEncoding.DecodeString(OneDriveSc.Value)
global.CONF.System.OneDriveSc = string(scItem)
if _, err := settingRepo.Get(settingRepo.WithByKey("SystemStatus")); err != nil { if _, err := settingRepo.Get(settingRepo.WithByKey("SystemStatus")); err != nil {
_ = settingRepo.Create("SystemStatus", "Free") _ = settingRepo.Create("SystemStatus", "Free")
} }

View File

@ -410,6 +410,12 @@ var AddMfaInterval = &gormigrate.Migration{
if err := tx.Create(&model.Setting{Key: "SystemIP", Value: ""}).Error; err != nil { if err := tx.Create(&model.Setting{Key: "SystemIP", Value: ""}).Error; err != nil {
return err return err
} }
if err := tx.Create(&model.Setting{Key: "OneDriveID", Value: "MDEwOTM1YTktMWFhOS00ODU0LWExZGMtNmU0NWZlNjI4YzZi"}).Error; err != nil {
return err
}
if err := tx.Create(&model.Setting{Key: "OneDriveSc", Value: "akpuOFF+YkNXOU1OLWRzS1ZSRDdOcG1LT2ZRM0RLNmdvS1RkVWNGRA=="}).Error; err != nil {
return err
}
return nil return nil
}, },
} }

View File

@ -41,6 +41,7 @@ func (s *SettingRouter) InitSettingRouter(Router *gin.RouterGroup) {
settingRouter.POST("/snapshot/description/update", baseApi.UpdateSnapDescription) settingRouter.POST("/snapshot/description/update", baseApi.UpdateSnapDescription)
settingRouter.GET("/backup/search", baseApi.ListBackup) settingRouter.GET("/backup/search", baseApi.ListBackup)
settingRouter.GET("/backup/onedrive", baseApi.LoadOneDriveInfo)
settingRouter.POST("/backup/backup", baseApi.Backup) settingRouter.POST("/backup/backup", baseApi.Backup)
settingRouter.POST("/backup/recover", baseApi.Recover) settingRouter.POST("/backup/recover", baseApi.Recover)
settingRouter.POST("/backup/recover/byupload", baseApi.RecoverByUpload) settingRouter.POST("/backup/recover/byupload", baseApi.RecoverByUpload)

View File

@ -240,8 +240,8 @@ func (onedrive *oneDriveClient) loadIDByPath(path string) (string, error) {
func refreshToken(oldToken string) (string, error) { func refreshToken(oldToken string) (string, error) {
data := url.Values{} data := url.Values{}
data.Set("client_id", constant.OneDriveClientID) data.Set("client_id", global.CONF.System.OneDriveID)
data.Set("client_secret", constant.OneDriveClientSecret) data.Set("client_secret", global.CONF.System.OneDriveSc)
data.Set("grant_type", "refresh_token") data.Set("grant_type", "refresh_token")
data.Set("refresh_token", oldToken) data.Set("refresh_token", oldToken)
data.Set("redirect_uri", constant.OneDriveRedirectURI) data.Set("redirect_uri", constant.OneDriveRedirectURI)

View File

@ -7085,6 +7085,31 @@ var doc = `{
} }
} }
}, },
"/settings/backup/onedrive": {
"get": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "获取 OneDrive 信息",
"consumes": [
"application/json"
],
"tags": [
"Backup Account"
],
"summary": "Load OneDrive info",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
},
"/settings/backup/record/del": { "/settings/backup/record/del": {
"post": { "post": {
"security": [ "security": [

View File

@ -7071,6 +7071,31 @@
} }
} }
}, },
"/settings/backup/onedrive": {
"get": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "获取 OneDrive 信息",
"consumes": [
"application/json"
],
"tags": [
"Backup Account"
],
"summary": "Load OneDrive info",
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
}
}
},
"/settings/backup/record/del": { "/settings/backup/record/del": {
"post": { "post": {
"security": [ "security": [

View File

@ -7881,6 +7881,21 @@ paths:
formatEN: delete backup account [types] formatEN: delete backup account [types]
formatZH: 删除备份账号 [types] formatZH: 删除备份账号 [types]
paramKeys: [] paramKeys: []
/settings/backup/onedrive:
get:
consumes:
- application/json
description: 获取 OneDrive 信息
responses:
"200":
description: OK
schema:
type: string
security:
- ApiKeyAuth: []
summary: Load OneDrive info
tags:
- Backup Account
/settings/backup/record/del: /settings/backup/record/del:
post: post:
consumes: consumes:

View File

@ -85,6 +85,9 @@ export const searchBackupRecords = (params: Backup.SearchBackupRecord) => {
export const getBackupList = () => { export const getBackupList = () => {
return http.get<Array<Backup.BackupInfo>>(`/settings/backup/search`); return http.get<Array<Backup.BackupInfo>>(`/settings/backup/search`);
}; };
export const getOneDriveInfo = () => {
return http.get<string>(`/settings/backup/onedrive`);
};
export const getFilesFromBackup = (type: string) => { export const getFilesFromBackup = (type: string) => {
return http.post<Array<any>>(`/settings/backup/search/files`, { type: type }); return http.post<Array<any>>(`/settings/backup/search/files`, { type: type });
}; };

View File

@ -254,7 +254,7 @@ import i18n from '@/lang';
import { ElForm } from 'element-plus'; import { ElForm } from 'element-plus';
import { Backup } from '@/api/interface/backup'; import { Backup } from '@/api/interface/backup';
import DrawerHeader from '@/components/drawer-header/index.vue'; import DrawerHeader from '@/components/drawer-header/index.vue';
import { addBackup, editBackup, listBucket } from '@/api/modules/setting'; import { addBackup, editBackup, getOneDriveInfo, listBucket } from '@/api/modules/setting';
import { deepCopy } from '@/utils/util'; import { deepCopy } from '@/utils/util';
import { MsgSuccess } from '@/utils/message'; import { MsgSuccess } from '@/utils/message';
@ -309,10 +309,9 @@ const handleClose = () => {
emit('search'); emit('search');
drawerVisiable.value = false; drawerVisiable.value = false;
}; };
const jumpAzure = async () => {
const jumpAzure = () => { const res = await getOneDriveInfo();
let commonUrl = let commonUrl = `response_type=code&client_id=${res.data}&redirect_uri=http://localhost/login/authorized&scope=offline_access+Files.ReadWrite.All+User.Read`;
'response_type=code&client_id=5446cfe3-4c79-47a0-ae25-fc645478e2d9&redirect_uri=http://localhost/login/authorized&scope=offline_access+Files.ReadWrite.All+User.Read';
if (!dialogData.value.rowData!.varsJson['isCN']) { if (!dialogData.value.rowData!.varsJson['isCN']) {
window.open('https://login.microsoftonline.com/common/oauth2/v2.0/authorize?' + commonUrl, '_blank'); window.open('https://login.microsoftonline.com/common/oauth2/v2.0/authorize?' + commonUrl, '_blank');
} else { } else {