三十七、Gin完成登陆功能

目录

一、完成dao

二、services包下新建login.go

三、路由绑定


一、完成dao

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

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

二、services包下新建login.go

复制代码
package services

import (
	"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.UserID
		password = req.Password
	)
	//实例化dao赋值accountDao
	accountDao := 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 保存sessionID
	return "session-id"
}

三、路由绑定

复制代码
	noAuth.POST("cms/login", cmsApp.Login)
相关推荐
Brilliantwxx7 分钟前
【C++】 vector(代码实现+坑点讲解)
开发语言·c++·笔记·算法
野生技术架构师8 分钟前
2026年最全Java面试题及答案汇总(建议收藏,面试前看这篇就够了)
java·开发语言·面试
程序员飞哥8 分钟前
重构 AI 思维(一):Prompt Engineering,如何下达不可违抗的指令?
人工智能·后端
百锦再1 小时前
Auto.js变成基础知识学习
开发语言·javascript·学习·sqlite·kotlin·android studio·数据库开发
叼烟扛炮1 小时前
C++第三讲:类和对象(中)
开发语言·c++·类和对象
皮皮林5511 小时前
@Autowired 和 @Resource 注解有啥区别?你这项目怎么还混着用呢?
后端
iDao技术魔方2 小时前
DeepSeek TUI:原生 Rust 打造的终端 AI 编码 Agent
开发语言·人工智能·rust
jghhh012 小时前
认知无线电中基于能量检测的双门限频谱感知的 MATLAB 仿真
开发语言·matlab
程序员小假2 小时前
HTTP3 性能更好,为什么内网微服务依然多用 HTTP2?HTTP2 内网优势是什么?
java·后端
Mr数据杨2 小时前
【Codex】用教案主体模块沉淀标准化教学设计内容
java·开发语言·django·codex·项目开发