Files
crawlab/core/notification/oauth2_gmail.go
Marvin Zhang 3276083994 refactor: replace apex/log with structured logger across multiple services
- Replaced all instances of apex/log with a structured logger interface in various services, including Api, Server, Config, and others, to enhance logging consistency and context.
- Updated logging calls to utilize the new logger methods, improving error tracking and service monitoring.
- Added logger initialization in services and controllers to ensure proper logging setup.
- Improved error handling and logging messages for better clarity during service operations.
- Removed unused apex/log imports and cleaned up related code for better maintainability.
2024-12-24 19:11:19 +08:00

47 lines
1.2 KiB
Go

package notification
import (
"context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"net/smtp"
"time"
)
// 获取服务账户的OAuth2配置
func getGmailOAuth2Token(oauth2Json string) (token *oauth2.Token, err error) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// 读取服务账户 JSON 密钥
b := []byte(oauth2Json)
// 使用服务账户 JSON 密钥文件创建 JWT 配置
config, err := google.JWTConfigFromJSON(b, "https://mail.google.com/")
if err != nil {
logger.Errorf("Unable to parse service account key file to config: %v", err)
return nil, err
}
// 使用服务账户的电子邮件和访问令牌
token, err = config.TokenSource(ctx).Token()
if err != nil {
logger.Errorf("Unable to generate token: %v", err)
return nil, err
}
return token, nil
}
// GmailOAuth2Auth 自定义OAuth2认证
type GmailOAuth2Auth struct {
username, accessToken string
}
func (a *GmailOAuth2Auth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
return "XOAUTH2", []byte("user=" + a.username + "\x01auth=Bearer " + a.accessToken + "\x01\x01"), nil
}
func (a *GmailOAuth2Auth) Next(_ []byte, _ bool) ([]byte, error) {
return nil, nil
}