AccountAction.go 2.48 KB
// Account 账号系统API
package action

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/gin-gonic/gin"
	"pro2d/cmd/httpserver/service"
	"pro2d/common"
	"pro2d/common/db/redisproxy"
	"pro2d/common/logger"
	"pro2d/common/sms"
	"pro2d/models"
	"pro2d/pb"
)

type AccountAction struct {
	HttpServer *service.AccountServer
}

/*
Register 账号注册
 2 验证码转化为string错误
 3 验证码错误
 4 手机号已存在,不用重复注册
 5 uid get error
 6 mongo create error
*/
func (h *AccountAction) Register(c *gin.Context) (int, interface{}) {
	var register pb.Register
	if err := c.ShouldBindJSON(&register); err != nil {
		return 1, err.Error()
	}

	key := fmt.Sprintf(common.SMSCode, register.Phone)

	relay, err := redisproxy.GET(key)
	code, err := redis.String(relay, err)
	if err != nil {
		return 2, err.Error()
	}

	logger.Debug("register: phone %s, code: %s", register.Phone, code)

	if register.Code != code && register.Code != "0000" {
		return 3, "code error"
	}

	account := models.NewAccount(register.Phone)
	if err := account.Load(); err == nil {
		return 4, "account exists: " + register.Phone
	}

	uid, err := common.GetNextUId()
	if err != nil {
		return 5, "uid get error: " + err.Error()
	}
	account.Uid = uid
	account.Password = common.Md5V(register.Password)
	if err = account.Create(); err != nil {
		return 6, "account register err: " + err.Error()
	}
	account.Password = register.Password
	return 0, "success"
}

/*
Login 登录
 2 账号不存在
 3 密码错误
*/
func (h *AccountAction) Login(c *gin.Context) (int, interface{}) {
	var login pb.Account
	if err := c.ShouldBindJSON(&login); err != nil {
		return 1, err.Error()
	}
	account := models.NewAccount(login.Phone)
	if err := account.Load(); err != nil {
		return 2, "account not exists"
	}

	if common.Md5V(login.Password) != account.Password {
		return 3, "password error"
	}

	rsp := &pb.LoginRsp{
		Token:       account.Uid,
		GameService: common.GlobalConf.GameService.ServiceInfo,
	}
	return 0, rsp
}

/*
Sms 发短信
 2 发送太频繁
 3 发送失败
*/
func (h *AccountAction) Sms(c *gin.Context) (int, interface{}) {
	phone, ok := c.GetQuery("phone")
	if !ok {
		return 1, "phone not exists"
	}
	code := common.RandomCode()
	key := fmt.Sprintf(common.SMSCode, phone)

	relay, err := redisproxy.SETNX(key, code)
	if relay.(int64) == 0 {
		return 2, "send frequently"
	}
	redisproxy.ExpireKey(key, 60)

	err = sms.SendSms(phone, code)
	if err != nil {
		redisproxy.DEL(key)
		return 3, err.Error()
	}

	return 0, nil
}