feat: 完成用户登录的路由函数

main
熊二 2 years ago
parent c0540a6483
commit df6243f6d3
  1. 62
      app/rts.go

@ -3,11 +3,18 @@ package app
import (
"errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
"gorm.io/gorm"
"net/http"
"strings"
)
var tokenAuth *jwtauth.JWTAuth
func init() {
tokenAuth = jwtauth.New("HS256", []byte("secret"), nil)
}
type userInfo struct {
id uint
Name string
@ -170,7 +177,62 @@ func ListUser(w *ResponseWriter, r *Request) {
// Login 用户登录
func Login(w *ResponseWriter, r *Request) {
var phoneNumber string
var password string
var token string
var ok bool
// 提交的手机号码
if phoneNumber, ok = r.Get("phone_number"); ok && len(phoneNumber) > 0 {
if len(phoneNumber) != 11 {
w.Error(NewError(2, "手机号码格式错误"))
return
}
} else {
w.Error(NewError(2, "缺少手机号码"))
return
}
// 提交的登陆密码
if password, ok = r.Get("password"); ok && len(password) > 0 {
if len(password) < 6 {
w.Error(NewError(2, "密码太短"))
return
}
} else {
w.Error(NewError(2, "缺少密码"))
return
}
// 提交的设备码
if token, ok = r.Get("token"); !ok || len(token) == 0 {
w.Error(NewError(2, "缺少设备码"))
return
}
// 查询用户是否存在
var user User
err := DB.First(&user, "phone_number = ?", phoneNumber).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
w.Error(NewError(1, "手机号码或密码错误"))
} else if err != nil {
w.Error(err)
} else {
if password != user.Password {
w.Error(NewError(1, "手机号码或密码错误"))
return
}
_, tokenString, err := tokenAuth.Encode(map[string]any{"uid": user.ID, "tkn": token})
if err != nil {
LogError(err)
w.Error(NewError(1, "登录失败"))
return
}
w.Ok(map[string]any{
"user": user,
"token": tokenString,
}, "登录成功")
}
}
// CreateGoods 创建商品

Loading…
Cancel
Save