Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

合并idl文件 #13

Merged
merged 10 commits into from
Jul 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/go-services/auth/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ func main() {

// 启动 HTTP 服务器以提供 Prometheus 指标
httpSrv := &http.Server{
Addr: config.Conf.Pod.PodIp + config.Metrics,
Addr: config.Conf.Pod.PodIp + config.AuthMetrics,
}
g.Add(func() error {
// 设置 HTTP 处理函数
Expand Down
56 changes: 28 additions & 28 deletions backend/go-services/auth/services/auth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,43 +19,43 @@ import (
var log = logging.LogService(config.AuthRpcServerName) // 使用logging库,添加日志字段为微服务的名字

// 注册
func RegisterUser(newuser models.User) error {
log.Infof("Attempting to register user: %s", newuser.Username)
func RegisterUser(newUser models.User) error {
log.Infof("Attempting to register user: %s", newUser.Username)

// 注册用户的逻辑
isExistUser, err := getUserByUsername(newuser.Username)
isExistUser, err := getUserByUsername(newUser.Username)
if err != nil {
log.Errorf("while checking existing user: %v", err)
return fmt.Errorf("while checking existing user: %w", err)
}
if isExistUser {
log.Warnf("User already exists: %s", newuser.Username)
log.Warnf("User already exists: %s", newUser.Username)
return errors.New("用户名已存在")
}

// 生成新的ObjectID
newuser.ID = primitive.NewObjectID().Hex()
newUser.ID = primitive.NewObjectID().Hex()

// 初始化其他字段
newuser.Coins = 0
newuser.Blacklist = []string{}
newuser.CoinsRecord = []models.CoinRecord{}
newuser.Followed = []string{}
newuser.Follower = []string{}
newuser.QuestionsAsk = []string{}
newuser.QuestionsAsw = []string{}
newuser.QuestionsCollect = []string{}
newuser.CreateAt = time.Now()
newuser.UpdateAt = time.Now()
newuser.DeleteAt = time.Time{}
newUser.Coins = 0
newUser.Blacklist = []string{}
newUser.CoinsRecord = []models.CoinRecord{}
newUser.Followed = []string{}
newUser.Follower = []string{}
newUser.QuestionsAsk = []string{}
newUser.QuestionsAsw = []string{}
newUser.QuestionsCollect = []string{}
newUser.CreateAt = time.Now()
newUser.UpdateAt = time.Now()
newUser.DeleteAt = time.Time{}

// 保存用户到数据库
if err := storeUser(newuser); err != nil {
if err := storeUser(newUser); err != nil {
log.Errorf("Failed to store user: %v", err)
return errors.New("注册失败")
}

log.Infof("User registered successfully: %s", newuser.Username)
log.Infof("User registered successfully: %s", newUser.Username)

return nil
}
Expand All @@ -77,7 +77,7 @@ func storeUser(user models.User) error {
// 验证用户密码是否正确,返回 JWT令牌,过期时间,刷新令牌,用户基本信息,错误信息
func AuthenticateUser(user models.LoginRequest) (string, int64, string, models.SimpleUser, error) {
// 检查用户是否存在
storedUser, err := getUserbyID(user.Username)
storedUser, err := getUserByID(user.Username)
if err != nil {
log.Error("Failed to get user from database: ", err)
return "", 0, "", models.SimpleUser{}, errors.New("failed to get user from database")
Expand Down Expand Up @@ -115,24 +115,24 @@ func AuthenticateUser(user models.LoginRequest) (string, int64, string, models.S
}

// 从数据库获取用户
func getUserbyID(id string) (models.User, error) {
func getUserByID(userName string) (models.User, error) {
user := models.User{}

// 将字符串转换为 ObjectID
objectID, err := primitive.ObjectIDFromHex(id)
if err != nil {
log.Println("Failed to convert string to ObjectID: ", err)
return models.User{}, err
}
//objectID, err := primitive.ObjectIDFromHex(id)
//if err != nil {
// log.Println("Failed to convert string to ObjectID: ", err)
// return models.User{}, err
//}

// 使用 ObjectID 进行查询
result := database.MongoDbClient.Database("aorb").Collection("users").FindOne(context.TODO(), bson.M{"_id": objectID})
result := database.MongoDbClient.Database("aorb").Collection("users").FindOne(context.TODO(), bson.M{"userName": userName})

// 解码结果到 user 结构体
err = result.Decode(&user)
err := result.Decode(&user)
if err != nil {
if err == mongo.ErrNoDocuments {
log.Println("No user found with ID: ", id)
log.Println("No user found with ID: ", userName)
} else {
log.Println("Failed to decode result: ", err)
}
Expand Down
98 changes: 98 additions & 0 deletions backend/go-services/auth/web/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package web

import (
"github.com/BigNoseCattyHome/aorb/backend/go-services/auth/models"
"github.com/BigNoseCattyHome/aorb/backend/rpc/auth"
"github.com/BigNoseCattyHome/aorb/backend/utils/constants/config"
"github.com/BigNoseCattyHome/aorb/backend/utils/constants/strings"
"github.com/BigNoseCattyHome/aorb/backend/utils/extra/tracing"
grpc2 "github.com/BigNoseCattyHome/aorb/backend/utils/grpc"
"github.com/BigNoseCattyHome/aorb/backend/utils/json"
"github.com/BigNoseCattyHome/aorb/backend/utils/logging"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"net/http"
)

var Client auth.AuthServiceClient

func LoginHandler(c *gin.Context) {
var req models.LoginRequest
_, span := tracing.Tracer.Start(c.Request.Context(), "LoginHandler")
defer span.End()
logging.SetSpanWithHostname(span)
logger := logging.LogService("GateWay.Login").WithContext(c.Request.Context())

if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusOK, models.LoginResponse{
StatusCode: strings.GateWayParamsErrorCode,
StatusMsg: strings.GateWayParamsError,
UserId: 0,
Token: "",
})
return
}

res, err := Client.Login(c.Request.Context(), &auth.LoginRequest{
Username: req.UserName,
Password: req.Password,
})
if err != nil {
logger.WithFields(logrus.Fields{
"Username": req.UserName,
}).Warnf("Error when trying to connect with AuthService")
c.Render(http.StatusOK, json.CustomJSON{Data: res, Context: c})
return
}

logger.WithFields(logrus.Fields{
"Username": req.UserName,
"Token": res.Token,
"UserId": res.UserId,
}).Infof("User log in")

c.Render(http.StatusOK, json.CustomJSON{Data: res, Context: c})
}

func RegisterHandle(c *gin.Context) {
var req models.RegisterRequ
_, span := tracing.Tracer.Start(c.Request.Context(), "RegisterHandler")
defer span.End()
logger := logging.LogService("GateWay.Register").WithContext(c.Request.Context())

if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusOK, models.RegisterRes{
StatusCode: strings.GateWayParamsErrorCode,
StatusMsg: strings.GateWayParamsError,
UserId: 0,
Token: "",
})
return
}

res, err := Client.Register(c.Request.Context(), &auth.RegisterRequest{
Username: req.UserName,
Password: req.Password,
})

if err != nil {
logger.WithFields(logrus.Fields{
"Username": req.UserName,
}).Warnf("Error when trying to connect with AuthService")
c.Render(http.StatusOK, json.CustomJSON{Data: res, Context: c})
return
}

logger.WithFields(logrus.Fields{
"Username": req.UserName,
"Token": res.Token,
"UserId": res.UserId,
}).Infof("User register in")

c.Render(http.StatusOK, json.CustomJSON{Data: res, Context: c})
}

func init() {
conn := grpc2.Connect(config.AuthRpcServerName)
Client = auth.NewAuthServiceClient(conn)
}
26 changes: 13 additions & 13 deletions backend/go-services/comment/models/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@ type Comment struct {
ID uint32 `json:"id" bson:"_id,omitempty"`
UserId uint32 `json:"user_id" bson:"user_id,omitempty"`
PollId uint32 `json:"poll_id" bson:"poll_id,omitempty"`
Content string `json:"content" bson:"comment,omitempty"`
Content string `json:"content" bson:"content,omitempty"`
CreateAt time.Time `json:"create_at" bson:"create_at,omitempty"`
DeleteAt time.Time `json:"delete_at" bson:"delete_at"`
}

type ActionCommentReq struct {
Token string `json:"token" binding:"required"`
ActorId int `json:"actor_id"`
PollId int `json:"poll_id"`
ActionType int `json:"action_type"`
CommentText string `json:"comment_text"`
CommentId int `json:"comment_id"`
Token string `form:"token" binding:"required"`
ActorId int `form:"actor_id"`
PollId int `form:"poll_id"`
ActionType int `form:"action_type"`
CommentText string `form:"comment_text"`
CommentId int `form:"comment_id"`
}

type ActionCommentRes struct {
Expand All @@ -31,9 +31,9 @@ type ActionCommentRes struct {
}

type ListCommentReq struct {
Token string `json:"token"`
ActorId int `json:"actor_id"`
PollId int `json:"poll_id" binding:"-"`
Token string `form:"token"`
ActorId int `form:"actor_id"`
PollId int `form:"poll_id" binding:"-"`
}

type ListCommentRes struct {
Expand All @@ -43,9 +43,9 @@ type ListCommentRes struct {
}

type CountCommentReq struct {
Token string `json:"token"`
ActorId int `json:"actor_id"`
PollId int `json:"poll_id"`
Token string `form:"token"`
ActorId int `form:"actor_id"`
PollId int `form:"poll_id"`
}

type CountCommentRes struct {
Expand Down
10 changes: 5 additions & 5 deletions backend/go-services/comment/services/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,8 +209,8 @@ func (c CommentServiceImpl) ActionComment(ctx context.Context, request *comment.
}).Errorf("Video ID does not exist")
logging.SetSpanError(span, err)
resp = &comment.ActionCommentResponse{
StatusCode: strings.UnableToQueryVideoErrorCode,
StatusMsg: strings.UnableToQueryVideoError,
StatusCode: strings.UnableToQueryPollErrorCode,
StatusMsg: strings.UnableToQueryPollError,
}
return
}
Expand Down Expand Up @@ -254,7 +254,7 @@ func (c CommentServiceImpl) ActionComment(ctx context.Context, request *comment.
return
}

countCommentKey := fmt.Sprintf("Comment-Count-%s", request.PollId)
countCommentKey := fmt.Sprintf("Comment-Count-%d", request.PollId)
cached.TagDelete(ctx, countCommentKey)

logger.WithFields(logrus.Fields{
Expand Down Expand Up @@ -296,8 +296,8 @@ func (c CommentServiceImpl) ListComment(ctx context.Context, request *comment.Li
}).Errorf("Poll ID does not exist")
logging.SetSpanError(span, err)
resp = &comment.ListCommentResponse{
StatusCode: strings.UnableToQueryVideoErrorCode,
StatusMsg: strings.UnableToQueryVideoError,
StatusCode: strings.UnableToQueryPollErrorCode,
StatusMsg: strings.UnableToQueryPollError,
}
return
}
Expand Down
Loading