// Copyright 2019 getensh.com. All rights reserved. // Use of this source code is governed by getensh.com. package user import ( "context" "crypto/sha256" "encoding/json" "fmt" "git.getensh.com/common/gopkgs/database" "git.getensh.com/common/gopkgs/logger" "git.getensh.com/common/gopkgs/util" "go.uber.org/zap" "google.golang.org/grpc/status" "gorm.io/gorm" "time" "xingjia-management-gateway/apis" "xingjia-management-gateway/consts" "xingjia-management-gateway/errors" dbmodel "xingjia-management-gateway/model" ) // func Login(ctx context.Context, req *apis.LoginRequest) (reply *apis.LoginReply, err error) { reply = &apis.LoginReply{} // 捕获各个task中的异常并返回给调用者 defer func() { if r := recover(); r != nil { err = fmt.Errorf("%+v", r) e := &status.Status{} if er := json.Unmarshal([]byte(err.Error()), e); er != nil { logger.Error("err", zap.String("system_err", err.Error()), zap.Stack("stacktrace")) } } }() if req.User == "" || req.Password == "" { return reply, errors.ParamsError } p := &dbmodel.TUser{} db := database.DB() where := map[string]interface{}{ "user": req.User, } // 查找用户是否存在 err = p.Find(db, where) if err != nil { if err == gorm.ErrRecordNotFound { return reply, errors.UserNotExist } return reply, errors.DataBaseError } passwd, _ := util.GetMd5Pass(req.Password, consts.CRYPTO_KEY) if passwd != p.Password { return reply, errors.PasswordError } if p.UserType == consts.UserTypeTemp && (p.EffectiveEnd < time.Now().Unix() || p.EffectiveStart > time.Now().Unix()) { return reply, errors.UserNotEffective } reply.Uid = p.ID reply.UserType = p.UserType reply.EffectiveEnd = p.EffectiveEnd reply.EffectiveStart = p.EffectiveStart return reply, nil } func InitUser() { // 检查是否存在默认管理员 p := &dbmodel.TUser{} count, err := p.Count(database.DB(), nil, nil) if err != nil { panic(err.Error()) } if count > 0 { return } // 不存在则创建 now := time.Now() password := fmt.Sprintf("%x", sha256.Sum256([]byte("zaq123edc"))) md5pass, _ := util.GetMd5Pass(password, consts.CRYPTO_KEY) p = &dbmodel.TUser{ User: "admin", Password: md5pass, CreatedAt: now, UpdatedAt: now, UserType: consts.UserTypeSuper, RealName: "超级管理员", EffectiveStart: now.Unix(), } err = p.Insert(database.DB()) if err != nil { panic(err.Error()) } return }