From df6243f6d3b3e8cff75c4e47feb6138b7381dbaa Mon Sep 17 00:00:00 2001 From: hupeh Date: Mon, 2 Jan 2023 12:38:48 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20:sparkles:=20=E5=AE=8C=E6=88=90?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E7=99=BB=E5=BD=95=E7=9A=84=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/rts.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/app/rts.go b/app/rts.go index 8c9c84f..045b8e2 100644 --- a/app/rts.go +++ b/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 创建商品