feat:完善信息

This commit is contained in:
henry
2021-09-30 12:09:45 +08:00
parent 3d84af2e0c
commit 022fef28f7
23 changed files with 1111 additions and 170 deletions

View File

@ -432,7 +432,7 @@ func (c *Instance) MemberBind(id uint64, status int) error {
} else if !isExist {
return errors.New("用户信息不存在")
}
if model2.SysUserTenantStatus(status) == mSysUserTenant.Status {
if model2.AccountStatusKind(status) == mSysUserTenant.Status {
return errors.New("状态异常,不可操作")
}
if err := model2.Updates(mSysUserTenant.SysUserTenant, map[string]interface{}{

View File

@ -13,10 +13,10 @@ type SysUserTenant struct {
type (
// SysUserTenantBasic 基本信息
SysUserTenantBasic struct {
ID uint64 `json:"id"`
Name string `json:"name"`
Mobile string `json:"mobile"`
Status model.SysUserTenantStatus `json:"status"`
ID uint64 `json:"id"`
Name string `json:"name"`
Mobile string `json:"mobile"`
Status model.AccountStatus `json:"status"`
}
// SysUserTenantUser 用户信息
SysUserTenantUser struct {

View File

@ -0,0 +1,8 @@
package config
type Area struct {
Province uint64 `json:"province"`
City uint64 `json:"city"`
District uint64 `json:"district"`
Address string `json:"address"`
}

View File

@ -1,48 +0,0 @@
package model
import (
"SciencesServer/utils"
"gorm.io/gorm"
"time"
)
type TenantUser struct {
Model
UUID uint64 `gorm:"column:uuid;uniqueIndex:idx_tenant_user_uuid;type:int;default:0;comment:用户唯一UUID" json:"-"`
Avatar string `gorm:"column:avatar;type:varchar(255);default:null;comment:头像" json:"avatar"`
Name string `gorm:"column:name;type:varchar(20);default:null;comment:真实姓名" json:"name"`
Mobile string `gorm:"column:mobile;index:idx_tenant_user_mobile;type:varchar(15);default:null;comment:联系方式" json:"mobile"`
Email string `gorm:"column:email;type:varchar(50);default:null;comment:邮箱" json:"email"`
Identity int `gorm:"column:identity;type:int(8);default:0;comment:身份信息" json:"-"`
Password string `gorm:"column:password;type:varchar(100);default:null;comment:密码" json:"-"`
Salt string `gorm:"column:salt;type:varchar(10);default:null;comment:盐值" json:"-"`
Province uint64 `gorm:"column:province;type:int;default:0;comment:所在省" json:"province"`
City uint64 `gorm:"column:city;type:int;default:0;comment:所在市" json:"city"`
District uint64 `gorm:"column:district;type:int;default:0;comment:所在区/县" json:"district"`
Address string `gorm:"column:address;type:varchar(255);default:null;comment:详细地址" json:"address"`
AccountStatus
ModelDeleted
ModelAt
}
func (m *TenantUser) TableName() string {
return m.NewTableName("tenant_user")
}
func (m *TenantUser) BeforeCreate(db *gorm.DB) error {
m.NewPassword()
snowflake, _ := utils.NewSnowflake(1)
m.UUID = uint64(snowflake.GetID())
m.Status = AccountStatusForEnable
m.CreatedAt = time.Now()
return nil
}
func (m *TenantUser) NewPassword() {
m.Salt = utils.GetRandomString(8)
m.Password = utils.HashString([]byte(utils.Md5String(m.Password, m.Salt)))
}
func NewTenantUser() *TenantUser {
return &TenantUser{}
}

View File

@ -0,0 +1,42 @@
package model
import (
"SciencesServer/utils"
"gorm.io/gorm"
"time"
)
// UserInstance 账号信息
type UserInstance struct {
Model
UUID uint64 `gorm:"column:uuid;uniqueIndex:idx_tenant_user_uuid;type:int;default:0;comment:用户唯一UUID" json:"-"`
Mobile string `gorm:"column:mobile;index:idx_user_instance_mobile;type:varchar(15);default:null;comment:联系方式" json:"mobile"`
Identity int `gorm:"column:identity;type:int(8);default:0;comment:身份信息" json:"-"`
Password string `gorm:"column:password;type:varchar(100);default:null;comment:密码" json:"-"`
Salt string `gorm:"column:salt;type:varchar(10);default:null;comment:盐值" json:"-"`
AccountStatus
ModelDeleted
ModelAt
}
func (m *UserInstance) TableName() string {
return "user_instance"
}
func (m *UserInstance) BeforeCreate(db *gorm.DB) error {
m.NewPassword()
snowflake, _ := utils.NewSnowflake(1)
m.UUID = uint64(snowflake.GetID())
m.Status = AccountStatusForEnable
m.CreatedAt = time.Now()
return nil
}
func (m *UserInstance) NewPassword() {
m.Salt = utils.GetRandomString(8)
m.Password = utils.HashString([]byte(utils.Md5String(m.Password, m.Salt)))
}
func NewUserInstance() *UserInstance {
return &UserInstance{}
}

View File

@ -0,0 +1,51 @@
package model
import (
"SciencesServer/utils"
"gorm.io/gorm"
"time"
)
type UserTenant struct {
Model
ModelTenant
UID uint64 `gorm:"column:uid;index:idx_tenant_user_uuid;type:int;default:0;comment:用户表UUID" json:"-"`
UUID uint64 `gorm:"column:uuid;uniqueIndex:idx_tenant_user_uuid;type:int;default:0;comment:用户唯一UUID" json:"-"`
Avatar string `gorm:"column:avatar;type:varchar(255);default:null;comment:头像" json:"avatar"`
Name string `gorm:"column:name;type:varchar(20);default:null;comment:真实姓名" json:"name"`
Email string `gorm:"column:email;type:varchar(50);default:null;comment:邮箱" json:"email"`
Identity int `gorm:"column:identity;type:tinyint(3);default:0;comment:身份信息" json:"-"`
Province uint64 `gorm:"column:province;type:int;default:0;comment:所在省" json:"province"`
City uint64 `gorm:"column:city;type:int;default:0;comment:所在市" json:"city"`
District uint64 `gorm:"column:district;type:int;default:0;comment:所在区/县" json:"district"`
Address string `gorm:"column:address;type:varchar(255);default:null;comment:详细地址" json:"address"`
Selected UserTenantSelected `gorm:"column:selected;type:tinyint(1);default:0;comment:最后一次选中的身份状态,用于下次登陆展示" json:"-"`
Other string `gorm:"column:other;type:varchar(255);default:null;comment:其他信息" json:"-"`
Status int `gorm:"column:status;type:tinyint(0);default:0;comment:状态" json:"-"`
ModelDeleted
ModelAt
}
type UserTenantSelected int
const (
// UserTenantSelectedForNo 未选中
UserTenantSelectedForNo UserTenantSelected = iota
// UserTenantSelectedForYes 以选中
UserTenantSelectedForYes
)
func (m *UserTenant) TableName() string {
return m.NewTableName("user_tenant")
}
func (m *UserTenant) BeforeCreate(db *gorm.DB) error {
snowflake, _ := utils.NewSnowflake(1)
m.UUID = uint64(snowflake.GetID())
m.CreatedAt = time.Now()
return nil
}
func NewUserTenant() *UserTenant {
return &UserTenant{}
}

View File

@ -0,0 +1,211 @@
package platform
import (
"SciencesServer/utils"
)
// 高德API
type Gaode struct{}
type (
Location struct {
Province string `json:"province"`
City string `json:"city"`
AdCode string `json:"adcode"`
Rectangle string `json:"rectangle"`
}
// GaoDeLocationResponse 第三方位置响应参数
GaoDeLocationResponse struct {
Status string `json:"status"`
Count string `json:"count"`
Info string `json:"info"`
InfoCode string `json:"infocode"`
GeoCodes []struct {
FormattedAddress string `json:"formatted_address"`
Country string `json:"country"`
Province string `json:"province"`
CityCode string `json:"citycode"`
City string `json:"city"`
District string `json:"district"`
Township []string `json:"township"`
Neighborhood []struct {
Name string `json:"name"`
Type string `json:"type"`
} `json:"neighborhood"`
Building []struct {
Name string `json:"name"`
Type string `json:"type"`
} `json:"building"`
AdCode string `json:"adcode"`
Street string `json:"street"`
Number string `json:"number"`
Location string `json:"location"`
Level string `json:"level"`
} `json:"geocodes"`
}
// GaoDeLocationReverseResponse 第三方反向位置响应参数
GaoDeLocationReverseResponse struct {
Status string `json:"status"`
Count string `json:"count"`
Info string `json:"info"`
InfoCode string `json:"infocode"`
ReGeoCode struct {
FormattedAddress string `json:"formatted_address"`
AddressComponent struct {
Country string `json:"country"`
Province string `json:"province"`
City string `json:"city"`
CityCode string `json:"citycode"`
District string `json:"district"`
AdCode string `json:"adcode"`
Township string `json:"township"`
TownCode string `json:"town_code"`
Neighborhood struct {
Name string `json:"name"`
Type string `json:"type"`
} `json:"neighborhood"`
Building struct {
Name string `json:"name"`
Type string `json:"type"`
} `json:"building"`
StreetNumber struct {
Street string `json:"street"`
Number string `json:"number"`
Location string `json:"location"`
Direction string `json:"direction"`
Distance string `json:"distance"`
} `json:"streetNumber"`
BusinessAreas []struct {
Location string `json:"location"`
Name string `json:"name"`
ID string `json:"id"`
} `json:"businessAreas"`
} `json:"addressComponent"`
} `json:"regeocode"`
}
// GaoDeLocationIPResponse IP定位查询
GaoDeLocationIPResponse struct {
Status string `json:"status"`
Count string `json:"count"`
Info string `json:"info"`
InfoCode string `json:"infocode"`
Province interface{} `json:"province"`
City interface{} `json:"city"`
AdCode interface{} `json:"adcode"`
Rectangle interface{} `json:"rectangle"`
}
// GaoDeWeatherResponse 第三方天气响应参数
GaoDeWeatherResponse struct {
Status string `json:"status"`
Count string `json:"count"`
Info string `json:"info"`
InfoCode string `json:"infocode"`
Lives []struct {
Province string `json:"province"`
City string `json:"city"`
AdCode string `json:"adcode"`
Weather string `json:"weather"`
Temperature string `json:"temperature"`
WindDirection string `json:"winddirection"`
WindPower string `json:"windpower"`
Humidity string `json:"humidity"`
ReportTime string `json:"reporttime"`
} `json:"lives"`
}
)
const (
GDKey = "11b1e9db2756e3482b10754bf59d0d94"
gaoDeRequestURLForLocation string = "https://restapi.amap.com/v3/geocode/geo"
gaoDeRequestURLForLocationReverse string = "https://restapi.amap.com/v3/geocode/regeo"
gaoDeRequestURLForLocationIP string = "https://restapi.amap.com/v3/ip"
gaoDeRequestURLForLocationWeather string = "https://restapi.amap.com/v3/weather/weatherInfo"
)
// Location 位置信息
func (this *Gaode) Location(address, city string) (*GaoDeLocationResponse, error) {
params := map[string]interface{}{
"key": GDKey, "address": "address", "city": city,
}
client := utils.NewClient(gaoDeRequestURLForLocation, utils.MethodForGet, params)
resp, err := client.Request(utils.RequestBodyFormatForFormData)
if err != nil {
return nil, err
}
response := new(GaoDeLocationResponse)
_ = utils.FromJSONBytes(resp, response)
return response, nil
}
// LocationReverse 反向位置
func (this *Gaode) LocationReverse(location string) (*GaoDeLocationReverseResponse, error) {
params := map[string]interface{}{
"key": GDKey, "location": location,
}
client := utils.NewClient(gaoDeRequestURLForLocationReverse, utils.MethodForGet, params)
resp, err := client.Request(utils.RequestBodyFormatForFormData)
if err != nil {
return nil, err
}
response := new(GaoDeLocationReverseResponse)
_ = utils.FromJSONBytes(resp, response)
return response, nil
}
// LocationIP IP查询
func (this *Gaode) LocationIP(ip string) (*GaoDeLocationIPResponse, error) {
params := map[string]interface{}{
"key": GDKey,
}
if ip != "" {
params["ip"] = ip
}
client := utils.NewClient(gaoDeRequestURLForLocationIP, utils.MethodForGet, params)
resp, err := client.Request(utils.RequestBodyFormatForFormData)
if err != nil {
return nil, err
}
response := new(GaoDeLocationIPResponse)
_ = utils.FromJSONBytes(resp, response)
return response, nil
}
// Weather 天气信息
func (this *Gaode) Weather(city string) (*GaoDeWeatherResponse, error) {
params := map[string]interface{}{
"key": GDKey, "city": city,
}
client := utils.NewClient(gaoDeRequestURLForLocationWeather, utils.MethodForGet, params)
resp, err := client.Request(utils.RequestBodyFormatForFormData)
if err != nil {
return nil, err
}
response := new(GaoDeWeatherResponse)
_ = utils.FromJSONBytes(resp, response)
return response, nil
}
func NewGaode() *Gaode {
return &Gaode{}
}

View File

@ -0,0 +1,92 @@
package platform
import (
"SciencesServer/utils"
"errors"
"strings"
"time"
)
// 短信API
type Sms struct{}
type SmsParam struct {
Mobile []string `json:"mobile"`
Content string `json:"content"`
}
type SmsSendMode int
const (
// SmsSendModeForAlone 常规单独发送
SmsSendModeForAlone SmsSendMode = iota + 1
// SmsSendModeForGroup 常规群发
SmsSendModeForGroup
// SmsSendModeForVariable 变量发送
SmsSendModeForVariable
)
const (
smsSendURLForAlone string = "http://122.144.203.27:8001/mt.ashx"
smsSendURLForGroup string = "http://122.144.203.27:8001/mts.ashx"
smsSendURLForVariable string = "http://122.144.203.27:8001/mts_var_json.ashx"
)
const (
keyForAccount string = "113934"
keyForPassword string = "zytDuehC"
)
type SmsSend func(mode SmsSendMode, params *SmsParam) error
var smsSendModeHandle = map[SmsSendMode]func(params *SmsParam) (string, utils.Method, map[string]interface{}){
SmsSendModeForAlone: alone,
SmsSendModeForGroup: group,
}
func alone(params *SmsParam) (string, utils.Method, map[string]interface{}) {
return smsSendURLForAlone, utils.MethodForGet, map[string]interface{}{
"msg": params.Content, "pn": params.Mobile[0],
}
}
func group(params *SmsParam) (string, utils.Method, map[string]interface{}) {
return smsSendURLForGroup, utils.MethodForPost, map[string]interface{}{
"msg": params.Content, "pn": strings.Join(params.Mobile, ","),
}
}
func (this *Sms) Send() SmsSend {
return func(mode SmsSendMode, params *SmsParam) error {
now := time.Now().Format("20060102150405")
_params := map[string]interface{}{
"account": keyForAccount,
"pswd": strings.ToUpper(utils.Md5String(keyForAccount + keyForPassword + now)),
"ts": now,
}
handle, has := smsSendModeHandle[mode]
if !has {
return errors.New("未知的短信模式")
}
url, method, parameter := handle(params)
if len(parameter) > 0 {
for k, v := range parameter {
_params[k] = v
}
}
client := utils.NewClient(url, method, _params)
_, err := client.Request(utils.RequestBodyFormatForFormData, utils.Headers{
ContentType: utils.RequestContentTypeForXWWWFormUrlencoded,
})
return err
}
}
func NewSms() *Sms {
return &Sms{}
}

View File

@ -0,0 +1,10 @@
package platform
import "testing"
func TestNewSms(t *testing.T) {
err := NewSms().Send()(SmsSendModeForGroup, &SmsParam{
Mobile: []string{"17718184079"}, Content: "【商挈科技】您的验证码是789789",
})
t.Log(err)
}

View File

@ -0,0 +1,76 @@
package platform
import "SciencesServer/utils"
type Wechat struct{}
type WechatScan struct{}
type WechatScanHandle func() *WechatScan
type (
WechatBasicRequest struct {
AppID, Secret string
}
WechatErrorResponse struct {
ErrCode int `json:"errcode"`
ErrMsg int `json:"errmsg"`
}
// WechatAccessTokenRequest 请求AccessToken参数
WechatAccessTokenRequest struct {
WechatBasicRequest
Code string
}
// WechatAccessTokenResponse 获取AccessToken响应参数
WechatAccessTokenResponse struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
OpenID string `json:"openid"`
Scope string `json:"scope"`
UnionID string `json:"unionid"`
*WechatErrorResponse
}
)
const (
// WechatAccessTokenUrl AccessToken访问地址
WechatAccessTokenUrl string = "https://api.weixin.qq.com/sns/oauth2/access_token"
)
func (this *WechatScan) Login() {
}
func (this *WechatScan) Pay() {
}
// AccessToken AccessToken操作
func (this *Wechat) AccessToken(req *WechatAccessTokenRequest) (*WechatAccessTokenResponse, error) {
params := map[string]interface{}{
"appid": req.AppID, "secret": req.Secret, "code": req.Code, "grant_type": "authorization_code",
}
resp, err := utils.NewClient(WechatAccessTokenUrl, utils.MethodForGet, params).Request(utils.RequestBodyFormatForXWWWFormUrlencoded)
if err != nil {
return nil, err
}
out := new(WechatAccessTokenResponse)
if err = utils.FromJSONBytes(resp, out); err != nil {
return nil, err
}
return out, nil
}
// Scan 扫码操作
func (this *Wechat) Scan() WechatScanHandle {
return func() *WechatScan {
return &WechatScan{}
}
}
func NewWechat() *Wechat {
return nil
}

View File

@ -32,7 +32,7 @@ func (a *Account) Login(c *gin.Context) {
api.APIFailure(err.(error))(c)
return
}
data, err := account.NewLogin()().Launch(account.LoginMode(form.Mode), &account.LoginRequest{
data, err := account.NewLogin()().Launch(account.LoginMode(form.Mode), &account.LoginParams{
Captcha: struct {
Mobile string
Captcha string
@ -52,7 +52,7 @@ func (a *Account) Register(c *gin.Context) {
api.APIFailure(err.(error))(c)
return
}
data, err := account.NewRegister()().Launch(&account.RegisterRequest{
data, err := account.NewRegister()().Launch(&account.RegisterParams{
Name: form.Name, Mobile: form.Mobile, Captcha: form.Captcha,
Password: form.Password, RepeatPass: form.RepeatPass,
})

View File

@ -1,41 +0,0 @@
package account
import (
"SciencesServer/app/enterprise/model"
"SciencesServer/app/service"
"SciencesServer/config"
"SciencesServer/utils"
)
type Account struct{}
type LoginCallback func(user *model.TenantUser) *LoginResponse
type (
LoginResponse struct {
Token string `json:"token"`
EffectTime int `json:"effect_time"`
}
)
func (c *Account) Login() LoginCallback {
return func(mTenantUser *model.TenantUser) *LoginResponse {
token := utils.JWTEncrypt(config.SettingInfo.TokenEffectTime, map[string]interface{}{
config.TokenForUID: mTenantUser.UUID,
})
session := service.NewSessionEnterprise()
session.Token = token
session.UID = mTenantUser.UUID
session.Name = mTenantUser.Name
session.Mobile = mTenantUser.Mobile
session.Identity = mTenantUser.Identity
service.Publish(config.EventForRedisHashProduce, config.RedisKeyForAccount, mTenantUser.UUIDToString(), session)
return &LoginResponse{Token: token, EffectTime: config.SettingInfo.TokenEffectTime}
}
}
func NewAccount() *Account {
return &Account{}
}

View File

@ -0,0 +1,52 @@
package account
import (
"SciencesServer/app/common/model"
"SciencesServer/app/service"
"SciencesServer/config"
"SciencesServer/utils"
)
type Instance struct{}
type InstanceHandle func() *Instance
type InstanceLoginCallback func(params *InstanceLoginParams) *InstanceLoginReturn
type (
InstanceLoginParams struct {
UID uint64
Name, Mobile string
Identity, SelectIdentity int
Status model.AccountStatusKind
}
InstanceLoginReturn struct {
Token string `json:"token"`
EffectTime int `json:"effect_time"`
}
)
func (c *Instance) Login() InstanceLoginCallback {
return func(params *InstanceLoginParams) *InstanceLoginReturn {
token := utils.JWTEncrypt(config.SettingInfo.TokenEffectTime, map[string]interface{}{
config.TokenForUID: params.UID,
})
session := service.NewSessionEnterprise()
session.Token = token
session.UID = params.UID
session.Name = params.Name
session.Mobile = params.Mobile
session.Identity = params.Identity
session.CurrentIdentity = params.SelectIdentity
service.Publish(config.EventForRedisHashProduce, config.RedisKeyForAccount, utils.UintToString(params.UID), session)
return &InstanceLoginReturn{Token: token, EffectTime: config.SettingInfo.TokenEffectTime}
}
}
func NewInstance() InstanceHandle {
return func() *Instance {
return &Instance{}
}
}

View File

@ -4,8 +4,10 @@ import (
model2 "SciencesServer/app/common/model"
"SciencesServer/app/enterprise/model"
"SciencesServer/app/handle"
"SciencesServer/serve/orm"
"SciencesServer/utils"
"errors"
"gorm.io/gorm"
)
type Login struct{}
@ -15,14 +17,12 @@ type (
)
type (
LoginRequest struct {
LoginParams struct {
Captcha struct {
Mobile string
Captcha string
Mobile, Captcha string
}
Password struct {
Mobile string
Password string
Mobile, Password string
}
Platform struct {
OpenID string
@ -40,17 +40,17 @@ const (
LoginModeForQQ // QQ登陆
)
var loginHandle = map[LoginMode]func(*LoginRequest) (*model.TenantUser, error){
var loginHandle = map[LoginMode]func(*LoginParams) (*InstanceLoginParams, error){
LoginModeForSmsCaptcha: loginForSmsCaptcha, LoginModeForPassword: loginForPassword,
}
// loginForSmsCaptcha 短信验证码登陆
func loginForSmsCaptcha(req *LoginRequest) (*model.TenantUser, error) {
if !utils.ValidateMobile(req.Captcha.Mobile) {
func loginForSmsCaptcha(params *LoginParams) (*InstanceLoginParams, error) {
if !utils.ValidateMobile(params.Captcha.Mobile) {
return nil, errors.New("手机号码格式异常")
}
pass, err := handle.NewCaptcha().Validate(&handle.CaptchaSms{
Mobile: req.Captcha.Mobile, Captcha: req.Captcha.Captcha,
Mobile: params.Captcha.Mobile, Captcha: params.Captcha.Captcha,
})
if err != nil {
return nil, err
@ -59,60 +59,94 @@ func loginForSmsCaptcha(req *LoginRequest) (*model.TenantUser, error) {
}
var isExist bool
mTenantUsr := model.NewTenantUser()
mUserInstance := model.NewUserInstance()
if isExist, err = model2.FirstField(mTenantUsr.TenantUser, []string{"id", "uuid", "name", "mobile", "status"},
model2.NewWhere("mobile", req.Captcha.Mobile)); err != nil {
mUserTenant := model.NewUserTenant()
if isExist, err = model2.FirstField(mUserInstance.UserInstance, []string{"id", "uuid", "name", "mobile", "status"},
model2.NewWhere("mobile", params.Captcha.Mobile)); err != nil {
return nil, err
} else if isExist {
return mTenantUsr, nil
}
mTenantUsr.Name = req.Captcha.Mobile
mTenantUsr.Password = utils.GetRandomString(12)
return mTenantUsr, nil
if isExist {
// 最后一次选中的身份信息
if _, err = model2.FirstField(mUserTenant.UserTenant, []string{"id", "uid", "uuid", "name", "identity"},
model2.NewWhere("uid", mUserInstance.UUID),
model2.NewWhere("selected", model2.UserTenantSelectedForYes)); err != nil {
return nil, err
}
} else {
mUserInstance.Password = utils.GetRandomString(12)
if err = orm.GetDB().Transaction(func(tx *gorm.DB) error {
if err = model2.Create(mUserInstance.UserInstance, tx); err != nil {
return err
}
mUserTenant.UID = mUserInstance.UUID
mUserTenant.Name = params.Captcha.Mobile
mUserTenant.Selected = model2.UserTenantSelectedForYes
return model2.Create(mUserTenant.UserTenant, tx)
}); err != nil {
return nil, err
}
}
return &InstanceLoginParams{
UID: mUserTenant.UUID, Name: mUserTenant.Name, Mobile: mUserInstance.Mobile,
Identity: mUserInstance.Identity, SelectIdentity: mUserTenant.Identity,
Status: mUserInstance.Status,
}, nil
}
// loginForPassword 密码登陆
func loginForPassword(req *LoginRequest) (*model.TenantUser, error) {
if !utils.ValidateMobile(req.Password.Mobile) {
func loginForPassword(params *LoginParams) (*InstanceLoginParams, error) {
if !utils.ValidateMobile(params.Password.Mobile) {
return nil, errors.New("手机号码格式异常")
}
mTenantUsr := model.NewTenantUser()
mUserInstance := model.NewUserInstance()
isExist, err := model2.FirstField(mTenantUsr.TenantUser, []string{"id", "uuid", "name", "mobile",
"password", "salt", "status"},
model2.NewWhere("mobile", req.Password.Mobile))
isExist, err := model2.FirstField(mUserInstance.UserInstance, []string{"id", "uuid", "mobile", "password", "salt", "status"},
model2.NewWhere("mobile", params.Password.Mobile))
if err != nil {
return nil, err
} else if isExist {
return nil, errors.New("当前手机号码未注册")
}
if !mTenantUsr.ValidatePassword(req.Password.Password) {
if !mUserInstance.ValidatePassword(params.Password.Password) {
return nil, errors.New("账户或密码错误")
}
return mTenantUsr, nil
mUserTenant := model.NewUserTenant()
// 最后一次选中的身份信息
if _, err = model2.FirstField(mUserTenant.UserTenant, []string{"id", "uid", "uuid", "name", "identity"},
model2.NewWhere("uid", mUserInstance.UUID),
model2.NewWhere("selected", model2.UserTenantSelectedForYes)); err != nil {
return nil, err
}
return &InstanceLoginParams{
UID: mUserTenant.UUID, Name: mUserTenant.Name, Mobile: mUserInstance.Mobile,
Identity: mUserInstance.Identity, SelectIdentity: mUserTenant.Identity,
Status: mUserInstance.Status,
}, nil
}
func loginForPlatform(req *LoginRequest) error {
func loginForPlatform(params *LoginParams) error {
return nil
}
func (c *Login) Launch(mode LoginMode, req *LoginRequest) (*LoginResponse, error) {
func (c *Login) Launch(mode LoginMode, params *LoginParams) (*InstanceLoginReturn, error) {
handle, has := loginHandle[mode]
if !has {
return nil, errors.New("未知的登陆模式")
}
user, err := handle(req)
ret, err := handle(params)
if err != nil {
return nil, err
}
if user.Status != model2.AccountStatusForEnable {
if ret.Status != model2.AccountStatusForEnable {
return nil, errors.New("该账号已禁止登陆,请联系管理员")
}
return NewAccount().Login()(user), err
return NewInstance()().Login()(ret), err
}
func (c *Login) BindName(token, name string) {
@ -124,7 +158,7 @@ func (c *Login) BindName(token, name string) {
}
}
func (c *Login) BindMobile(token, mobile, captcha string) (*LoginResponse, error) {
func (c *Login) BindMobile(token, mobile, captcha string) (*InstanceLoginReturn, error) {
pass, err := handle.NewCaptcha().Validate(&handle.CaptchaSms{
Mobile: mobile, Captcha: captcha,
})

View File

@ -4,7 +4,10 @@ import (
model2 "SciencesServer/app/common/model"
"SciencesServer/app/enterprise/model"
"SciencesServer/app/handle"
"SciencesServer/serve/orm"
"SciencesServer/utils"
"errors"
"gorm.io/gorm"
)
type Register struct{}
@ -12,53 +15,66 @@ type Register struct{}
type RegisterHandle func() *Register
type (
RegisterRequest struct {
RegisterParams struct {
Name, Mobile, Captcha, Password, RepeatPass string
}
)
func (c *RegisterRequest) checkPassword() bool {
func (c *RegisterParams) checkPassword() bool {
return c.Password == c.RepeatPass
}
func (c *RegisterRequest) checkUserExist(mTenantUser *model.TenantUser) (bool, error) {
func (c *RegisterParams) checkUserExist(mUserInstance *model2.UserInstance) (bool, error) {
var count int64
if err := model2.Count(mTenantUser.TenantUser, &count, model2.NewWhere("mobile", c.Mobile)); err != nil {
if err := model2.Count(mUserInstance, &count, model2.NewWhere("mobile", c.Mobile)); err != nil {
return false, err
}
return count > 0, nil
}
func (c *RegisterRequest) checkCaptcha() (bool, error) {
func (c *RegisterParams) checkCaptcha() (bool, error) {
return handle.NewCaptcha().Validate(&handle.CaptchaSms{Captcha: c.Captcha, Mobile: c.Mobile})
}
func (c *Register) Launch(req *RegisterRequest) (*LoginResponse, error) {
if req.checkPassword() {
func (c *Register) Launch(params *RegisterParams) (*InstanceLoginReturn, error) {
if params.checkPassword() {
return nil, errors.New("两次密码不一致")
}
mTenantUser := model.NewTenantUser()
mUserInstance := model.NewUserInstance()
pass, err := req.checkUserExist(mTenantUser)
pass, err := params.checkUserExist(mUserInstance.UserInstance)
if err != nil {
return nil, err
} else if pass {
return nil, errors.New("当前手机号码已注册")
}
if pass, err = req.checkCaptcha(); err != nil {
if pass, err = params.checkCaptcha(); err != nil {
return nil, err
} else if !pass {
return nil, errors.New("验证码错误或已过期")
}
mTenantUser.Name = req.Name
mTenantUser.Mobile = req.Mobile
mTenantUser.Password = req.Password
mUserInstance.Password = utils.GetRandomString(12)
mUserInstance.Mobile = params.Mobile
mUserInstance.Password = params.Password
if err = model2.Create(mTenantUser.TenantUser); err != nil {
mUserTenant := model.NewUserTenant()
if err = orm.GetDB().Transaction(func(tx *gorm.DB) error {
if err = model2.Create(mUserInstance.UserInstance, tx); err != nil {
return err
}
mUserTenant.UID = mUserInstance.UUID
mUserTenant.Name = params.Name
mUserTenant.Selected = model2.UserTenantSelectedForYes
return model2.Create(mUserTenant.UserTenant, tx)
}); err != nil {
return nil, err
}
return NewAccount().Login()(mTenantUser), err
return NewInstance()().Login()(&InstanceLoginParams{
UID: mUserTenant.UUID, Name: mUserTenant.Name, Mobile: mUserInstance.Mobile,
Identity: mUserInstance.Identity,
}), err
}
func NewRegister() RegisterHandle {

View File

@ -0,0 +1,39 @@
package user
import (
"SciencesServer/app/basic/config"
"SciencesServer/app/service"
)
type Instance struct{ *service.SessionEnterprise }
type InstanceHandle func(enterprise *service.SessionEnterprise) *Instance
type InstanceBasic struct {
Avatar string `json:"avatar"` // 头像
Name string `json:"name"` // 名称
Email string `json:"email"` // 邮箱
}
type (
// InstancePerfectParams 完善信息参数
InstancePerfectParams struct {
*InstanceBasic
*config.Area
}
)
func (c *Instance) User() {
}
// Perfect 完善信息
func (c *Instance) Perfect(params *InstancePerfectParams) {
}
func NewInstance() InstanceHandle {
return func(enterprise *service.SessionEnterprise) *Instance {
return &Instance{enterprise}
}
}

View File

@ -1,22 +0,0 @@
package model
import (
"SciencesServer/app/common/model"
"SciencesServer/utils"
)
type TenantUser struct {
*model.TenantUser
}
func (m *TenantUser) UUIDToString() string {
return utils.UintToString(m.UUID)
}
func (m *TenantUser) ValidatePassword(password string) bool {
return utils.HashCompare([]byte(m.Password), []byte(utils.Md5String(password, m.Salt)))
}
func NewTenantUser() *TenantUser {
return &TenantUser{TenantUser: model.NewTenantUser()}
}

View File

@ -0,0 +1,20 @@
package model
import (
"SciencesServer/app/common/model"
"SciencesServer/utils"
)
type UserInstance struct{ *model.UserInstance }
func (m *UserInstance) UUIDToString() string {
return utils.UintToString(m.UUID)
}
func (m *UserInstance) ValidatePassword(password string) bool {
return utils.HashCompare([]byte(m.Password), []byte(utils.Md5String(password, m.Salt)))
}
func NewUserInstance() *UserInstance {
return &UserInstance{UserInstance: model.NewUserInstance()}
}

View File

@ -0,0 +1,13 @@
package model
import (
"SciencesServer/app/common/model"
)
type UserTenant struct {
*model.UserTenant
}
func NewUserTenant() *UserTenant {
return &UserTenant{UserTenant: model.NewUserTenant()}
}

View File

@ -29,11 +29,12 @@ func NewSession() *Session {
// SessionEnterprise 企业用户
type SessionEnterprise struct {
UID uint64 `json:"uid"` // 唯一标识ID
Token string `json:"token"` // token
Name string `json:"name"` // 名称
Mobile string `json:"mobile"` // 手机号码
Identity int `json:"identity"` // 身份信息
UID uint64 `json:"uid"` // 唯一标识ID
Token string `json:"token"` // token
Name string `json:"name"` // 名称
Mobile string `json:"mobile"` // 手机号码
Identity int `json:"identity"` // 身份信息
CurrentIdentity int `json:"current_identity"` // 当前身份信息
}
func (this *SessionEnterprise) MarshalBinary() ([]byte, error) {

View File

@ -16,10 +16,13 @@ const (
ServePort string = "serve_port" // 服务器端口
)
const (
WechatForAppID string = "appid"
)
const (
UploadPath string = "upload_path" // 上传路径
UploadExt string = "upload_ext" // 上传文件限制
UploadSize string = "upload_size" // 上传文件大小限制
UploadRename string = "upload_rename" // 上传文件是否重命名
)

118
utils/request.go Normal file
View File

@ -0,0 +1,118 @@
package utils
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
type (
// Headers 消息头
Headers struct {
UserAgent string
ContentType string
Cookies map[string]string
Others map[string]string
}
// Method 请求方式
Method string
// Client
Client struct {
Url string
Method Method
Params map[string]interface{}
}
)
const (
MethodForGet Method = "GET"
MethodForPost Method = "POST"
DefaultUserAgent string = "Mozilla/5.0 (SF) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.6.6666.66 Safari/537.36"
)
// RequestBodyFormat 请求消息内容格式
type RequestBodyFormat int
const (
RequestBodyFormatForFormData RequestBodyFormat = iota + 1
RequestBodyFormatForXWWWFormUrlencoded
RequestBodyFormatForRaw
)
const (
RequestContentTypeForFormData string = "application/form-data"
RequestContentTypeForXWWWFormUrlencoded string = "application/x-www-form-urlencoded"
)
// Request 发起请求
func (this *Client) Request(format RequestBodyFormat, headers ...Headers) ([]byte, error) {
client := new(http.Client)
var reqBody io.Reader
if this.Method == MethodForGet {
_params := make([]string, 0)
for k, v := range this.Params {
_params = append(_params, fmt.Sprintf("%s=%v", k, v))
}
this.Url += "?" + strings.Join(_params, "&")
} else {
if format == RequestBodyFormatForFormData || format == RequestBodyFormatForXWWWFormUrlencoded {
_params := make([]string, 0)
for k, v := range this.Params {
_params = append(_params, fmt.Sprintf("%s=%v", k, v))
}
reqBody = strings.NewReader(strings.Join(_params, "&"))
} else if format == RequestBodyFormatForRaw {
_bytes, _ := json.Marshal(this.Params)
reqBody = bytes.NewReader(_bytes)
}
}
req, err := http.NewRequest(string(this.Method), this.Url, reqBody)
if err != nil {
return nil, err
}
for _, v := range headers {
if v.UserAgent != "" {
req.Header.Add("User-Agent", v.UserAgent)
}
if v.ContentType != "" {
req.Header.Add("Content-Type", v.ContentType)
}
if len(v.Cookies) > 0 {
for key, val := range v.Cookies {
req.AddCookie(&http.Cookie{Name: key, Value: val})
}
}
if len(v.Others) > 0 {
for key, val := range v.Others {
req.Header.Add(key, val)
}
}
}
resp := new(http.Response)
if resp, err = client.Do(req); err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
return bytes, err
}
// NewClient
func NewClient(url string, method Method, params map[string]interface{}) *Client {
return &Client{
Url: url, Method: method, Params: params,
}
}

266
utils/request_test.go Normal file
View File

@ -0,0 +1,266 @@
package utils
import (
"encoding/binary"
"log"
"os"
"testing"
)
type (
// BaiDuError 错误提示
BaiDuError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
// BaiDuAccessToken AccessToken信息
BaiDuAccessToken struct {
RefreshToken string `json:"refresh_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
SessionKey string `json:"session_key"`
AccessToken string `json:"access_token"`
SessionSecret string `json:"session_secret"`
BaiDuError
}
// BaiDuSpeechQuick SpeechQuick信息
BaiDuSpeechQuick struct {
ErrNo int `json:"err_no"`
ErrMsg string `json:"err_msg"`
SN string `json:"sn"`
Result []string `json:"result"`
}
// BaiDuRobotDialogue 机器人对话
BaiDuRobotDialogue struct {
ErrorCode int `json:"error_code"`
ErrorMsg string `json:"error_msg"`
Result struct {
Version string `json:"version"`
ServiceID string `json:"service_id"`
LogID string `json:"log_id"`
InteractionID string `json:"interaction_id"`
Response struct {
Status int `json:"status"`
Msg string `json:"msg"`
ActionList []struct {
Confidence float64 `json:"confidence"`
ActionID string `json:"action_id"`
Say string `json:"say"`
CustomReply string `json:"custom_reply"`
Type string `json:"type"`
} `json:"action_list"`
Schema struct {
Confidence float64 `json:"confidence"`
Intent string `json:"intent"`
IntentConfidence float64 `json:"intent_confidence"`
Slots []struct {
Confidence float64 `json:"confidence"`
Begin int `json:"begin"`
Length int `json:"length"`
OriginalWord string `json:"original_word"`
NormalizedWord string `json:"normalized_word"`
WordType string `json:"word_type"`
Name string `json:"name"`
SessionOffset string `json:"session_offset"`
MergeMethod string `json:"merge_method"`
} `json:"slots"`
} `json:"schema"`
} `json:"response"`
} `json:"result"`
}
)
const (
baiDuClientID string = "Sy0tLT7bHWE2RhollVOqelHq"
baiDuClientSecret string = "jSr0a2Isaivi1yvgk2TXlB7tqg21Gf1m"
//baiDuClientID string = "MDNsII2jkUtbF729GQOZt7FS"
//baiDuClientSecret string = "0vWCVCLsbWHMSH1wjvxaDq4VmvCZM2O9"
// baiDuRequestURLForAccessToken 获取token地址
baiDuRequestURLForAccessToken string = "https://aip.baidubce.com/oauth/2.0/token"
// baiDuRequestURLForVoiceQuick 语音识别极速版
baiDuRequestURLForVoiceQuick string = "https://vop.baidu.com/pro_api"
// baiDuRequestURLForRobotDialogue 语音机器人对话
baiDuRequestURLForRobotDialogue string = "https://aip.baidubce.com/rpc/2.0/unit/bot/chat"
//baiDuRequestURLForRobotDialogue string = "https://aip.baidubce.com/rpc/2.0/unit/service/chat"
)
func TestNewClient(t *testing.T) {
//file := "../upload/20210624/16k1.pcm"
//
client2 := NewClient(baiDuRequestURLForAccessToken, MethodForPost, map[string]interface{}{
"grant_type": "client_credentials", "client_id": baiDuClientID, "client_secret": baiDuClientSecret,
})
resp2, err := client2.Request(RequestBodyFormatForFormData)
if err != nil {
t.Log(err)
return
}
response := new(BaiDuAccessToken)
_ = FromJSONBytes(resp2, response)
if response.Error != "" {
t.Logf("获取百度AccessToken错误%v - %v", response.Error, response.ErrorDescription)
return
}
//t.Log(response.AccessToken)
//
//reader, err := os.OpenFile(file, os.O_RDONLY, 0666)
//
//if err != nil {
// t.Log(err)
// return
//}
//defer reader.Close()
//
//content, _ := ioutil.ReadAll(reader)
//
//cuid := ""
//
//netitfs, err := net.Interfaces()
//
//if err != nil {
// cuid = "anonymous_sqzn"
//} else {
// for _, itf := range netitfs {
// if cuid = itf.HardwareAddr.String(); len(cuid) > 0 {
// break
// }
// }
//}
//t.Log(cuid)
//t.Log(base64.StdEncoding.EncodeToString(content))
//t.Log(fmt.Sprintf("%d", len(content)))
//
//_params := map[string]interface{}{
// "format": file[len(file)-3:],
// "rate": 16000,
// "dev_pid": 1537,
// "channel": 1,
// "token": "24.1f876b06d070d7403c90832dddb813cb.2592000.1627110943.282335-24431674",
// "cuid": cuid,
// "speech": base64.StdEncoding.EncodeToString(content),
// "len": len(content),
//}
//_json, _ := json.Marshal(_params)
//
//req, err := http.NewRequest("GET", "http://vop.baidu.com/server_api", bytes.NewBuffer(_json))
//
//if err != nil {
// t.Log(err)
// return
//}
//resp := new(http.Response)
//
//client := new(http.Client)
//
//if resp, err = client.Do(req); err != nil {
// t.Log(err)
// return
//}
//bytes, err := ioutil.ReadAll(resp.Body)
//defer resp.Body.Close()
//
//response1 := new(BaiDuSpeechQuick)
//
//_ = FromJSONBytes(bytes, response1)
//
//t.Logf("resp%v\n", AnyToJSON(response1))
serviceID := "1101579"
params2 := map[string]interface{}{
"version": "2.0",
//"service_id": serviceID,
"bot_id": serviceID,
"log_id": Md5String(AnyToJSON(2040256374931197952), serviceID),
"session_id": Sha256String(AnyToJSON(2040256374931197952) + serviceID),
"request": map[string]interface{}{
"query": "公告",
"user_id": AnyToJSON(2040256374931197952),
"query_info": map[string]interface{}{
"asr_candidates": []string{},
"source": "KEYBOARD",
"type": "TEXT",
},
},
"bernard_level": 1,
}
t.Log(params2)
client3 := NewClient(baiDuRequestURLForRobotDialogue+"?access_token="+response.AccessToken,
MethodForPost, params2)
resp3, err := client3.Request(RequestBodyFormatForRaw, Headers{ContentType: "application/json; charset=UTF-8"})
if err != nil {
t.Log(err)
return
}
response3 := new(BaiDuRobotDialogue)
_ = FromJSONBytes(resp3, response3)
t.Log(AnyToJSON(response3))
return
//
//client1 := NewClient("http://vop.baidu.com/server_api", MethodForPost, params)
//
//resp1 := make([]byte, 0)
//
//if resp1, err = client1.Request(RequestBodyFormatForRaw, Headers{
// ContentType: "application/json",
//}); err != nil {
// t.Log(err)
// return
//}
//response1 := new(BaiDuSpeechQuick)
//
//_ = FromJSONBytes(resp1, response1)
//
//t.Logf("resp%v\n", AnyToJSON(response1))
}
func TestClient_Request(t *testing.T) {
request := NewClient("https://image1.ljcdn.com/hdic-resblock/4494aa6e-4165-4f4a-b7ba-4ab095dd1ffa.JPG.710x400.jpg", "GET", nil)
resp, err := request.Request(RequestBodyFormatForFormData, Headers{
Others: map[string]string{
"Referer": "http://drc.hefei.gov.cn/group4/M00/07/4D/wKgEIWEM9X-AXLhsAAONk965l5o088.png",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36",
"Cookie": "__jsluid_h=9fcece02433a024c638dd5e8d4cf6f92; __jsl_clearance=1628842172.968|0|8rBRZzH5SoW3MMG1%2FWkYpLUeRXA%3D",
},
})
f, err := os.Create("test.jpg")
if err != nil {
log.Fatal("Couldn't open file")
}
defer f.Close()
err = binary.Write(f, binary.LittleEndian, resp)
if err != nil {
log.Fatal("Write failed")
}
//resp, err := request.Request(RequestBodyFormatForFormData, Headers{
// //Others: map[string]string{
// // "Referer": "http://drc.hefei.gov.cn/group4/M00/07/4D/wKgEIWEM9X-AXLhsAAONk965l5o088.png",
// // "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36",
// // "Cookie": "__jsluid_h=2844bb494bad8b1cd372e28c65844abd; __jsl_clearance=1628840623.068|0|vNUfDD1V4muQrHrWy%2BmhoGbOFr0%3D",
// //},
//})
//f, err := os.Create("test.jpg")
//if err != nil {
// log.Fatal("Couldn't open file")
//}
//defer f.Close()
//
//err = binary.Write(f, binary.LittleEndian, resp)
//
//if err != nil {
// log.Fatal("Write failed")
//}
}