Files
SourceTrace/SourceTraceFront/controllers/login.go
2024-05-25 16:45:31 +08:00

75 lines
1.6 KiB
Go

package controllers
import (
"context"
"fmt"
"log"
"net/http"
"strconv"
"github.com/NothAmor/SourceTraceFront/common"
"github.com/NothAmor/SourceTraceFront/proto"
"github.com/gin-gonic/gin"
)
func LoginPage(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
}
func Login(c *gin.Context) {
//1.获取参数
loginReq := proto.LoginReq{}
err := c.ShouldBindJSON(&loginReq)
if err != nil {
println(err)
}
if loginReq.Username == "" || loginReq.Password == "" {
c.JSON(http.StatusOK, gin.H{
"code": 100,
"msg": "用户名&&密码不能为空",
"data": nil,
})
return
}
println(" 测试参数获取成功,后续可删除"+loginReq.Username, loginReq.Password+"开始调用远程服务接口")
//2.RPC调用接口实现登录功能
var loginResult proto.LoginResult
err = common.RPC.Call(context.Background(), "Login", loginReq, &loginResult)
if err != nil {
log.Printf("failed to call: %v", err)
return
}
fmt.Println(loginResult)
cookieOfUserID := &http.Cookie{
Name: "userID",
Value: strconv.Itoa(loginResult.ID),
Path: "/",
Secure: false,
HttpOnly: true,
}
cookieOfUsername := &http.Cookie{
Name: "username",
Value: loginResult.Username,
Path: "/",
Secure: false,
HttpOnly: true,
}
cookieOfRole := &http.Cookie{
Name: "role",
Value: strconv.Itoa(loginResult.Role),
Path: "/",
Secure: false,
HttpOnly: true,
}
http.SetCookie(c.Writer, cookieOfUserID)
http.SetCookie(c.Writer, cookieOfUsername)
http.SetCookie(c.Writer, cookieOfRole)
c.JSON(http.StatusOK, gin.H{
"code": 200,
"msg": loginResult.Msg,
"data": nil,
})
}