Skip to content
This repository has been archived by the owner on Jan 13, 2021. It is now read-only.

Commit

Permalink
Merge pull request #224 from RTradeLtd/api/error-extract
Browse files Browse the repository at this point in the history
Extract Errors To Seperate Package
  • Loading branch information
potsables authored Oct 13, 2018
2 parents f83cff8 + 54e892a commit 51e56bd
Show file tree
Hide file tree
Showing 13 changed files with 193 additions and 168 deletions.
3 changes: 2 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (

"github.com/RTradeLtd/Temporal/api/middleware"
"github.com/RTradeLtd/Temporal/database"
"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/models"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -152,7 +153,7 @@ func (api *API) setupRoutes() {
statsProtected.GET("/stats", func(c *gin.Context) { // admin locked
username := GetAuthenticatedUserFromContext(c)
if err := api.validateAdminRequest(username); err != nil {
FailNotAuthorized(c, UnAuthorizedAdminAccess)
FailNotAuthorized(c, eh.UnAuthorizedAdminAccess)
return
}
c.JSON(http.StatusOK, stats.Report())
Expand Down
33 changes: 18 additions & 15 deletions api/routes_account.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"strconv"

"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/queue"
"github.com/RTradeLtd/Temporal/utils"
"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -35,12 +36,12 @@ func (api *API) changeAccountPassword(c *gin.Context) {

suceeded, err := api.um.ChangePassword(username, oldPassword, newPassword)
if err != nil {
api.LogError(err, PasswordChangeError)(c)
api.LogError(err, eh.PasswordChangeError)(c)
return
}
if !suceeded {
err = fmt.Errorf("password changed failed for user %s to due an unspecified error", username)
api.LogError(err, PasswordChangeError)(c)
api.LogError(err, eh.PasswordChangeError)(c)
return
}

Expand Down Expand Up @@ -74,11 +75,13 @@ func (api *API) registerUserAccount(c *gin.Context) {
}).Info("user account registration detected")

userModel, err := api.um.NewUserAccount(username, password, email, false)
if err != nil {
api.LogError(err, UserAccountCreationError)(c)
if err.Error() != eh.DuplicateEmailError || err.Error() != eh.DuplicateUserNameError {
api.LogError(err, eh.UserAccountCreationError)(c, http.StatusBadRequest)
return
} else if err != nil {
api.LogError(err, err.Error())(c, http.StatusBadRequest)
return
}

api.l.WithFields(log.Fields{
"service": "api",
"user": username,
Expand Down Expand Up @@ -111,7 +114,7 @@ func (api *API) createIPFSKey(c *gin.Context) {

user, err := api.um.FindByUserName(username)
if err != nil {
api.LogError(err, UserSearchError)(c, http.StatusNotFound)
api.LogError(err, eh.UserSearchError)(c, http.StatusNotFound)
return
}
var cost float64
Expand All @@ -127,11 +130,11 @@ func (api *API) createIPFSKey(c *gin.Context) {
}
}
if err != nil {
api.LogError(err, CallCostCalculationError)(c, http.StatusBadRequest)
api.LogError(err, eh.CallCostCalculationError)(c, http.StatusBadRequest)
return
}
if err := api.validateUserCredits(username, cost); err != nil && cost > 0 {
api.LogError(err, InvalidBalanceError)(c, http.StatusPaymentRequired)
api.LogError(err, eh.InvalidBalanceError)(c, http.StatusPaymentRequired)
return
}
keyBits, exists := c.GetPostForm("key_bits")
Expand All @@ -150,15 +153,15 @@ func (api *API) createIPFSKey(c *gin.Context) {

keys, err := api.um.GetKeysForUser(username)
if err != nil {
api.LogError(err, KeySearchError)(c, http.StatusNotFound)
api.LogError(err, eh.KeySearchError)(c, http.StatusNotFound)
api.refundUserCredits(username, "key", cost)
return
}
keyNamePrefixed := fmt.Sprintf("%s-%s", username, keyName)
for _, v := range keys["key_names"] {
if v == keyNamePrefixed {
err = fmt.Errorf("key with name already exists")
api.LogError(err, DuplicateKeyCreationError)(c, http.StatusConflict)
api.LogError(err, eh.DuplicateKeyCreationError)(c, http.StatusConflict)
api.refundUserCredits(username, "key", cost)
return
}
Expand Down Expand Up @@ -187,13 +190,13 @@ func (api *API) createIPFSKey(c *gin.Context) {

qm, err := queue.Initialize(queue.IpfsKeyCreationQueue, mqConnectionURL, true, false)
if err != nil {
api.LogError(err, QueueInitializationError)(c)
api.LogError(err, eh.QueueInitializationError)(c)
api.refundUserCredits(username, "key", cost)
return
}

if err = qm.PublishMessageWithExchange(key, queue.IpfsKeyExchange); err != nil {
api.LogError(err, QueuePublishError)(c)
api.LogError(err, eh.QueuePublishError)(c)
api.refundUserCredits(username, "key", cost)
return
}
Expand All @@ -212,12 +215,12 @@ func (api *API) getIPFSKeyNamesForAuthUser(c *gin.Context) {

keys, err := api.um.GetKeysForUser(username)
if err != nil {
api.LogError(err, KeySearchError)(c)
api.LogError(err, eh.KeySearchError)(c)
return
}
// if the user has no keys, fail with an error
if len(keys["key_names"]) == 0 || len(keys["key_ids"]) == 0 {
Fail(c, errors.New(NoKeyError), http.StatusNotFound)
Fail(c, errors.New(eh.NoKeyError), http.StatusNotFound)
return
}
api.LogWithUser(username).Info("key name list requested")
Expand All @@ -230,7 +233,7 @@ func (api *API) getCredits(c *gin.Context) {
username := GetAuthenticatedUserFromContext(c)
credits, err := api.um.GetCreditsForUser(username)
if err != nil {
api.LogError(err, CreditCheckError)(c, http.StatusBadRequest)
api.LogError(err, eh.CreditCheckError)(c, http.StatusBadRequest)
return
}
api.LogWithUser(username).Info("credit check requested")
Expand Down
7 changes: 4 additions & 3 deletions api/routes_database.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"net/http"

"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/models"
"github.com/gin-gonic/gin"
)
Expand All @@ -13,14 +14,14 @@ var dev = false
func (api *API) getUploadsFromDatabase(c *gin.Context) {
username := GetAuthenticatedUserFromContext(c)
if err := api.validateAdminRequest(username); err != nil {
FailNotAuthorized(c, UnAuthorizedAdminAccess)
FailNotAuthorized(c, eh.UnAuthorizedAdminAccess)
return
}
um := models.NewUploadManager(api.dbm.DB)
// fetch the uplaods
uploads, err := um.GetUploads()
if err != nil {
api.LogError(err, UploadSearchError)(c, http.StatusInternalServerError)
api.LogError(err, eh.UploadSearchError)(c, http.StatusInternalServerError)
return
}
api.LogInfo("all uploads from database requested")
Expand All @@ -42,7 +43,7 @@ func (api *API) getUploadsForUser(c *gin.Context) {
// fetch all uploads for that address
uploads, err := um.GetUploadsForUser(queryUser)
if err != nil {
api.LogError(err, UploadSearchError)(c, http.StatusInternalServerError)
api.LogError(err, eh.UploadSearchError)(c, http.StatusInternalServerError)
return
}
api.LogInfo("specific uploads from database requested")
Expand Down
5 changes: 3 additions & 2 deletions api/routes_frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"net/http"
"strconv"

"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/rtfs"
"github.com/RTradeLtd/Temporal/utils"
"github.com/gin-gonic/gin"
Expand All @@ -22,7 +23,7 @@ func (api *API) calculatePinCost(c *gin.Context) {
holdTime := c.Param("holdtime")
manager, err := rtfs.Initialize("", "")
if err != nil {
api.LogError(err, IPFSConnectionError)(c)
api.LogError(err, eh.IPFSConnectionError)(c)
return
}
holdTimeInt, err := strconv.ParseInt(holdTime, 10, 64)
Expand All @@ -40,7 +41,7 @@ func (api *API) calculatePinCost(c *gin.Context) {
}
totalCost, err := utils.CalculatePinCost(hash, holdTimeInt, manager.Shell, isPrivate)
if err != nil {
api.LogError(err, PinCostCalculationError)
api.LogError(err, eh.PinCostCalculationError)
Fail(c, err)
return
}
Expand Down
21 changes: 11 additions & 10 deletions api/routes_ipns.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strconv"
"time"

"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/queue"
"github.com/RTradeLtd/Temporal/utils"
gocid "github.com/ipfs/go-cid"
Expand Down Expand Up @@ -54,23 +55,23 @@ func (api *API) publishToIPNSDetails(c *gin.Context) {

cost, err := utils.CalculateAPICallCost("ipns", false)
if err != nil {
api.LogError(err, CallCostCalculationError)(c, http.StatusBadRequest)
api.LogError(err, eh.CallCostCalculationError)(c, http.StatusBadRequest)
return
}
if err := api.validateUserCredits(username, cost); err != nil {
api.LogError(err, InvalidBalanceError)(c, http.StatusPaymentRequired)
api.LogError(err, eh.InvalidBalanceError)(c, http.StatusPaymentRequired)
return
}
ownsKey, err := api.um.CheckIfKeyOwnedByUser(username, key)
if err != nil {
api.LogError(err, KeySearchError)(c)
api.LogError(err, eh.KeySearchError)(c)
api.refundUserCredits(username, "ipns", cost)
return
}

if !ownsKey {
err = fmt.Errorf("user %s attempted to generate IPFS entry with unowned key", username)
api.LogError(err, KeyUseError)(c)
api.LogError(err, eh.KeyUseError)(c)
api.refundUserCredits(username, "ipns", cost)
return
}
Expand Down Expand Up @@ -106,14 +107,14 @@ func (api *API) publishToIPNSDetails(c *gin.Context) {

qm, err := queue.Initialize(queue.IpnsEntryQueue, mqURL, true, false)
if err != nil {
api.LogError(err, QueueInitializationError)(c)
api.LogError(err, eh.QueueInitializationError)(c)
api.refundUserCredits(username, "ipns", cost)
return
}
// in order to avoid generating too much IPFS dht traffic, we publish round-robin style
// as we announce the records to the swarm, we will eventually achieve consistency across nodes automatically
if err = qm.PublishMessage(ie); err != nil {
api.LogError(err, QueuePublishError)(c)
api.LogError(err, eh.QueuePublishError)(c)
api.refundUserCredits(username, "ipns", cost)
return
}
Expand All @@ -131,7 +132,7 @@ func (api *API) getIPNSRecordsPublishedByUser(c *gin.Context) {
username := GetAuthenticatedUserFromContext(c)
records, err := api.im.FindByUserName(username)
if err != nil {
api.LogError(err, IpnsRecordSearchError)(c, http.StatusBadRequest)
api.LogError(err, eh.IpnsRecordSearchError)(c, http.StatusBadRequest)
return
}
// check if records is nil, or no entries. For len we must dereference first
Expand All @@ -146,7 +147,7 @@ func (api *API) getIPNSRecordsPublishedByUser(c *gin.Context) {
func (api *API) generateDNSLinkEntry(c *gin.Context) {
username := GetAuthenticatedUserFromContext(c)
if err := api.validateAdminRequest(username); err != nil {
FailNotAuthorized(c, UnAuthorizedAdminAccess)
FailNotAuthorized(c, eh.UnAuthorizedAdminAccess)
return
}
recordName, exists := c.GetPostForm("record_name")
Expand Down Expand Up @@ -188,14 +189,14 @@ func (api *API) generateDNSLinkEntry(c *gin.Context) {

awsManager, err := dlink.GenerateAwsLinkManager("get", aKey, aSecret, awsZone, region)
if err != nil {
api.LogError(err, DNSLinkManagerError)
api.LogError(err, eh.DNSLinkManagerError)
Fail(c, err)
return
}

resp, err := awsManager.AddDNSLinkEntry(recordName, recordValue)
if err != nil {
api.LogError(err, DNSLinkEntryError)
api.LogError(err, eh.DNSLinkEntryError)
Fail(c, err)
return
}
Expand Down
7 changes: 4 additions & 3 deletions api/routes_mini.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"net/http"

"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/mini"
"github.com/gin-gonic/gin"
)
Expand All @@ -12,7 +13,7 @@ import (
func (api *API) makeBucket(c *gin.Context) {
username := GetAuthenticatedUserFromContext(c)
if err := api.validateAdminRequest(username); err != nil {
FailNotAuthorized(c, UnAuthorizedAdminAccess)
FailNotAuthorized(c, eh.UnAuthorizedAdminAccess)
return
}
bucketName, exists := c.GetPostForm("bucket_name")
Expand All @@ -28,14 +29,14 @@ func (api *API) makeBucket(c *gin.Context) {
)
manager, err := mini.NewMinioManager(endpoint, accessKey, secretKey, true)
if err != nil {
api.LogError(err, MinioConnectionError)(c)
api.LogError(err, eh.MinioConnectionError)(c)
return
}

args := make(map[string]string)
args["name"] = bucketName
if err = manager.MakeBucket(args); err != nil {
api.LogError(err, MinioBucketCreationError)(c)
api.LogError(err, eh.MinioBucketCreationError)(c)
return
}

Expand Down
17 changes: 9 additions & 8 deletions api/routes_payment.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"net/http"

"github.com/RTradeLtd/Temporal/eh"
"github.com/RTradeLtd/Temporal/models"
"github.com/RTradeLtd/Temporal/queue"
"github.com/RTradeLtd/Temporal/utils"
Expand All @@ -20,12 +21,12 @@ func (api *API) CreatePayment(c *gin.Context) {
}
usdValue, err := api.getUSDValue(paymentType)
if err != nil {
api.LogError(err, CmcCheckError)(c, http.StatusBadRequest)
api.LogError(err, eh.CmcCheckError)(c, http.StatusBadRequest)
return
}
depositAddress, err := api.getDepositAddress(paymentType)
if err != nil {
api.LogError(err, DepositAddressCheckError)(c, http.StatusBadRequest)
api.LogError(err, eh.DepositAddressCheckError)(c, http.StatusBadRequest)
return
}
txHash, exists := c.GetPostForm("tx_hash")
Expand All @@ -39,12 +40,12 @@ func (api *API) CreatePayment(c *gin.Context) {
return
}
if check := api.validateBlockchain(blockchain); !check {
api.LogError(err, InvalidPaymentBlockchainError)(c, http.StatusBadRequest)
api.LogError(err, eh.InvalidPaymentBlockchainError)(c, http.StatusBadRequest)
return
}
pm := models.NewPaymentManager(api.dbm.DB)
if _, err := pm.NewPayment(depositAddress, txHash, usdValue, blockchain, paymentType, username); err != nil {
api.LogError(err, PaymentCreationError)(c, http.StatusBadRequest)
api.LogError(err, eh.PaymentCreationError)(c, http.StatusBadRequest)
return
}
pc := queue.PaymentCreation{
Expand All @@ -55,11 +56,11 @@ func (api *API) CreatePayment(c *gin.Context) {
mqURL := api.cfg.RabbitMQ.URL
qm, err := queue.Initialize(queue.PaymentCreationQueue, mqURL, true, false)
if err != nil {
api.LogError(err, QueueInitializationError)(c, http.StatusBadRequest)
api.LogError(err, eh.QueueInitializationError)(c, http.StatusBadRequest)
return
}
if err = qm.PublishMessage(pc); err != nil {
api.LogError(err, QueuePublishError)(c, http.StatusBadRequest)
api.LogError(err, eh.QueuePublishError)(c, http.StatusBadRequest)
return
}
Respond(c, http.StatusOK, gin.H{"response": "payment created"})
Expand All @@ -70,7 +71,7 @@ func (api *API) GetDepositAddress(c *gin.Context) {
paymentType := c.Param("type")
address, err := api.getDepositAddress(paymentType)
if err != nil {
api.LogError(err, InvalidPaymentTypeError)(c, http.StatusBadRequest)
api.LogError(err, eh.InvalidPaymentTypeError)(c, http.StatusBadRequest)
return
}
Respond(c, http.StatusOK, gin.H{"response": address})
Expand All @@ -90,5 +91,5 @@ func (api *API) getUSDValue(paymentType string) (float64, error) {
case "rtc":
return RtcCostUsd, nil
}
return 0, errors.New(InvalidPaymentTypeError)
return 0, errors.New(eh.InvalidPaymentTypeError)
}
Loading

0 comments on commit 51e56bd

Please sign in to comment.