Compare commits
15 Commits
aed09d4341
...
feature/em
| Author | SHA1 | Date | |
|---|---|---|---|
| 057681561a | |||
| 9876169c84 | |||
| 5371b1d1c6 | |||
| fcd9816b0b | |||
|
|
18597ba7fa | ||
| 2fafcb9bfd | |||
|
|
b5d177910c | ||
|
|
7df6587fd6 | ||
|
|
94988790f8 | ||
|
|
45dcef5702 | ||
|
|
ed7232e5c0 | ||
|
|
8852ee5a3a | ||
|
|
a7b73b0928 | ||
|
|
e35f3ed684 | ||
| 6786d174a6 |
@@ -38,15 +38,20 @@ func SetupRouter(engine *gin.RouterGroup) {
|
|||||||
ossRouter.POST("/file/upload", endpoint.UploadFile)
|
ossRouter.POST("/file/upload", endpoint.UploadFile)
|
||||||
}
|
}
|
||||||
|
|
||||||
userRouter := v1.Group("/user", common.GetAuthMiddleware())
|
userEndpoint := user.NewUserEndpoint()
|
||||||
|
|
||||||
|
userRouter := v1.Group("/user")
|
||||||
{
|
{
|
||||||
userEndpoint := user.NewUserEndpoint()
|
userRouter.POST("/sms", userEndpoint.SendVerificationCode)
|
||||||
{
|
userRouter.POST("/register", userEndpoint.RegisterByEmail)
|
||||||
userRouter.POST("/sms", userEndpoint.SendVerificationCode)
|
userRouter.POST("/login", userEndpoint.LoginByEmail)
|
||||||
userRouter.POST("/register", userEndpoint.RegisterByEmail)
|
userRouter.GET("/oauth/google/url", userEndpoint.GetGoogleOAuthUrl)
|
||||||
userRouter.POST("/login", userEndpoint.LoginByEmail)
|
userRouter.POST("/oauth/google/callback", userEndpoint.GoogleOAuthCallback)
|
||||||
userRouter.GET("/info", common.MustAuthMiddleware(), userEndpoint.GetUserInfo)
|
}
|
||||||
}
|
|
||||||
|
userAuthRouter := v1.Group("/user", common.GetAuthMiddleware())
|
||||||
|
{
|
||||||
|
userAuthRouter.GET("/info", common.MustAuthMiddleware(), userEndpoint.GetUserInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 数据埋点路由
|
// 数据埋点路由
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package user
|
package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
"gitea.com/texpixel/document_ai/config"
|
"gitea.com/texpixel/document_ai/config"
|
||||||
model "gitea.com/texpixel/document_ai/internal/model/user"
|
model "gitea.com/texpixel/document_ai/internal/model/user"
|
||||||
@@ -98,15 +100,9 @@ func (h *UserEndpoint) GetUserInfo(ctx *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
status := 0
|
|
||||||
if user.ID > 0 {
|
|
||||||
status = 1
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.JSON(http.StatusOK, common.SuccessResponse(ctx, model.UserInfoResponse{
|
ctx.JSON(http.StatusOK, common.SuccessResponse(ctx, model.UserInfoResponse{
|
||||||
Username: user.Username,
|
Username: user.Username,
|
||||||
Phone: user.Phone,
|
Email: user.Email,
|
||||||
Status: status,
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,3 +165,69 @@ func (h *UserEndpoint) LoginByEmail(ctx *gin.Context) {
|
|||||||
ExpiresAt: tokenResult.ExpiresAt,
|
ExpiresAt: tokenResult.ExpiresAt,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (h *UserEndpoint) GetGoogleOAuthUrl(ctx *gin.Context) {
|
||||||
|
req := model.GoogleAuthUrlRequest{}
|
||||||
|
if err := ctx.ShouldBindQuery(&req); err != nil {
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeParamError, common.CodeParamErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
googleConfig := config.GlobalConfig.Google
|
||||||
|
if googleConfig.ClientID == "" {
|
||||||
|
log.Error(ctx, "func", "GetGoogleOAuthUrl", "msg", "Google OAuth not configured")
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeSystemError, common.CodeSystemErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
authURL := fmt.Sprintf(
|
||||||
|
"https://accounts.google.com/o/oauth2/v2/auth?client_id=%s&redirect_uri=%s&response_type=code&scope=openid%%20email%%20profile&state=%s",
|
||||||
|
url.QueryEscape(googleConfig.ClientID),
|
||||||
|
url.QueryEscape(req.RedirectURI),
|
||||||
|
url.QueryEscape(req.State),
|
||||||
|
)
|
||||||
|
|
||||||
|
ctx.JSON(http.StatusOK, common.SuccessResponse(ctx, model.GoogleAuthUrlResponse{
|
||||||
|
AuthURL: authURL,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *UserEndpoint) GoogleOAuthCallback(ctx *gin.Context) {
|
||||||
|
req := model.GoogleOAuthCallbackRequest{}
|
||||||
|
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeParamError, common.CodeParamErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
googleConfig := config.GlobalConfig.Google
|
||||||
|
if googleConfig.ClientID == "" || googleConfig.ClientSecret == "" {
|
||||||
|
log.Error(ctx, "func", "GoogleOAuthCallback", "msg", "Google OAuth not configured")
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeSystemError, common.CodeSystemErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
userInfo, err := h.userService.ExchangeGoogleCodeAndGetUserInfo(ctx, googleConfig.ClientID, googleConfig.ClientSecret, req.Code, req.RedirectURI)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "GoogleOAuthCallback", "msg", "exchange code failed", "error", err)
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeSystemError, common.CodeSystemErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
uid, err := h.userService.FindOrCreateGoogleUser(ctx, userInfo)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "GoogleOAuthCallback", "msg", "find or create user failed", "error", err)
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeSystemError, common.CodeSystemErrorMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenResult, err := jwt.CreateToken(jwt.User{UserId: uid})
|
||||||
|
if err != nil {
|
||||||
|
ctx.JSON(http.StatusOK, common.ErrorResponse(ctx, common.CodeUnauthorized, common.CodeUnauthorizedMsg))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.JSON(http.StatusOK, common.SuccessResponse(ctx, model.GoogleOAuthCallbackResponse{
|
||||||
|
Token: tokenResult.Token,
|
||||||
|
ExpiresAt: tokenResult.ExpiresAt,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,21 +6,48 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Log log.LogConfig `mapstructure:"log"`
|
Log log.LogConfig `mapstructure:"log"`
|
||||||
Server ServerConfig `mapstructure:"server"`
|
Server ServerConfig `mapstructure:"server"`
|
||||||
Database DatabaseConfig `mapstructure:"database"`
|
Database DatabaseConfig `mapstructure:"database"`
|
||||||
Redis RedisConfig `mapstructure:"redis"`
|
Redis RedisConfig `mapstructure:"redis"`
|
||||||
UploadDir string `mapstructure:"upload_dir"`
|
UploadDir string `mapstructure:"upload_dir"`
|
||||||
Limit LimitConfig `mapstructure:"limit"`
|
Limit LimitConfig `mapstructure:"limit"`
|
||||||
Aliyun AliyunConfig `mapstructure:"aliyun"`
|
Aliyun AliyunConfig `mapstructure:"aliyun"`
|
||||||
Mathpix MathpixConfig `mapstructure:"mathpix"`
|
Mathpix MathpixConfig `mapstructure:"mathpix"`
|
||||||
BaiduOCR BaiduOCRConfig `mapstructure:"baidu_ocr"`
|
BaiduOCR BaiduOCRConfig `mapstructure:"baidu_ocr"`
|
||||||
|
Google GoogleOAuthConfig `mapstructure:"google"`
|
||||||
|
Email EmailConfig `mapstructure:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type EmailConfig struct {
|
||||||
|
FromName string `mapstructure:"from_name"`
|
||||||
|
FromAddr string `mapstructure:"from_addr"`
|
||||||
|
AliyunSMTP AliyunSMTPConfig `mapstructure:"aliyun_smtp"`
|
||||||
|
Resend ResendEmailConfig `mapstructure:"resend"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AliyunSMTPConfig struct {
|
||||||
|
Host string `mapstructure:"host"`
|
||||||
|
Port int `mapstructure:"port"`
|
||||||
|
Username string `mapstructure:"username"`
|
||||||
|
Password string `mapstructure:"password"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResendEmailConfig struct {
|
||||||
|
APIKey string `mapstructure:"api_key"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type BaiduOCRConfig struct {
|
type BaiduOCRConfig struct {
|
||||||
Token string `mapstructure:"token"`
|
Token string `mapstructure:"token"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GoogleOAuthConfig struct {
|
||||||
|
ClientID string `mapstructure:"client_id"`
|
||||||
|
ClientSecret string `mapstructure:"client_secret"`
|
||||||
|
RedirectURI string `mapstructure:"redirect_uri"`
|
||||||
|
Proxy string `mapstructure:"proxy"`
|
||||||
|
}
|
||||||
|
|
||||||
type MathpixConfig struct {
|
type MathpixConfig struct {
|
||||||
AppID string `mapstructure:"app_id"`
|
AppID string `mapstructure:"app_id"`
|
||||||
AppKey string `mapstructure:"app_key"`
|
AppKey string `mapstructure:"app_key"`
|
||||||
|
|||||||
@@ -4,25 +4,25 @@ server:
|
|||||||
|
|
||||||
database:
|
database:
|
||||||
driver: mysql
|
driver: mysql
|
||||||
host: mysql
|
host: localhost
|
||||||
port: 3306
|
port: 3006
|
||||||
username: root
|
username: root
|
||||||
password: texpixel#pwd123!
|
password: root123
|
||||||
dbname: doc_ai
|
dbname: doc_ai
|
||||||
max_idle: 10
|
max_idle: 10
|
||||||
max_open: 100
|
max_open: 100
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
addr: redis:6379
|
addr: localhost:6079
|
||||||
password: yoge@123321!
|
password: redis123
|
||||||
db: 0
|
db: 0
|
||||||
|
|
||||||
limit:
|
limit:
|
||||||
formula_recognition: 3
|
formula_recognition: 3
|
||||||
|
|
||||||
log:
|
log:
|
||||||
appName: document_ai
|
appName: document_ai
|
||||||
level: info
|
level: info
|
||||||
format: console # json, console
|
format: console # json, console
|
||||||
outputPath: ./logs/app.log # 日志文件路径
|
outputPath: ./logs/app.log # 日志文件路径
|
||||||
maxSize: 2 # 单个日志文件最大尺寸,单位MB
|
maxSize: 2 # 单个日志文件最大尺寸,单位MB
|
||||||
@@ -30,7 +30,6 @@ log:
|
|||||||
maxBackups: 1 # 保留的旧日志文件最大数量
|
maxBackups: 1 # 保留的旧日志文件最大数量
|
||||||
compress: false # 是否压缩旧日志
|
compress: false # 是否压缩旧日志
|
||||||
|
|
||||||
|
|
||||||
aliyun:
|
aliyun:
|
||||||
sms:
|
sms:
|
||||||
access_key_id: "LTAI5tB9ur4ExCF4dYPq7hLz"
|
access_key_id: "LTAI5tB9ur4ExCF4dYPq7hLz"
|
||||||
@@ -43,12 +42,28 @@ aliyun:
|
|||||||
inner_endpoint: oss-cn-beijing-internal.aliyuncs.com
|
inner_endpoint: oss-cn-beijing-internal.aliyuncs.com
|
||||||
access_key_id: LTAI5t8qXhow6NCdYDtu1saF
|
access_key_id: LTAI5t8qXhow6NCdYDtu1saF
|
||||||
access_key_secret: qZ2SwYsNCEBckCVSOszH31yYwXU44A
|
access_key_secret: qZ2SwYsNCEBckCVSOszH31yYwXU44A
|
||||||
bucket_name: texpixel-doc
|
bucket_name: texpixel-doc1
|
||||||
|
|
||||||
mathpix:
|
mathpix:
|
||||||
app_id: "ocr_eede6f_ea9b5c"
|
app_id: "ocr_eede6f_ea9b5c"
|
||||||
app_key: "fb72d251e33ac85c929bfd4eec40d78368d08d82fb2ee1cffb04a8bb967d1db5"
|
app_key: "fb72d251e33ac85c929bfd4eec40d78368d08d82fb2ee1cffb04a8bb967d1db5"
|
||||||
|
|
||||||
|
|
||||||
baidu_ocr:
|
baidu_ocr:
|
||||||
token: "e3a47bd2438f1f38840c203fc5939d17a54482d1"
|
token: "e3a47bd2438f1f38840c203fc5939d17a54482d1"
|
||||||
|
|
||||||
|
google:
|
||||||
|
client_id: "404402221037-nqdsk11bkpk5a7oh396mrg1ieh28u6q1.apps.googleusercontent.com"
|
||||||
|
client_secret: "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"
|
||||||
|
redirect_uri: "https://app.cloud.texpixel.com:10443/auth/google/callback"
|
||||||
|
proxy: "http://localhost:7890"
|
||||||
|
|
||||||
|
email:
|
||||||
|
from_name: "TexPixel Support"
|
||||||
|
from_addr: "support@texpixel.com"
|
||||||
|
aliyun_smtp:
|
||||||
|
host: "smtp.qiye.aliyun.com"
|
||||||
|
port: 465
|
||||||
|
username: "support@texpixel.com"
|
||||||
|
password: "8bPw2W9LlgHSTTfk"
|
||||||
|
resend:
|
||||||
|
api_key: "re_xxxxxxxxxxxx"
|
||||||
|
|||||||
@@ -50,3 +50,20 @@ mathpix:
|
|||||||
|
|
||||||
baidu_ocr:
|
baidu_ocr:
|
||||||
token: "e3a47bd2438f1f38840c203fc5939d17a54482d1"
|
token: "e3a47bd2438f1f38840c203fc5939d17a54482d1"
|
||||||
|
|
||||||
|
google:
|
||||||
|
client_id: "404402221037-nqdsk11bkpk5a7oh396mrg1ieh28u6q1.apps.googleusercontent.com"
|
||||||
|
client_secret: "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"
|
||||||
|
redirect_uri: "https://texpixel.com/auth/google/callback"
|
||||||
|
proxy: "http://100.115.184.74:7890"
|
||||||
|
|
||||||
|
email:
|
||||||
|
from_name: "TexPixel Support"
|
||||||
|
from_addr: "support@texpixel.com"
|
||||||
|
aliyun_smtp:
|
||||||
|
host: "smtp.qiye.aliyun.com"
|
||||||
|
port: 465
|
||||||
|
username: "support@texpixel.com"
|
||||||
|
password: "8bPw2W9LlgHSTTfk"
|
||||||
|
resend:
|
||||||
|
api_key: "re_xxxxxxxxxxxx"
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ ssh ubuntu << 'ENDSSH'
|
|||||||
cd /home/yoge/Dev/doc_ai_backed
|
cd /home/yoge/Dev/doc_ai_backed
|
||||||
git checkout test
|
git checkout test
|
||||||
git pull origin test
|
git pull origin test
|
||||||
docker compose down
|
docker compose -f docker-compose.infra.yml up -d
|
||||||
|
docker compose down
|
||||||
docker image rm doc_ai_backed-doc_ai:latest
|
docker image rm doc_ai_backed-doc_ai:latest
|
||||||
docker compose -f docker-compose.yml up -d
|
docker compose up -d
|
||||||
ENDSSH
|
ENDSSH
|
||||||
32
docker-compose.infra.yml
Normal file
32
docker-compose.infra.yml
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:8.0
|
||||||
|
container_name: mysql
|
||||||
|
environment:
|
||||||
|
MYSQL_ROOT_PASSWORD: texpixel#pwd123!
|
||||||
|
MYSQL_DATABASE: doc_ai
|
||||||
|
MYSQL_USER: texpixel
|
||||||
|
MYSQL_PASSWORD: texpixel#pwd123!
|
||||||
|
ports:
|
||||||
|
- "3006:3306"
|
||||||
|
volumes:
|
||||||
|
- mysql_data:/var/lib/mysql
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-ptexpixel#pwd123!"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
start_period: 30s
|
||||||
|
restart: always
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:latest
|
||||||
|
container_name: redis
|
||||||
|
command: redis-server --requirepass "yoge@123321!"
|
||||||
|
ports:
|
||||||
|
- "6079:6379"
|
||||||
|
restart: always
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
mysql_data:
|
||||||
|
driver: local
|
||||||
@@ -2,58 +2,9 @@ services:
|
|||||||
doc_ai:
|
doc_ai:
|
||||||
build: .
|
build: .
|
||||||
container_name: doc_ai
|
container_name: doc_ai
|
||||||
ports:
|
network_mode: host
|
||||||
- "8024:8024"
|
|
||||||
volumes:
|
volumes:
|
||||||
- ./config:/app/config
|
- ./config:/app/config
|
||||||
- ./logs:/app/logs
|
- ./logs:/app/logs
|
||||||
networks:
|
|
||||||
- backend
|
|
||||||
depends_on:
|
|
||||||
mysql:
|
|
||||||
condition: service_healthy
|
|
||||||
redis:
|
|
||||||
condition: service_started
|
|
||||||
command: ["-env", "dev"]
|
command: ["-env", "dev"]
|
||||||
restart: always
|
restart: always
|
||||||
|
|
||||||
mysql:
|
|
||||||
image: mysql:8.0
|
|
||||||
container_name: mysql
|
|
||||||
environment:
|
|
||||||
MYSQL_ROOT_PASSWORD: texpixel#pwd123!
|
|
||||||
MYSQL_DATABASE: doc_ai
|
|
||||||
MYSQL_USER: texpixel
|
|
||||||
MYSQL_PASSWORD: texpixel#pwd123!
|
|
||||||
ports:
|
|
||||||
- "3006:3306"
|
|
||||||
volumes:
|
|
||||||
- mysql_data:/var/lib/mysql
|
|
||||||
networks:
|
|
||||||
- backend
|
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-ptexpixel#pwd123!"]
|
|
||||||
interval: 5s
|
|
||||||
timeout: 5s
|
|
||||||
retries: 10
|
|
||||||
start_period: 30s
|
|
||||||
restart: always
|
|
||||||
|
|
||||||
redis:
|
|
||||||
image: redis:latest
|
|
||||||
container_name: redis
|
|
||||||
command: redis-server --requirepass "yoge@123321!"
|
|
||||||
ports:
|
|
||||||
- "6079:6379"
|
|
||||||
networks:
|
|
||||||
- backend
|
|
||||||
restart: always
|
|
||||||
|
|
||||||
volumes:
|
|
||||||
mysql_data:
|
|
||||||
# 持久化MySQL数据卷
|
|
||||||
driver: local
|
|
||||||
|
|
||||||
networks:
|
|
||||||
backend:
|
|
||||||
driver: bridge
|
|
||||||
|
|||||||
BIN
document_ai
Executable file
BIN
document_ai
Executable file
Binary file not shown.
@@ -20,8 +20,7 @@ type PhoneLoginResponse struct {
|
|||||||
|
|
||||||
type UserInfoResponse struct {
|
type UserInfoResponse struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
Phone string `json:"phone"`
|
Email string `json:"email"`
|
||||||
Status int `json:"status"` // 0: not login, 1: login
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type EmailRegisterRequest struct {
|
type EmailRegisterRequest struct {
|
||||||
@@ -43,3 +42,31 @@ type EmailLoginResponse struct {
|
|||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
ExpiresAt int64 `json:"expires_at"`
|
ExpiresAt int64 `json:"expires_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GoogleAuthUrlRequest struct {
|
||||||
|
RedirectURI string `form:"redirect_uri" binding:"required"`
|
||||||
|
State string `form:"state" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GoogleAuthUrlResponse struct {
|
||||||
|
AuthURL string `json:"auth_url"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GoogleOAuthCallbackRequest struct {
|
||||||
|
Code string `json:"code" binding:"required"`
|
||||||
|
State string `json:"state" binding:"required"`
|
||||||
|
RedirectURI string `json:"redirect_uri" binding:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GoogleOAuthCallbackResponse struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
ExpiresAt int64 `json:"expires_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type GoogleUserInfo struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Picture string `json:"picture"`
|
||||||
|
VerifiedEmail bool `json:"verified_email"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"gitea.com/texpixel/document_ai/internal/model/task"
|
"gitea.com/texpixel/document_ai/internal/model/task"
|
||||||
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
||||||
@@ -187,7 +188,13 @@ func (svc *TaskService) ExportTask(ctx context.Context, req *task.ExportTaskRequ
|
|||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
log.Error(ctx, "func", "ExportTask", "msg", "http request failed", "status", resp.StatusCode)
|
respBody, _ := io.ReadAll(resp.Body)
|
||||||
|
log.Error(ctx, "func", "ExportTask", "msg", "export service returned non-200",
|
||||||
|
"status", resp.StatusCode,
|
||||||
|
"body", string(respBody),
|
||||||
|
"markdown_len", len(markdown),
|
||||||
|
"filename", filename,
|
||||||
|
)
|
||||||
return nil, "", fmt.Errorf("export service returned status: %d", resp.StatusCode)
|
return nil, "", fmt.Errorf("export service returned status: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,15 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"gitea.com/texpixel/document_ai/config"
|
||||||
|
model "gitea.com/texpixel/document_ai/internal/model/user"
|
||||||
"gitea.com/texpixel/document_ai/internal/storage/cache"
|
"gitea.com/texpixel/document_ai/internal/storage/cache"
|
||||||
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
||||||
"gitea.com/texpixel/document_ai/pkg/common"
|
"gitea.com/texpixel/document_ai/pkg/common"
|
||||||
@@ -159,3 +164,126 @@ func (svc *UserService) LoginByEmail(ctx context.Context, email, password string
|
|||||||
|
|
||||||
return user.ID, nil
|
return user.ID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type googleTokenResponse struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
IDToken string `json:"id_token"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (svc *UserService) googleHTTPClient() *http.Client {
|
||||||
|
if config.GlobalConfig.Google.Proxy == "" {
|
||||||
|
return &http.Client{}
|
||||||
|
}
|
||||||
|
proxyURL, err := url.Parse(config.GlobalConfig.Google.Proxy)
|
||||||
|
if err != nil {
|
||||||
|
return &http.Client{}
|
||||||
|
}
|
||||||
|
return &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (svc *UserService) ExchangeGoogleCodeAndGetUserInfo(ctx context.Context, clientID, clientSecret, code, redirectURI string) (*model.GoogleUserInfo, error) {
|
||||||
|
tokenURL := "https://oauth2.googleapis.com/token"
|
||||||
|
formData := url.Values{
|
||||||
|
"client_id": {clientID},
|
||||||
|
"client_secret": {clientSecret},
|
||||||
|
"code": {code},
|
||||||
|
"grant_type": {"authorization_code"},
|
||||||
|
"redirect_uri": {redirectURI},
|
||||||
|
}
|
||||||
|
|
||||||
|
client := svc.googleHTTPClient()
|
||||||
|
resp, err := client.PostForm(tokenURL, formData)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "ExchangeGoogleCodeAndGetUserInfo", "msg", "exchange code failed", "error", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var tokenResp googleTokenResponse
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&tokenResp); err != nil {
|
||||||
|
log.Error(ctx, "func", "ExchangeGoogleCodeAndGetUserInfo", "msg", "decode token response failed", "error", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if tokenResp.AccessToken == "" {
|
||||||
|
log.Error(ctx, "func", "ExchangeGoogleCodeAndGetUserInfo", "msg", "no access token in response")
|
||||||
|
return nil, errors.New("no access token in response")
|
||||||
|
}
|
||||||
|
|
||||||
|
userInfo, err := svc.getGoogleUserInfo(ctx, tokenResp.AccessToken)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "ExchangeGoogleCodeAndGetUserInfo", "msg", "get user info failed", "error", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &model.GoogleUserInfo{
|
||||||
|
ID: userInfo.ID,
|
||||||
|
Email: userInfo.Email,
|
||||||
|
Name: userInfo.Name,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (svc *UserService) getGoogleUserInfo(ctx context.Context, accessToken string) (*model.GoogleUserInfo, error) {
|
||||||
|
req, err := http.NewRequestWithContext(ctx, "GET", "https://www.googleapis.com/oauth2/v2/userinfo", nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+accessToken)
|
||||||
|
|
||||||
|
client := svc.googleHTTPClient()
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
var userInfo model.GoogleUserInfo
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &userInfo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (svc *UserService) FindOrCreateGoogleUser(ctx context.Context, userInfo *model.GoogleUserInfo) (uid int64, err error) {
|
||||||
|
existingUser, err := svc.userDao.GetByGoogleID(dao.DB.WithContext(ctx), userInfo.ID)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "FindOrCreateGoogleUser", "msg", "get user by google id error", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if existingUser != nil {
|
||||||
|
return existingUser.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
existingUser, err = svc.userDao.GetByEmail(dao.DB.WithContext(ctx), userInfo.Email)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "FindOrCreateGoogleUser", "msg", "get user by email error", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if existingUser != nil {
|
||||||
|
existingUser.GoogleID = userInfo.ID
|
||||||
|
err = svc.userDao.Update(dao.DB.WithContext(ctx), existingUser)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "FindOrCreateGoogleUser", "msg", "update user google id error", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return existingUser.ID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
user := &dao.User{
|
||||||
|
Email: userInfo.Email,
|
||||||
|
GoogleID: userInfo.ID,
|
||||||
|
Username: userInfo.Name,
|
||||||
|
}
|
||||||
|
err = svc.userDao.Create(dao.DB.WithContext(ctx), user)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "FindOrCreateGoogleUser", "msg", "create user error", "error", err)
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return user.ID, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ type User struct {
|
|||||||
Password string `gorm:"column:password" json:"password"`
|
Password string `gorm:"column:password" json:"password"`
|
||||||
WechatOpenID string `gorm:"column:wechat_open_id" json:"wechat_open_id"`
|
WechatOpenID string `gorm:"column:wechat_open_id" json:"wechat_open_id"`
|
||||||
WechatUnionID string `gorm:"column:wechat_union_id" json:"wechat_union_id"`
|
WechatUnionID string `gorm:"column:wechat_union_id" json:"wechat_union_id"`
|
||||||
|
GoogleID string `gorm:"column:google_id" json:"google_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *User) TableName() string {
|
func (u *User) TableName() string {
|
||||||
@@ -63,3 +64,18 @@ func (dao *UserDao) GetByEmail(tx *gorm.DB, email string) (*User, error) {
|
|||||||
}
|
}
|
||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (dao *UserDao) GetByGoogleID(tx *gorm.DB, googleID string) (*User, error) {
|
||||||
|
var user User
|
||||||
|
if err := tx.Where("google_id = ?", googleID).First(&user).Error; err != nil {
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dao *UserDao) Update(tx *gorm.DB, user *User) error {
|
||||||
|
return tx.Save(user).Error
|
||||||
|
}
|
||||||
|
|||||||
2
main.go
2
main.go
@@ -16,6 +16,7 @@ import (
|
|||||||
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
"gitea.com/texpixel/document_ai/internal/storage/dao"
|
||||||
"gitea.com/texpixel/document_ai/pkg/common"
|
"gitea.com/texpixel/document_ai/pkg/common"
|
||||||
"gitea.com/texpixel/document_ai/pkg/cors"
|
"gitea.com/texpixel/document_ai/pkg/cors"
|
||||||
|
"gitea.com/texpixel/document_ai/pkg/email"
|
||||||
"gitea.com/texpixel/document_ai/pkg/log"
|
"gitea.com/texpixel/document_ai/pkg/log"
|
||||||
"gitea.com/texpixel/document_ai/pkg/middleware"
|
"gitea.com/texpixel/document_ai/pkg/middleware"
|
||||||
"gitea.com/texpixel/document_ai/pkg/sms"
|
"gitea.com/texpixel/document_ai/pkg/sms"
|
||||||
@@ -44,6 +45,7 @@ func main() {
|
|||||||
dao.InitDB(config.GlobalConfig.Database)
|
dao.InitDB(config.GlobalConfig.Database)
|
||||||
cache.InitRedisClient(config.GlobalConfig.Redis)
|
cache.InitRedisClient(config.GlobalConfig.Redis)
|
||||||
sms.InitSmsClient()
|
sms.InitSmsClient()
|
||||||
|
email.InitEmailClient()
|
||||||
|
|
||||||
// 设置gin模式
|
// 设置gin模式
|
||||||
gin.SetMode(config.GlobalConfig.Server.Mode)
|
gin.SetMode(config.GlobalConfig.Server.Mode)
|
||||||
|
|||||||
160
pkg/email/email.go
Normal file
160
pkg/email/email.go
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
package email
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/mail"
|
||||||
|
"net/smtp"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"gitea.com/texpixel/document_ai/config"
|
||||||
|
"gitea.com/texpixel/document_ai/pkg/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
once sync.Once
|
||||||
|
client *Client
|
||||||
|
)
|
||||||
|
|
||||||
|
// chineseDomainRe matches email domains that should be routed via Aliyun SMTP.
|
||||||
|
var chineseDomainRe = regexp.MustCompile(`(?i)(\.edu\.cn|qq\.com|163\.com|126\.com|sina\.com|sohu\.com)$`)
|
||||||
|
|
||||||
|
type Client struct {
|
||||||
|
cfg config.EmailConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitEmailClient() *Client {
|
||||||
|
once.Do(func() {
|
||||||
|
client = &Client{cfg: config.GlobalConfig.Email}
|
||||||
|
})
|
||||||
|
return client
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send routes the email to the appropriate provider based on the recipient domain.
|
||||||
|
func Send(ctx context.Context, to, subject, body string) error {
|
||||||
|
if client == nil {
|
||||||
|
return fmt.Errorf("email client not initialized, call InitEmailClient first")
|
||||||
|
}
|
||||||
|
return client.Send(ctx, to, subject, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) Send(ctx context.Context, to, subject, body string) error {
|
||||||
|
if _, err := mail.ParseAddress(to); err != nil {
|
||||||
|
return fmt.Errorf("invalid email address %q: %w", to, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
domain := to[strings.LastIndex(to, "@")+1:]
|
||||||
|
if chineseDomainRe.MatchString(domain) {
|
||||||
|
return c.sendViaAliyunSMTP(ctx, to, subject, body)
|
||||||
|
}
|
||||||
|
return c.sendViaResend(ctx, to, subject, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendViaAliyunSMTP(ctx context.Context, to, subject, body string) error {
|
||||||
|
cfg := c.cfg.AliyunSMTP
|
||||||
|
addr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
|
||||||
|
|
||||||
|
tlsConfig := &tls.Config{ServerName: cfg.Host}
|
||||||
|
conn, err := tls.Dial("tcp", addr, tlsConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "tls dial failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
smtpClient, err := smtp.NewClient(conn, cfg.Host)
|
||||||
|
if err != nil {
|
||||||
|
conn.Close()
|
||||||
|
log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "smtp new client failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer smtpClient.Close()
|
||||||
|
|
||||||
|
auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
|
||||||
|
if err = smtpClient.Auth(auth); err != nil {
|
||||||
|
log.Error(ctx, "func", "sendViaAliyunSMTP", "msg", "smtp auth failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
from := c.cfg.FromAddr
|
||||||
|
if err = smtpClient.Mail(from); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = smtpClient.Rcpt(to); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
wc, err := smtpClient.Data()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer wc.Close()
|
||||||
|
|
||||||
|
if _, err = wc.Write([]byte(buildMessage(c.cfg.FromName, from, to, subject, body))); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(ctx, "func", "sendViaAliyunSMTP", "msg", "email sent via aliyun smtp", "to", to)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type resendRequest struct {
|
||||||
|
From string `json:"from"`
|
||||||
|
To []string `json:"to"`
|
||||||
|
Subject string `json:"subject"`
|
||||||
|
Html string `json:"html"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Client) sendViaResend(ctx context.Context, to, subject, body string) error {
|
||||||
|
payload := resendRequest{
|
||||||
|
From: fmt.Sprintf("%s <%s>", c.cfg.FromName, c.cfg.FromAddr),
|
||||||
|
To: []string{to},
|
||||||
|
Subject: subject,
|
||||||
|
Html: body,
|
||||||
|
}
|
||||||
|
jsonData, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.resend.com/emails", bytes.NewReader(jsonData))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.cfg.Resend.APIKey)
|
||||||
|
|
||||||
|
resp, err := (&http.Client{}).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
log.Error(ctx, "func", "sendViaResend", "msg", "http request failed", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
|
||||||
|
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
||||||
|
log.Error(ctx, "func", "sendViaResend", "msg", "resend api returned non-2xx", "status", resp.StatusCode, "to", to, "body", string(respBody))
|
||||||
|
return fmt.Errorf("resend api returned status %d: %s", resp.StatusCode, string(respBody))
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Info(ctx, "func", "sendViaResend", "msg", "email sent via resend", "to", to)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildMessage(fromName, fromAddr, to, subject, body string) string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
buf.WriteString(fmt.Sprintf("From: %s <%s>\r\n", fromName, fromAddr))
|
||||||
|
buf.WriteString(fmt.Sprintf("To: %s\r\n", to))
|
||||||
|
buf.WriteString(fmt.Sprintf("Subject: %s\r\n", subject))
|
||||||
|
buf.WriteString("MIME-Version: 1.0\r\n")
|
||||||
|
buf.WriteString("Content-Type: text/html; charset=UTF-8\r\n")
|
||||||
|
buf.WriteString("\r\n")
|
||||||
|
buf.WriteString(body)
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user