67 lines
1.7 KiB
Go
67 lines
1.7 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"picgo/configs"
|
|
"picgo/corelib"
|
|
"picgo/corelib/captcha"
|
|
"picgo/model"
|
|
)
|
|
|
|
func LoginHandler(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
|
|
corelib.TemplateHandler(w, r, nil, "view/login.html")
|
|
case http.MethodPost:
|
|
loginService(w, r)
|
|
default:
|
|
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
func loginService(w http.ResponseWriter, r *http.Request) {
|
|
var (
|
|
res model.LoginRequest
|
|
user model.SysUser
|
|
)
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&res)
|
|
if err != nil {
|
|
http.Error(w, "Bad Request", http.StatusBadRequest)
|
|
return
|
|
}
|
|
cid := getCaptchaId(r)
|
|
if ok := captcha.Verify(cid, res.Captcha); !ok {
|
|
corelib.WriteJsonResponse(w, 1040, "验证码错误", nil)
|
|
return
|
|
}
|
|
if user, err = sysUserSelectDataByUsername(res.Username); err != nil {
|
|
corelib.WriteJsonResponse(w, 1041, "用户不存在", nil)
|
|
return
|
|
}
|
|
// 验证用户名密码
|
|
if !corelib.ComparePasswords(user.Password, res.Password, user.Salt) {
|
|
corelib.WriteJsonResponse(w, 1042, "用户名或密码错误", nil)
|
|
return
|
|
}
|
|
session, _ := corelib.SessionStore.Get(r, configs.Settings.Server.SessionName)
|
|
session.Values["username"] = user.Username
|
|
if err = session.Save(r, w); err != nil {
|
|
corelib.WriteJsonResponse(w, 1043, "回话保存失败", nil)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
corelib.WriteJsonResponse(w, 200, "登录成功", nil)
|
|
}
|
|
|
|
// sysUserSelectDataByUsername 通过用户名查询用户
|
|
func sysUserSelectDataByUsername(userName string) (model.SysUser, error) {
|
|
var user model.SysUser
|
|
if err := corelib.DbMysql.Model(model.SysUser{Username: userName}).First(&user).Error; err != nil {
|
|
return user, err
|
|
}
|
|
return user, nil
|
|
}
|