fix: 修改 OneDrive token 刷新 (#5659)

This commit is contained in:
ssongliu 2024-07-03 18:01:30 +08:00 committed by GitHub
parent 1e553fc14e
commit 80f78548fd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 28 additions and 29 deletions

View File

@ -414,8 +414,6 @@ func (u *BackupService) NewClient(backup *model.BackupAccount) (cloud_storage.Cl
case constant.OSS, constant.S3, constant.MinIo, constant.Cos, constant.Kodo:
varMap["accessKey"] = backup.AccessKey
varMap["secretKey"] = backup.Credential
case constant.OneDrive:
varMap["accessToken"] = backup.Credential
}
backClient, err := cloud_storage.NewCloudStorageClient(backup.Type, varMap)
@ -453,12 +451,11 @@ func (u *BackupService) loadAccessToken(backup *model.BackupAccount) error {
if err := json.Unmarshal([]byte(backup.Vars), &varMap); err != nil {
return fmt.Errorf("unmarshal backup vars failed, err: %v", err)
}
token, refreshToken, err := client.RefreshToken("authorization_code", varMap)
refreshToken, err := client.RefreshToken("authorization_code", "refreshToken", varMap)
if err != nil {
return err
}
delete(varMap, "code")
backup.Credential = token
varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
varMap["refresh_token"] = refreshToken
@ -599,7 +596,7 @@ func (u *BackupService) checkBackupConn(backup *model.BackupAccount) (bool, erro
func StartRefreshOneDriveToken() {
service := NewIBackupService()
oneDriveCronID, err := global.Cron.AddJob("0 * * * *", service)
oneDriveCronID, err := global.Cron.AddJob("0 3 */31 * *", service)
if err != nil {
global.LOG.Errorf("can not add OneDrive corn job: %s", err.Error())
return
@ -613,17 +610,13 @@ func (u *BackupService) Run() {
if backupItem.ID == 0 {
return
}
if len(backupItem.Credential) == 0 {
global.LOG.Error("OneDrive configuration lacks token information, please rebind.")
return
}
global.LOG.Info("start to refresh token of OneDrive ...")
varMap := make(map[string]interface{})
if err := json.Unmarshal([]byte(backupItem.Vars), &varMap); err != nil {
global.LOG.Errorf("Failed to refresh OneDrive token, please retry, err: %v", err)
return
}
token, refreshToken, err := client.RefreshToken("refresh_token", varMap)
refreshToken, err := client.RefreshToken("refresh_token", "refreshToken", varMap)
varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
if err != nil {
@ -638,8 +631,7 @@ func (u *BackupService) Run() {
_ = global.DB.Model(&model.BackupAccount{}).
Where("id = ?", backupItem.ID).
Updates(map[string]interface{}{
"credential": token,
"vars": varsItem,
"vars": varsItem,
}).Error
global.LOG.Info("Successfully refreshed OneDrive token.")
}

View File

@ -249,7 +249,7 @@ var UpdateOneDriveToken = &gormigrate.Migration{
varMap["client_secret"] = global.CONF.System.OneDriveSc
varMap["redirect_uri"] = constant.OneDriveRedirectURI
varMap["refresh_token"] = backup.Credential
token, refreshToken, err := client.RefreshToken("refresh_token", varMap)
refreshToken, err := client.RefreshToken("refresh_token", "refreshToken", varMap)
varMap["refresh_status"] = constant.StatusSuccess
varMap["refresh_time"] = time.Now().Format(constant.DateTimeLayout)
if err != nil {
@ -261,8 +261,7 @@ var UpdateOneDriveToken = &gormigrate.Migration{
if err := tx.Model(&model.BackupAccount{}).
Where("id = ?", backup.ID).
Updates(map[string]interface{}{
"credential": token,
"vars": string(itemVars),
"vars": string(itemVars),
}).Error; err != nil {
return err
}

View File

@ -27,7 +27,10 @@ type oneDriveClient struct {
}
func NewOneDriveClient(vars map[string]interface{}) (*oneDriveClient, error) {
token := loadParamFromVars("accessToken", vars)
token, err := RefreshToken("refresh_token", "accessToken", vars)
if err != nil {
return nil, err
}
isCN := loadParamFromVars("isCN", vars)
ctx := context.Background()
ts := oauth2.StaticTokenSource(
@ -196,7 +199,7 @@ func (o *oneDriveClient) loadIDByPath(path string) (string, error) {
return driveItem.Id, nil
}
func RefreshToken(grantType string, varMap map[string]interface{}) (string, string, error) {
func RefreshToken(grantType string, tokenType string, varMap map[string]interface{}) (string, error) {
data := url.Values{}
isCN := loadParamFromVars("isCN", varMap)
data.Set("client_id", loadParamFromVars("client_id", varMap))
@ -216,32 +219,37 @@ func RefreshToken(grantType string, varMap map[string]interface{}) (string, stri
}
req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
if err != nil {
return "", "", fmt.Errorf("new http post client for access token failed, err: %v", err)
return "", fmt.Errorf("new http post client for access token failed, err: %v", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return "", "", fmt.Errorf("request for access token failed, err: %v", err)
return "", fmt.Errorf("request for access token failed, err: %v", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", "", fmt.Errorf("read data from response body failed, err: %v", err)
return "", fmt.Errorf("read data from response body failed, err: %v", err)
}
tokenMap := map[string]interface{}{}
if err := json.Unmarshal(respBody, &tokenMap); err != nil {
return "", "", fmt.Errorf("unmarshal data from response body failed, err: %v", err)
return "", fmt.Errorf("unmarshal data from response body failed, err: %v", err)
}
accessToken, ok := tokenMap["access_token"].(string)
if !ok {
return "", "", errors.New("no such access token in response")
if tokenType == "accessToken" {
accessToken, ok := tokenMap["access_token"].(string)
if !ok {
return "", errors.New("no such access token in response")
}
tokenMap = nil
return accessToken, nil
}
refreshToken, ok := tokenMap["refresh_token"].(string)
if !ok {
return "", "", errors.New("no such access token in response")
return "", errors.New("no such access token in response")
}
return accessToken, refreshToken, nil
tokenMap = nil
return refreshToken, nil
}
func (o *oneDriveClient) createFolder(parent string) error {
@ -356,8 +364,8 @@ func (o *oneDriveClient) upBig(ctx context.Context, srcPath, folderID string, fi
fileSessionUploadUrl := sessionCreationResp.UploadURL
sizePerSplit := int64(3200 * 1024)
buffer := make([]byte, 3200*1024)
sizePerSplit := int64(5 * 1024 * 1024)
buffer := make([]byte, 5*1024*1024)
splitCount := fileSize / sizePerSplit
if fileSize%sizePerSplit != 0 {
splitCount += 1

View File

@ -1016,7 +1016,7 @@ const message = {
clamHelper:
'ClamAV 的最低建议配置为3 GiB 以上的 RAM2.0 GHz 以上的单核 CPU以及至少 5 GiB 的可用硬盘空间',
noClam: '未检测到 ClamAV 服务请参考官方文档进行安装',
notStart: '当前未 ClamAV 服务请先开启',
notStart: '当前未开启 ClamAV 服务请先开启',
removeResult: '删除报告文件',
removeResultHelper: '删除任务执行过程中生成的报告文件以清理存储空间',
removeInfected: '删除病毒文件',