三十七、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)
相关推荐
ytttr8731 小时前
隐马尔可夫模型(HMM)MATLAB实现范例
开发语言·算法·matlab
天远Date Lab1 小时前
Python实战:对接天远数据手机号码归属地API,实现精准用户分群与本地化运营
大数据·开发语言·python
listhi5201 小时前
基于Gabor纹理特征与K-means聚类的图像分割(Matlab实现)
开发语言·matlab
qq_433776422 小时前
【无标题】
开发语言·php
盖世英雄酱581362 小时前
Java 组长年终总结:靠 AI 提效 50%,25 年搞副业只赚 4k?
后端·程序员·trae
Davina_yu2 小时前
Windows 下升级 R 语言至最新版
开发语言·windows·r语言
阿珊和她的猫2 小时前
IIFE:JavaScript 中的立即调用函数表达式
开发语言·javascript·状态模式
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue在线音乐播放系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
listhi5203 小时前
卷积码编码和维特比译码的MATLAB仿真程序
开发语言·matlab
yuan199973 小时前
基于主成分分析(PCA)的故障诊断MATLAB仿真
开发语言·matlab