管理员登录解析
控制器文件:admins/controllers/login.go
package controllers import ( "github.com/gin-gonic/gin" "github.com/gorilla/sessions" "goadmin/common" "goadmin/modes" "net/http" "os" "strconv" ) //定义一个LoginForm 用于接收登录的请求参数,并定义验证规则 type LoginForm struct { UserName string `form:"username" binding:"required,alphanum,min=6,max=20"` Passwd string `form:"passwd" bindding:"required,alphanum,min=6,max=20"` Captcha string `form:"captcha" binding:"required,capt"` CaptchaId string `form:"captcha_id" bingding:"required"` Online string `form:"online"` } //定义session的存储方式 var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY"))) //登录页面 func AdminLogin(c *gin.Context) { //显示登录模板 c.HTML(http.StatusOK,"login/index.html",nil) } //登录请求处理 func AdminLoginAction(c *gin.Context) { var u LoginForm err := c.ShouldBind(&u) if err != nil { // 401 验证码错误 c.JSON(http.StatusOK, gin.H{ "code": 401, "msg": err.Error(),}) return } //验证账号密码 res := modes.AdminLogin(u.UserName,u.Passwd,c) if res.Status != true { c.JSON(http.StatusOK, gin.H{ "code": 402, "msg": res.Msg,}) return } //类型断言,将接口转换为 admins类型 admins,_ := (res.Data).(modes.Admins) //session过期时间为2小时 common.SetSession("admin_uid",strconv.Itoa(admins.AdminUid),c) common.SetSession("admin_auth",common.MyMd5(strconv.Itoa(admins.AdminUid)+admins.AdminUname),c) if u.Online == "1" { //保持登录状态1周 记录session 和cookie common.SetCookie("admin_uid",strconv.Itoa(admins.AdminUid),c) common.SetCookie("admin_auth",""+common.MyMd5(strconv.Itoa(admins.AdminUid)+admins.AdminUname),c) } c.JSON(http.StatusOK, gin.H{ "code": 0, "msg": "success", }) return } //无路由 func AdminError(c *gin.Context) { //显示登录模板 c.HTML(http.StatusOK,"login/404.html",nil) }
模型文件:modes/adminsModel.go
var DB = common.DB //管理员 type Admins struct { AdminUid int `form:"admin_uid"` AdminUname string `form:"admin_uname"` AdminPasswd string `form:"admin_passwd"` AdminTruename string `form:"admin_truename"` AdminDept string `form:"admin_dept"` Lastlogin string `form:"last_login"` Logincount int `form:"logincount"` IsAdmin int `form:"is_admin"` AdminStatus int `form:"admin_status"` AdminRemark string `form:"admin_remark"` AddDatetime string `form:"add_datetime"` } //管理员登录 func AdminLogin(name string,pass string,c *gin.Context) (common.ReData) { admin := Admins{} pass = common.MyMd5(pass) //验证账号,和密码是否正确 res := DB.Table("admins").Where("admin_uname=?",name).Where("admin_passwd=?",pass). Find(&admin) if res.Error != nil { return common.ReData{false,res.Error.Error(),&admin,} } //查询结果失败 if admin.AdminUid == 0 { return common.ReData{false,"账号或密码输入错误",admin,} } lastlogin:=time.Now().Format(common.TimeTem) //更新登录次数,和最后登录时间 upres := DB.Model(&admin).Where("admin_uid=?",admin.AdminUid). Updates(Admins{Lastlogin: lastlogin,Logincount:admin.Logincount+1}) if upres.Error != nil { return common.ReData{false,res.Error.Error(),admin,} } //写入日志 AddAdminLog(admin.AdminUid,c) return common.ReData{true,"登录成功",admin,} } //写入管理员日志 func AddAdminLog(admin_uid int,c *gin.Context) bool { var url string var params_str string //记录日志 if(strings.Contains(c.Request.RequestURI,"?")){ spurl := strings.Split(c.Request.RequestURI,"?") url = spurl[0] }else{ url = c.Request.RequestURI } if (c.Request.Method == "POST") { if err := c.Request.ParseMultipartForm(32 << 20); err != nil { if !errors.Is(err, http.ErrNotMultipart) { fmt.Println(nil, err) } } var postMap = make(map[string]any, len(c.Request.PostForm)) for k, v := range c.Request.PostForm { if len(v) > 1 { postMap[k] = v } else if len(v) == 1 { postMap[k] = v[0] } } //密码,加密存储 if url == "/admin/dologin" { postMap["passwd"] = common.MyMd5(postMap["passwd"].(string)) } dataType , _ := json.Marshal(postMap) params_str = string(dataType) }else{ query := c.Request.URL.Query() var queryMap = make(map[string]any, len(query)) for k := range query { queryMap[k] = c.Query(k) } dataType1 , _ := json.Marshal(queryMap) params_str = string(dataType1) } admins_log := AdminsLog{ AdminUid: admin_uid, RequestUrl: url, RequestMethod: c.Request.Method, RequestParams: params_str, IpAddr: c.Request.RemoteAddr, AddDatetime: time.Now().Format(common.TimeTem), } res := DB.Model(AdminsLog{}).Create(&admins_log) if res.RowsAffected == 1{ return true } return false }
模板文件:views/admins/login/index.html
{{define "login/index.html"}} <div id="loginform" class="loginBox"> <form class="form form-horizontal" action="#" method="post"> <div class="row cl"> <label class="form-label col-xs-3"><i class="Hui-iconfont"></i></label> <div class="formControls col-xs-8"> <input id="username" name="username" type="text" placeholder="账户" class="input-text size-L"> </div> </div> <div class="row cl"> <label class="form-label col-xs-3"><i class="Hui-iconfont"></i></label> <div class="formControls col-xs-8"> <input id="passwd" name="passwd" type="password" placeholder="密码" class="input-text size-L"> </div> </div> <div class="row cl"> <div class="formControls col-xs-8 col-xs-offset-3"> <input name="captcha" id="captcha" class="input-text size-L" type="text" placeholder="验证码" onblur="if(this.value==''){this.value='验证码:'}" onclick="if(this.value=='验证码:'){this.value='';}" value="验证码:" style="width:150px;"> <img id="captcha_img" src="/admin/getCaptcha" onclick="showCaptcha()" style="width: 120px"> <input type="hidden" name="captcha_id" id="captcha_id" /> <a id="kanbuq" href="javascript:showCaptcha();">看不清,换一张</a> </div> </div> <div class="row cl"> <div class="formControls col-xs-8 col-xs-offset-3"> <label for="online"> <input type="checkbox" name="online" id="online" value="0"> 使我保持登录状态</label> </div> </div> <div class="row cl"> <div class="formControls col-xs-8 col-xs-offset-3"> <input name="sub" id="sub" type="button" class="btn btn-success radius size-L" value=" 登 录 "> </div> </div> </form> </div> <script type="text/javascript" src="/static/h-ui.lib/jquery/1.9.1/jquery.min.js"></script> <script> //提交数据进行登录 $("#sub").click(function (){ u = $("#username").val() p = $("#passwd").val() o = $("#online").prop("checked")==true?1:0 ca= $("#captcha").val() caid = $("#captcha_id").val() $.post("/admin/dologin",{username:u,passwd:p,online:o,captcha:ca,captcha_id:caid},function (res){ if (res.code == "401"){ $("body").Huimodalalert({content: '验证码输入错误', speed: 2000 }) showCaptcha() }else if (res.code == "0"){ window.location = "/admin/index" }else{ $("body").Huimodalalert({content: res.msg, speed: 2000 }) showCaptcha() } },'json') }) //显示验证码 function showCaptcha(){ $.get("/admin/getCaptcha",function (res){ $("#captcha_img").attr("src",res.data) $("#captcha_id").val(res.captchaId) }) } showCaptcha() </script> {{end}}
至此 管理员登录已完成了。
完结
但行好事,莫问前程!
本文来自博客园,作者:yangphp,转载请注明原文链接:https://www.cnblogs.com/ypeih/p/17338614.html