Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/job/main/passport-user/cmd:all-srcs",
"//app/job/main/passport-user/conf:all-srcs",
"//app/job/main/passport-user/dao:all-srcs",
"//app/job/main/passport-user/http:all-srcs",
"//app/job/main/passport-user/model:all-srcs",
"//app/job/main/passport-user/service:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,23 @@
## passport-user
#### Version 1.1.3
> 1. fix duplicate msg
> 2. asoAccount msg infinite retry
#### Version 1.1.1
> 1. infinite retry
> 2. add chan size
> 3. add sns check exist
> 4. del unused code
#### Version 1.1.0
> 1. add ipv6
#### Version 1.0.11
> 1. fix email verified
#### Version 1.0.10
> 1. fix write cache
#### Version 1.0.0
> 1. init

View File

@@ -0,0 +1,10 @@
# Owner
wutao
wanghuan01
# Author
chenjunxi
# Reviewer
wutao
wanghuan01

View File

@@ -0,0 +1,16 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- chenjunxi
- wanghuan01
- wutao
labels:
- job
- job/main/passport-user
- main
options:
no_parent_owners: true
reviewers:
- chenjunxi
- wanghuan01
- wutao

View File

@@ -0,0 +1,20 @@
## passport-user
#### 项目简介
> 1.数据同步job主要用于同步全量历史数据和订阅源站变更的数据
#### 编译环境
> 请只用golang v1.8.x以上版本编译执行。
#### 依赖包
> 1.公共包go-common
#### 数据同步流程
> 1.user_secret添加aes key
> 2.country_code导入数据
> 3.全量同步aso_account
全量同步aso_account_sns
> 4.全量同步aso_account_info
全量同步aso_tel_bind_log
> 5.全量同步aso_account_reg
> 6.增量同步

View File

@@ -0,0 +1,43 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_binary",
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = [
"passport-user-job.toml",
"passport-user-job-uat.toml",
],
importpath = "go-common/app/job/main/passport-user/cmd",
tags = ["automanaged"],
visibility = ["//visibility:private"],
deps = [
"//app/job/main/passport-user/conf:go_default_library",
"//app/job/main/passport-user/http:go_default_library",
"//library/log:go_default_library",
"//library/net/trace:go_default_library",
],
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
visibility = ["//visibility:public"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,40 @@
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"go-common/app/job/main/passport-user/conf"
"go-common/app/job/main/passport-user/http"
"go-common/library/log"
"go-common/library/net/trace"
)
func main() {
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Xlog)
defer log.Close()
trace.Init(conf.Conf.Tracer)
defer trace.Close()
http.Init(conf.Conf)
log.Info("passport-user-job start")
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("passport-user-job get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
log.Info("passport-user-job exit")
return
case syscall.SIGHUP:
default:
return
}
}
}

View File

@@ -0,0 +1,119 @@
[incSync]
switch = false
[fullSync]
asoCountryCodeSwitch = false
[fullSync.asoAccount]
switch = false
chanNum = 20
chanSize = 1024
start = 0
end = 100000000
count = 10000
[fullSync.asoAccountInfo]
switch = false
chanNum = 20
chanSize = 1024
start = 0
end = 100000000
count = 10000
[fullSync.asoAccountReg]
switch = false
chanNum = 20
chanSize = 1024
start = 0
end = 100000000
count = 10000
[fullSync.asoAccountSns]
switch = false
chanNum = 20
chanSize = 1024
start = 0
end = 100000000
count = 10000
[fullSync.asoTelBindLog]
switch = false
chanNum = 20
chanSize = 1024
start = 0
end = 100000000
count = 10000
[scheduler]
switch = false
telDuplicateCron = "*/5 * * * * ?"
emailDuplicateCron = "*/5 * * * * ?"
[bm]
addr = "0.0.0.0:8000"
timeout = "1s"
[db]
[db.originDB]
addr = "172.22.34.101:3309"
dsn = "aso:WsjbodupJcZlBeWPEiYyK8HOTIcp3n3Z@tcp(172.22.34.101:3309)/aso?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
queryTimeout = "1s"
execTimeout = "2s"
tranTimeout = "2s"
[db.originDB.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[db.userDB]
addr = "172.22.34.101:3308"
dsn = "passport:G5ntsSqTixJak0oyjceP1buXfVFBQH47@tcp(172.22.34.101:3308)/passport_user?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
queryTimeout = "1s"
execTimeout = "2s"
tranTimeout = "2s"
[db.userDB.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[db.encryptDB]
addr = "172.22.34.101:3308"
dsn = "secret_reader:VK7UMbq8Z4dBxyCzOYkh20EFsa1IWrAi@tcp(172.22.34.101:3308)/passport_secret?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
queryTimeout = "1s"
execTimeout = "2s"
tranTimeout = "2s"
[db.encryptDB.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[databusUtil]
size = 200
num = 32
ticker = "1s"
chan = 1024
[databus]
[databus.asoBinLogSub]
key = "4ba46ba31f9a44ef"
secret = "e4c5a7fce28695209e6b4f0af8cf91c5"
group = "PassportUserBinlog-MainAccount-S"
topic = "PassportUserBinlog-T"
action = "sub"
offset = "old"
buffer = 2048
name = "passport-user/databus"
proto = "tcp"
addr = "172.18.33.50:6205"
idle = 1
active = 1
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"

View File

@@ -0,0 +1,133 @@
[xlog]
dir = "/data/log/passport-user"
[incSync]
switch = true
[fullSync]
asoCountryCodeSwitch = false
[fullSync.asoAccount]
switch = true
chanNum = 2
chanSize = 1024
start = 0
end = 100
count = 10
[fullSync.asoAccountInfo]
switch = false
chanNum = 2
chanSize = 1024
start = 0
end = 100000
count = 10000
[fullSync.asoAccountReg]
switch = false
chanNum = 2
chanSize = 1024
start = 0
end = 100000
count = 10000
[fullSync.asoAccountSns]
switch = false
chanNum = 2
chanSize = 1024
start = 0
end = 100000
count = 10000
[fullSync.asoTelBindLog]
switch = false
chanNum = 2
chanSize = 1024
start = 0
end = 100000
count = 10000
[scheduler]
switch = false
telDuplicateCron = "*/5 * * * * ?"
emailDuplicateCron = "*/5 * * * * ?"
[bm]
addr = "0.0.0.0:8000"
timeout = "1s"
[db]
[db.originDB]
addr = "172.16.33.205:3306"
dsn = "aso:hA0DAnENNFz78kYB@tcp(172.16.33.205:3306)/aso?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
queryTimeout = "1s"
execTimeout = "2s"
tranTimeout = "2s"
[db.originDB.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[db.userDB]
addr = "127.0.0.1:3306"
dsn = "root:root@tcp(127.0.0.1:3306)/user?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
queryTimeout = "1s"
execTimeout = "2s"
tranTimeout = "2s"
[db.userDB.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[db.encryptDB]
addr = "127.0.0.1:3306"
dsn = "root:root@tcp(127.0.0.1:3306)/user?timeout=1s&readTimeout=1s&writeTimeout=1s&parseTime=true&loc=Local&charset=utf8,utf8mb4"
active = 5
idle = 2
queryTimeout = "1s"
execTimeout = "2s"
tranTimeout = "2s"
[db.encryptDB.breaker]
window = "3s"
sleep = "100ms"
bucket = 10
ratio = 0.5
request = 100
[databusUtil]
size = 200
num = 32
ticker = "1s"
chan = 1024
[databus]
[databus.asoBinLogSub]
key = "4ba46ba31f9a44ef"
secret = "99985eb4451cfb1b899ca0fbe3c4bdc8"
group = "PassportUserBinlog-MainAccount-S"
topic = "PassportUserBinlog-T"
action = "sub"
offset = "old"
buffer = 2048
name = "passport-user/databus"
proto = "tcp"
addr = "172.16.38.154:6205"
idle = 1
active = 1
dialTimeout = "1s"
readTimeout = "60s"
writeTimeout = "1s"
idleTimeout = "10s"
[memcache]
name = "passport-user-service"
proto = "tcp"
addr = "172.22.33.137:11219"
idle = 1000
active = 1000
dialTimeout = "10s"
readTimeout = "10s"
writeTimeout = "10s"
idleTimeout = "30s"

View File

@@ -0,0 +1,38 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/job/main/passport-user/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/cache/memcache:go_default_library",
"//library/conf:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/trace:go_default_library",
"//library/queue/databus:go_default_library",
"//library/queue/databus/databusutil:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/BurntSushi/toml:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,150 @@
package conf
import (
"errors"
"flag"
"go-common/library/cache/memcache"
"go-common/library/conf"
"go-common/library/database/sql"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/trace"
"go-common/library/queue/databus"
"go-common/library/queue/databus/databusutil"
xtime "go-common/library/time"
"github.com/BurntSushi/toml"
)
var (
confPath string
// Conf conf.
Conf = &Config{}
client *conf.Client
)
// Config config.
type Config struct {
// log
Xlog *log.Config
// Tracer tracer
Tracer *trace.Config
// http
BM *bm.ServerConfig
// Database
DB *DB
// mc
Memcache *Memcache
//Databus databus
DataBus *DataBus
// DataUtil config
DatabusUtil *databusutil.Config
// IncSync
IncSync *IncSync
// FullSync
FullSync *FullSync
// Scheduler
Scheduler *Scheduler
}
// DB db config
type DB struct {
OriginDB *sql.Config
UserDB *sql.Config
EncryptDB *sql.Config
}
// Memcache memcache
type Memcache struct {
*memcache.Config
Expire xtime.Duration
}
// DataBus databus.
type DataBus struct {
AsoBinLogSub *databus.Config
}
// IncSync increment sync
type IncSync struct {
Switch bool
}
// FullSync full sync
type FullSync struct {
AsoCountryCodeSwitch bool
AsoAccount *SyncConf
AsoAccountInfo *SyncConf
AsoAccountReg *SyncConf
AsoAccountSns *SyncConf
AsoTelBindLog *SyncConf
}
// SyncConf sync conf
type SyncConf struct {
Switch bool
ChanNum int
ChanSize int
Start int64
End int64
Count int64
}
// Scheduler scheduler
type Scheduler struct {
Switch bool
TelDuplicateCron string
EmailDuplicateCron string
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init init config.
func Init() (err error) {
if confPath != "" {
return local()
}
return remote()
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
go func() {
for range client.Event() {
log.Info("config reload")
if load() != nil {
log.Error("config reload error (%v)", err)
}
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf = &Config{}
)
if s, ok = client.Toml2(); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}

View File

@@ -0,0 +1,58 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"duplicate.go",
"mc.go",
"mysql.go",
"user.go",
],
importpath = "go-common/app/job/main/passport-user/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/passport-user/conf:go_default_library",
"//app/job/main/passport-user/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = [
"dao_test.go",
"mc_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/job/main/passport-user/conf:go_default_library",
"//app/job/main/passport-user/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)

View File

@@ -0,0 +1,73 @@
package dao
import (
"context"
"time"
"go-common/app/job/main/passport-user/conf"
"go-common/library/cache/memcache"
"go-common/library/database/sql"
"go-common/library/log"
)
// Dao dao
type Dao struct {
c *conf.Config
originDB *sql.DB
userDB *sql.DB
encryptDB *sql.DB
mc *memcache.Pool
mcExpire int32
}
// New new dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
originDB: sql.NewMySQL(c.DB.OriginDB),
userDB: sql.NewMySQL(c.DB.UserDB),
encryptDB: sql.NewMySQL(c.DB.EncryptDB),
mc: memcache.NewPool(c.Memcache.Config),
mcExpire: int32(time.Duration(c.Memcache.Expire) / time.Second),
}
return
}
// Ping check dao ok.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.originDB.Ping(c); err != nil {
log.Info("dao.originDB.Ping() error(%v)", err)
}
if err = d.userDB.Ping(c); err != nil {
log.Info("dao.userDB.Ping() error(%v)", err)
}
if err = d.encryptDB.Ping(c); err != nil {
log.Info("dao.encryptDB.Ping() error(%v)", err)
}
if err = d.pingMC(c); err != nil {
log.Info("d.pingMC() error(%v)", err)
}
return
}
// Close close connections of mc, cloudDB.
func (d *Dao) Close() (err error) {
if d.originDB != nil {
d.originDB.Close()
}
if d.userDB != nil {
d.userDB.Close()
}
if d.encryptDB != nil {
d.encryptDB.Close()
}
if d.mc != nil {
d.mc.Close()
}
return
}
// BeginTran begin transcation.
func (d *Dao) BeginTran(c context.Context) (tx *sql.Tx, err error) {
return d.userDB.Begin(c)
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"flag"
"os"
"testing"
"go-common/app/job/main/passport-user/conf"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.passport.passport-user-job")
flag.Set("conf_token", "975fc031e0cc0b9b2825dd0d7f73b55b")
flag.Set("tree_id", "60684")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/passport-user-job.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
os.Exit(m.Run())
}

View File

@@ -0,0 +1,99 @@
package dao
import (
"context"
"database/sql"
"go-common/app/job/main/passport-user/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_addUserTelDuplicateSQL = "INSERT INTO user_tel_duplicate (mid,tel,cid,tel_bind_time,ts) VALUES (?,?,?,?,?)"
_addUserEmailDuplicateSQL = "INSERT INTO user_email_duplicate (mid,email,verified,email_bind_time,ts) VALUES (?,?,?,?,?)"
_getUserTelDuplicateSQL = "SELECT id,mid,tel,cid,tel_bind_time,status,ts FROM user_tel_duplicate WHERE status = 0 order by ts"
_getUserEmailDuplicateSQL = "SELECT id,mid,email,verified,email_bind_time,status,ts FROM user_email_duplicate WHERE status = 0 order by ts"
_updateTelDuplicateStatusSQL = "UPDATE user_tel_duplicate SET status = 1 WHERE id = ?"
_updateEmailDuplicateStatusSQL = "UPDATE user_email_duplicate SET status = 1 WHERE id = ?"
)
// AddUserTelDuplicate add user tel duplicate.
func (d *Dao) AddUserTelDuplicate(c context.Context, a *model.UserTelDuplicate) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _addUserTelDuplicateSQL, a.Mid, a.Tel, a.Cid, a.TelBindTime, a.Timestamp); err != nil {
log.Error("fail to add user tel duplicate, userTelDuplicate(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// AddUserEmailDuplicate add user email duplicate.
func (d *Dao) AddUserEmailDuplicate(c context.Context, a *model.UserEmailDuplicate) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _addUserEmailDuplicateSQL, a.Mid, a.Email, a.Verified, a.EmailBindTime, a.Timestamp); err != nil {
log.Error("fail to add user email duplicate, userEmailDuplicate(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UserTelDuplicate get user tel duplicate.
func (d *Dao) UserTelDuplicate(c context.Context) (res []*model.UserTelDuplicate, err error) {
var rows *xsql.Rows
if rows, err = d.userDB.Query(c, _getUserTelDuplicateSQL); err != nil {
log.Error("fail to get UserTelDuplicate, dao.userDB.Query(%s) error(%v)", _getUserTelDuplicateSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.UserTelDuplicate)
if err = rows.Scan(&r.ID, &r.Mid, &r.Tel, &r.Cid, &r.TelBindTime, &r.Status, &r.Timestamp); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// UserEmailDuplicate get user email duplicate.
func (d *Dao) UserEmailDuplicate(c context.Context) (res []*model.UserEmailDuplicate, err error) {
var rows *xsql.Rows
if rows, err = d.userDB.Query(c, _getUserEmailDuplicateSQL); err != nil {
log.Error("fail to get UserEmailDuplicate, dao.userDB.Query(%s) error(%v)", _getUserEmailDuplicateSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.UserEmailDuplicate)
if err = rows.Scan(&r.ID, &r.Mid, &r.Email, &r.Verified, &r.EmailBindTime, &r.Status, &r.Timestamp); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// UpdateUserTelDuplicateStatus update user tel duplicate status.
func (d *Dao) UpdateUserTelDuplicateStatus(c context.Context, id int64) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateTelDuplicateStatusSQL, id); err != nil {
log.Error("fail to update tel duplicate status, id(%d) dao.userDB.Exec() error(%+v)", id, err)
return
}
return res.RowsAffected()
}
// UpdateUserEmailDuplicateStatus update user email duplicate status.
func (d *Dao) UpdateUserEmailDuplicateStatus(c context.Context, id int64) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateEmailDuplicateStatusSQL, id); err != nil {
log.Error("fail to update email duplicate status, id(%d) dao.userDB.Exec() error(%+v)", id, err)
return
}
return res.RowsAffected()
}

View File

@@ -0,0 +1,206 @@
package dao
import (
"context"
"fmt"
"go-common/app/job/main/passport-user/model"
"go-common/library/cache/memcache"
"go-common/library/log"
)
func ubKey(mid int64) string {
return fmt.Sprintf("ub_%d", mid)
}
func utKey(mid int64) string {
return fmt.Sprintf("ut_%d", mid)
}
func ueKey(mid int64) string {
return fmt.Sprintf("ue_%d", mid)
}
func uroKey(mid int64) string {
return fmt.Sprintf("uro_%d", mid)
}
func usqKey(mid int64) string {
return fmt.Sprintf("usq_%d", mid)
}
func qqKey(mid int64) string {
return fmt.Sprintf("utb_qq_%d", mid)
}
func sinaKey(mid int64) string {
return fmt.Sprintf("utb_sina_%d", mid)
}
// SetUserBaseCache set user base to cache
func (d *Dao) SetUserBaseCache(c context.Context, ub *model.UserBase) (err error) {
key := ubKey(ub.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: ub.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user base to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// SetUserTelCache set user tel to cache
func (d *Dao) SetUserTelCache(c context.Context, ut *model.UserTel) (err error) {
key := utKey(ut.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: ut.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user tel to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// SetUserEmailCache set user email to cache
func (d *Dao) SetUserEmailCache(c context.Context, ue *model.UserEmail) (err error) {
key := ueKey(ue.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: ue.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user email to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// SetUserRegOriginCache set user reg origin to cache
func (d *Dao) SetUserRegOriginCache(c context.Context, uro *model.UserRegOrigin) (err error) {
key := uroKey(uro.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: uro.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user reg origin to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// SetUserSafeQuestionCache set user safe question to cache
func (d *Dao) SetUserSafeQuestionCache(c context.Context, usq *model.UserSafeQuestion) (err error) {
key := usqKey(usq.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: usq.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user safe question to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// SetUserThirdBindQQCache set user third bind qq to cache
func (d *Dao) SetUserThirdBindQQCache(c context.Context, utb *model.UserThirdBind) (err error) {
key := qqKey(utb.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: utb.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user third bind qq to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// SetUserThirdBindSinaCache set user third bind sina to cache
func (d *Dao) SetUserThirdBindSinaCache(c context.Context, utb *model.UserThirdBind) (err error) {
key := sinaKey(utb.Mid)
conn := d.mc.Get(c)
defer conn.Close()
item := &memcache.Item{Key: key, Object: utb.ConvertToProto(), Flags: memcache.FlagProtobuf, Expiration: d.mcExpire}
if err = conn.Set(item); err != nil {
log.Error("fail to set user third bind sina to mc, key(%s) expire(%d) error(%+v)", key, d.mcExpire, err)
}
return
}
// DelUserBaseCache del user base cache
func (d *Dao) DelUserBaseCache(c context.Context, mid int64) (err error) {
key := ubKey(mid)
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("fail to del user base cache, key(%s) error(%+v)", key, err)
}
return
}
// DelUserTelCache del user tel cache
func (d *Dao) DelUserTelCache(c context.Context, mid int64) (err error) {
key := utKey(mid)
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("fail to del user tel cache, key(%s) error(%+v)", key, err)
}
return
}
// DelUserEmailCache del user email cache
func (d *Dao) DelUserEmailCache(c context.Context, mid int64) (err error) {
key := ueKey(mid)
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("fail to del user email cache, key(%s) error(%+v)", key, err)
}
return
}
// DelUserThirdBindQQCache del user third bind qq cache
func (d *Dao) DelUserThirdBindQQCache(c context.Context, mid int64) (err error) {
key := qqKey(mid)
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("fail to del user third bind qq cache, key(%s) error(%+v)", key, err)
}
return
}
// DelUserThirdBindSinaCache del user third bind sina cache
func (d *Dao) DelUserThirdBindSinaCache(c context.Context, mid int64) (err error) {
key := sinaKey(mid)
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("fail to del user third bind sina cache, key(%s) error(%+v)", key, err)
}
return
}
// pingMC
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mc.Get(c)
item := memcache.Item{Key: "ping", Value: []byte{1}, Expiration: d.mcExpire}
err = conn.Set(&item)
conn.Close()
return
}

View File

@@ -0,0 +1,272 @@
package dao
import (
"context"
"testing"
"go-common/app/job/main/passport-user/model"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoubKey(t *testing.T) {
convey.Convey("ubKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := ubKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoutKey(t *testing.T) {
convey.Convey("utKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := utKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoueKey(t *testing.T) {
convey.Convey("ueKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := ueKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaouroKey(t *testing.T) {
convey.Convey("uroKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := uroKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaousqKey(t *testing.T) {
convey.Convey("usqKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := usqKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoqqKey(t *testing.T) {
convey.Convey("qqKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := qqKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaosinaKey(t *testing.T) {
convey.Convey("sinaKey", t, func(ctx convey.C) {
var (
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := sinaKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSetUserBaseCache(t *testing.T) {
convey.Convey("SetUserBaseCache", t, func(ctx convey.C) {
var (
c = context.Background()
ub = &model.UserBase{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserBaseCache(c, ub)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserTelCache(t *testing.T) {
convey.Convey("SetUserTelCache", t, func(ctx convey.C) {
var (
c = context.Background()
ut = &model.UserTel{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserTelCache(c, ut)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserEmailCache(t *testing.T) {
convey.Convey("SetUserEmailCache", t, func(ctx convey.C) {
var (
c = context.Background()
ue = &model.UserEmail{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserEmailCache(c, ue)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserRegOriginCache(t *testing.T) {
convey.Convey("SetUserRegOriginCache", t, func(ctx convey.C) {
var (
c = context.Background()
uro = &model.UserRegOrigin{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserRegOriginCache(c, uro)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserSafeQuestionCache(t *testing.T) {
convey.Convey("SetUserSafeQuestionCache", t, func(ctx convey.C) {
var (
c = context.Background()
usq = &model.UserSafeQuestion{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserSafeQuestionCache(c, usq)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserThirdBindQQCache(t *testing.T) {
convey.Convey("SetUserThirdBindQQCache", t, func(ctx convey.C) {
var (
c = context.Background()
utb = &model.UserThirdBind{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserThirdBindQQCache(c, utb)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserThirdBindSinaCache(t *testing.T) {
convey.Convey("SetUserThirdBindSinaCache", t, func(ctx convey.C) {
var (
c = context.Background()
utb = &model.UserThirdBind{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserThirdBindSinaCache(c, utb)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelUserBaseCache(t *testing.T) {
convey.Convey("DelUserBaseCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelUserBaseCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelUserTelCache(t *testing.T) {
convey.Convey("DelUserTelCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelUserTelCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelUserEmailCache(t *testing.T) {
convey.Convey("DelUserEmailCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelUserEmailCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaopingMC(t *testing.T) {
convey.Convey("pingMC", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.pingMC(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,203 @@
package dao
import (
"context"
"fmt"
"strings"
"go-common/app/job/main/passport-user/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_getOriginAccountSQL = "SELECT mid,userid,uname,pwd,salt,email,tel,mobile_verified,isleak,country_id,modify_time FROM aso_account WHERE mid > ? limit ?"
_getOriginAccountInfoSQL = "SELECT id,mid,spacesta,safe_question,safe_answer,join_time,join_ip,join_ip_v6,port,active_time,modify_time FROM aso_account_info%d WHERE id > ? limit ?"
_getOriginAccountRegSQL = "SELECT id,mid,origintype,regtype,appid,ctime,mtime FROM aso_account_reg_origin_%d WHERE id > ? limit ?"
_getOriginAccountSnsSQL = "SELECT mid,sina_uid,sina_access_token,sina_access_expires,qq_openid,qq_access_token,qq_access_expires FROM aso_account_sns WHERE mid > ? limit ?"
_getOriginCountryCodeSQL = "SELECT id,code,cname,rank,type,ename FROM aso_country_code"
_getOriginTelBindLogSQL = "SELECT timestamp FROM aso_telephone_bind_log WHERE mid = ? order by timestamp limit 1"
_getOriginAccountByMidSQL = "SELECT mid,userid,uname,pwd,salt,email,tel,mobile_verified,isleak,country_id,modify_time FROM aso_account WHERE mid = ?"
_getOriginAccountSnsByMidSQL = "SELECT mid,sina_uid,sina_access_token,sina_access_expires,qq_openid,qq_access_token,qq_access_expires FROM aso_account_sns WHERE mid = ?"
_getOriginAccountInfoByMidSQL = "SELECT id,mid,spacesta,safe_question,safe_answer,join_time,join_ip,join_ip_v6,port,active_time,modify_time FROM aso_account_info%d WHERE mid = ?"
_getOriginAccountRegByMidSQL = "SELECT id,mid,origintype,regtype,appid,ctime,mtime FROM aso_account_reg_origin_%d WHERE mid = ?"
)
// AsoAccount get account by mid.
func (d *Dao) AsoAccount(c context.Context, start, count int64) (res []*model.OriginAccount, err error) {
var rows *xsql.Rows
if rows, err = d.originDB.Query(c, _getOriginAccountSQL, start, count); err != nil {
log.Error("fail to get AsoAccount, dao.originDB.Query(%s) error(%v)", _getOriginAccountSQL, err)
return
}
defer rows.Close()
for rows.Next() {
var telPtr, emailPtr *string
r := new(model.OriginAccount)
if err = rows.Scan(&r.Mid, &r.UserID, &r.Uname, &r.Pwd, &r.Salt, &emailPtr, &telPtr, &r.MobileVerified, &r.Isleak, &r.CountryID, &r.MTime); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
if telPtr != nil {
r.Tel = *telPtr
}
if emailPtr != nil {
r.Email = strings.ToLower(*emailPtr)
}
res = append(res, r)
}
return
}
// AsoAccountInfo get account info by id.
func (d *Dao) AsoAccountInfo(c context.Context, start, count, suffix int64) (res []*model.OriginAccountInfo, err error) {
var rows *xsql.Rows
if rows, err = d.originDB.Query(c, fmt.Sprintf(_getOriginAccountInfoSQL, suffix), start, count); err != nil {
log.Error("fail to get AsoAccountInfo, dao.originDB.Query(%s) error(%v)", _getOriginAccountInfoSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.OriginAccountInfo)
if err = rows.Scan(&r.ID, &r.Mid, &r.Spacesta, &r.SafeQuestion, &r.SafeAnswer, &r.JoinTime, &r.JoinIP, &r.JoinIPV6, &r.Port, &r.ActiveTime, &r.MTime); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// AsoAccountReg get account reg by id.
func (d *Dao) AsoAccountReg(c context.Context, start, count, suffix int64) (res []*model.OriginAccountReg, err error) {
var rows *xsql.Rows
if rows, err = d.originDB.Query(c, fmt.Sprintf(_getOriginAccountRegSQL, suffix), start, count); err != nil {
log.Error("fail to get AsoAccountReg, dao.originDB.Query(%s) error(%v)", _getOriginAccountRegSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.OriginAccountReg)
if err = rows.Scan(&r.ID, &r.Mid, &r.OriginType, &r.RegType, &r.AppID, &r.CTime, &r.MTime); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// AsoAccountSns get account sns by id.
func (d *Dao) AsoAccountSns(c context.Context, start, count int64) (res []*model.OriginAccountSns, err error) {
var rows *xsql.Rows
if rows, err = d.originDB.Query(c, _getOriginAccountSnsSQL, start, count); err != nil {
log.Error("fail to get AsoAccountSns, dao.originDB.Query(%s) error(%v)", _getOriginAccountSnsSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.OriginAccountSns)
if err = rows.Scan(&r.Mid, &r.SinaUID, &r.SinaAccessToken, &r.SinaAccessExpires, &r.QQOpenid, &r.QQAccessToken, &r.QQAccessExpires); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// AsoCountryCode get aso country code.
func (d *Dao) AsoCountryCode(c context.Context) (res []*model.CountryCode, err error) {
var rows *xsql.Rows
if rows, err = d.originDB.Query(c, _getOriginCountryCodeSQL); err != nil {
log.Error("fail to get AsoCountryCode, dao.originDB.Query(%s) error(%v)", _getOriginCountryCodeSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.CountryCode)
if err = rows.Scan(&r.ID, &r.Code, &r.Cname, &r.Rank, &r.Type, &r.Ename); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// AsoTelBindLog get aso tel bind log.
func (d *Dao) AsoTelBindLog(c context.Context, mid int64) (res int64, err error) {
if err = d.originDB.QueryRow(c, _getOriginTelBindLogSQL, mid).Scan(&res); err != nil {
if err == xsql.ErrNoRows {
err = nil
} else {
log.Error("fail to get AsoTelBindLog, dao.originDB.QueryRow(%s) error(%v)", _getOriginTelBindLogSQL, err)
}
return
}
return
}
// GetAsoAccountByMid get aso account by mid.
func (d *Dao) GetAsoAccountByMid(c context.Context, mid int64) (res *model.OriginAccount, err error) {
row := d.originDB.QueryRow(c, _getOriginAccountByMidSQL, mid)
var telPtr, emailPtr *string
res = &model.OriginAccount{}
if err = row.Scan(&res.Mid, &res.UserID, &res.Uname, &res.Pwd, &res.Salt, &emailPtr, &telPtr, &res.MobileVerified, &res.Isleak, &res.CountryID, &res.MTime); err != nil {
log.Error("fail to get AsoAccount, dao.originDB.QueryRow(%s) error(%v)", _getOriginAccountByMidSQL, err)
return
}
if telPtr != nil {
res.Tel = *telPtr
}
if emailPtr != nil {
res.Email = strings.ToLower(*emailPtr)
}
return
}
// GetAsoAccountSnsByMid get aso account sns by mid.
func (d *Dao) GetAsoAccountSnsByMid(c context.Context, mid int64) (res *model.OriginAccountSns, err error) {
row := d.originDB.QueryRow(c, _getOriginAccountSnsByMidSQL, mid)
res = &model.OriginAccountSns{}
if err = row.Scan(&res.Mid, &res.SinaUID, &res.SinaAccessToken, &res.SinaAccessExpires, &res.QQOpenid, &res.QQAccessToken, &res.QQAccessExpires); err != nil {
log.Error("fail to get AsoAccountSns, dao.originDB.QueryRow(%s) error(%v)", _getOriginAccountSnsByMidSQL, err)
return
}
return
}
// GetAsoAccountInfoByMid get aso account info by mid.
func (d *Dao) GetAsoAccountInfoByMid(c context.Context, mid int64) (res *model.OriginAccountInfo, err error) {
row := d.originDB.QueryRow(c, fmt.Sprintf(_getOriginAccountInfoByMidSQL, accountInfoIndex(mid)), mid)
res = &model.OriginAccountInfo{}
if err = row.Scan(&res.ID, &res.Mid, &res.Spacesta, &res.SafeQuestion, &res.SafeAnswer, &res.JoinTime, &res.JoinIP, &res.JoinIPV6, &res.Port, &res.ActiveTime, &res.MTime); err != nil {
log.Error("fail to get AsoAccountInfo, dao.originDB.QueryRow(%s) error(%v)", _getOriginAccountInfoByMidSQL, err)
return
}
return
}
// GetAsoAccountRegByMid get aso account reg by mid.
func (d *Dao) GetAsoAccountRegByMid(c context.Context, mid int64) (res *model.OriginAccountReg, err error) {
row := d.originDB.QueryRow(c, fmt.Sprintf(_getOriginAccountRegByMidSQL, accountRegIndex(mid)), mid)
res = &model.OriginAccountReg{}
if err = row.Scan(&res.ID, &res.Mid, &res.OriginType, &res.RegType, &res.AppID, &res.CTime, &res.MTime); err != nil {
log.Error("fail to get AsoAccountReg, dao.originDB.QueryRow(%s) error(%v)", _getOriginAccountRegByMidSQL, err)
return
}
return
}
func accountInfoIndex(mid int64) int64 {
return mid % 30
}
func accountRegIndex(mid int64) int64 {
return mid % 20
}

View File

@@ -0,0 +1,654 @@
package dao
import (
"context"
"database/sql"
"fmt"
"go-common/app/job/main/passport-user/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
)
const (
_addCountryCodeSQL = "INSERT INTO country_code (id,code,cname,rank,type,ename) VALUES(?,?,?,?,?,?)"
_getAesKeySQL = "SELECT `key` FROM user_secret WHERE key_type = 2"
_getSaltSQL = "SELECT `key` FROM user_secret WHERE key_type = 3"
_getCountryCodeMapSQL = "SELECT id,code FROM country_code"
_getUserTelSQL = "SELECT mid FROM user_tel WHERE mid > ? limit ?"
_getUserEmailByMidSQL = "SELECT mid,email,verified,email_bind_time,ctime,mtime FROM user_email WHERE mid = ?"
_getUserTelByMidSQL = "SELECT mid,tel,cid,tel_bind_time,ctime,mtime FROM user_tel WHERE mid = ?"
_addUserBaseSQL = "INSERT INTO user_base (mid,userid,pwd,salt,status,deleted,mtime) VALUES(?,?,?,?,?,?,?)"
_addUserEmailSQL = "INSERT INTO user_email (mid,email,verified,email_bind_time,mtime) VALUES(?,?,?,?,?)"
_addUserTelSQL = "INSERT INTO user_tel (mid,tel,cid,tel_bind_time,mtime) VALUES(?,?,?,?,?)"
_addUserSafeQuestionSQL = "INSERT INTO user_safe_question%02d (mid,safe_question,safe_answer,safe_bind_time) VALUES(?,?,?,?)"
_addUserThirdBindSQL = "INSERT INTO user_third_bind (mid,openid,platform,token,expires) VALUES(?,?,?,?,?)"
_updateUserBaseSQL = "UPDATE user_base SET userid=?,pwd=?,salt=?,status=? WHERE mid =?"
_updateUserEmailSQL = "UPDATE user_email SET email=? WHERE mid =?"
_updateUserEmailAndBindTimeSQL = "UPDATE user_email SET email=?,email_bind_time=? WHERE mid =?"
_updateUserTelSQL = "UPDATE user_tel SET tel=?,cid=? WHERE mid =?"
_updateUserTelAndBindTimeSQL = "UPDATE user_tel SET tel=?,cid=?,tel_bind_time=? WHERE mid =?"
_updateUserSafeQuestionSQL = "UPDATE user_safe_question%02d SET safe_question=?,safe_answer=? WHERE mid =?"
_updateUserThirdBindSQL = "UPDATE user_third_bind SET openid=?,token=?,expires=? WHERE mid =? and platform=?"
_updateUserEmailVerifiedSQL = "UPDATE user_email SET verified=? WHERE mid =?"
_updateUserEmailBindTimeSQL = "UPDATE user_email SET verified=?,email_bind_time=? WHERE mid =?"
_updateUserTelBindTimeSQL = "UPDATE user_tel SET tel_bind_time=? WHERE mid =?"
_insertUpdateUserRegOriginSQL = "INSERT INTO user_reg_origin%02d (mid,join_ip,join_ip_v6,port,join_time) VALUES (?,?,?,?,?) ON DUPLICATE KEY UPDATE join_ip=?,join_ip_v6=?,port=?,join_time=?"
_insertUpdateUserRegOriginTypeSQL = "INSERT INTO user_reg_origin%02d (mid,origin,reg_type,appid,ctime,mtime) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE origin=?,reg_type=?,appid=?,ctime=?,mtime=?"
_delUserBase = "UPDATE user_base SET deleted=1 WHERE mid =?"
_delUserTel = "UPDATE user_tel SET tel=null,cid=null WHERE mid =?"
_delUserEmail = "UPDATE user_email SET email=null WHERE mid =?"
_getMidByTelSQL = "SELECT mid FROM user_tel WHERE tel = ? and cid = ?"
_getMidByEmailSQL = "SELECT mid FROM user_email WHERE email = ?"
_getUserBaseByMidSQL = "SELECT mid,userid,pwd,salt,status,ctime,mtime FROM user_base WHERE mid = ?"
_getUserSafeQuestionByMidSQL = "SELECT mid,safe_question,safe_answer,safe_bind_time,ctime,mtime FROM user_safe_question%02d where mid = ?"
_getUserThirdBindByMidSQL = "SELECT id,mid,openid,platform,token,expires,ctime,mtime FROM user_third_bind where mid = ?"
_getUserThirdBindByMidAndPlatformSQL = "SELECT id,mid,openid,platform,token,expires,ctime,mtime FROM user_third_bind where mid = ? and platform = ? limit 1"
_getUserRegOriginByMidSQL = "SELECT mid,join_ip,join_ip_v6,port,join_time,origin,reg_type,appid from user_reg_origin%02d where mid = ?"
_insertUpdateUserBaseSQL = "INSERT INTO user_base (mid,userid,pwd,salt,status,deleted,mtime) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE userid=?,pwd=?,salt=?,status=?"
_insertIgnoreUserSafeQuestionSQL = "INSERT IGNORE INTO user_safe_question%02d (mid,safe_question,safe_answer,safe_bind_time) VALUES(?,?,?,?)"
_insertIgnoreUserRegOriginSQL = "INSERT IGNORE INTO user_reg_origin%02d (mid,join_ip,join_ip_v6,port,join_time) VALUES (?,?,?,?,?)"
_delUserThirdBindSQL = "UPDATE user_third_bind SET openid='',token='',expires=0 WHERE mid =?"
)
// AddCountryCode add country code.
func (d *Dao) AddCountryCode(c context.Context, a *model.CountryCode) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _addCountryCodeSQL, a.ID, a.Code, a.Cname, a.Rank, a.Type, a.Ename); err != nil {
log.Error("fail to add country code, countryCode(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// AesKey get aes key.
func (d *Dao) AesKey(c context.Context) (res string, err error) {
if err = d.encryptDB.QueryRow(c, _getAesKeySQL).Scan(&res); err != nil {
log.Error("fail to get AesKey, dao.encryptDB.QueryRow(%s) error(%v)", _getAesKeySQL, err)
return
}
return
}
// Salt get salt.
func (d *Dao) Salt(c context.Context) (res string, err error) {
if err = d.encryptDB.QueryRow(c, _getSaltSQL).Scan(&res); err != nil {
log.Error("fail to get Salt, dao.encryptDB.QueryRow(%s) error(%v)", _getSaltSQL, err)
return
}
return
}
// UserTel get user tel.
func (d *Dao) UserTel(c context.Context, start, count int64) (res []*model.UserTel, err error) {
var rows *xsql.Rows
if rows, err = d.userDB.Query(c, _getUserTelSQL, start, count); err != nil {
log.Error("fail to get UserTel, dao.userDB.Query(%s) error(%v)", _getUserTelSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.UserTel)
if err = rows.Scan(&r.Mid); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// GetUserEmailByMid get user email by mid.
func (d *Dao) GetUserEmailByMid(c context.Context, mid int64) (res *model.UserEmail, err error) {
res = &model.UserEmail{}
if err = d.userDB.QueryRow(c, _getUserEmailByMidSQL, mid).Scan(&res.Mid, &res.Email, &res.Verified, &res.EmailBindTime, &res.CTime, &res.MTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("fail to get UserEmail by mid(%d), dao.encryptDB.QueryRow(%s) error(%v)", mid, _getUserEmailByMidSQL, err)
}
return
}
return
}
// GetUserTelByMid get user email by mid.
func (d *Dao) GetUserTelByMid(c context.Context, mid int64) (res *model.UserTel, err error) {
var cidPtr *string
res = &model.UserTel{}
if err = d.userDB.QueryRow(c, _getUserTelByMidSQL, mid).Scan(&res.Mid, &res.Tel, &cidPtr, &res.TelBindTime, &res.CTime, &res.MTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("fail to get UserTel by mid(%d), dao.encryptDB.QueryRow(%s) error(%v)", mid, _getUserTelByMidSQL, err)
}
return
}
if cidPtr != nil {
res.Cid = *cidPtr
}
return
}
// AddUserBase add user base.
func (d *Dao) AddUserBase(c context.Context, a *model.UserBase) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _addUserBaseSQL, a.Mid, a.UserID, a.Pwd, a.Salt, a.Status, a.Deleted, a.MTime); err != nil {
log.Error("fail to add user base, userBase(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxAddUserBase add user base.
func (d *Dao) TxAddUserBase(tx *xsql.Tx, a *model.UserBase) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_addUserBaseSQL, a.Mid, a.UserID, a.Pwd, a.Salt, a.Status, a.Deleted, a.MTime); err != nil {
log.Error("fail to add user base, userBase(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// AddUserEmail add user email.
func (d *Dao) AddUserEmail(c context.Context, a *model.UserEmail) (affected int64, err error) {
var (
res sql.Result
emailPtr *[]byte
)
if len(a.Email) != 0 {
emailPtr = &a.Email
}
if res, err = d.userDB.Exec(c, _addUserEmailSQL, a.Mid, emailPtr, a.Verified, a.EmailBindTime, a.MTime); err != nil {
log.Error("fail to add user email, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxAddUserEmail add user email.
func (d *Dao) TxAddUserEmail(tx *xsql.Tx, a *model.UserEmail) (affected int64, err error) {
var (
res sql.Result
emailPtr *[]byte
)
if len(a.Email) != 0 {
emailPtr = &a.Email
}
if res, err = tx.Exec(_addUserEmailSQL, a.Mid, emailPtr, a.Verified, a.EmailBindTime, a.MTime); err != nil {
log.Error("fail to add user email, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// AddUserTel add user tel.
func (d *Dao) AddUserTel(c context.Context, a *model.UserTel) (affected int64, err error) {
var (
res sql.Result
telPtr *[]byte
cidPtr *string
)
if len(a.Tel) != 0 {
telPtr = &a.Tel
cidPtr = &a.Cid
}
if res, err = d.userDB.Exec(c, _addUserTelSQL, a.Mid, telPtr, cidPtr, a.TelBindTime, a.MTime); err != nil {
log.Error("fail to add user tel, userTel(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxAddUserTel add user tel.
func (d *Dao) TxAddUserTel(tx *xsql.Tx, a *model.UserTel) (affected int64, err error) {
var (
res sql.Result
telPtr *[]byte
cidPtr *string
)
if len(a.Tel) != 0 {
telPtr = &a.Tel
cidPtr = &a.Cid
}
if res, err = tx.Exec(_addUserTelSQL, a.Mid, telPtr, cidPtr, a.TelBindTime, a.MTime); err != nil {
log.Error("fail to add user tel, userTel(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// AddUserSafeQuestion add user safe question.
func (d *Dao) AddUserSafeQuestion(c context.Context, a *model.UserSafeQuestion) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, fmt.Sprintf(_addUserSafeQuestionSQL, tableIndex(a.Mid)), a.Mid, a.SafeQuestion, a.SafeAnswer, a.SafeBindTime); err != nil {
log.Error("fail to add user safe question, userSafeQuestion(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxAddUserSafeQuestion add user safe question.
func (d *Dao) TxAddUserSafeQuestion(tx *xsql.Tx, a *model.UserSafeQuestion) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(fmt.Sprintf(_addUserSafeQuestionSQL, tableIndex(a.Mid)), a.Mid, a.SafeQuestion, a.SafeAnswer, a.SafeBindTime); err != nil {
log.Error("fail to add user safe question, userSafeQuestion(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// AddUserThirdBind add user third bind.
func (d *Dao) AddUserThirdBind(c context.Context, a *model.UserThirdBind) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _addUserThirdBindSQL, a.Mid, a.OpenID, a.PlatForm, a.Token, a.Expires); err != nil {
log.Error("fail to add user third bind, userThirdBind(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxAddUserThirdBind add user third bind.
func (d *Dao) TxAddUserThirdBind(tx *xsql.Tx, a *model.UserThirdBind) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_addUserThirdBindSQL, a.Mid, a.OpenID, a.PlatForm, a.Token, a.Expires); err != nil {
log.Error("fail to add user third bind, userThirdBind(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserBase update user base.
func (d *Dao) UpdateUserBase(c context.Context, a *model.UserBase) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateUserBaseSQL, a.UserID, a.Pwd, a.Salt, a.Status, a.Mid); err != nil {
log.Error("fail to update user base, userBase(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserEmail update user email.
func (d *Dao) UpdateUserEmail(c context.Context, a *model.UserEmail) (affected int64, err error) {
var (
res sql.Result
emailPtr *[]byte
)
if len(a.Email) != 0 {
emailPtr = &a.Email
}
if res, err = d.userDB.Exec(c, _updateUserEmailSQL, emailPtr, a.Mid); err != nil {
log.Error("fail to update user email, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserEmailAndBindTime update user email and bind time.
func (d *Dao) UpdateUserEmailAndBindTime(c context.Context, a *model.UserEmail) (affected int64, err error) {
var (
res sql.Result
emailPtr *[]byte
)
if len(a.Email) != 0 {
emailPtr = &a.Email
}
if res, err = d.userDB.Exec(c, _updateUserEmailAndBindTimeSQL, emailPtr, a.EmailBindTime, a.Mid); err != nil {
log.Error("fail to update user email and bind time, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxUpdateUserEmail update user email.
func (d *Dao) TxUpdateUserEmail(tx *xsql.Tx, a *model.UserEmail) (affected int64, err error) {
var (
res sql.Result
emailPtr *[]byte
)
if len(a.Email) != 0 {
emailPtr = &a.Email
}
if res, err = tx.Exec(_updateUserEmailSQL, emailPtr, a.Mid); err != nil {
log.Error("fail to update user email, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserTel update user tel.
func (d *Dao) UpdateUserTel(c context.Context, a *model.UserTel) (affected int64, err error) {
var (
res sql.Result
telPtr *[]byte
cidPtr *string
)
if len(a.Tel) != 0 {
telPtr = &a.Tel
cidPtr = &a.Cid
}
if res, err = d.userDB.Exec(c, _updateUserTelSQL, telPtr, cidPtr, a.Mid); err != nil {
log.Error("fail to update user tel, userTel(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserTelAndBindTime update user tel and bind time.
func (d *Dao) UpdateUserTelAndBindTime(c context.Context, a *model.UserTel) (affected int64, err error) {
var (
res sql.Result
telPtr *[]byte
cidPtr *string
)
if len(a.Tel) != 0 {
telPtr = &a.Tel
cidPtr = &a.Cid
}
if res, err = d.userDB.Exec(c, _updateUserTelAndBindTimeSQL, telPtr, cidPtr, a.TelBindTime, a.Mid); err != nil {
log.Error("fail to update user tel and bind time, userTel(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserSafeQuesion update user safe question.
func (d *Dao) UpdateUserSafeQuesion(c context.Context, a *model.UserSafeQuestion) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, fmt.Sprintf(_updateUserSafeQuestionSQL, tableIndex(a.Mid)), a.SafeQuestion, a.SafeAnswer, a.Mid); err != nil {
log.Error("fail to update user safe question, userSafeQuestion(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxUpdateUserSafeQuesion update user safe question.
func (d *Dao) TxUpdateUserSafeQuesion(tx *xsql.Tx, a *model.UserSafeQuestion) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(fmt.Sprintf(_updateUserSafeQuestionSQL, tableIndex(a.Mid)), a.SafeQuestion, a.SafeAnswer, a.Mid); err != nil {
log.Error("fail to update user safe question, userSafeQuestion(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserThirdBind update user third bind.
func (d *Dao) UpdateUserThirdBind(c context.Context, a *model.UserThirdBind) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateUserThirdBindSQL, a.OpenID, a.Token, a.Expires, a.Mid, a.PlatForm); err != nil {
log.Error("fail to update user third bind, userThirdBind(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserEmailVerified update user email verified.
func (d *Dao) UpdateUserEmailVerified(c context.Context, a *model.UserEmail) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateUserEmailVerifiedSQL, a.Verified, a.Mid); err != nil {
log.Error("fail to update user email verified, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxUpdateUserEmailVerified update user email verified.
func (d *Dao) TxUpdateUserEmailVerified(tx *xsql.Tx, a *model.UserEmail) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_updateUserEmailVerifiedSQL, a.Verified, a.Mid); err != nil {
log.Error("fail to update user email verified, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserEmailBindTime update user email bind time.
func (d *Dao) UpdateUserEmailBindTime(c context.Context, a *model.UserEmail) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateUserEmailBindTimeSQL, a.Verified, a.EmailBindTime, a.Mid); err != nil {
log.Error("fail to update user email bind time, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxUpdateUserEmailBindTime update user email bind time.
func (d *Dao) TxUpdateUserEmailBindTime(tx *xsql.Tx, a *model.UserEmail) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_updateUserEmailBindTimeSQL, a.Verified, a.EmailBindTime, a.Mid); err != nil {
log.Error("fail to update user email bind time, userEmail(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// UpdateUserTelBindTime update user tel bind time.
func (d *Dao) UpdateUserTelBindTime(c context.Context, a *model.UserTel) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _updateUserTelBindTimeSQL, a.TelBindTime, a.Mid); err != nil {
log.Error("fail to update user tel bind time, userTel(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxDelUserBase update user base deleted = 1.
func (d *Dao) TxDelUserBase(tx *xsql.Tx, mid int64) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_delUserBase, mid); err != nil {
log.Error("fail to del user base, mid(%d) dao.userDB.Exec() error(%+v)", mid, err)
return
}
return res.RowsAffected()
}
// TxDelUserTel update user tel deleted = 1.
func (d *Dao) TxDelUserTel(tx *xsql.Tx, mid int64) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_delUserTel, mid); err != nil {
log.Error("fail to del user tel, mid(%d) dao.userDB.Exec() error(%+v)", mid, err)
return
}
return res.RowsAffected()
}
// TxDelUserEmail update user email deleted = 1.
func (d *Dao) TxDelUserEmail(tx *xsql.Tx, mid int64) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(_delUserEmail, mid); err != nil {
log.Error("fail to del user email, mid(%d) dao.userDB.Exec() error(%+v)", mid, err)
return
}
return res.RowsAffected()
}
// TxInsertUpdateUserRegOrigin insert update user reg origin.
func (d *Dao) TxInsertUpdateUserRegOrigin(tx *xsql.Tx, a *model.UserRegOrigin) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(fmt.Sprintf(_insertUpdateUserRegOriginSQL, tableIndex(a.Mid)), a.Mid, a.JoinIP, a.JoinIPV6, a.Port, a.JoinTime, a.JoinIP, a.JoinIPV6, a.Port, a.JoinTime); err != nil {
log.Error("fail to insert update user reg origin, userRegOrigin(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// InsertUpdateUserRegOriginType insert update user reg origin type.
func (d *Dao) InsertUpdateUserRegOriginType(c context.Context, a *model.UserRegOrigin) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, fmt.Sprintf(_insertUpdateUserRegOriginTypeSQL, tableIndex(a.Mid)), a.Mid, a.Origin, a.RegType, a.AppID, a.CTime, a.MTime,
a.Origin, a.RegType, a.AppID, a.CTime, a.MTime); err != nil {
log.Error("fail to insert update user reg origin type, userRegOrigin(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// CountryCodeMap get country code map.
func (d *Dao) CountryCodeMap(c context.Context) (res map[int64]string, err error) {
var rows *xsql.Rows
if rows, err = d.userDB.Query(c, _getCountryCodeMapSQL); err != nil {
log.Error("fail to get CountryCodeMap, dao.userDB.Query(%s) error(%+v)", _getCountryCodeMapSQL, err)
return
}
defer rows.Close()
res = make(map[int64]string)
for rows.Next() {
var (
id int64
code string
)
if err = rows.Scan(&id, &code); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res[id] = code
}
return
}
// GetMidByTel get mid by tel.
func (d *Dao) GetMidByTel(c context.Context, a *model.UserTel) (mid int64, err error) {
if err = d.userDB.QueryRow(c, _getMidByTelSQL, a.Tel, a.Cid).Scan(&mid); err != nil {
log.Error("fail to get mid by tel, dao.userDB.QueryRow(%s) error(%+v)", _getMidByTelSQL, err)
return
}
return
}
// GetMidByEmail get mid by email.
func (d *Dao) GetMidByEmail(c context.Context, a *model.UserEmail) (mid int64, err error) {
if err = d.userDB.QueryRow(c, _getMidByEmailSQL, a.Email).Scan(&mid); err != nil {
log.Error("fail to get mid by email, dao.userDB.QueryRow(%s) error(%+v)", _getMidByEmailSQL, err)
return
}
return
}
// GetUserBaseByMid get user base by mid.
func (d *Dao) GetUserBaseByMid(c context.Context, mid int64) (res *model.UserBase, err error) {
res = &model.UserBase{}
if err = d.userDB.QueryRow(c, _getUserBaseByMidSQL, mid).Scan(&res.Mid, &res.UserID, &res.Pwd, &res.Salt, &res.Status, &res.CTime, &res.MTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("fail to get UserBase by mid(%d), dao.userDB.QueryRow(%s) error(%+v)", mid, _getUserBaseByMidSQL, err)
}
return
}
return
}
// GetUserSafeQuestionByMid get user safe question by mid.
func (d *Dao) GetUserSafeQuestionByMid(c context.Context, mid int64) (res *model.UserSafeQuestion, err error) {
res = &model.UserSafeQuestion{}
if err = d.userDB.QueryRow(c, fmt.Sprintf(_getUserSafeQuestionByMidSQL, tableIndex(mid)), mid).Scan(&res.Mid, &res.SafeQuestion, &res.SafeAnswer, &res.SafeBindTime, &res.CTime, &res.MTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("fail to get UserSafeQuestion by mid(%d), dao.userDB.QueryRow(%s) error(%+v)", mid, _getUserSafeQuestionByMidSQL, err)
}
return
}
return
}
// GetUserThirdBindByMid get user third bind by mid.
func (d *Dao) GetUserThirdBindByMid(c context.Context, mid int64) (res []*model.UserThirdBind, err error) {
var rows *xsql.Rows
if rows, err = d.userDB.Query(c, _getUserThirdBindByMidSQL, mid); err != nil {
log.Error("fail to get UserThirdBind, dao.userDB.Query(%s) error(%+v)", _getUserThirdBindByMidSQL, err)
return
}
defer rows.Close()
for rows.Next() {
r := new(model.UserThirdBind)
if err = rows.Scan(&r.ID, &r.Mid, &r.OpenID, &r.PlatForm, &r.Token, &r.Expires, &r.CTime, &r.MTime); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
return
}
// GetUserThirdBindByMidAndPlatform get user third bind by mid and platform.
func (d *Dao) GetUserThirdBindByMidAndPlatform(c context.Context, mid, platform int64) (res *model.UserThirdBind, err error) {
res = &model.UserThirdBind{}
if err = d.userDB.QueryRow(c, _getUserThirdBindByMidAndPlatformSQL, mid, platform).Scan(&res.ID, &res.Mid, &res.OpenID, &res.PlatForm, &res.Token, &res.Expires, &res.CTime, &res.MTime); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("fail to get UserSafeQuestion by mid(%d) platform(%d), dao.userDB.QueryRow(%s) error(%+v)", mid, platform, _getUserThirdBindByMidAndPlatformSQL, err)
}
return
}
return
}
// GetUserRegOriginByMid get user reg origin by mid.
func (d *Dao) GetUserRegOriginByMid(c context.Context, mid int64) (res *model.UserRegOrigin, err error) {
res = &model.UserRegOrigin{}
if err = d.userDB.QueryRow(c, fmt.Sprintf(_getUserRegOriginByMidSQL, tableIndex(mid)), mid).Scan(&res.Mid, &res.JoinIP, &res.JoinIPV6, &res.Port, &res.JoinTime, &res.Origin, &res.RegType, &res.AppID); err != nil {
if err == xsql.ErrNoRows {
err = nil
res = nil
} else {
log.Error("fail to get UserRegOrigin by mid(%d), dao.userDB.QueryRow(%s) error(%+v)", mid, _getUserRegOriginByMidSQL, err)
}
return
}
return
}
// InsertUpdateUserBase insert update user base.
func (d *Dao) InsertUpdateUserBase(c context.Context, a *model.UserBase) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _insertUpdateUserBaseSQL, a.Mid, a.UserID, a.Pwd, a.Salt, a.Status, a.Deleted, a.MTime, a.UserID, a.Pwd, a.Salt, a.Status); err != nil {
log.Error("fail to insert update user base, userBase(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxInsertIgnoreUserSafeQuestion insert ignore user safe question.
func (d *Dao) TxInsertIgnoreUserSafeQuestion(tx *xsql.Tx, a *model.UserSafeQuestion) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(fmt.Sprintf(_insertIgnoreUserSafeQuestionSQL, tableIndex(a.Mid)), a.Mid, a.SafeQuestion, a.SafeAnswer, a.SafeBindTime); err != nil {
log.Error("fail to insert ignore user safe question, userSafeQuestion(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// TxInsertIgnoreUserRegOrigin insert ignore user reg origin.
func (d *Dao) TxInsertIgnoreUserRegOrigin(tx *xsql.Tx, a *model.UserRegOrigin) (affected int64, err error) {
var res sql.Result
if res, err = tx.Exec(fmt.Sprintf(_insertIgnoreUserRegOriginSQL, tableIndex(a.Mid)), a.Mid, a.JoinIP, a.JoinIPV6, a.Port, a.JoinTime); err != nil {
log.Error("fail to insert ignore user reg origin, userRegOrigin(%+v) dao.userDB.Exec() error(%+v)", a, err)
return
}
return res.RowsAffected()
}
// DelUserThirdBind del user third bind.
func (d *Dao) DelUserThirdBind(c context.Context, mid int64) (affected int64, err error) {
var res sql.Result
if res, err = d.userDB.Exec(c, _delUserThirdBindSQL, mid); err != nil {
log.Error("fail to del user third bind, mid(%d) dao.userDB.Exec() error(%+v)", mid, err)
return
}
return res.RowsAffected()
}
func tableIndex(mid int64) int64 {
return mid % 100
}

View File

@@ -0,0 +1,32 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["http.go"],
importpath = "go-common/app/job/main/passport-user/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/passport-user/conf:go_default_library",
"//app/job/main/passport-user/service:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,38 @@
package http
import (
"net/http"
"go-common/app/job/main/passport-user/conf"
"go-common/app/job/main/passport-user/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
var (
srv *service.Service
)
// Init init http sever instance.
func Init(c *conf.Config) {
srv = service.New(c)
engine := bm.DefaultServer(c.BM)
innerRouter(engine)
if err := engine.Start(); err != nil {
log.Error("engine.Start() error(%v)", err)
panic(err)
}
}
// innerRouter init inner router.
func innerRouter(e *bm.Engine) {
e.Ping(ping)
}
// ping service
func ping(c *bm.Context) {
if err := srv.Ping(c); err != nil {
log.Error("ping error(%v)", err)
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}

View File

@@ -0,0 +1,56 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"message.go",
"passport.go",
"user.go",
],
embed = [":model_go_proto"],
importpath = "go-common/app/job/main/passport-user/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/time:go_default_library",
"@com_github_gogo_protobuf//gogoproto:go_default_library",
"@com_github_golang_protobuf//proto:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
proto_library(
name = "model_proto",
srcs = ["user.proto"],
tags = ["automanaged"],
deps = ["@gogo_special_proto//github.com/gogo/protobuf/gogoproto"],
)
go_proto_library(
name = "model_go_proto",
compilers = ["@io_bazel_rules_go//proto:gogofast_proto"],
importpath = "go-common/app/job/main/passport-user/model",
proto = ":model_proto",
tags = ["automanaged"],
deps = ["@com_github_gogo_protobuf//gogoproto:go_default_library"],
)

View File

@@ -0,0 +1,12 @@
package model
import "encoding/json"
// BMsg databus binlog message.
type BMsg struct {
Action string `json:"action"`
Table string `json:"table"`
New json.RawMessage `json:"new"`
Old json.RawMessage `json:"old"`
Timestamp int64 `json:"timestamp"`
}

View File

@@ -0,0 +1,65 @@
package model
import "go-common/library/time"
// OriginAccount origin aso account.
type OriginAccount struct {
Mid int64 `json:"mid"`
UserID string `json:"userid"`
Uname string `json:"uname"`
Pwd string `json:"pwd"`
Salt string `json:"salt"`
Email string `json:"email"`
Tel string `json:"tel"`
CountryID int64 `json:"country_id"`
MobileVerified int32 `json:"mobile_verified"`
Isleak int32 `json:"isleak"`
MTime time.Time `json:"-"`
}
// OriginAccountInfo origin aso account info.
type OriginAccountInfo struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Spacesta int32 `json:"spacesta"`
SafeQuestion int32 `json:"safe_question"`
SafeAnswer string `json:"safe_answer"`
JoinTime int64 `json:"join_time"`
JoinIP string `json:"join_ip"`
JoinIPV6 []byte `json:"join_ip_v6"`
Port int32 `json:"port"`
ActiveTime int64 `json:"active_time"`
MTime time.Time `json:"-"`
}
// OriginAccountReg origin aso account reg.
type OriginAccountReg struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
OriginType int32 `json:"origintype"`
RegType int32 `json:"regtype"`
AppID int64 `json:"appid"`
CTime time.Time `json:"-"`
MTime time.Time `json:"-"`
}
// OriginAccountSns origin aso account sns.
type OriginAccountSns struct {
Mid int64 `json:"mid"`
SinaUID int64 `json:"sina_uid"`
SinaAccessToken string `json:"sina_access_token"`
SinaAccessExpires int64 `json:"sina_access_expires"`
QQOpenid string `json:"qq_openid"`
QQAccessToken string `json:"qq_access_token"`
QQAccessExpires int64 `json:"qq_access_expires"`
}
// CountryCode aso country code.
type CountryCode struct {
ID int64 `json:"id"`
Code string `json:"code"`
Cname string `json:"cname"`
Rank int64 `json:"rank"`
Type int8 `json:"type"`
Ename string `json:"ename"`
}

View File

@@ -0,0 +1,7 @@
#! /bin/sh
# proto.sh
gopath=$GOPATH/src
gogopath=$GOPATH/src/go-common/vendor/github.com/gogo/protobuf
protoc --gofast_out=. --proto_path=$gopath:$gogopath:. *.proto

View File

@@ -0,0 +1,160 @@
package model
import "go-common/library/time"
// UserBase user base.
type UserBase struct {
Mid int64 `json:"mid"`
UserID string `json:"userid"`
Pwd []byte `json:"pwd"`
Salt string `json:"salt"`
Status int32 `json:"status"`
Deleted int8 `json:"deleted"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// UserEmail user email.
type UserEmail struct {
Mid int64 `json:"mid"`
Email []byte `json:"email"`
Verified int32 `json:"verified"`
EmailBindTime int64 `json:"email_bind_time"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// UserTel user tel.
type UserTel struct {
Mid int64 `json:"mid"`
Tel []byte `json:"tel"`
Cid string `json:"cid"`
TelBindTime int64 `json:"tel_bind_time"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// UserRegOrigin user reg origin.
type UserRegOrigin struct {
Mid int64 `json:"mid"`
JoinIP int64 `json:"join_ip"`
JoinIPV6 []byte `json:"join_ip_v6"`
Port int32 `json:"port"`
JoinTime int64 `json:"join_time"`
Origin int32 `json:"origin"`
RegType int32 `json:"reg_type"`
AppID int64 `json:"appid"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// UserSafeQuestion user safe question.
type UserSafeQuestion struct {
Mid int64 `json:"mid"`
SafeQuestion int32 `json:"safe_question"`
SafeAnswer []byte `json:"safe_answer"`
SafeBindTime int64 `json:"safe_bind_time"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// UserThirdBind user third bind.
type UserThirdBind struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
OpenID string `json:"openid"`
PlatForm int64 `json:"platform"`
Token string `json:"token"`
Expires int64 `json:"expires"`
CTime time.Time `json:"ctime"`
MTime time.Time `json:"mtime"`
}
// UserTelDuplicate user tel duplicate.
type UserTelDuplicate struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Tel []byte `json:"tel"`
Cid string `json:"cid"`
TelBindTime int64 `json:"tel_bind_time"`
Status int8 `json:"status"`
Timestamp int64 `json:"ts"`
}
// UserEmailDuplicate user email duplicate.
type UserEmailDuplicate struct {
ID int64 `json:"id"`
Mid int64 `json:"mid"`
Email []byte `json:"email"`
Verified int32 `json:"verified"`
EmailBindTime int64 `json:"email_bind_time"`
Status int8 `json:"status"`
Timestamp int64 `json:"ts"`
}
// ConvertToProto convert to proto
func (u *UserBase) ConvertToProto() *UserBaseProto {
return &UserBaseProto{
Mid: u.Mid,
UserID: u.UserID,
Pwd: u.Pwd,
Salt: u.Salt,
Status: u.Status,
}
}
// ConvertToProto convert to proto
func (u *UserTel) ConvertToProto() *UserTelProto {
return &UserTelProto{
Mid: u.Mid,
Tel: u.Tel,
Cid: u.Cid,
TelBindTime: u.TelBindTime,
}
}
// ConvertToProto convert to proto
func (u *UserEmail) ConvertToProto() *UserEmailProto {
return &UserEmailProto{
Mid: u.Mid,
Email: u.Email,
Verified: u.Verified,
EmailBindTime: u.EmailBindTime,
}
}
// ConvertToProto convert to proto
func (u *UserRegOrigin) ConvertToProto() *UserRegOriginProto {
return &UserRegOriginProto{
Mid: u.Mid,
JoinIP: u.JoinIP,
JoinIPV6: u.JoinIPV6,
Port: u.Port,
JoinTime: u.JoinTime,
Origin: u.Origin,
RegType: u.RegType,
AppID: u.AppID,
}
}
// ConvertToProto convert to proto
func (u *UserThirdBind) ConvertToProto() *UserThirdBindProto {
return &UserThirdBindProto{
ID: u.ID,
Mid: u.Mid,
OpenID: u.OpenID,
PlatForm: u.PlatForm,
Token: u.Token,
Expires: u.Expires,
}
}
// ConvertToProto convert to proto
func (u *UserSafeQuestion) ConvertToProto() *UserSafeQuestionProto {
return &UserSafeQuestionProto{
Mid: u.Mid,
SafeQuestion: u.SafeQuestion,
SafeAnswer: u.SafeAnswer,
SafeBindTime: u.SafeBindTime,
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,54 @@
syntax = "proto3";
package passport.job.user;
option go_package = "model";
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
message UserBaseProto {
int64 Mid = 1 [(gogoproto.jsontag) = "mid"];
string UserID = 2 [(gogoproto.jsontag) = "userid"];
bytes Pwd = 3 [(gogoproto.jsontag) = "pwd"];
string Salt = 4 [(gogoproto.jsontag) = "salt"];
int32 Status = 5 [(gogoproto.jsontag) = "status"];
}
message UserEmailProto {
int64 Mid = 1 [(gogoproto.jsontag) = "mid"];
bytes Email = 2 [(gogoproto.jsontag) = "email"];
int32 Verified = 3 [(gogoproto.jsontag) = "verified"];
int64 EmailBindTime = 4 [(gogoproto.jsontag) = "email_bind_time"];
}
message UserTelProto {
int64 Mid = 1 [(gogoproto.jsontag) = "mid"];
bytes Tel = 2 [(gogoproto.jsontag) = "tel"];
string Cid = 3 [(gogoproto.jsontag) = "cid"];
int64 TelBindTime = 4 [(gogoproto.jsontag) = "tel_bind_time"];
}
message UserRegOriginProto {
int64 Mid = 1 [(gogoproto.jsontag) = "mid"];
int64 JoinIP = 2 [(gogoproto.jsontag) = "join_ip"];
bytes JoinIPV6 = 3 [(gogoproto.jsontag) = "join_ip_v6"];
int32 port = 4 [(gogoproto.jsontag) = "port"];
int64 JoinTime = 5 [(gogoproto.jsontag) = "join_time"];
int32 Origin = 6 [(gogoproto.jsontag) = "origin"];
int32 RegType = 7 [(gogoproto.jsontag) = "reg_type"];
int64 AppID = 8 [(gogoproto.jsontag) = "appid"];
}
message UserSafeQuestionProto {
int64 Mid = 1 [(gogoproto.jsontag) = "mid"];
int32 SafeQuestion = 2 [(gogoproto.jsontag) = "safe_question"];
bytes SafeAnswer = 3 [(gogoproto.jsontag) = "safe_answer"];
int64 SafeBindTime = 4 [(gogoproto.jsontag) = "safe_bind_time"];
}
message UserThirdBindProto {
int64 ID = 1 [(gogoproto.jsontag) = "id"];
int64 Mid = 2 [(gogoproto.jsontag) = "mid"];
string OpenID = 3 [(gogoproto.jsontag) = "openid"];
int64 PlatForm = 4 [(gogoproto.jsontag) = "platform"];
string Token = 5 [(gogoproto.jsontag) = "token"];
int64 Expires = 6 [(gogoproto.jsontag) = "expires"];
}

View File

@@ -0,0 +1,54 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"aes.go",
"aso_full_migration.go",
"aso_incr_migration.go",
"duplicate.go",
"passport_util.go",
"service.go",
"user.go",
],
importpath = "go-common/app/job/main/passport-user/service",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/job/main/passport-user/conf:go_default_library",
"//app/job/main/passport-user/dao:go_default_library",
"//app/job/main/passport-user/model:go_default_library",
"//library/database/sql:go_default_library",
"//library/log:go_default_library",
"//library/queue/databus:go_default_library",
"//library/queue/databus/databusutil:go_default_library",
"//vendor/github.com/go-sql-driver/mysql:go_default_library",
"//vendor/github.com/pkg/errors:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)
go_test(
name = "go_default_test",
srcs = ["aes_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
)

View File

@@ -0,0 +1,51 @@
package service
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
//var key = []byte("bili_account_enc")
// CBCEncrypt aes cbc encrypt
func (s *Service) CBCEncrypt(origData []byte) ([]byte, error) {
block, err := aes.NewCipher(s.aesKey)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, s.aesKey[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
// CBCDecrypt aes cbc decrypt
func (s *Service) CBCDecrypt(crypted []byte) ([]byte, error) {
block, err := aes.NewCipher(s.aesKey)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, s.aesKey[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}
// PKCS5Padding padding
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// PKCS5UnPadding unpadding
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}

View File

@@ -0,0 +1,90 @@
package service
import (
"crypto/aes"
"crypto/cipher"
"fmt"
"testing"
)
var key = []byte("bili_account_enc")
func TestService_cbcEncrypt(t *testing.T) {
tel := []byte("18612340123")
cipherText, _ := cbcEncrypt(tel)
fmt.Println(len(cipherText))
fmt.Println(cipherText)
}
func TestService_cbcDecrypt(t *testing.T) {
cipherText := []byte{115, 201, 179, 163, 254, 77, 59, 220, 62, 178, 19, 241, 165, 28, 249, 249}
fmt.Println(string(cipherText))
tel, _ := cbcDecrypt(cipherText)
fmt.Println(string(tel))
}
func TestService_cfbEncrypt(t *testing.T) {
tel := []byte("18612340123")
cipherText, _ := cfbEncrypt(tel)
fmt.Println(len(cipherText))
fmt.Println(cipherText)
}
func TestService_cfbDecrypt(t *testing.T) {
cipherText := []byte{48, 35, 4, 24, 80, 204, 171, 226, 219, 74, 16, 95, 138, 184, 249, 205}
fmt.Println(string(cipherText))
tel, _ := cfbDecrypt(cipherText)
fmt.Println(string(tel))
}
func cbcEncrypt(origData []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
func cbcDecrypt(crypted []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func cfbEncrypt(origData []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
cfb := cipher.NewCFBEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
cfb.XORKeyStream(crypted, origData)
return crypted, nil
}
func cfbDecrypt(crypted []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
cfb := cipher.NewCFBDecrypter(block, key[:blockSize])
origData := make([]byte, len(crypted))
cfb.XORKeyStream(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}

View File

@@ -0,0 +1,263 @@
package service
import (
"context"
"go-common/app/job/main/passport-user/model"
"go-common/library/log"
"time"
)
func (s *Service) getAsoAccount(start, end, count int64) {
chanNum := int64(s.c.FullSync.AsoAccount.ChanNum)
for {
log.Info("getAsoAccount, start %d, end %d, count %d", start, end, count)
var (
res []*model.OriginAccount
err error
)
for {
if res, err = s.d.AsoAccount(context.Background(), start, count); err != nil {
log.Error("fail to get AsoAccount error(%+v)", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for _, a := range res {
s.asoAccountChan[a.Mid%chanNum] <- a
}
if start > end || len(res) == 0 {
log.Info("sync asoAccount finished! endID(%d)", start)
break
}
start = res[len(res)-1].Mid
}
}
func (s *Service) asoAccountConsume(c chan *model.OriginAccount) {
for {
a, ok := <-c
if !ok {
log.Error("asoAccountChan closed")
return
}
for i := 0; i < _retry; i++ {
if err := s.syncAsoAccount(a); err != nil {
log.Error("fail to sync asoAccount(%+v) error(%+v)", a, err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
}
func (s *Service) getAsoAccountInfo(start, end, count int64) {
chanNum := int64(s.c.FullSync.AsoAccountInfo.ChanNum)
initStart, initEnd, initCount := start, end, count
for i := 0; i < _asoAccountInfoSharding; i++ {
start, end, count = initStart, initEnd, initCount
for {
log.Info("getAsoAccountInfo, start %d, end %d, count %d, suffix %d", start, end, count, i)
var (
res []*model.OriginAccountInfo
err error
)
for {
if res, err = s.d.AsoAccountInfo(context.Background(), start, count, int64(i)); err != nil {
log.Error("fail to get AsoAccountInfo error(%+v)", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for _, a := range res {
s.asoAccountInfoChan[a.ID%chanNum] <- a
}
if start > end || len(res) == 0 {
log.Info("sync asoAccountInfo(%d) finished! endID(%d)", i, start)
break
}
start = res[len(res)-1].ID
}
}
}
func (s *Service) asoAccountInfoConsume(c chan *model.OriginAccountInfo) {
for {
a, ok := <-c
if !ok {
log.Error("asoAccountInfoChan closed")
return
}
for {
if err := s.syncAsoAccountInfo(a); err != nil {
log.Error("fail to sync asoAccountInfo(%+v) error(%+v)", a, err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
}
func (s *Service) getAsoAccountReg(start, end, count int64) {
chanNum := int64(s.c.FullSync.AsoAccountReg.ChanNum)
initStart, initEnd, initCount := start, end, count
for i := 0; i < _asoAccountRegOriginSharding; i++ {
start, end, count = initStart, initEnd, initCount
for {
log.Info("getAsoAccountReg, start %d, end %d, count %d, suffix %d", start, end, count, i)
var (
res []*model.OriginAccountReg
err error
)
for {
if res, err = s.d.AsoAccountReg(context.Background(), start, count, int64(i)); err != nil {
log.Error("fail to get AsoAccountReg error(%+v)", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for _, a := range res {
s.asoAccountRegChan[a.ID%chanNum] <- a
}
if start > end || len(res) == 0 {
log.Info("sync asoAccountReg(%d) finished! endID(%d)", i, start)
break
}
start = res[len(res)-1].ID
}
}
}
func (s *Service) asoAccountRegConsume(c chan *model.OriginAccountReg) {
for {
a, ok := <-c
if !ok {
log.Error("asoAccountRegChan closed")
return
}
for {
if err := s.syncAsoAccountReg(a); err != nil {
log.Error("fail to sync asoAccountReg(%+v) error(%+v)", a, err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
}
func (s *Service) getAsoAccountSns(start, end, count int64) {
chanNum := int64(s.c.FullSync.AsoAccountReg.ChanNum)
for {
log.Info("getAsoAccountSns, start %d, end %d, count %d", start, end, count)
var (
res []*model.OriginAccountSns
err error
)
for {
if res, err = s.d.AsoAccountSns(context.Background(), start, count); err != nil {
log.Error("fail to get AsoAccountSns error(%+v)", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for _, a := range res {
s.asoAccountSnsChan[a.Mid%chanNum] <- a
}
if start > end || len(res) == 0 {
log.Info("sync asoAccountSns finished! endID(%d)", start)
break
}
start = res[len(res)-1].Mid
}
}
func (s *Service) asoAccountSnsConsume(c chan *model.OriginAccountSns) {
for {
a, ok := <-c
if !ok {
log.Error("asoAccountSnsChan closed")
return
}
for {
if err := s.syncAsoAccountSns(a); err != nil {
log.Error("fail to sync asoAccountSns(%+v) error(%+v)", a, err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
}
func (s *Service) getAsoTelBindLog(start, end, count int64) {
chanNum := int64(s.c.FullSync.AsoAccountReg.ChanNum)
for {
log.Info("getAsoTelBindLog, start %d, end %d, count %d", start, end, count)
var (
res []*model.UserTel
err error
)
for {
if res, err = s.d.UserTel(context.Background(), start, count); err != nil {
log.Error("fail to get UserTel error(%+v)", err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
for _, a := range res {
s.asoTelBindLogChan[a.Mid%chanNum] <- a
}
if start > end || len(res) == 0 {
log.Info("sync asoTelBindLog finished! endID(%d)", start)
break
}
start = res[len(res)-1].Mid
}
}
func (s *Service) asoTelBindLogConsume(c chan *model.UserTel) {
filterStart := 1536572121
filterEnd := 1536616436
for {
a, ok := <-c
if !ok {
log.Error("asoTelBindLogChan closed")
return
}
for {
var (
err error
telBindTime int64
)
if telBindTime, err = s.d.AsoTelBindLog(context.Background(), a.Mid); err != nil {
log.Error("fail to get AsoTelBindLog error(%+v)", err)
time.Sleep(100 * time.Millisecond)
continue
}
if telBindTime == 0 {
break
}
if telBindTime > int64(filterStart) && telBindTime < int64(filterEnd) {
break
}
userTel := &model.UserTel{
Mid: a.Mid,
TelBindTime: telBindTime,
}
if _, err = s.d.UpdateUserTelBindTime(context.Background(), userTel); err != nil {
log.Error("fail to update tel bind log userTel(%+v) error(%+v)", userTel, err)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,123 @@
package service
//func (s *Service) updateTelDuplicateJob() {
// log.Info("update tel duplicate job start...")
// res, err := s.d.UserTelDuplicate(context.Background())
// if err != nil {
// log.Error("fail to get UserTelDuplicate, error(%+v)", err)
// return
// }
// for _, r := range res {
// userTel := &model.UserTel{
// Mid: r.Mid,
// Tel: r.Tel,
// Cid: r.Cid,
// }
// if _, err = s.d.UpdateUserTel(context.Background(), userTel); err != nil {
// log.Error("fail to update user tel userTel(%+v), error(%+v)", userTel, err)
// continue
// }
// log.Info("update userTel by userTelDuplicate success, userTelDuplicate(%+v)", r)
// if _, err = s.d.UpdateUserTelDuplicateStatus(context.Background(), r.Mid); err != nil {
// log.Error("fail to update user tel duplicate status, mid(%d) error(%+v)", r.Mid, err)
// }
// log.Info("update userTelDuplicate status success, mid(%d)", r.Mid)
// }
// log.Info("update tel duplicate job end...")
//}
//
//func (s *Service) updateEmailDuplicateJob() {
// log.Info("update email duplicate job start...")
// res, err := s.d.UserEmailDuplicate(context.Background())
// if err != nil {
// log.Error("fail to get UserTelDuplicate, error(%+v)", err)
// return
// }
// for _, r := range res {
// userEmail := &model.UserEmail{
// Mid: r.Mid,
// Email: r.Email,
// }
// if _, err = s.d.UpdateUserEmail(context.Background(), userEmail); err != nil {
// log.Error("fail to update user email userEmail(%+v), error(%+v)", userEmail, err)
// continue
// }
// log.Info("update userEmail by userEmailDuplicate success, userEmailDuplicate(%+v)", r)
// if _, err = s.d.UpdateUserTelDuplicateStatus(context.Background(), r.Mid); err != nil {
// log.Error("fail to update user email duplicate status, mid(%d) error(%+v)", r.Mid, err)
// }
// log.Info("update userEmailDuplicate status success, mid(%d)", r.Mid)
// }
// log.Info("update email duplicate job end...")
//}
/**
func (s *Service) checkTelDuplicateJob() {
log.Info("check tel duplicate job start...")
res, err := s.d.UserTelDuplicate(context.Background())
if err != nil {
log.Error("fail to get UserTelDuplicate, error(%+v)", err)
return
}
var (
asoAccount *model.OriginAccount
userTel *model.UserTel
)
for _, r := range res {
if asoAccount, err = s.d.GetAsoAccountByMid(context.Background(), r.Mid); err != nil {
log.Error("fail to check tel duplicate mid(%d) error(%+v)", r.Mid, err)
return
}
if userTel, err = s.d.GetUserTelByMid(context.Background(), r.Mid); err != nil {
log.Error("fail to check tel duplicate mid(%d) error(%+v)", r.Mid, err)
return
}
a := s.convertAccountToUserTel(asoAccount)
originHex := hex.EncodeToString(a.Tel)
newHex := hex.EncodeToString(userTel.Tel)
if originHex == newHex {
log.Info("check user tel duplicate success, userTelDuplicate(%+v)", r)
if _, err = s.d.UpdateUserTelDuplicateStatus(context.Background(), r.ID); err != nil {
log.Error("fail to update user tel duplicate status, id(%d) error(%+v)", r.ID, err)
}
} else {
log.Info("fail to check user tel duplicate, new(%s) origin(%s) userTelDuplicate(%+v)", newHex, originHex, r)
}
}
log.Info("update tel duplicate job end...")
}
func (s *Service) checkEmailDuplicateJob() {
log.Info("check email duplicate job start...")
res, err := s.d.UserEmailDuplicate(context.Background())
if err != nil {
log.Error("fail to get UserEmailDuplicate, error(%+v)", err)
return
}
var (
asoAccount *model.OriginAccount
userEmail *model.UserEmail
)
for _, r := range res {
if asoAccount, err = s.d.GetAsoAccountByMid(context.Background(), r.Mid); err != nil {
log.Error("fail to check email duplicate mid(%d) error(%+v)", r.Mid, err)
return
}
if userEmail, err = s.d.GetUserEmailByMid(context.Background(), r.Mid); err != nil {
log.Error("fail to check email duplicate mid(%d) error(%+v)", r.Mid, err)
return
}
a := s.convertAccountToUserEmail(asoAccount)
originHex := hex.EncodeToString(a.Email)
newHex := hex.EncodeToString(userEmail.Email)
if originHex == newHex {
log.Info("check user email duplicate success, userEmailDuplicate(%+v)", r)
if _, err = s.d.UpdateUserTelDuplicateStatus(context.Background(), r.ID); err != nil {
log.Error("fail to update user email duplicate status, id(%d) error(%+v)", r.ID, err)
}
} else {
log.Info("fail to check user tel duplicate, new(%s) origin(%s) userEmailDuplicate(%+v)", newHex, originHex, r)
}
}
log.Info("update email duplicate job end...")
}**/

View File

@@ -0,0 +1,63 @@
package service
import (
"crypto/md5"
"fmt"
"math/big"
"net"
)
func (s *Service) doEncrypt(param string) []byte {
var (
err error
res = make([]byte, 0)
)
if param == "" || len(param) == 0 {
return nil
}
input := []byte(param)
if res, err = s.CBCEncrypt(input); err != nil {
return input
}
return res
}
//func (s *Service) doDecrypt(param []byte) string {
// var (
// err error
// res = make([]byte, 0)
// )
// if param == nil {
// return ""
// }
// input := []byte(param)
// if res, err = s.CBCDecrypt(input); err != nil {
// return string(param)
// }
// return string(res)
//}
// InetNtoA convert int64 to ip addr .
func InetNtoA(ip int64) string {
return fmt.Sprintf("%d.%d.%d.%d",
byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}
// InetAtoN convert ip addr to int64.
func InetAtoN(ip string) int64 {
ret := big.NewInt(0)
ret.SetBytes(net.ParseIP(ip).To4())
return ret.Int64()
}
func (s *Service) doHash(plaintext string) []byte {
var res = make([]byte, 0)
if plaintext == "" {
return res
}
hash := md5.New()
hash.Write([]byte(plaintext))
hash.Write([]byte(s.salt))
res = hash.Sum(nil)
return res
}

View File

@@ -0,0 +1,176 @@
package service
import (
"context"
"go-common/app/job/main/passport-user/conf"
"go-common/app/job/main/passport-user/dao"
"go-common/app/job/main/passport-user/model"
"go-common/library/log"
"go-common/library/queue/databus"
"go-common/library/queue/databus/databusutil"
)
const (
_asoAccountTable = "aso_account"
_asoAccountInfoTable = "aso_account_info"
_asoAccountSnsTable = "aso_account_sns"
_asoAccountRegOriginTable = "aso_account_reg_origin"
_insertAction = "insert"
_updateAction = "update"
_deleteAction = "delete"
_asoAccountInfoSharding = 30
_asoAccountRegOriginSharding = 20
_mySQLErrCodeDuplicateEntry = 1062
_retry = 3
)
// Service service.
type Service struct {
c *conf.Config
d *dao.Dao
// aso binlog consumer
asoBinLogConsumer *databus.Databus
group *databusutil.Group
// fullSync chan
asoAccountChan []chan *model.OriginAccount
asoAccountInfoChan []chan *model.OriginAccountInfo
asoAccountRegChan []chan *model.OriginAccountReg
asoAccountSnsChan []chan *model.OriginAccountSns
asoTelBindLogChan []chan *model.UserTel
countryMap map[int64]string
aesKey []byte
salt []byte
//cron *cron.Cron
ch chan func()
}
// New new a service instance.
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
d: dao.New(c),
asoAccountChan: make([]chan *model.OriginAccount, c.FullSync.AsoAccount.ChanNum),
asoAccountInfoChan: make([]chan *model.OriginAccountInfo, c.FullSync.AsoAccountInfo.ChanNum),
asoAccountRegChan: make([]chan *model.OriginAccountReg, c.FullSync.AsoAccountReg.ChanNum),
asoAccountSnsChan: make([]chan *model.OriginAccountSns, c.FullSync.AsoAccountSns.ChanNum),
asoTelBindLogChan: make([]chan *model.UserTel, c.FullSync.AsoTelBindLog.ChanNum),
ch: make(chan func(), 1024000),
}
go s.cacheproc()
if c.FullSync.AsoCountryCodeSwitch {
err := s.syncAsoCountryCode()
if err != nil {
log.Error("fail to sync AsoCountryCode")
panic(err)
}
}
aesKey, err := s.d.AesKey(context.Background())
if err != nil || aesKey == "" {
log.Error("fail to get rsaKey")
panic(err)
}
s.aesKey = []byte(aesKey)
salt, err := s.d.Salt(context.Background())
if err != nil || salt == "" {
log.Error("fail to get salt")
panic(err)
}
s.salt = []byte(salt)
s.countryMap, err = s.d.CountryCodeMap(context.Background())
if err != nil || len(s.countryMap) == 0 {
log.Error("fail to get country map")
panic(err)
}
if c.FullSync.AsoAccount.Switch {
for i := 0; i < c.FullSync.AsoAccount.ChanNum; i++ {
ch := make(chan *model.OriginAccount, c.FullSync.AsoAccount.ChanSize)
s.asoAccountChan[i] = ch
go s.asoAccountConsume(ch)
}
go s.getAsoAccount(c.FullSync.AsoAccount.Start, c.FullSync.AsoAccount.End, c.FullSync.AsoAccount.Count)
}
if c.FullSync.AsoAccountInfo.Switch {
for i := 0; i < c.FullSync.AsoAccountInfo.ChanNum; i++ {
ch := make(chan *model.OriginAccountInfo, c.FullSync.AsoAccountInfo.ChanSize)
s.asoAccountInfoChan[i] = ch
go s.asoAccountInfoConsume(ch)
}
go s.getAsoAccountInfo(c.FullSync.AsoAccountInfo.Start, c.FullSync.AsoAccountInfo.End, c.FullSync.AsoAccountInfo.Count)
}
if c.FullSync.AsoAccountReg.Switch {
for i := 0; i < c.FullSync.AsoAccountReg.ChanNum; i++ {
ch := make(chan *model.OriginAccountReg, c.FullSync.AsoAccountReg.ChanSize)
s.asoAccountRegChan[i] = ch
go s.asoAccountRegConsume(ch)
}
go s.getAsoAccountReg(c.FullSync.AsoAccountReg.Start, c.FullSync.AsoAccountReg.End, c.FullSync.AsoAccountReg.Count)
}
if c.FullSync.AsoAccountSns.Switch {
for i := 0; i < c.FullSync.AsoAccountSns.ChanNum; i++ {
ch := make(chan *model.OriginAccountSns, c.FullSync.AsoAccountSns.ChanSize)
s.asoAccountSnsChan[i] = ch
go s.asoAccountSnsConsume(ch)
}
go s.getAsoAccountSns(c.FullSync.AsoAccountSns.Start, c.FullSync.AsoAccountSns.End, c.FullSync.AsoAccountSns.Count)
}
if c.FullSync.AsoTelBindLog.Switch {
for i := 0; i < c.FullSync.AsoTelBindLog.ChanNum; i++ {
ch := make(chan *model.UserTel, c.FullSync.AsoTelBindLog.ChanSize)
s.asoTelBindLogChan[i] = ch
go s.asoTelBindLogConsume(ch)
}
go s.getAsoTelBindLog(c.FullSync.AsoTelBindLog.Start, c.FullSync.AsoTelBindLog.End, c.FullSync.AsoTelBindLog.Count)
}
if c.IncSync.Switch {
s.asoBinLogConsumer = databus.New(c.DataBus.AsoBinLogSub)
s.group = databusutil.NewGroup(
c.DatabusUtil,
s.asoBinLogConsumer.Messages(),
)
s.consumeproc()
}
//if c.Scheduler.Switch {
// s.cron = cron.New()
// if err := s.cron.AddFunc(c.Scheduler.EmailDuplicateCron, s.checkEmailDuplicateJob); err != nil {
// panic(err)
// }
// if err := s.cron.AddFunc(c.Scheduler.TelDuplicateCron, s.checkTelDuplicateJob); err != nil {
// panic(err)
// }
// s.cron.Start()
//}
return
}
// Ping check server ok.
func (s *Service) Ping(c context.Context) (err error) {
return s.d.Ping(c)
}
// Close close service, including databus and outer service.
func (s *Service) Close() (err error) {
if err = s.group.Close(); err != nil {
log.Error("s.group.Close() error(%v)", err)
}
s.d.Close()
return
}
func (s *Service) addCache(f func()) {
select {
case s.ch <- f:
default:
log.Warn("cacheproc chan full")
}
}
// cacheproc is a routine for executing closure.
func (s *Service) cacheproc() {
for {
f := <-s.ch
f()
}
}

View File

@@ -0,0 +1,294 @@
package service
import (
"context"
"encoding/hex"
"strconv"
"time"
"go-common/app/job/main/passport-user/model"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
_platformSINA = 1
_platformQQ = 2
)
func (s *Service) convertAccountToUserBase(a *model.OriginAccount) (res *model.UserBase, err error) {
pwdBytes, err := hex.DecodeString(a.Pwd)
if err != nil {
log.Error("fail to hex decode pwd(%+v) error(%+v)", a.Pwd, err)
return
}
res = &model.UserBase{
Mid: a.Mid,
UserID: a.UserID,
Pwd: pwdBytes,
Salt: a.Salt,
Status: a.Isleak,
Deleted: 0,
MTime: a.MTime,
}
return
}
func (s *Service) convertAccountToUserEmail(a *model.OriginAccount) (res *model.UserEmail) {
if a.Email == "" {
res = &model.UserEmail{
Mid: a.Mid,
EmailBindTime: time.Now().Unix(),
MTime: a.MTime,
}
return
}
res = &model.UserEmail{
Mid: a.Mid,
Email: s.doEncrypt(a.Email),
EmailBindTime: time.Now().Unix(),
MTime: a.MTime,
}
return
}
func (s *Service) convertAccountToUserTel(a *model.OriginAccount) (res *model.UserTel) {
if a.Tel == "" {
res = &model.UserTel{
Mid: a.Mid,
TelBindTime: time.Now().Unix(),
MTime: a.MTime,
}
return
}
res = &model.UserTel{
Mid: a.Mid,
Tel: s.doEncrypt(a.Tel),
Cid: s.countryMap[a.CountryID],
TelBindTime: time.Now().Unix(),
MTime: a.MTime,
}
return
}
func (s *Service) convertAccountInfoToUserSafeQuestion(a *model.OriginAccountInfo) (res *model.UserSafeQuestion) {
res = &model.UserSafeQuestion{
Mid: a.Mid,
SafeQuestion: a.SafeQuestion,
SafeAnswer: s.doHash(a.SafeAnswer),
SafeBindTime: time.Now().Unix(),
}
return
}
func (s *Service) convertAccountInfoToUserRegOrigin(a *model.OriginAccountInfo) (res *model.UserRegOrigin) {
res = &model.UserRegOrigin{
Mid: a.Mid,
JoinIP: InetAtoN(a.JoinIP),
JoinIPV6: a.JoinIPV6,
JoinTime: a.JoinTime,
}
return
}
func (s *Service) convertAccountInfoToUserEmail(a *model.OriginAccountInfo) (res *model.UserEmail) {
var (
verified int32
activeTime int64
)
if a.Spacesta >= 0 {
verified = 1
activeTime = a.ActiveTime
}
res = &model.UserEmail{
Mid: a.Mid,
Verified: verified,
EmailBindTime: activeTime,
}
return
}
func (s *Service) convertAccountRegToUserRegOrigin(a *model.OriginAccountReg) (res *model.UserRegOrigin) {
res = &model.UserRegOrigin{
Mid: a.Mid,
Origin: a.OriginType,
RegType: a.RegType,
AppID: a.AppID,
CTime: a.MTime,
MTime: a.CTime,
}
return
}
func (s *Service) convertAccountSnsToUserThirdBindQQ(a *model.OriginAccountSns) (res *model.UserThirdBind) {
res = &model.UserThirdBind{
Mid: a.Mid,
OpenID: a.QQOpenid,
PlatForm: _platformQQ,
Token: a.QQAccessToken,
Expires: a.QQAccessExpires,
}
return
}
func (s *Service) convertAccountSnsToUserThirdBindSina(a *model.OriginAccountSns) (res *model.UserThirdBind) {
res = &model.UserThirdBind{
Mid: a.Mid,
OpenID: strconv.FormatInt(a.SinaUID, 10),
PlatForm: _platformSINA,
Token: a.SinaAccessToken,
Expires: a.SinaAccessExpires,
}
return
}
func (s *Service) syncAsoAccount(a *model.OriginAccount) (err error) {
var (
tx *sql.Tx
userBase *model.UserBase
)
userBase, err = s.convertAccountToUserBase(a)
if err != nil {
log.Error("fail to convert AsoAccount(%+v) to UserBase error(%+v)", a, err)
return
}
tx, err = s.d.BeginTran(context.Background())
if err != nil {
log.Error("s.dao.Begin error(%+v)", err)
return
}
if _, err = s.d.TxAddUserBase(tx, userBase); err != nil {
log.Error("fail to add UserBase(%+v) error(%+v)", userBase, err)
tx.Rollback()
return
}
if a.Email != "" {
userEmail := s.convertAccountToUserEmail(a)
userEmail.EmailBindTime = 0
if _, err = s.d.TxAddUserEmail(tx, userEmail); err != nil {
log.Error("fail to add userEmail(%+v) error(%+v)", userEmail, err)
tx.Rollback()
return
}
}
if a.Tel != "" {
userTel := s.convertAccountToUserTel(a)
userTel.TelBindTime = 0
if _, err = s.d.TxAddUserTel(tx, userTel); err != nil {
log.Error("fail to add userTel(%+v) error(%+v)", userTel, err)
tx.Rollback()
return
}
}
if err = tx.Commit(); err != nil {
log.Error("tx.Commit(), error(%v)", err)
return
}
return
}
func (s *Service) syncAsoAccountInfo(a *model.OriginAccountInfo) (err error) {
var (
tx *sql.Tx
userSafeQuestion *model.UserSafeQuestion
userRegOrigin *model.UserRegOrigin
userEmail *model.UserEmail
)
userRegOrigin = s.convertAccountInfoToUserRegOrigin(a)
userEmail = s.convertAccountInfoToUserEmail(a)
tx, err = s.d.BeginTran(context.Background())
if err != nil {
log.Error("s.dao.Begin error(%+v)", err)
return
}
if a.SafeQuestion != 0 || a.SafeAnswer != "" {
userSafeQuestion = s.convertAccountInfoToUserSafeQuestion(a)
userSafeQuestion.SafeBindTime = 0
if _, err = s.d.TxInsertIgnoreUserSafeQuestion(tx, userSafeQuestion); err != nil {
tx.Rollback()
return
}
}
if _, err = s.d.TxInsertIgnoreUserRegOrigin(tx, userRegOrigin); err != nil {
tx.Rollback()
return
}
if err = tx.Commit(); err != nil {
log.Error("tx.Commit(), error(%v)", err)
return
}
if _, err = s.d.UpdateUserEmailBindTime(context.Background(), userEmail); err != nil {
tx.Rollback()
return
}
return
}
func (s *Service) syncAsoAccountReg(a *model.OriginAccountReg) (err error) {
userRegOrigin := s.convertAccountRegToUserRegOrigin(a)
if _, err = s.d.InsertUpdateUserRegOriginType(context.Background(), userRegOrigin); err != nil {
log.Error("fail to insert update reg origin type userRegOrigin(%+v) error(%+v)", userRegOrigin, err)
}
return
}
func (s *Service) syncAsoAccountSns(a *model.OriginAccountSns) (err error) {
var (
tx *sql.Tx
qq *model.UserThirdBind
sina *model.UserThirdBind
utb *model.UserThirdBind
)
sina = s.convertAccountSnsToUserThirdBindSina(a)
qq = s.convertAccountSnsToUserThirdBindQQ(a)
tx, err = s.d.BeginTran(context.Background())
if err != nil {
log.Error("s.dao.Begin error(%+v)", err)
return
}
if a.QQOpenid != "" {
if utb, err = s.d.GetUserThirdBindByMidAndPlatform(context.Background(), a.Mid, _platformQQ); err != nil {
return
}
if utb == nil {
if _, err = s.d.TxAddUserThirdBind(tx, qq); err != nil {
log.Error("fail to add third bind qq userThirdBind(%+v) error(%+v)", qq, err)
tx.Rollback()
return
}
} else {
log.Error("third bind qq is exist, userThirdBind(%+v)", utb)
}
}
if a.SinaUID != 0 {
if utb, err = s.d.GetUserThirdBindByMidAndPlatform(context.Background(), a.Mid, _platformSINA); err != nil {
return
}
if utb == nil {
if _, err = s.d.TxAddUserThirdBind(tx, sina); err != nil {
log.Error("fail to add third bind sina userThirdBind(%+v) error(%+v)", sina, err)
tx.Rollback()
return
}
} else {
log.Error("third bind weibo is exist, userThirdBind(%+v)", utb)
}
}
if err = tx.Commit(); err != nil {
log.Error("tx.Commit(), error(%v)", err)
return
}
return
}
func (s *Service) syncAsoCountryCode() (err error) {
res, err := s.d.AsoCountryCode(context.Background())
if err != nil {
log.Error("fail to get country code error(%+v)", err)
return
}
for _, r := range res {
s.d.AddCountryCode(context.Background(), r)
}
return
}