🐛 fix session bug

This commit is contained in:
landaiqing
2024-11-17 20:02:59 +08:00
parent 34c4690f80
commit 78a162a19a
72 changed files with 1304 additions and 453 deletions

View File

@@ -9,7 +9,6 @@ type Config struct {
}
Auth struct {
AccessSecret string
AccessExpire int64
}
Mysql struct {
DataSource string

View File

@@ -3,7 +3,9 @@ package captcha
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/captcha"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
)
@@ -13,7 +15,8 @@ func GenerateRotateCaptchaHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := captcha.NewGenerateRotateCaptchaLogic(r.Context(), svcCtx)
resp, err := l.GenerateRotateCaptcha()
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,7 +3,9 @@ package captcha
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/captcha"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
)
@@ -13,7 +15,8 @@ func GenerateSlideBasicCaptchaHandler(svcCtx *svc.ServiceContext) http.HandlerFu
l := captcha.NewGenerateSlideBasicCaptchaLogic(r.Context(), svcCtx)
resp, err := l.GenerateSlideBasicCaptcha()
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,6 +3,7 @@ package client
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/common/utils"
@@ -15,8 +16,9 @@ func GenerateClientIdHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
clientIP := utils.GetClientIP(r)
l := client.NewGenerateClientIdLogic(r.Context(), svcCtx)
resp, err := l.GenerateClientId(clientIP)
if err != nil || resp.Code == 500 {
httpx.ErrorCtx(r.Context(), w, err)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func DislikeCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CommentDisLikeRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewDislikeCommentLogic(r.Context(), svcCtx)
resp, err := l.DislikeComment(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func GetCommentListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CommentListRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewGetCommentListLogic(r.Context(), svcCtx)
resp, err := l.GetCommentList(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func GetReplyListHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ReplyListRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewGetReplyListLogic(r.Context(), svcCtx)
resp, err := l.GetReplyList(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func LikeCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CommentLikeRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewLikeCommentLogic(r.Context(), svcCtx)
resp, err := l.LikeComment(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func SubmitCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.CommentRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewSubmitCommentLogic(r.Context(), svcCtx)
resp, err := l.SubmitComment(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func SubmitReplyCommentHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ReplyCommentRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewSubmitReplyCommentLogic(r.Context(), svcCtx)
resp, err := l.SubmitReplyComment(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/comment"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
)
func SubmitReplyReplyHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ReplyReplyRequest
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := comment.NewSubmitReplyReplyLogic(r.Context(), svcCtx)
resp, err := l.SubmitReplyReply(&req)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}

View File

@@ -3,7 +3,9 @@ package oauth
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
)
@@ -13,7 +15,8 @@ func GetGiteeOauthUrlHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewGetGiteeOauthUrlLogic(r.Context(), svcCtx)
resp, err := l.GetGiteeOauthUrl()
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,7 +3,9 @@ package oauth
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
@@ -20,7 +22,8 @@ func GetGithubOauthUrlHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewGetGithubOauthUrlLogic(r.Context(), svcCtx)
resp, err := l.GetGithubOauthUrl(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,7 +3,9 @@ package oauth
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
@@ -20,7 +22,8 @@ func GetQqOauthUrlHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewGetQqOauthUrlLogic(r.Context(), svcCtx)
resp, err := l.GetQqOauthUrl(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,6 +3,7 @@ package oauth
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
@@ -21,7 +22,8 @@ func GetWechatQrcodeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewGetWechatQrcodeLogic(r.Context(), svcCtx)
resp, err := l.GetWechatQrcode(r, &req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -1,8 +1,10 @@
package oauth
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
@@ -21,7 +23,8 @@ func GiteeCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewGiteeCallbackLogic(r.Context(), svcCtx)
err := l.GiteeCallback(w, r, &req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.ErrorCtx(r.Context(), w, errors.New("server error"))
} else {
httpx.Ok(w)
}

View File

@@ -1,8 +1,10 @@
package oauth
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
@@ -21,7 +23,8 @@ func GithubCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewGithubCallbackLogic(r.Context(), svcCtx)
err := l.GithubCallback(w, r, &req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.ErrorCtx(r.Context(), w, errors.New("server error"))
} else {
httpx.Ok(w)
}

View File

@@ -1,8 +1,10 @@
package oauth
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
@@ -21,7 +23,8 @@ func QqCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewQqCallbackLogic(r.Context(), svcCtx)
err := l.QqCallback(w, r, &req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.ErrorCtx(r.Context(), w, errors.New("server error"))
} else {
httpx.Ok(w)
}

View File

@@ -1,8 +1,10 @@
package oauth
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/oauth"
@@ -14,7 +16,8 @@ func WechatCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := oauth.NewWechatCallbackLogic(r.Context(), svcCtx)
err := l.WechatCallback(w, r)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.ErrorCtx(r.Context(), w, errors.New("server error"))
} else {
httpx.Ok(w)
}

View File

@@ -9,6 +9,7 @@ import (
captcha "schisandra-album-cloud-microservices/app/core/api/internal/handler/captcha"
client "schisandra-album-cloud-microservices/app/core/api/internal/handler/client"
comment "schisandra-album-cloud-microservices/app/core/api/internal/handler/comment"
oauth "schisandra-album-cloud-microservices/app/core/api/internal/handler/oauth"
sms "schisandra-album-cloud-microservices/app/core/api/internal/handler/sms"
user "schisandra-album-cloud-microservices/app/core/api/internal/handler/user"
@@ -56,6 +57,54 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
rest.WithMaxBytes(1048576),
)
server.AddRoutes(
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.SecurityHeadersMiddleware, serverCtx.CasbinVerifyMiddleware},
[]rest.Route{
{
Method: http.MethodPost,
Path: "/dislike",
Handler: comment.DislikeCommentHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/like",
Handler: comment.LikeCommentHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/list",
Handler: comment.GetCommentListHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/reply/list",
Handler: comment.GetReplyListHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/reply/reply/submit",
Handler: comment.SubmitReplyReplyHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/reply/submit",
Handler: comment.SubmitReplyCommentHandler(serverCtx),
},
{
Method: http.MethodPost,
Path: "/submit",
Handler: comment.SubmitCommentHandler(serverCtx),
},
}...,
),
rest.WithJwt(serverCtx.Config.Auth.AccessSecret),
rest.WithSignature(serverCtx.Config.Signature),
rest.WithPrefix("/api/auth/comment"),
rest.WithTimeout(10000*time.Millisecond),
rest.WithMaxBytes(1048576),
)
server.AddRoutes(
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.SecurityHeadersMiddleware},
@@ -184,6 +233,5 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
},
},
rest.WithPrefix("/api/ws"),
rest.WithTimeout(10000*time.Millisecond),
)
}

View File

@@ -3,7 +3,9 @@ package sms
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/sms"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
@@ -20,7 +22,8 @@ func SendSmsByAliyunHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := sms.NewSendSmsByAliyunLogic(r.Context(), svcCtx)
resp, err := l.SendSmsByAliyun(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,7 +3,9 @@ package sms
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/sms"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
@@ -20,7 +22,8 @@ func SendSmsBySmsbaoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := sms.NewSendSmsBySmsbaoLogic(r.Context(), svcCtx)
resp, err := l.SendSmsBySmsbao(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,7 +3,9 @@ package sms
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/sms"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
@@ -20,7 +22,8 @@ func SendSmsByTestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := sms.NewSendSmsByTestLogic(r.Context(), svcCtx)
resp, err := l.SendSmsByTest(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,6 +3,7 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/user"
@@ -20,8 +21,9 @@ func AccountLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := user.NewAccountLoginLogic(r.Context(), svcCtx)
resp, err := l.AccountLogin(w, r, &req)
if err != nil || resp.Code == 500 {
httpx.ErrorCtx(r.Context(), w, err)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -1,8 +1,10 @@
package user
import (
"errors"
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/user"
@@ -14,7 +16,8 @@ func GetUserDeviceHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := user.NewGetUserDeviceLogic(r.Context(), svcCtx)
err := l.GetUserDevice(r)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.ErrorCtx(r.Context(), w, errors.New("server error"))
} else {
httpx.Ok(w)
}

View File

@@ -3,6 +3,7 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/user"
@@ -21,7 +22,8 @@ func PhoneLoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := user.NewPhoneLoginLogic(r.Context(), svcCtx)
resp, err := l.PhoneLogin(r, w, &req)
if err != nil || resp.Code == 500 {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,6 +3,7 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/user"
@@ -14,7 +15,8 @@ func RefreshTokenHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := user.NewRefreshTokenLogic(r.Context(), svcCtx)
resp, err := l.RefreshToken(r)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,6 +3,7 @@ package user
import (
"net/http"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/user"
@@ -20,8 +21,9 @@ func ResetPasswordHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
l := user.NewResetPasswordLogic(r.Context(), svcCtx)
resp, err := l.ResetPassword(&req)
if err != nil || resp.Code == 500 {
httpx.ErrorCtx(r.Context(), w, err)
if err != nil {
logx.Error(err)
httpx.WriteJsonCtx(r.Context(), w, http.StatusInternalServerError, resp)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}

View File

@@ -3,8 +3,6 @@ package websocket
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/websocket"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
)
@@ -12,11 +10,6 @@ import (
func MessageWebsocketHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := websocket.NewMessageWebsocketLogic(r.Context(), svcCtx)
err := l.MessageWebsocket(w, r)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.Ok(w)
}
l.MessageWebsocket(w, r)
}
}

View File

@@ -3,8 +3,6 @@ package websocket
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"schisandra-album-cloud-microservices/app/core/api/internal/logic/websocket"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
)
@@ -12,11 +10,6 @@ import (
func QrcodeWebsocketHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := websocket.NewQrcodeWebsocketLogic(r.Context(), svcCtx)
err := l.QrcodeWebsocket(w, r)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.Ok(w)
}
l.QrcodeWebsocket(w, r)
}
}

View File

@@ -36,7 +36,6 @@ func (l *GenerateClientIdLogic) GenerateClientId(clientIP string) (resp *types.R
}
simpleUuid := kgo.SimpleUuid()
if err = l.svcCtx.RedisClient.SetEx(l.ctx, constant.UserClientPrefix+clientIP, simpleUuid, time.Hour*24*7).Err(); err != nil {
l.Error(err)
return response.Error(), err
}
return response.SuccessWithData(simpleUuid), nil

View File

@@ -0,0 +1,30 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type DislikeCommentLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewDislikeCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DislikeCommentLogic {
return &DislikeCommentLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *DislikeCommentLogic) DislikeComment(req *types.CommentDisLikeRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,31 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/common/response"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetCommentListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetCommentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCommentListLogic {
return &GetCommentListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetCommentListLogic) GetCommentList(req *types.CommentListRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return response.Success(), nil
}

View File

@@ -0,0 +1,30 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetReplyListLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewGetReplyListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetReplyListLogic {
return &GetReplyListLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetReplyListLogic) GetReplyList(req *types.ReplyListRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,30 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type LikeCommentLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewLikeCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LikeCommentLogic {
return &LikeCommentLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *LikeCommentLogic) LikeComment(req *types.CommentLikeRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,30 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SubmitCommentLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSubmitCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubmitCommentLogic {
return &SubmitCommentLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SubmitCommentLogic) SubmitComment(req *types.CommentRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,30 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SubmitReplyCommentLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSubmitReplyCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubmitReplyCommentLogic {
return &SubmitReplyCommentLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SubmitReplyCommentLogic) SubmitReplyComment(req *types.ReplyCommentRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -0,0 +1,30 @@
package comment
import (
"context"
"schisandra-album-cloud-microservices/app/core/api/internal/svc"
"schisandra-album-cloud-microservices/app/core/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SubmitReplyReplyLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSubmitReplyReplyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubmitReplyReplyLogic {
return &SubmitReplyReplyLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SubmitReplyReplyLogic) SubmitReplyReply(req *types.ReplyReplyRequest) (resp *types.Response, err error) {
// todo: add your logic here and delete this line
return
}

View File

@@ -3,7 +3,6 @@ package oauth
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
@@ -79,7 +78,7 @@ func (l *GithubCallbackLogic) GithubCallback(w http.ResponseWriter, r *http.Requ
}
if token == nil {
return errors.New("failed to get token")
return nil
}
// 获取用户信息
@@ -90,7 +89,7 @@ func (l *GithubCallbackLogic) GithubCallback(w http.ResponseWriter, r *http.Requ
}
if userInfo == nil {
return errors.New("failed to get user info")
return nil
}
// 处理用户信息

View File

@@ -3,7 +3,6 @@ package oauth
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
@@ -75,7 +74,7 @@ func (l *QqCallbackLogic) QqCallback(w http.ResponseWriter, r *http.Request, req
return err
}
if token == nil {
return errors.New("get qq token failed")
return nil
}
// 通过 token 获取 openid

View File

@@ -61,9 +61,9 @@ func (l *WechatCallbackLogic) WechatCallback(w http.ResponseWriter, r *http.Requ
key := strings.TrimPrefix(msg.EventKey, "qrscene_")
err = l.HandlerWechatLogin(msg.FromUserName, key, w, r)
if err != nil {
return messages.NewText(i18n.FormatText(l.ctx, "login.loginFailed", "登录失败"))
return messages.NewText(i18n.FormatText(l.ctx, "login.loginFailed"))
}
return messages.NewText(i18n.FormatText(l.ctx, "login.loginSuccess", "登录成功"))
return messages.NewText(i18n.FormatText(l.ctx, "login.loginSuccess"))
case models.CALLBACK_EVENT_UNSUBSCRIBE:
msg := models.EventUnSubscribe{}
@@ -83,9 +83,9 @@ func (l *WechatCallbackLogic) WechatCallback(w http.ResponseWriter, r *http.Requ
}
err = l.HandlerWechatLogin(msg.FromUserName, msg.EventKey, w, r)
if err != nil {
return messages.NewText(i18n.FormatText(l.ctx, "login.loginFailed", "登录失败"))
return messages.NewText(i18n.FormatText(l.ctx, "login.loginFailed"))
}
return messages.NewText(i18n.FormatText(l.ctx, "login.loginSuccess", "登录成功"))
return messages.NewText(i18n.FormatText(l.ctx, "login.loginSuccess"))
}
@@ -101,11 +101,11 @@ func (l *WechatCallbackLogic) WechatCallback(w http.ResponseWriter, r *http.Requ
})
if err != nil {
panic(err)
return err
}
err = helper.HttpResponseSend(rs, w)
if err != nil {
panic(err)
return err
}
return nil
}

View File

@@ -36,15 +36,15 @@ func (l *SendSmsByAliyunLogic) SendSmsByAliyun(req *types.SmsSendRequest) (resp
checkRotateData := verify.VerifyRotateCaptcha(l.ctx, l.svcCtx.RedisClient, req.Angle, req.Key)
if !checkRotateData {
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure", "验证码错误"), nil
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure"), nil
}
isPhone := utils.IsPhone(req.Phone)
if !isPhone {
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError", "手机号格式错误"), nil
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError"), nil
}
val := l.svcCtx.RedisClient.Get(l.ctx, constant.UserSmsRedisPrefix+req.Phone).Val()
if val != "" {
return response.ErrorWithI18n(l.ctx, "sms.smsSendTooFrequently", "验证码发送过于频繁,请稍后再试"), nil
return response.ErrorWithI18n(l.ctx, "sms.smsSendTooFrequently"), nil
}
sms := gosms.NewParser(gateways.Gateways{
ALiYun: aliyun.ALiYun{
@@ -56,7 +56,7 @@ func (l *SendSmsByAliyunLogic) SendSmsByAliyun(req *types.SmsSendRequest) (resp
code := utils.GenValidateCode(6)
wrong := l.svcCtx.RedisClient.Set(l.ctx, constant.UserSmsRedisPrefix+req.Phone, code, time.Minute).Err()
if wrong != nil {
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed", "验证码发送失败"), wrong
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed"), wrong
}
_, err = sms.Send(req.Phone, gosms.MapStringAny{
"content": "您的验证码是:****。请不要把验证码泄露给其他人。",
@@ -67,7 +67,7 @@ func (l *SendSmsByAliyunLogic) SendSmsByAliyun(req *types.SmsSendRequest) (resp
},
}, nil)
if err != nil {
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed", "验证码发送失败"), err
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed"), err
}
return response.Success(), nil
}

View File

@@ -35,15 +35,15 @@ func NewSendSmsBySmsbaoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *S
func (l *SendSmsBySmsbaoLogic) SendSmsBySmsbao(req *types.SmsSendRequest) (resp *types.Response, err error) {
checkRotateData := verify.VerifyRotateCaptcha(l.ctx, l.svcCtx.RedisClient, req.Angle, req.Key)
if !checkRotateData {
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure", "验证码错误"), nil
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure"), nil
}
isPhone := utils.IsPhone(req.Phone)
if !isPhone {
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError", "手机号格式错误"), nil
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError"), nil
}
val := l.svcCtx.RedisClient.Get(l.ctx, constant.UserSmsRedisPrefix+req.Phone).Val()
if val != "" {
return response.ErrorWithI18n(l.ctx, "sms.smsSendTooFrequently", "验证码发送过于频繁,请稍后再试"), nil
return response.ErrorWithI18n(l.ctx, "sms.smsSendTooFrequently"), nil
}
sms := gosms.NewParser(gateways.Gateways{
SmsBao: smsbao.SmsBao{
@@ -54,13 +54,13 @@ func (l *SendSmsBySmsbaoLogic) SendSmsBySmsbao(req *types.SmsSendRequest) (resp
code := utils.GenValidateCode(6)
wrong := l.svcCtx.RedisClient.Set(l.ctx, constant.UserSmsRedisPrefix+req.Phone, code, time.Minute).Err()
if wrong != nil {
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed", "验证码发送失败"), wrong
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed"), wrong
}
_, err = sms.Send(req.Phone, gosms.MapStringAny{
"content": "您的验证码是:" + code + "。请不要把验证码泄露给其他人。",
}, nil)
if err != nil {
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed", "验证码发送失败"), err
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed"), err
}
return response.Success(), nil
}

View File

@@ -31,20 +31,20 @@ func NewSendSmsByTestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Sen
func (l *SendSmsByTestLogic) SendSmsByTest(req *types.SmsSendRequest) (resp *types.Response, err error) {
checkRotateData := verify.VerifyRotateCaptcha(l.ctx, l.svcCtx.RedisClient, req.Angle, req.Key)
if !checkRotateData {
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure", "验证码错误"), nil
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure"), nil
}
isPhone := utils.IsPhone(req.Phone)
if !isPhone {
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError", "手机号格式错误"), nil
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError"), nil
}
val := l.svcCtx.RedisClient.Get(l.ctx, constant.UserSmsRedisPrefix+req.Phone).Val()
if val != "" {
return response.ErrorWithI18n(l.ctx, "sms.smsSendTooFrequently", "验证码发送过于频繁,请稍后再试"), nil
return response.ErrorWithI18n(l.ctx, "sms.smsSendTooFrequently"), nil
}
code := utils.GenValidateCode(6)
wrong := l.svcCtx.RedisClient.Set(l.ctx, constant.UserSmsRedisPrefix+req.Phone, code, time.Minute).Err()
if wrong != nil {
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed", "验证码发送失败"), wrong
return response.ErrorWithI18n(l.ctx, "sms.smsSendFailed"), wrong
}
return response.Success(), nil
}

View File

@@ -36,7 +36,7 @@ func NewAccountLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Acco
func (l *AccountLoginLogic) AccountLogin(w http.ResponseWriter, r *http.Request, req *types.AccountLoginRequest) (resp *types.Response, err error) {
verifyResult := verify.VerifyRotateCaptcha(l.ctx, l.svcCtx.RedisClient, req.Angle, req.Key)
if !verifyResult {
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure", "验证失败!"), nil
return response.ErrorWithI18n(l.ctx, "captcha.verificationFailure"), nil
}
var user *ent.ScaAuthUser
var query *ent.ScaAuthUserQuery
@@ -49,23 +49,27 @@ func (l *AccountLoginLogic) AccountLogin(w http.ResponseWriter, r *http.Request,
case utils.IsUsername(req.Account):
query = l.svcCtx.MySQLClient.ScaAuthUser.Query().Where(scaauthuser.UsernameEQ(req.Account), scaauthuser.DeletedEQ(0))
default:
return response.ErrorWithI18n(l.ctx, "login.invalidAccount", "无效账号!"), nil
return response.ErrorWithI18n(l.ctx, "login.invalidAccount"), nil
}
user, err = query.First(l.ctx)
if err != nil {
if ent.IsNotFound(err) {
return response.ErrorWithI18n(l.ctx, "login.userNotRegistered", "用户未注册!"), nil
return response.ErrorWithI18n(l.ctx, "login.userNotRegistered"), nil
}
return nil, err
}
if !utils.Verify(user.Password, req.Password) {
return response.ErrorWithI18n(l.ctx, "login.invalidPassword", "密码错误!"), nil
return response.ErrorWithI18n(l.ctx, "login.invalidPassword"), nil
}
data, result := HandleUserLogin(user, l.svcCtx, req.AutoLogin, r, w, l.ctx)
if !result {
return response.ErrorWithI18n(l.ctx, "login.loginFailed", "登录失败!"), nil
return response.ErrorWithI18n(l.ctx, "login.loginFailed"), nil
}
// 记录用户登录设备
if !GetUserLoginDevice(user.UID, r, l.svcCtx.Ip2Region, l.svcCtx.MySQLClient, l.ctx) {
return response.ErrorWithI18n(l.ctx, "login.loginFailed"), nil
}
return response.SuccessWithData(data), nil
}
@@ -95,32 +99,26 @@ func HandleUserLogin(user *ent.ScaAuthUser, svcCtx *svc.ServiceContext, autoLogi
}
redisToken := types.RedisToken{
AccessToken: accessToken,
UID: user.UID,
AccessToken: accessToken,
RefreshToken: refreshToken,
UID: user.UID,
}
err := svcCtx.RedisClient.Set(ctx, constant.UserTokenPrefix+user.UID, redisToken, days).Err()
if err != nil {
logc.Error(ctx, err)
return nil, false
}
sessionData := types.SessionData{
RefreshToken: refreshToken,
UID: user.UID,
}
session, err := svcCtx.Session.Get(r, constant.SESSION_KEY)
if err != nil {
logc.Error(ctx, err)
return nil, false
}
session.Values[constant.SESSION_KEY] = sessionData
session.Values["refresh_token"] = refreshToken
session.Values["uid"] = user.UID
err = session.Save(r, w)
if err != nil {
return nil, false
}
// 记录用户登录设备
if !GetUserLoginDevice(user.UID, r, svcCtx.Ip2Region, svcCtx.MySQLClient, ctx) {
return nil, false
}
return &data, true
}

View File

@@ -39,7 +39,7 @@ func (l *GetUserDeviceLogic) GetUserDevice(r *http.Request) error {
}
sessionData, ok := session.Values[constant.SESSION_KEY]
if !ok {
return errors.New("User not found or device not found")
return errors.New("user session not found")
}
var data types.SessionData
err = json.Unmarshal(sessionData.([]byte), &data)
@@ -49,7 +49,7 @@ func (l *GetUserDeviceLogic) GetUserDevice(r *http.Request) error {
res := GetUserLoginDevice(data.UID, r, l.svcCtx.Ip2Region, l.svcCtx.MySQLClient, l.ctx)
if !res {
return errors.New("User not found or device not found")
return errors.New("user device not found")
}
return nil
}

View File

@@ -34,19 +34,19 @@ func NewPhoneLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PhoneL
func (l *PhoneLoginLogic) PhoneLogin(r *http.Request, w http.ResponseWriter, req *types.PhoneLoginRequest) (resp *types.Response, err error) {
if !utils.IsPhone(req.Phone) {
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError", "手机号格式错误"), nil
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError"), nil
}
code := l.svcCtx.RedisClient.Get(l.ctx, constant.UserSmsRedisPrefix+req.Phone).Val()
if code == "" {
return response.ErrorWithI18n(l.ctx, "login.captchaExpired", "验证码已过期"), nil
return response.ErrorWithI18n(l.ctx, "login.captchaExpired"), nil
}
if req.Captcha != code {
return response.ErrorWithI18n(l.ctx, "login.captchaError", "验证码错误"), nil
return response.ErrorWithI18n(l.ctx, "login.captchaError"), nil
}
user, err := l.svcCtx.MySQLClient.ScaAuthUser.Query().Where(scaauthuser.Phone(req.Phone), scaauthuser.Deleted(0)).First(l.ctx)
tx, wrong := l.svcCtx.MySQLClient.Tx(l.ctx)
if wrong != nil {
return response.ErrorWithI18n(l.ctx, "login.loginFailed", "登录失败"), err
return response.ErrorWithI18n(l.ctx, "login.loginFailed"), err
}
if ent.IsNotFound(err) {
uid := idgen.NextId()
@@ -64,17 +64,21 @@ func (l *PhoneLoginLogic) PhoneLogin(r *http.Request, w http.ResponseWriter, req
Save(l.ctx)
if fault != nil {
err = tx.Rollback()
return response.ErrorWithI18n(l.ctx, "login.registerError", "注册失败"), err
return response.ErrorWithI18n(l.ctx, "login.registerError"), err
}
_, err = l.svcCtx.CasbinEnforcer.AddRoleForUser(uidStr, constant.User)
if err != nil {
err = tx.Rollback()
return response.ErrorWithI18n(l.ctx, "login.registerError", "注册失败"), err
return response.ErrorWithI18n(l.ctx, "login.registerError"), err
}
data, result := HandleUserLogin(addUser, l.svcCtx, req.AutoLogin, r, w, l.ctx)
if !result {
err = tx.Rollback()
return response.ErrorWithI18n(l.ctx, "login.registerError", "注册失败"), err
return response.ErrorWithI18n(l.ctx, "login.registerError"), err
}
// 记录用户登录设备
if !GetUserLoginDevice(addUser.UID, r, l.svcCtx.Ip2Region, l.svcCtx.MySQLClient, l.ctx) {
return response.ErrorWithI18n(l.ctx, "login.registerError"), nil
}
err = tx.Commit()
if err != nil {
@@ -85,7 +89,11 @@ func (l *PhoneLoginLogic) PhoneLogin(r *http.Request, w http.ResponseWriter, req
data, result := HandleUserLogin(user, l.svcCtx, req.AutoLogin, r, w, l.ctx)
if !result {
err = tx.Rollback()
return response.ErrorWithI18n(l.ctx, "login.loginFailed", "登录失败"), err
return response.ErrorWithI18n(l.ctx, "login.loginFailed"), err
}
// 记录用户登录设备
if !GetUserLoginDevice(user.UID, r, l.svcCtx.Ip2Region, l.svcCtx.MySQLClient, l.ctx) {
return response.ErrorWithI18n(l.ctx, "login.loginFailed"), nil
}
err = tx.Commit()
if err != nil {
@@ -93,6 +101,6 @@ func (l *PhoneLoginLogic) PhoneLogin(r *http.Request, w http.ResponseWriter, req
}
return response.SuccessWithData(data), nil
} else {
return response.ErrorWithI18n(l.ctx, "login.loginFailed", "登录失败"), nil
return response.ErrorWithI18n(l.ctx, "login.loginFailed"), nil
}
}

View File

@@ -34,28 +34,41 @@ func (l *RefreshTokenLogic) RefreshToken(r *http.Request) (resp *types.Response,
if err != nil {
return response.ErrorWithCode(403), err
}
sessionData, ok := session.Values[constant.SESSION_KEY]
refreshSessionToken, ok := session.Values["refresh_token"].(string)
if !ok {
return response.ErrorWithCode(403), err
return response.ErrorWithCode(403), nil
}
data := types.SessionData{}
err = json.Unmarshal(sessionData.([]byte), &data)
userId, ok := session.Values["uid"].(string)
if !ok {
return response.ErrorWithCode(403), nil
}
tokenData := l.svcCtx.RedisClient.Get(l.ctx, constant.UserTokenPrefix+userId).Val()
if tokenData == "" {
return response.ErrorWithCode(403), nil
}
redisTokenData := types.RedisToken{}
err = json.Unmarshal([]byte(tokenData), &redisTokenData)
if err != nil {
return response.ErrorWithCode(403), err
}
refreshToken, result := jwt.ParseRefreshToken(l.svcCtx.Config.Auth.AccessSecret, data.RefreshToken)
if redisTokenData.RefreshToken != refreshSessionToken {
return response.ErrorWithCode(403), nil
}
refreshToken, result := jwt.ParseRefreshToken(l.svcCtx.Config.Auth.AccessSecret, refreshSessionToken)
if !result {
return response.ErrorWithCode(403), err
return response.ErrorWithCode(403), nil
}
accessToken := jwt.GenerateAccessToken(l.svcCtx.Config.Auth.AccessSecret, jwt.AccessJWTPayload{
UserID: refreshToken.UserID,
})
if accessToken == "" {
return response.ErrorWithCode(403), err
return response.ErrorWithCode(403), nil
}
redisToken := types.RedisToken{
AccessToken: accessToken,
UID: refreshToken.UserID,
AccessToken: accessToken,
RefreshToken: refreshSessionToken,
UID: refreshToken.UserID,
}
err = l.svcCtx.RedisClient.Set(l.ctx, constant.UserTokenPrefix+refreshToken.UserID, redisToken, time.Hour*24*7).Err()
if err != nil {

View File

@@ -30,36 +30,36 @@ func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Res
func (l *ResetPasswordLogic) ResetPassword(req *types.ResetPasswordRequest) (resp *types.Response, err error) {
if !utils.IsPhone(req.Phone) {
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError", "手机号格式错误"), nil
return response.ErrorWithI18n(l.ctx, "login.phoneFormatError"), nil
}
if req.Password != req.Repassword {
return response.ErrorWithI18n(l.ctx, "login.passwordNotMatch", "两次密码输入不一致"), nil
return response.ErrorWithI18n(l.ctx, "login.passwordNotMatch"), nil
}
if !utils.IsPassword(req.Password) {
return response.ErrorWithI18n(l.ctx, "login.passwordFormatError", "密码格式错误"), nil
return response.ErrorWithI18n(l.ctx, "login.passwordFormatError"), nil
}
code := l.svcCtx.RedisClient.Get(l.ctx, constant.UserSmsRedisPrefix+req.Phone).Val()
if code == "" {
return response.ErrorWithI18n(l.ctx, "login.captchaExpired", "验证码已过期"), nil
return response.ErrorWithI18n(l.ctx, "login.captchaExpired"), nil
}
if req.Captcha != code {
return response.ErrorWithI18n(l.ctx, "login.captchaError", "验证码错误"), nil
return response.ErrorWithI18n(l.ctx, "login.captchaError"), nil
}
// 验证码检查通过后立即删除或标记为已使用
if err = l.svcCtx.RedisClient.Del(l.ctx, constant.UserSmsRedisPrefix+req.Phone).Err(); err != nil {
return response.ErrorWithI18n(l.ctx, "login.captchaError", "验证码错误"), nil
return response.ErrorWithI18n(l.ctx, "login.captchaError"), err
}
user, err := l.svcCtx.MySQLClient.ScaAuthUser.Query().Where(scaauthuser.Phone(req.Phone), scaauthuser.Deleted(constant.NotDeleted)).First(l.ctx)
if err != nil && ent.IsNotFound(err) {
return response.ErrorWithI18n(l.ctx, "login.userNotRegistered", "用户未注册"), nil
return response.ErrorWithI18n(l.ctx, "login.userNotRegistered"), err
}
encrypt, err := utils.Encrypt(req.Password)
if err != nil {
return response.ErrorWithI18n(l.ctx, "login.resetPasswordError", "重置密码失败"), nil
return response.ErrorWithI18n(l.ctx, "login.resetPasswordError"), err
}
err = user.Update().SetPassword(encrypt).Exec(l.ctx)
if err != nil {
return response.ErrorWithI18n(l.ctx, "login.resetPasswordError", "重置密码失败"), err
return response.ErrorWithI18n(l.ctx, "login.resetPasswordError"), err
}
return response.Success(), nil
}

View File

@@ -42,7 +42,7 @@ var MessageWebSocketHandler *MessageWebSocket
func InitializeWebSocketHandler(svcCtx *svc.ServiceContext) {
MessageWebSocketHandler = NewMessageWebSocket(svcCtx)
}
func (l *MessageWebsocketLogic) MessageWebsocket(w http.ResponseWriter, r *http.Request) error {
func (l *MessageWebsocketLogic) MessageWebsocket(w http.ResponseWriter, r *http.Request) {
upgrader := gws.NewUpgrader(MessageWebSocketHandler, &gws.ServerOption{
HandshakeTimeout: 5 * time.Second, // 握手超时时间
ReadBufferSize: 1024, // 读缓冲区大小
@@ -71,12 +71,11 @@ func (l *MessageWebsocketLogic) MessageWebsocket(w http.ResponseWriter, r *http.
})
socket, err := upgrader.Upgrade(w, r)
if err != nil {
return err
panic(err)
}
go func() {
socket.ReadLoop() // 此处阻塞会使请求上下文不能顺利被GC
}()
return nil
}
// NewMessageWebSocket 创建WebSocket实例

View File

@@ -40,7 +40,7 @@ type QrcodeWebSocket struct {
var QrcodeWebSocketHandler = NewWebSocket()
func (l *QrcodeWebsocketLogic) QrcodeWebsocket(w http.ResponseWriter, r *http.Request) error {
func (l *QrcodeWebsocketLogic) QrcodeWebsocket(w http.ResponseWriter, r *http.Request) {
upgrader := gws.NewUpgrader(QrcodeWebSocketHandler, &gws.ServerOption{
HandshakeTimeout: 5 * time.Second, // 握手超时时间
ReadBufferSize: 1024, // 读缓冲区大小
@@ -66,12 +66,11 @@ func (l *QrcodeWebsocketLogic) QrcodeWebsocket(w http.ResponseWriter, r *http.Re
})
socket, err := upgrader.Upgrade(w, r)
if err != nil {
return err
panic(err)
}
go func() {
socket.ReadLoop() // 此处阻塞会使请求上下文不能顺利被GC
}()
return nil
}
// MustLoad 从session中加载数据

View File

@@ -0,0 +1,29 @@
package middleware
import (
"net/http"
"github.com/casbin/casbin/v2"
)
type CasbinVerifyMiddleware struct {
casbin *casbin.CachedEnforcer
}
func NewCasbinVerifyMiddleware(casbin *casbin.CachedEnforcer) *CasbinVerifyMiddleware {
return &CasbinVerifyMiddleware{
casbin: casbin,
}
}
func (m *CasbinVerifyMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
userId := r.Context().Value("user_id")
correct, err := m.casbin.Enforce(userId, r.URL.Path, r.Method)
if err != nil || !correct {
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
next(w, r)
}
}

View File

@@ -15,7 +15,7 @@ func NewSecurityHeadersMiddleware() *SecurityHeadersMiddleware {
func (m *SecurityHeadersMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
middleware.SecurityHeadersMiddleware(w, r)
middleware.SecurityHeadersMiddleware(r)
next(w, r)
}
}

View File

@@ -30,6 +30,7 @@ import (
type ServiceContext struct {
Config config.Config
SecurityHeadersMiddleware rest.Middleware
CasbinVerifyMiddleware rest.Middleware
MySQLClient *ent.Client
RedisClient *redis.Client
MongoClient *mongo.Database
@@ -43,15 +44,17 @@ type ServiceContext struct {
}
func NewServiceContext(c config.Config) *ServiceContext {
casbinEnforcer := casbinx.NewCasbin(c.Mysql.DataSource)
return &ServiceContext{
Config: c,
SecurityHeadersMiddleware: middleware.NewSecurityHeadersMiddleware().Handle,
CasbinVerifyMiddleware: middleware.NewCasbinVerifyMiddleware(casbinEnforcer).Handle,
MySQLClient: mysql.NewMySQL(c.Mysql.DataSource),
RedisClient: redisx.NewRedis(c.Redis.Host, c.Redis.Pass, c.Redis.DB),
MongoClient: mongodb.NewMongoDB(c.Mongo.Uri, c.Mongo.Username, c.Mongo.Password, c.Mongo.AuthSource, c.Mongo.Database),
Session: redis_session.NewRedisSession(c.Redis.Host, c.Redis.Pass),
Ip2Region: ip2region.NewIP2Region(),
CasbinEnforcer: casbinx.NewCasbin(c.Mysql.DataSource),
CasbinEnforcer: casbinEnforcer,
WechatPublic: wechat_public.NewWechatPublic(c.Wechat.AppID, c.Wechat.AppSecret, c.Wechat.Token, c.Wechat.AESKey, c.Redis.Host, c.Redis.Pass, c.Redis.DB),
Sensitive: sensitivex.NewSensitive(),
RotateCaptcha: captcha.NewRotateCaptcha(),

View File

@@ -3,8 +3,9 @@ package types
import "encoding/json"
type RedisToken struct {
AccessToken string `json:"access_token"`
UID string `json:"uid"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
UID string `json:"uid"`
}
func (res RedisToken) MarshalBinary() ([]byte, error) {

View File

@@ -11,6 +11,32 @@ type AccountLoginRequest struct {
Key string `json:"key"`
}
type CommentDisLikeRequest struct {
TopicId string `json:"topic_id"`
CommentId int64 `json:"comment_id"`
}
type CommentLikeRequest struct {
TopicId string `json:"topic_id"`
CommentId int64 `json:"comment_id"`
}
type CommentListRequest struct {
TopicId string `json:"topic_id"`
Page int `json:"page,default=1,optional"`
Size int `json:"size,default=5,optional"`
IsHot bool `json:"is_hot,default=true,optional"`
}
type CommentRequest struct {
Content string `json:"content"`
Images []string `json:"images,optional"`
TopicId string `json:"topic_id"`
Author string `json:"author"`
Key string `json:"key"`
Point []int64 `json:"point"`
}
type LoginResponse struct {
AccessToken string `json:"access_token"`
UID string `json:"uid"`
@@ -38,6 +64,36 @@ type PhoneLoginRequest struct {
AutoLogin bool `json:"auto_login"`
}
type ReplyCommentRequest struct {
Content string `json:"content"`
Images []string `json:"images,optional"`
TopicId string `json:"topic_id" `
ReplyId int64 `json:"reply_id" `
ReplyUser string `json:"reply_user" `
Author string `json:"author"`
Key string `json:"key"`
Point []int64 `json:"point"`
}
type ReplyListRequest struct {
TopicId string `json:"topic_id"`
CommentId int64 `json:"comment_id"`
Page int `json:"page,default=1,optional"`
Size int `json:"size,default=5,optional"`
}
type ReplyReplyRequest struct {
Content string `json:"content"`
Images []string `json:"images,optional"`
TopicId string `json:"topic_id"`
ReplyTo int64 `json:"reply_to"`
ReplyId int64 `json:"reply_id"`
ReplyUser string `json:"reply_user" `
Author string `json:"author"`
Key string `json:"key"`
Point []int64 `json:"point"`
}
type ResetPasswordRequest struct {
Phone string `json:"phone"`
Captcha string `json:"captcha"`