三十七、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)
相关推荐
疑惑的杰瑞3 分钟前
[C语言]连子棋游戏
c语言·开发语言·游戏
wrx繁星点点3 分钟前
创建型模式-单例模式
java·开发语言·单例模式
杨~friendship19 分钟前
Ubuntu上使用qt和opencv显示图像
linux·开发语言·c++·qt·opencv·ubuntu
街 三 仔23 分钟前
【C语言零基础入门篇 - 3】:格式化输入输出、字符操作和sizeof运算符揭秘
c语言·开发语言
喜欢猪猪38 分钟前
TCP/IP网络编程概念及Java实现TCP/IP通讯Demo
开发语言·php
UvwxyZ6661 小时前
python日志记录与命令行交互
开发语言·python
解孔明1 小时前
IDEA2023.1添加java虚拟机启动参数,打开断言
java·开发语言
关关不烦恼1 小时前
【Java数据结构】二叉树
java·开发语言·数据结构
苹果酱05671 小时前
使用 React Testing Library 测试自定义 React Hooks
java·开发语言·spring boot·后端·中间件
蒙娜丽宁1 小时前
Go语言错误处理详解
ios·golang·go·xcode·go1.19