欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > 三十七、Gin完成登陆功能

三十七、Gin完成登陆功能

2024/10/24 19:25:23 来源:https://blog.csdn.net/qq_34077993/article/details/142143733  浏览:    关键词:三十七、Gin完成登陆功能

目录

一、完成dao

二、services包下新建login.go

三、路由绑定


一、完成dao

这个方法意思是通过这个userid查询数据

func (a *AccountDao) Fist(UserID string) (*model.Account, error) {var account model.Accounterr := a.db.Where("user_id = ?", UserID).First(&account).Errorif err != nil {fmt.Printf("AccountDao Fist = [%v]", err)return nil, err}return &account, nil
}

二、services包下新建login.go

package servicesimport ("ContentSystem/internal/dao""github.com/gin-gonic/gin""golang.org/x/crypto/bcrypt""net/http"
)// 入参
type LoginReq struct {UserID   string `json:"user_id" binding:"required"`Password string `json:"password" binding:"required"`
}// 回包
type LoginRsp struct {SessionID string `json:"session_id"`UserID    string `json:"user_id"`Nickname  string `json:"nickname"`
}// 登陆方法
func (c *CmsApp) Login(ctx *gin.Context) {//入参声明var req LoginReq//入参绑定结构体if err := ctx.ShouldBindJSON(&req); err != nil {ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}//声明数据,不写需要频繁调用req.UserID ...var (userID   = req.UserIDpassword = req.Password)//实例化dao赋值accountDaoaccountDao := dao.NewAccountDao(c.db)//调用查询方法account, err := accountDao.Fist(userID)if err != nil {ctx.JSON(http.StatusInternalServerError, gin.H{"error": "账号输入错误"})return}//密码校验 比较数据库中密码与传递进来的密码,不报错则验证通过,报错则验证失败if err := bcrypt.CompareHashAndPassword([]byte(account.Password),[]byte(password)); err != nil {ctx.JSON(http.StatusBadRequest, gin.H{"error": "密码输入错误"})return}//todo 生成sessionid方法待完善sessionID := generateSessionID()//回报填值ctx.JSON(http.StatusOK, gin.H{"code": http.StatusOK,"msg":  "登陆成功","data": &LoginRsp{SessionID: sessionID,UserID:    account.UserID,Nickname:  account.Nickname,},})return
}
func generateSessionID() string {//todo 生成sessionID//todo 保存sessionIDreturn "session-id"
}

三、路由绑定

	noAuth.POST("cms/login", cmsApp.Login)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com