prepair to using go concurrent
This commit is contained in:
1 parent
ce0508294c
commit
47816debd3
10 files changed
+222
-139
No files matched your search
+29
-17
@@ -3,9 +3,13 @@ package rest_api
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"linhdevtran99/rest-api/models"
|
||||
"linhdevtran99/rest-api/rest-api/routes"
|
||||
"linhdevtran99/rest-api/rest-api/services"
|
||||
"linhdevtran99/rest-api/utils"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type APIServer struct {
|
||||
@@ -30,11 +34,13 @@ func (s *APIServer) Run() {
|
||||
router := mux.NewRouter()
|
||||
|
||||
routes.AuthRouterSetup(router)
|
||||
|
||||
router.HandleFunc("/test", utils.MakeHTTPHandlerFn(s.TestRoute))
|
||||
|
||||
startMuxServer(s, router)
|
||||
}
|
||||
|
||||
func (s *APIServer) AuthRoute(w http.ResponseWriter, r *http.Request) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
func (s *APIServer) TestRoute(w http.ResponseWriter, r *http.Request) error {
|
||||
|
||||
if r.Method == http.MethodGet {
|
||||
fmt.Println("hit")
|
||||
@@ -56,23 +62,29 @@ func (s *APIServer) AuthRoute(w http.ResponseWriter, r *http.Request) error {
|
||||
//}
|
||||
|
||||
//serect := os.Getenv("EMAIL_VERIFY_SECRET")
|
||||
//isPass, _ := generatorOtp("hello", "nhocdl.poro1@gmail.com", 12, serect)
|
||||
//fmt.Println(isPass)
|
||||
//cipherBase64 := createLinkVerify(&models.CreateUser{
|
||||
// Username: "thewind121212",
|
||||
// Email: "nhocdl.poro1@gmail.com",
|
||||
// Password: "linhporoQ1@",
|
||||
// ConfirmPassword: "linhporoQ1@",
|
||||
//}, serect)
|
||||
|
||||
//_, otp := services.GeneratorOtp("hello", "nhocdl.poro1@gmail.com", 12, serect)
|
||||
//fmt.Println(otp.HashOTP)
|
||||
//fmt.Println(otp.PureOTP)
|
||||
|
||||
//utils.EncryptAESMailLink("nhocdl.poro2@gmail.com", serect, w)
|
||||
|
||||
//jsonData, _ := json.Marshal(map[string]string{"email": "nhocdl.poro1@gmail.com", "user": "thewind121212"})
|
||||
////
|
||||
//utils.Redis.Set(context.Background(), "otp:nhocdl.poro1@gmail.com", string(jsonData), time.Minute)
|
||||
//
|
||||
//key := []byte(serect)
|
||||
//utils.CheckAndWriteRedis("nhocdl.poro1@gmail.com", "thewind121212", "lasdjflasdjlfj")
|
||||
|
||||
services.CheckAndWritePreuser(&models.PreusersMongo{
|
||||
Username: "thewind121212",
|
||||
Email: "nhocdl.poro2@gmail.com",
|
||||
PhoneNumber: "0918327132",
|
||||
VerifySentCount: 0,
|
||||
CreatedDate: time.Now(),
|
||||
UpdateDate: time.Now(),
|
||||
})
|
||||
|
||||
//
|
||||
//i, err := utils.DecryptAES(cipherBase64, key)
|
||||
//if err != nil {
|
||||
// return err
|
||||
//}
|
||||
//
|
||||
//fmt.Println(string(i))
|
||||
|
||||
}
|
||||
|
||||
|
||||
+27
-8
@@ -2,28 +2,47 @@ package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/gorilla/mux"
|
||||
"linhdevtran99/rest-api/models"
|
||||
"linhdevtran99/rest-api/rest-api/services"
|
||||
"linhdevtran99/rest-api/utils"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func RegisterNewAccount(w http.ResponseWriter, r *http.Request) error {
|
||||
client := utils.MongoDB
|
||||
if r.Method == http.MethodPost {
|
||||
var registerInfo models.CreateUser
|
||||
|
||||
_ = json.NewDecoder(r.Body).Decode(®isterInfo)
|
||||
//call function check info user type in
|
||||
validRegisterInfo := services.CheckAndValidRegisterFiled(®isterInfo, w)
|
||||
//call function check data user use in past or not
|
||||
isValidData := services.CheckAccountExist(client, registerInfo.Username, registerInfo.Email, w)
|
||||
|
||||
if isValidData == false || validRegisterInfo == false {
|
||||
return errors.New("USER DON'T HAVE VALID INFO FOR REGISTER ACCOUNT")
|
||||
validRegisterInfo, responseAPI := services.CheckAndValidRegisterFiled(®isterInfo)
|
||||
if responseAPI != nil {
|
||||
return utils.WriteJSON(w, responseAPI.Code, responseAPI.Err.Error())
|
||||
}
|
||||
//call function check data user use in past or not
|
||||
isValidData, responseAPI := services.CheckAccountExist(utils.MongoDB, registerInfo.Username, registerInfo.Email)
|
||||
if responseAPI != nil {
|
||||
return utils.WriteJSON(w, responseAPI.Code, responseAPI.Err.Error())
|
||||
}
|
||||
|
||||
preUserData := &models.PreusersMongo{
|
||||
Username: registerInfo.Username,
|
||||
Email: registerInfo.Email,
|
||||
PhoneNumber: registerInfo.PhoneNumber,
|
||||
HashPassword: registerInfo.Password,
|
||||
CreatedDate: time.Now(),
|
||||
UpdateDate: time.Now(),
|
||||
VerifySentCount: 1,
|
||||
}
|
||||
|
||||
services.CheckAndWritePreuser(preUserData)
|
||||
|
||||
//debug
|
||||
if isValidData == true || validRegisterInfo == true {
|
||||
return utils.WriteJSON(w, http.StatusOK, "USER HAVE VALID INFO FOR REGISTER ACCOUNT")
|
||||
}
|
||||
//debug
|
||||
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -3,8 +3,8 @@ package services
|
||||
import (
|
||||
"context"
|
||||
"encoding/base32"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/pquerna/otp"
|
||||
@@ -15,10 +15,16 @@ import (
|
||||
"linhdevtran99/rest-api/models"
|
||||
"linhdevtran99/rest-api/utils"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Check the user register field is valid or not
|
||||
func CheckAndValidRegisterFiled(registerData *models.CreateUser, w http.ResponseWriter) bool {
|
||||
type ResponseError struct {
|
||||
Code int
|
||||
Err error
|
||||
}
|
||||
|
||||
// CheckAndValidRegisterFiled Check the user register field is valid or not
|
||||
func CheckAndValidRegisterFiled(registerData *models.CreateUser) (bool, *ResponseError) {
|
||||
_ = models.Validate.RegisterValidation("customPassword", models.PasswordValidator)
|
||||
errs := models.Validate.Struct(registerData)
|
||||
var errStack []string
|
||||
@@ -27,49 +33,45 @@ func CheckAndValidRegisterFiled(registerData *models.CreateUser, w http.Response
|
||||
switch err.Field() {
|
||||
case "Email":
|
||||
{
|
||||
fmt.Println("Email không hợp lệ")
|
||||
fmt.Println("Internal Log: Email không hợp lệ")
|
||||
errStack = append(errStack, "Email")
|
||||
}
|
||||
case "Username":
|
||||
{
|
||||
fmt.Println("User không hợp lệ")
|
||||
fmt.Println("Internal Log: User không hợp lệ")
|
||||
errStack = append(errStack, "User")
|
||||
}
|
||||
case "Password":
|
||||
{
|
||||
fmt.Println("Password không hợp lệ")
|
||||
fmt.Println("Internal Log: Password không hợp lệ")
|
||||
errStack = append(errStack, "Password")
|
||||
}
|
||||
case "ConfirmPassword":
|
||||
{
|
||||
fmt.Println("Nhập lại mật khẩu sai")
|
||||
fmt.Println("Internal Log: Nhập lại mật khẩu sai")
|
||||
errStack = append(errStack, "ConfirmPassword")
|
||||
}
|
||||
case "PhoneNumber":
|
||||
{
|
||||
fmt.Println("SĐT không hợp lệ")
|
||||
fmt.Println("Internal Log: SĐT không hợp lệ")
|
||||
errStack = append(errStack, "PhoneNumber")
|
||||
}
|
||||
}
|
||||
}
|
||||
//handle repose error
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
err := json.NewEncoder(w).Encode(errStack)
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("There is error in write reponse at checking info user")
|
||||
}
|
||||
return false
|
||||
jsonData, _ := json.Marshal(errStack)
|
||||
return false, &ResponseError{Code: http.StatusBadRequest, Err: errors.New(string(jsonData))}
|
||||
}
|
||||
|
||||
return true
|
||||
return true, nil
|
||||
|
||||
}
|
||||
|
||||
// Checking in db is user input same data in
|
||||
func CheckAccountExist(mongoClient *mongo.Client, userName string, email string, w http.ResponseWriter) bool {
|
||||
// CheckAccountExist Checking in db is user input same data in
|
||||
func CheckAccountExist(mongoClient *mongo.Client, userName string, email string) (bool, *ResponseError) {
|
||||
//filter in mongodb
|
||||
var isValid bool
|
||||
var errAPI *ResponseError
|
||||
|
||||
filter := bson.D{
|
||||
{"$or", bson.A{
|
||||
@@ -78,27 +80,24 @@ func CheckAccountExist(mongoClient *mongo.Client, userName string, email string,
|
||||
}},
|
||||
}
|
||||
|
||||
userData := mongoClient.Database("Totoday-shop").Collection("users")
|
||||
|
||||
var result models.UsersMongo
|
||||
err := userData.FindOne(context.TODO(), filter).Decode(&result)
|
||||
_, err := utils.PreUserData.FindOne(context.TODO(), filter).Raw()
|
||||
if err != nil {
|
||||
isValid = true
|
||||
}
|
||||
if err == nil {
|
||||
fmt.Println("Email or username already had register")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
err := json.NewEncoder(w).Encode("Your username or email had been register before")
|
||||
if err != nil {
|
||||
fmt.Println("There is error in write reponse at checking data user register")
|
||||
}
|
||||
errAPI = nil
|
||||
} else {
|
||||
fmt.Println("Internal Log: Email or username already had register")
|
||||
isValid = false
|
||||
errAPI = &ResponseError{
|
||||
Code: http.StatusBadRequest,
|
||||
Err: errors.New("your username or email had been register before"),
|
||||
}
|
||||
}
|
||||
|
||||
return isValid
|
||||
return isValid, errAPI
|
||||
}
|
||||
|
||||
// Generate HOtp for confirm infomation
|
||||
// GeneratorOtp Generate HOtp for confirm information
|
||||
|
||||
func GeneratorOtp(userName string, email string, counter uint64, serect string) (bool, *models.OtpGenerate) {
|
||||
|
||||
serectBase32 := base32.StdEncoding.EncodeToString([]byte(serect + userName + email))
|
||||
@@ -109,19 +108,13 @@ func GeneratorOtp(userName string, email string, counter uint64, serect string)
|
||||
|
||||
if err != nil {
|
||||
fmt.Println("Fail to create OTP")
|
||||
return false, &models.OtpGenerate{
|
||||
PureOTP: "none",
|
||||
HashOTP: "none",
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(passCode), 5)
|
||||
if err != nil {
|
||||
fmt.Println("Fail to create OTP")
|
||||
return false, &models.OtpGenerate{
|
||||
PureOTP: "none",
|
||||
HashOTP: "none",
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return true, &models.OtpGenerate{
|
||||
@@ -130,15 +123,43 @@ func GeneratorOtp(userName string, email string, counter uint64, serect string)
|
||||
}
|
||||
}
|
||||
|
||||
// Create a alternative verify link
|
||||
func CreateLinkVerify(registerInfo *models.CreateUser, secrect string) string {
|
||||
// CreateLinkVerify Create a alternative verify link
|
||||
func CreateLinkVerify(registerInfo string, secrect string) string {
|
||||
return "linh"
|
||||
|
||||
}
|
||||
|
||||
// check and write pre use into mongo db
|
||||
func CheckAndWritePreuser(registerInfo *models.PreusersMongo) {
|
||||
//checking
|
||||
email := registerInfo.Email
|
||||
filter := bson.D{{"email", email}}
|
||||
_, err := utils.PreUserData.FindOne(context.Background(), filter).Raw()
|
||||
if err != nil {
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(registerInfo.HashPassword), 10)
|
||||
if err != nil {
|
||||
fmt.Println("Fail to create OTP")
|
||||
}
|
||||
registerInfo.HashPassword = string(hashed)
|
||||
_, err = utils.PreUserData.InsertOne(context.Background(), registerInfo)
|
||||
if err != nil {
|
||||
fmt.Println("Something Went Wrong")
|
||||
}
|
||||
} else {
|
||||
update := bson.D{
|
||||
{"$inc", bson.D{
|
||||
{"verify_sent_count", 1},
|
||||
}},
|
||||
{"$set", bson.D{
|
||||
{"update_date", time.Now()},
|
||||
},
|
||||
}}
|
||||
|
||||
_, err := utils.PreUserData.UpdateOne(context.Background(), filter, update)
|
||||
if err != nil {
|
||||
fmt.Println("Internal log: update document fail")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
data, _ := json.Marshal(registerInfo)
|
||||
key := []byte(secrect)
|
||||
|
||||
ciphertext, _ := utils.EncryptAES(data, key)
|
||||
|
||||
cipherTextBase64 := base64.StdEncoding.EncodeToString(ciphertext)
|
||||
|
||||
return cipherTextBase64
|
||||
}
|
||||
Reference in new issue
Block a user