Skip to content

Commit

Permalink
update jwt pacakge
Browse files Browse the repository at this point in the history
  • Loading branch information
maxyzli committed Oct 12, 2023
1 parent e405b31 commit 1f38641
Show file tree
Hide file tree
Showing 77 changed files with 1,812 additions and 503 deletions.
9 changes: 7 additions & 2 deletions configs/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,10 @@ sendgrid:
sender_email: xxx

recaptcha:
site_key: xxx
secret_key: xxx
# For reCAPTCHA v2, use the following test keys.
# You will always get No CAPTCHA and all verification requests will pass.
# The reCAPTCHA widget will show a warning message to ensure it's not used
# for production traffic.
site_key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
secret_key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

52 changes: 44 additions & 8 deletions global/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"flag"
"fmt"
"log"
"os"
"strings"
"sync"

Expand All @@ -13,18 +14,31 @@ import (
)

var (
once = new(sync.Once)
configName = flag.String("config", "development", "config file name, default is development")
once = new(sync.Once)
configName = flag.String(
"config",
"development",
"config file name, default is development",
)
ShowVersionInfo = flag.Bool("v", false, "show version info or not")
)

func Init() {
once.Do(func() {
if !flag.Parsed() {
isTest := false
for _, arg := range os.Args {
if strings.Contains(arg, "test") {
isTest = true
break
}
}

if !isTest && !flag.Parsed() {
flag.Parse()
}

if err := initConfig(); err != nil {
panic(fmt.Errorf("initconfig failed: %s \n", err))
panic(fmt.Errorf("initconfig failed: %s", err))
}
watchConfig()

Expand All @@ -33,16 +47,38 @@ func Init() {
}

func initConfig() error {
if err := setConfigNameAndType(); err != nil {
return fmt.Errorf("setting config name and type failed: %w", err)
}

addConfigPaths()

if err := setupEnvironmentVariables(); err != nil {
return fmt.Errorf("setting up environment variables failed: %w", err)
}

if err := viper.ReadInConfig(); err != nil {
return fmt.Errorf("reading config failed: %w", err)
}

return nil
}

func setConfigNameAndType() error {
viper.SetConfigName(*configName)
viper.SetConfigType("yaml")
return nil
}

func addConfigPaths() {
viper.AddConfigPath("configs")
viper.AddConfigPath(App.RootDir + "/configs")
viper.SetConfigType("yaml")
}

func setupEnvironmentVariables() error {
viper.AutomaticEnv()
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
return err
}
return nil
}

Expand Down
60 changes: 49 additions & 11 deletions internal/app/http/controller/account_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,12 @@ func (a *accountHandler) RegisterRoutes(
a.once.Do(func() {
private.Path("/account").HandlerFunc(a.accountPage()).Methods("GET")
private.Path("/account").HandlerFunc(a.updateAccount()).Methods("POST")
adminPrivate.Path("/accounts").HandlerFunc(a.searchAccountPage()).Methods("GET")
adminPrivate.Path("/accounts/search").HandlerFunc(a.searchAccount()).Methods("GET")
adminPrivate.Path("/accounts").
HandlerFunc(a.searchAccountPage()).
Methods("GET")
adminPrivate.Path("/accounts/search").
HandlerFunc(a.searchAccount()).
Methods("GET")
})
}

Expand Down Expand Up @@ -122,7 +126,12 @@ func (a *accountHandler) searchAccount() func(http.ResponseWriter, *http.Request
res := sreachResponse{FormData: f, Result: new(findAccountResult)}

if f.Filter != "business" && f.LastName == "" && f.Email == "" {
t.Render(w, r, res, []string{"Please enter at least one search criteria."})
t.Render(
w,
r,
res,
[]string{"Please enter at least one search criteria."},
)
return
}

Expand Down Expand Up @@ -284,7 +293,10 @@ func (a *accountHandler) updateAccount() func(http.ResponseWriter, *http.Request
// Validate the user inputs.
errorMessages := []string{}
if formData.CurrentPassword != "" {
_, err := service.User.Login(formData.User.Email, formData.CurrentPassword)
_, err := service.User.Login(
formData.User.Email,
formData.CurrentPassword,
)
if err != nil {
l.Logger.Error("appServer UpdateAccount failed", zap.Error(err))
t.Error(w, r, formData, err)
Expand All @@ -298,7 +310,10 @@ func (a *accountHandler) updateAccount() func(http.ResponseWriter, *http.Request
errorMessages = append(errorMessages, data.Validate()...)
}
if len(errorMessages) > 0 {
l.Logger.Info("appServer UpdateAccount failed", zap.Strings("input invalid", errorMessages))
l.Logger.Info(
"appServer UpdateAccount failed",
zap.Strings("input invalid", errorMessages),
)
t.Render(w, r, formData, errorMessages)
return
}
Expand All @@ -311,22 +326,35 @@ func (a *accountHandler) updateAccount() func(http.ResponseWriter, *http.Request
return
}

offersAdded, offersRemoved := helper.TagDifference(formData.Business.Offers, oldBusiness.Offers)
offersAdded, offersRemoved := helper.TagDifference(
formData.Business.Offers,
oldBusiness.Offers,
)
formData.Business.OffersAdded = offersAdded
formData.Business.OffersRemoved = offersRemoved
wantsAdded, wantsRemoved := helper.TagDifference(formData.Business.Wants, oldBusiness.Wants)
wantsAdded, wantsRemoved := helper.TagDifference(
formData.Business.Wants,
oldBusiness.Wants,
)
formData.Business.WantsAdded = wantsAdded
formData.Business.WantsRemoved = wantsRemoved

err = service.Business.UpdateBusiness(user.CompanyID, formData.Business, false)
err = service.Business.UpdateBusiness(
user.CompanyID,
formData.Business,
false,
)
if err != nil {
l.Logger.Error("appServer UpdateAccount failed", zap.Error(err))
t.Error(w, r, formData, err)
return
}

if formData.CurrentPassword != "" && formData.ConfirmPassword != "" {
err = service.User.ResetPassword(user.Email, formData.ConfirmPassword)
err = service.User.ResetPassword(
user.Email,
formData.ConfirmPassword,
)
if err != nil {
l.Logger.Error("appServer UpdateAccount failed", zap.Error(err))
t.Error(w, r, formData, err)
Expand All @@ -335,9 +363,19 @@ func (a *accountHandler) updateAccount() func(http.ResponseWriter, *http.Request
}

go func() {
err := service.UserAction.Log(log.User.ModifyAccount(user, formData.User, oldBusiness, formData.Business))
err := service.UserAction.Log(
log.User.ModifyAccount(
user,
formData.User,
oldBusiness,
formData.Business,
),
)
if err != nil {
l.Logger.Error("BuildModifyAccountAction failed", zap.Error(err))
l.Logger.Error(
"BuildModifyAccountAction failed",
zap.Error(err),
)
}
}()

Expand Down
103 changes: 83 additions & 20 deletions internal/app/http/controller/admin_business_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,16 @@ func (a *adminBusinessHandler) RegisterRoutes(
adminPrivate *mux.Router,
) {
a.once.Do(func() {
adminPrivate.Path("/businesses/{id}").HandlerFunc(a.adminBusinessPage()).Methods("GET")
adminPrivate.Path("/businesses/{id}").HandlerFunc(a.updateBusiness()).Methods("POST")
adminPrivate.Path("/businesses/{id}").
HandlerFunc(a.adminBusinessPage()).
Methods("GET")
adminPrivate.Path("/businesses/{id}").
HandlerFunc(a.updateBusiness()).
Methods("POST")

adminPrivate.Path("/api/businesses/{id}").HandlerFunc(a.deleteBusiness()).Methods("DELETE")
adminPrivate.Path("/api/businesses/{id}").
HandlerFunc(a.deleteBusiness()).
Methods("DELETE")
})
}

Expand Down Expand Up @@ -97,12 +103,18 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
errorMessages := validator.UpdateBusiness(d.Business)
maxPosBal, err := strconv.ParseFloat(r.FormValue("max_pos_bal"), 64)
if err != nil {
errorMessages = append(errorMessages, "Max pos balance should be a number")
errorMessages = append(
errorMessages,
"Max pos balance should be a number",
)
}
d.Balance.MaxPosBal = math.Abs(maxPosBal)
maxNegBal, err := strconv.ParseFloat(r.FormValue("max_neg_bal"), 64)
if err != nil {
errorMessages = append(errorMessages, "Max neg balance should be a number")
errorMessages = append(
errorMessages,
"Max neg balance should be a number",
)
}
if math.Abs(maxNegBal) == 0 {
d.Balance.MaxNegBal = 0
Expand All @@ -118,10 +130,22 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
return
}
if account.Balance > d.Balance.MaxPosBal {
errorMessages = append(errorMessages, "The current account balance ("+fmt.Sprintf("%.2f", account.Balance)+") has exceed your max pos balance input")
errorMessages = append(
errorMessages,
"The current account balance ("+fmt.Sprintf(
"%.2f",
account.Balance,
)+") has exceed your max pos balance input",
)
}
if account.Balance < -math.Abs(d.Balance.MaxNegBal) {
errorMessages = append(errorMessages, "The current account balance ("+fmt.Sprintf("%.2f", account.Balance)+") has exceed your max neg balance input")
errorMessages = append(
errorMessages,
"The current account balance ("+fmt.Sprintf(
"%.2f",
account.Balance,
)+") has exceed your max neg balance input",
)
}
if len(errorMessages) > 0 {
l.Logger.Error("UpdateBusiness failed", zap.Error(err))
Expand All @@ -136,10 +160,16 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
t.Error(w, r, d, err)
return
}
offersAdded, offersRemoved := helper.TagDifference(d.Business.Offers, oldBusiness.Offers)
offersAdded, offersRemoved := helper.TagDifference(
d.Business.Offers,
oldBusiness.Offers,
)
d.Business.OffersAdded = offersAdded
d.Business.OffersRemoved = offersRemoved
wantsAdded, wantsRemoved := helper.TagDifference(d.Business.Wants, oldBusiness.Wants)
wantsAdded, wantsRemoved := helper.TagDifference(
d.Business.Wants,
oldBusiness.Wants,
)
d.Business.WantsAdded = wantsAdded
d.Business.WantsRemoved = wantsRemoved
err = service.Business.UpdateBusiness(bID, d.Business, true)
Expand All @@ -156,7 +186,11 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
t.Error(w, r, d, err)
return
}
err = service.BalanceLimit.Update(account.ID, d.Balance.MaxPosBal, d.Balance.MaxNegBal)
err = service.BalanceLimit.Update(
account.ID,
d.Balance.MaxPosBal,
d.Balance.MaxNegBal,
)
if err != nil {
l.Logger.Error("UpdateBusiness failed", zap.Error(err))
t.Error(w, r, d, err)
Expand All @@ -175,12 +209,27 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
adminUser, err := service.AdminUser.FindByID(objID)
user, err := service.User.FindByBusinessID(bID)
if err != nil {
l.Logger.Error("log.Admin.ModifyBusiness failed", zap.Error(err))
l.Logger.Error(
"log.Admin.ModifyBusiness failed",
zap.Error(err),
)
return
}
err = service.UserAction.Log(log.Admin.ModifyBusiness(adminUser, user, oldBusiness, d.Business, oldBalance, d.Balance))
err = service.UserAction.Log(
log.Admin.ModifyBusiness(
adminUser,
user,
oldBusiness,
d.Business,
oldBalance,
d.Balance,
),
)
if err != nil {
l.Logger.Error("log.Admin.ModifyBusiness failed", zap.Error(err))
l.Logger.Error(
"log.Admin.ModifyBusiness failed",
zap.Error(err),
)
}
}()

Expand All @@ -190,21 +239,33 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
// 2. When the business is in accepted status.
// - only update added tags.
go func() {
if !util.IsAcceptedStatus(oldBusiness.Status) && util.IsAcceptedStatus(d.Business.Status) {
err := service.Business.UpdateAllTagsCreatedAt(oldBusiness.ID, time.Now())
if !util.IsAcceptedStatus(oldBusiness.Status) &&
util.IsAcceptedStatus(d.Business.Status) {
err := service.Business.UpdateAllTagsCreatedAt(
oldBusiness.ID,
time.Now(),
)
if err != nil {
l.Logger.Error("UpdateAllTagsCreatedAt failed", zap.Error(err))
l.Logger.Error(
"UpdateAllTagsCreatedAt failed",
zap.Error(err),
)
}
err = TagHandler.SaveOfferTags(helper.GetTagNames(d.Business.Offers))
err = TagHandler.SaveOfferTags(
helper.GetTagNames(d.Business.Offers),
)
if err != nil {
l.Logger.Error("saveOfferTags failed", zap.Error(err))
}
err = TagHandler.SaveWantTags(helper.GetTagNames(d.Business.Wants))
err = TagHandler.SaveWantTags(
helper.GetTagNames(d.Business.Wants),
)
if err != nil {
l.Logger.Error("saveWantTags failed", zap.Error(err))
}
}
if util.IsAcceptedStatus(oldBusiness.Status) && util.IsAcceptedStatus(d.Business.Status) {
if util.IsAcceptedStatus(oldBusiness.Status) &&
util.IsAcceptedStatus(d.Business.Status) {
err := TagHandler.SaveOfferTags(d.Business.OffersAdded)
if err != nil {
l.Logger.Error("saveOfferTags failed", zap.Error(err))
Expand All @@ -217,7 +278,9 @@ func (a *adminBusinessHandler) updateBusiness() func(http.ResponseWriter, *http.
}()
go func() {
// Set timestamp when first trading status applied.
if oldBusiness.MemberStartedAt.IsZero() && (oldBusiness.Status == constant.Business.Accepted) && (d.Business.Status == constant.Trading.Accepted) {
if oldBusiness.MemberStartedAt.IsZero() &&
(oldBusiness.Status == constant.Business.Accepted) &&
(d.Business.Status == constant.Trading.Accepted) {
service.Business.SetMemberStartedAt(bID)
}
}()
Expand Down
Loading

0 comments on commit 1f38641

Please sign in to comment.