Skip to content

Commit

Permalink
Support email registration
Browse files Browse the repository at this point in the history
  • Loading branch information
luhaoling committed Oct 12, 2023
1 parent 72bb2d5 commit cee94e9
Show file tree
Hide file tree
Showing 14 changed files with 703 additions and 545 deletions.
4 changes: 3 additions & 1 deletion cmd/api/chat-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@ package main
import (
"flag"
"fmt"
"github.com/OpenIMSDK/chat/tools/component"

"math/rand"
"net"
"strconv"
"time"

"github.com/OpenIMSDK/chat/tools/component"

mw2 "github.com/OpenIMSDK/chat/pkg/common/mw"

"github.com/OpenIMSDK/chat/internal/api"
Expand Down
9 changes: 9 additions & 0 deletions config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,15 @@ verifyCode:
accessKeySecret: ""
signName: ""
verificationCodeTemplateCode: ""
mail: # 根据对应的发件邮箱更改 sendMail、senderAuthorizationCode、smtpAddr、smtpPort 即可
title: ""
senderMail: "" # 发送者
senderAuthorizationCode: "" # 授权码
smtpAddr: "smtp.qq.com" # smtp 服务器地址
smtpPort: 25 # smtp 服务器邮件发送端口
testDepartMentID: 001
imAPIURL: http://127.0.0.1:10002


# 获取ip的header,没有配置直接获取远程地址
#proxyHeader: "X-Forwarded-For"
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ require (
github.com/OpenIMSDK/tools v0.0.14
github.com/go-zookeeper/zk v1.0.3
github.com/redis/go-redis/v9 v9.1.0
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
)

require (
Expand Down Expand Up @@ -87,6 +88,7 @@ require (
golang.org/x/sys v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,14 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
gopkg.in/ini.v1 v1.56.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
Expand Down
5 changes: 2 additions & 3 deletions internal/rpc/admin/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,8 @@ func Start(discov discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
panic(err)
}

admin.RegisterAdminServer(server, &adminServer{
Database: database.NewAdminDatabase(db, rdb),
Chat: chat.NewChatClient(discov),
admin.RegisterAdminServer(server, &adminServer{Database: database.NewAdminDatabase(db, rdb),
Chat: chat.NewChatClient(discov),
})
return nil
}
Expand Down
7 changes: 7 additions & 0 deletions internal/rpc/chat/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/OpenIMSDK/chat/pkg/common/db/database"
chat2 "github.com/OpenIMSDK/chat/pkg/common/db/table/chat"
"github.com/OpenIMSDK/chat/pkg/common/dbconn"
"github.com/OpenIMSDK/chat/pkg/email"
"github.com/OpenIMSDK/chat/pkg/proto/chat"
chatClient "github.com/OpenIMSDK/chat/pkg/rpclient/chat"
"github.com/OpenIMSDK/chat/pkg/sms"
Expand All @@ -47,13 +48,18 @@ func Start(discov discoveryregistry.SvcDiscoveryRegistry, server *grpc.Server) e
if err != nil {
return err
}
email, err := email.NewMail()
if err != nil {
return err
}
if err := discov.CreateRpcRootNodes([]string{config.Config.RpcRegisterName.OpenImAdminName, config.Config.RpcRegisterName.OpenImChatName}); err != nil {
panic(err)
}
chat.RegisterChatServer(server, &chatSvr{
Database: database.NewChatDatabase(db),
Admin: chatClient.NewAdminClient(discov),
SMS: s,
Mail: email,
})
return nil
}
Expand All @@ -62,4 +68,5 @@ type chatSvr struct {
Database database.ChatDatabaseInterface
Admin *chatClient.AdminClient
SMS sms.SMS
Mail email.Mail
}
62 changes: 48 additions & 14 deletions internal/rpc/chat/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,13 @@ package chat

import (
"context"
"github.com/OpenIMSDK/chat/pkg/common/mctx"
"math/rand"
"strconv"
"strings"
"time"

"github.com/OpenIMSDK/chat/pkg/common/mctx"

constant2 "github.com/OpenIMSDK/protocol/constant"

"github.com/OpenIMSDK/tools/errs"
Expand Down Expand Up @@ -57,14 +58,26 @@ func (o *chatSvr) SendVerifyCode(ctx context.Context, req *chat.SendVerifyCodeRe
if _, err := strconv.ParseUint(req.AreaCode[1:], 10, 64); err != nil {
return nil, errs.ErrArgs.Wrap("area code must be number")
}
if _, err := strconv.ParseUint(req.PhoneNumber, 10, 64); err != nil {
return nil, errs.ErrArgs.Wrap("phone number must be number")
}
_, err := o.Database.TakeAttributeByPhone(ctx, req.AreaCode, req.PhoneNumber)
if err == nil {
return nil, eerrs.ErrPhoneAlreadyRegister.Wrap("phone already register")
} else if !o.Database.IsNotFound(err) {
return nil, err
if req.PhoneNumber != "" {
if _, err := strconv.ParseUint(req.PhoneNumber, 10, 64); err != nil {
return nil, errs.ErrArgs.Wrap("phone number must be number")
}
_, err := o.Database.TakeAttributeByPhone(ctx, req.AreaCode, req.PhoneNumber)
if err == nil {
return nil, eerrs.ErrPhoneAlreadyRegister.Wrap("phone already register")
} else if !o.Database.IsNotFound(err) {
return nil, err
}
} else {
if err := chat.EmailCheck(req.Email); err != nil {
return nil, errs.ErrArgs.Wrap("email must be right")
}
_, err := o.Database.TakeAttributeByEmail(ctx, req.Email)
if err == nil {
return nil, eerrs.ErrPhoneAlreadyRegister.Wrap("phone already register")
} else if !o.Database.IsNotFound(err) {
return nil, err
}
}
conf, err := o.Admin.GetConfig(ctx)
if err != nil {
Expand Down Expand Up @@ -106,15 +119,30 @@ func (o *chatSvr) SendVerifyCode(ctx context.Context, req *chat.SendVerifyCodeRe
if verifyCode.MaxCount < int(count) {
return nil, eerrs.ErrVerifyCodeSendFrequently.Wrap()
}
var account string
var isEmail bool
if req.PhoneNumber != "" {
account = o.verifyCodeJoin(req.AreaCode, req.PhoneNumber)
} else {
isEmail = true
account = req.Email
}
t := &chat2.VerifyCode{
Account: o.verifyCodeJoin(req.AreaCode, req.PhoneNumber),
Account: account,
Code: o.genVerifyCode(),
Duration: uint(config.Config.VerifyCode.ValidTime),
CreateTime: time.Now(),
}
err = o.Database.AddVerifyCode(ctx, t, func() error {
return o.SMS.SendCode(ctx, req.AreaCode, req.PhoneNumber, t.Code)
})
if !isEmail {
err = o.Database.AddVerifyCode(ctx, t, func() error {
return o.SMS.SendCode(ctx, req.AreaCode, req.PhoneNumber, t.Code)
})
} else {
// 发送邮件验证码
err = o.Database.AddVerifyCode(ctx, t, func() error {
return o.Mail.SendMail(ctx, req.Email, t.Code)
})
}
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -163,7 +191,13 @@ func (o *chatSvr) verifyCode(ctx context.Context, account string, verifyCode str

func (o *chatSvr) VerifyCode(ctx context.Context, req *chat.VerifyCodeReq) (*chat.VerifyCodeResp, error) {
defer log.ZDebug(ctx, "return")
if _, err := o.verifyCode(ctx, o.verifyCodeJoin(req.AreaCode, req.PhoneNumber), req.VerifyCode); err != nil {
var account string
if req.PhoneNumber != "" {
account = o.verifyCodeJoin(req.AreaCode, req.PhoneNumber)
} else {
account = req.Email
}
if _, err := o.verifyCode(ctx, account, req.VerifyCode); err != nil {
return nil, err
}
return &chat.VerifyCodeResp{}, nil
Expand Down
9 changes: 9 additions & 0 deletions pkg/common/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ var Config struct {
SignName string `yaml:"signName"`
VerificationCodeTemplateCode string `yaml:"verificationCodeTemplateCode"`
} `yaml:"ali"`
Mail struct {
Title string `yaml:"title"`
SenderMail string `yaml:"senderMail"`
SenderAuthorizationCode string `yaml:"senderAuthorizationCode"`
SmtpAddr string `yaml:"smtpAddr"`
SmtpPort int `yaml:"smtpPort"`
} `yaml:"mail"`
TestDepartMentID string `yaml:"testDepartMentID"`
ImAPIURL string `yaml:"imAPIURL"`
} `yaml:"verifyCode"`
ProxyHeader string `yaml:"proxyHeader"`
AdminList []Admin `yaml:"adminList"`
Expand Down
5 changes: 5 additions & 0 deletions pkg/common/db/database/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type ChatDatabaseInterface interface {
FindAttribute(ctx context.Context, userIDs []string) ([]*table.Attribute, error)
FindAttributeByAccount(ctx context.Context, accounts []string) ([]*table.Attribute, error)
TakeAttributeByPhone(ctx context.Context, areaCode string, phoneNumber string) (*table.Attribute, error)
TakeAttributeByEmail(ctx context.Context, Email string) (*table.Attribute, error)
TakeAttributeByAccount(ctx context.Context, account string) (*table.Attribute, error)
TakeAttributeByUserID(ctx context.Context, userID string) (*table.Attribute, error)
Search(ctx context.Context, normalUser int32, keyword string, gender int32, pageNumber int32, showNumber int32) (uint32, []*table.Attribute, error)
Expand Down Expand Up @@ -132,6 +133,10 @@ func (o *ChatDatabase) TakeAttributeByPhone(ctx context.Context, areaCode string
return o.attribute.TakePhone(ctx, areaCode, phoneNumber)
}

func (o *ChatDatabase) TakeAttributeByEmail(ctx context.Context, email string) (*table.Attribute, error) {
return o.attribute.TakeEmail(ctx, email)
}

func (o *ChatDatabase) TakeAttributeByAccount(ctx context.Context, account string) (*table.Attribute, error) {
return o.attribute.TakeAccount(ctx, account)
}
Expand Down
5 changes: 5 additions & 0 deletions pkg/common/db/model/chat/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ func (o *Attribute) TakePhone(ctx context.Context, areaCode string, phoneNumber
return &a, errs.Wrap(o.db.WithContext(ctx).Where("area_code = ? and phone_number = ?", areaCode, phoneNumber).First(&a).Error)
}

func (o *Attribute) TakeEmail(ctx context.Context, email string) (*chat.Attribute, error) {
var a chat.Attribute
return &a, errs.Wrap(o.db.WithContext(ctx).Where("email = ?", email).First(&a).Error)
}

func (o *Attribute) TakeAccount(ctx context.Context, account string) (*chat.Attribute, error) {
var a chat.Attribute
return &a, errs.Wrap(o.db.WithContext(ctx).Where("account = ?", account).Take(&a).Error)
Expand Down
1 change: 1 addition & 0 deletions pkg/common/db/table/chat/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ type AttributeInterface interface {
FindAccount(ctx context.Context, accounts []string) ([]*Attribute, error)
Search(ctx context.Context, keyword string, genders []int32, page int32, size int32) (uint32, []*Attribute, error)
TakePhone(ctx context.Context, areaCode string, phoneNumber string) (*Attribute, error)
TakeEmail(ctx context.Context, email string) (*Attribute, error)
TakeAccount(ctx context.Context, account string) (*Attribute, error)
Take(ctx context.Context, userID string) (*Attribute, error)
SearchNormalUser(ctx context.Context, keyword string, forbiddenID []string, gender int32, page int32, size int32) (uint32, []*Attribute, error)
Expand Down
59 changes: 59 additions & 0 deletions pkg/email/mail.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright © 2023 OpenIM open source community. 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.

package email

import (
"context"
"fmt"

"github.com/OpenIMSDK/chat/pkg/common/config"
"github.com/OpenIMSDK/tools/errs"

"gopkg.in/gomail.v2"
)

func NewMail() (Mail, error) {
dail := gomail.NewDialer(
config.Config.VerifyCode.Mail.SmtpAddr,
config.Config.VerifyCode.Mail.SmtpPort,
config.Config.VerifyCode.Mail.SenderMail,
config.Config.VerifyCode.Mail.SenderAuthorizationCode)
return &mail{dail: dail}, nil
}

type Mail interface {
Name() string
SendMail(ctx context.Context, mail string, verifyCode string) error
}

type mail struct {
dail *gomail.Dialer
}

func (a *mail) Name() string {
return "mail"
}

func (a *mail) SendMail(ctx context.Context, mail string, verifyCode string) error {
m := gomail.NewMessage()
m.SetHeader(`From`, config.Config.VerifyCode.Mail.SenderMail)
m.SetHeader(`To`, []string{mail}...)
m.SetHeader(`Subject`, config.Config.VerifyCode.Mail.Title)
m.SetBody(`text/html`, fmt.Sprintf("您的验证码为:%s,该验证码5分钟内有效,请勿泄露于他人。", verifyCode))

// Send
err := a.dail.DialAndSend(m)
return errs.Wrap(err)
}
Loading

0 comments on commit cee94e9

Please sign in to comment.