Skip to content

Commit

Permalink
Fix sendCode dup.
Browse files Browse the repository at this point in the history
  • Loading branch information
wubenqi committed Jul 2, 2019
1 parent 6a16342 commit eb06697
Show file tree
Hide file tree
Showing 6 changed files with 583 additions and 47 deletions.
109 changes: 62 additions & 47 deletions messenger/biz_server/biz/core/auth/phone_code_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,55 +222,70 @@ func (code *phoneCodeData) DoSendCode(
var err error
code.checkDataType(kDBTypeCreate)

// 使用最简单的办法,每次新建
sentCodeType, nextCodeType := makeCodeType(phoneRegistered, allowFlashCall, currentNumber)
// TODO(@benqi): gen rand number

if sendSmsF == nil {
code.code = "12345"
do := code.dao.AuthPhoneTransactionsDAO.SelectLast(code.authKeyId, code.phoneNumber)
if do != nil && int32(time.Now().Unix()) < do.CodeExpired {
// 使用最简单的办法,每次新建
sentCodeType, nextCodeType := makeCodeType(phoneRegistered, allowFlashCall, currentNumber)

// err = mtproto.NewRpcError(int32(mtproto.TLRpcErrorCodes_PHONE_NUMBER_INVALID), "invalid phone number")
// glog.Error(err)
// return err
code.code = do.Code
code.codeHash = do.TransactionHash
code.sentCodeType = sentCodeType
code.nextCodeType = nextCodeType

code.tableId = do.Id
} else {
code.code = random2.RandomNumeric(5)
code.codeMsgId, err = sendSmsF(code.phoneNumber, code.code, code.codeHash, code.sentCodeType)
if err != nil {
glog.Errorf("sendSmsVerifyCode error - %v", err)
return err
// 使用最简单的办法,每次新建
sentCodeType, nextCodeType := makeCodeType(phoneRegistered, allowFlashCall, currentNumber)
// TODO(@benqi): gen rand number

if sendSmsF == nil {
code.code = "12345"
} else {
code.code = random2.RandomNumeric(5)
code.codeMsgId, err = sendSmsF(code.phoneNumber, code.code, code.codeHash, code.sentCodeType)
if err != nil {
glog.Errorf("sendSmsVerifyCode error - %v", err)
return err
}
}
//if sendSmsF != nil {
// return sendSmsF(code.phoneNumber, code.code, code.codeHash, code.sentCodeType)
//}

// code.codeHash = fmt.Sprintf("%20d", helper.NextSnowflakeId())
code.codeHash = crypto.GenerateStringNonce(16)
code.codeExpired = int32(time.Now().Unix() + 15*60)
code.sentCodeType = sentCodeType
code.nextCodeType = nextCodeType
//err := code.doSendCodeCallback()
//if err != nil {
// glog.Error(err)
// return err
//}

// sendSmsF
// save
do = &dataobject.AuthPhoneTransactionsDO{
AuthKeyId: code.authKeyId,
PhoneNumber: code.phoneNumber,
Code: code.code,
CodeExpired: code.codeExpired,
CodeMsgId: code.codeMsgId,
TransactionHash: code.codeHash,
SentCodeType: int8(code.sentCodeType),
FlashCallPattern: code.flashCallPattern,
NextCodeType: int8(code.nextCodeType),
State: kCodeStateSent,
ApiId: apiId,
ApiHash: apiHash,
CreatedTime: time.Now().Unix(),
}
code.tableId = code.dao.AuthPhoneTransactionsDAO.Insert(do)
}
//if sendSmsF != nil {
// return sendSmsF(code.phoneNumber, code.code, code.codeHash, code.sentCodeType)
//}


// code.codeHash = fmt.Sprintf("%20d", helper.NextSnowflakeId())
code.codeHash = crypto.GenerateStringNonce(16)
code.codeExpired = int32(time.Now().Unix() + 15*60)
code.sentCodeType = sentCodeType
code.nextCodeType = nextCodeType

//err := code.doSendCodeCallback()
//if err != nil {
// glog.Error(err)
// return err
//}

// sendSmsF
// save
do := &dataobject.AuthPhoneTransactionsDO{
AuthKeyId: code.authKeyId,
PhoneNumber: code.phoneNumber,
Code: code.code,
CodeExpired: code.codeExpired,
CodeMsgId: code.codeMsgId,
TransactionHash: code.codeHash,
SentCodeType: int8(code.sentCodeType),
FlashCallPattern: code.flashCallPattern,
NextCodeType: int8(code.nextCodeType),
State: kCodeStateSent,
ApiId: apiId,
ApiHash: apiHash,
CreatedTime: time.Now().Unix(),
}
code.tableId = code.dao.AuthPhoneTransactionsDAO.Insert(do)
//// TODO(@benqi):
//lastCreatedAt := time.Unix(time.Now().Unix()-15*60, 0).Format("2006-01-02 15:04:05")
//do := code.dao.AuthPhoneTransactionsDAO.SelectByPhoneAndApiIdAndHash(code.phoneNumber, apiId, apiHash, lastCreatedAt)
Expand Down Expand Up @@ -359,7 +374,7 @@ func (code *phoneCodeData) DoCancelCode() bool {
return true
}

func (code *phoneCodeData) DoSignIn(phoneCode string, phoneRegistered bool, verifySmsCodeF func(codeHash, code, extraData string) (error)) error {
func (code *phoneCodeData) DoSignIn(phoneCode string, phoneRegistered bool, verifySmsCodeF func(codeHash, code, extraData string) error) error {
defer func() {
if code.tableId != 0 {
// Update attempts
Expand Down Expand Up @@ -439,7 +454,7 @@ func (code *phoneCodeData) DoSignIn(phoneCode string, phoneRegistered bool, veri
}

// TODO(@benqi): 合并DoSignUp和DoSignIn部分代码
func (code *phoneCodeData) DoSignUp(phoneCode string, verifySmsCodeF func(codeHash, code, extraData string) (error)) error {
func (code *phoneCodeData) DoSignUp(phoneCode string, verifySmsCodeF func(codeHash, code, extraData string) error) error {
defer func() {
if code.tableId != 0 {
// Update attempts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,43 @@ func (dao *AuthPhoneTransactionsDAO) SelectByPhoneCodeHash(auth_key_id int64, ph
return do
}

// SELECT id, code, code_expired, code_msg_id, sent_code_type, flash_call_pattern, next_code_type, attempts, state FROM auth_phone_transactions WHERE auth_key_id = :auth_key_id AND phone_number = :phone_number ORDER BY id DESC LIMIT 1
// TODO(@benqi): sqlmap
func (dao *AuthPhoneTransactionsDAO) SelectLast(auth_key_id int64, phone_number string) *dataobject.AuthPhoneTransactionsDO {
var query = "SELECT id, code, code_expired, code_msg_id, sent_code_type, flash_call_pattern, next_code_type, attempts, state FROM auth_phone_transactions WHERE auth_key_id = ? AND phone_number = ? ORDER BY id DESC LIMIT 1"
// select id, code, code_expired, code_msg_id, sent_code_type, flash_call_pattern, next_code_type, attempts, state from auth_phone_transactions where auth_key_id = ? and phone_number = ? and transaction_hash = ?"
rows, err := dao.db.Queryx(query, auth_key_id, phone_number)

if err != nil {
errDesc := fmt.Sprintf("Queryx in SelectLast(_), error: %v", err)
glog.Error(errDesc)
panic(mtproto.NewRpcError(int32(mtproto.TLRpcErrorCodes_DBERR), errDesc))
}

defer rows.Close()

do := &dataobject.AuthPhoneTransactionsDO{}
if rows.Next() {
err = rows.StructScan(do)
if err != nil {
errDesc := fmt.Sprintf("StructScan in SelectLast(_), error: %v", err)
glog.Error(errDesc)
panic(mtproto.NewRpcError(int32(mtproto.TLRpcErrorCodes_DBERR), errDesc))
}
} else {
return nil
}

err = rows.Err()
if err != nil {
errDesc := fmt.Sprintf("rows in SelectLast(_), error: %v", err)
glog.Error(errDesc)
panic(mtproto.NewRpcError(int32(mtproto.TLRpcErrorCodes_DBERR), errDesc))
}

return do
}

// update auth_phone_transactions set state = :state where id = :id
// TODO(@benqi): sqlmap
func (dao *AuthPhoneTransactionsDAO) UpdateState(state int8, id int64) int64 {
Expand Down
10 changes: 10 additions & 0 deletions messenger/biz_server/biz/dal/tables/auth_phone_transactions.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@
auth_key_id = :auth_key_id AND phone_number = :phone_number AND transaction_hash = :transaction_hash
</sql>
</operation>
<operation name="SelectLast">
<sql>
SELECT
id, code, code_expired, code_msg_id, sent_code_type, flash_call_pattern, next_code_type, attempts, state
FROM
auth_phone_transactions
WHERE
state = 2 AND auth_key_id = :auth_key_id AND phone_number = :phone_number ORDER BY id DESC LIMIT 1
</sql>
</operation>
<operation name="UpdateState">
<sql>
UPDATE auth_phone_transactions SET state = :state WHERE id = :id
Expand Down
182 changes: 182 additions & 0 deletions messenger/biz_server/server/auth/crcloud_sms.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
// Copyright (c) 2018-present, NebulaChat Studio (https://nebula.chat).
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Author: Benqi ([email protected])

package auth

import (
"time"
//"fmt"
"encoding/json"
"github.com/golang/glog"
"github.com/nebula-chat/chatengine/pkg/http_client"
"nebula.chat/enterprise/pkg/log"
)

// TODO(@benqi): impl sendSms

//type SendSmsVerifyCodeF func(phoneNumber, code, codeHash string, sentCodeType int) (string, error)
//type VerifySmsCodeF func(codeHash, code, extraData string) (error)
//
//func getSendSmsVerifyCodeF() SendSmsVerifyCodeF {
// return jSendVerifyCode
//}
//
//func getVerifySmsCodeF() VerifySmsCodeF {
// return jVerifyCode
//}

const (
crCloudAppKey = "4erySvd5PIIdWTZD"
crCloudSecret = "00S3YA5oYWUcsnQwWfzkOKygmbI4IUo3"


intlApiUrl = "http://api.1cloudsp.com/intl/api/v2/send"
intlSignId = "1410"
intlTemplateId = "2101"

singleApiUrl = "http://api.1cloudsp.com/api/v2/single_send"
singleSignId = "32859"
templateId = "50451"

)



//var authorization string

func init() {
//authorization = "Basic " + base64.StdEncoding.EncodeToString([]byte(jPushAppKey+":"+jPushMasterSecret))
}


type crCloudSmsResponse struct {
Code string `json:"code,omitempty"`
Msg string `json:"msg,omitempty"`
SMUuid string `json:"smUuid,omitempty"`
}

func SendCRCloudVerifyCode(phone string,code string) (string, error) {
go func() {
httpRequest := http_client.NewBeegoRequest(singleApiUrl, "POST").
SetTimeout(time.Second*20, time.Second*10).
Header("Connection", "close")

//new NameValuePair("accesskey", accesskey),
// new NameValuePair("secret", accessSecret),
// new NameValuePair("sign", intlSignId),
// new NameValuePair("templateId", intlTemplateId),
// new NameValuePair("mobile", "8618916791325"),
// new NameValuePair("content", URLEncoder.encode("12345", "utf-8"))
//增加正则匹配号码是中国号码,如果是走国内通道,如果不是走海外通道


//国际
//params := map[string]string{
// "accesskey":crCloudAppKey,
// "secret":crCloudSecret,
// "sign":intlSignId,
// "templateId": intlTemplateId,
// "mobile": phone,
// "content": code,
//}

//国内
params := map[string]string{
"accesskey":crCloudAppKey,
"secret":crCloudSecret,
"sign":singleSignId,
"templateId": templateId,
"mobile": "18916791325",
"content": code,
}

httpRequest.JSONBody(params)

r := &crCloudSmsResponse{}
httpRequest.Debug(true)

body, err := httpRequest.Bytes()
glog.Infof("send_sms_help request:%s",string(httpRequest.DumpRequest()))
glog.Infof("send_sms_help body:%s",string(body))

if err != nil {
log.Debugf("err - %v", err)
}
//if err != nil {
// return "", err
//}
//
////err = httpRequest.ToJSON(r)
//
//err = json.Unmarshal(body, r)
//if err != nil {
// return "", err
//}
//
//if err != nil {
// return "", err
//}
//
//return r.Code, nil
}()

return code, nil
}

func VerifyCRCloudCode(rCode, code string) error {
//httpRequest := http_client.NewBeegoRequest(jPushVerifyCodeUrl+"/"+msgId+"/valid", "POST").
// SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
// SetTimeout(time.Second*20, time.Second*10).
// Header("Authorization", authorization)
//
//params := map[string]string{
// "code": code,
//}
//httpRequest.JSONBody(params)
//
//r := &jPushSmsResponse{}
//httpRequest.Debug(true)
//
//glog.Infof("send_sms_helper request:%s",string(httpRequest.DumpRequest()))
//body, err := httpRequest.Bytes()
//glog.Infof("send_sms_helper request:%s",string(httpRequest.DumpRequest()))
//glog.Infof("send_sms_helper body:%s",string(body))
//
////err = httpRequest.ToJSON(r)
//if err != nil {
// return err
//}
//
//err = json.Unmarshal(body, r)
//if err != nil {
// return err
//}
//
//if !r.IsValid {
// return fmt.Errorf("code invalid")
//}
return nil
}


func crCloudSendVerifyCode(phoneNumber, code, codeHash string, sentCodeType int) (string, error) {
return SendCRCloudVerifyCode(phoneNumber,code)
}

func crCloudVerifyCode(codeHash, code, extraData string) (error) {
return VerifyCRCloudCode(extraData, code)
}
Loading

0 comments on commit eb06697

Please sign in to comment.