Skip to content

Commit

Permalink
add auth utils, partial node apis
Browse files Browse the repository at this point in the history
  • Loading branch information
inciner8r committed Apr 5, 2024
1 parent 4a17fac commit 36f4e0c
Show file tree
Hide file tree
Showing 21 changed files with 711 additions and 117 deletions.
8 changes: 4 additions & 4 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ jobs:
run: |
export CURRENT_BRANCH=${GITHUB_REF#refs/heads/}
export TAG=$([[ $CURRENT_BRANCH == "main" ]] && echo $CURRENT_BRANCH || echo "latest")
export GITHUB_REF_IMAGE=ghcr.io/thelazarusnetwork/erebrus-gateway:$GITHUB_SHA
export GITHUB_BRANCH_IMAGE=ghcr.io/thelazarusnetwork/erebrus-gateway:$TAG
export GITHUB_REF_IMAGE=ghcr.io/NetSepio/erebrus-gateway:$GITHUB_SHA
export GITHUB_BRANCH_IMAGE=ghcr.io/NetSepio/erebrus-gateway:$TAG
docker build -t $GITHUB_REF_IMAGE -t $GITHUB_BRANCH_IMAGE .
echo "Pushing Image to GitHub Container Registry"
docker push $GITHUB_REF_IMAGE
Expand Down Expand Up @@ -106,5 +106,5 @@ jobs:
cd erebrus-gateway
podman stop erebrus-gateway && podman rm erebrus-gateway && podman image rm erebrus-gateway
echo ${{ secrets.GHCR_TOKEN }} | podman login ghcr.io -u secrets.GHCR_USERNAME --password-stdin
podman pull ghcr.io/thelazarusnetwork/erebrus-gateway:main
podman run --name="erebrus-gateway" --net=bridge -p 9001:9001 -v "$(pwd)"/identity.key:/app/identity.key:ro -d ghcr.io/thelazarusnetwork/erebrus-gateway:main
podman pull ghcr.io/NetSepio/erebrus-gateway:main
podman run --name="erebrus-gateway" --net=bridge -p 9001:9001 -v "$(pwd)"/identity.key:/app/identity.key:ro -d ghcr.io/NetSepio/erebrus-gateway:main
2 changes: 1 addition & 1 deletion api/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package api

import (
"github.com/TheLazarusNetwork/erebrus-gateway/api/status"
"github.com/NetSepio/erebrus-gateway/api/status"
"github.com/gin-gonic/gin"
)

Expand Down
2 changes: 1 addition & 1 deletion api/status/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package status
import (
"net/http"

"github.com/TheLazarusNetwork/erebrus-gateway/app/p2p-Node/service"
"github.com/NetSepio/erebrus-gateway/app/p2p-Node/service"
"github.com/gin-gonic/gin"
)

Expand Down
114 changes: 114 additions & 0 deletions api/v1/authenticate/aptos/authenticate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package authenticate

import (
"encoding/hex"
"fmt"
"net/http"

"github.com/NetSepio/erebrus-gateway/config/dbconfig"
"github.com/NetSepio/erebrus-gateway/config/envconfig"
"github.com/NetSepio/erebrus-gateway/models"
"github.com/NetSepio/erebrus-gateway/models/claims"
"github.com/TheLazarusNetwork/go-helpers/httpo"

"github.com/NetSepio/erebrus-gateway/util/pkg/auth"
"github.com/NetSepio/erebrus-gateway/util/pkg/cryptosign"
"github.com/NetSepio/erebrus-gateway/util/pkg/logwrapper"

// "github.com/TheLazarusNetwork/go-helpers/httpo"

"github.com/gin-gonic/gin"
)

// ApplyRoutes applies router to gin Router
func ApplyRoutes(r *gin.RouterGroup) {
g := r.Group("/authenticate")
{
g.POST("", authenticate)
}
}

func authenticate(c *gin.Context) {
db := dbconfig.GetDb()
//TODO remove flow id if 200
var req AuthenticateRequest
err := c.BindJSON(&req)
if err != nil {
httpo.NewErrorResponse(http.StatusBadRequest, fmt.Sprintf("payload is invalid: %s", err)).SendD(c)
return
}

//Get flowid type
var flowIdData models.FlowId
err = db.Model(&models.FlowId{}).Where("flow_id = ?", req.FlowId).First(&flowIdData).Error
if err != nil {
logwrapper.Errorf("failed to get flowId, error %v", err)
httpo.NewErrorResponse(http.StatusNotFound, "flow id not found").SendD(c)
return
}

if flowIdData.FlowIdType != models.AUTH {
httpo.NewErrorResponse(http.StatusBadRequest, "flow id not created for auth").SendD(c)
return
}

if err != nil {
logwrapper.Error(err)
httpo.NewErrorResponse(500, "Unexpected error occured").SendD(c)
return
}
userAuthEULA := envconfig.EnvVars.AUTH_EULA
message := fmt.Sprintf("APTOS\nmessage: %v\nnonce: %v", userAuthEULA, req.FlowId)

userId, walletAddr, isCorrect, err := cryptosign.CheckSign(req.Signature, req.FlowId, message, req.PubKey)

if err == cryptosign.ErrFlowIdNotFound {
httpo.NewErrorResponse(http.StatusNotFound, "Flow Id not found")
return
}

if err != nil {
logwrapper.Errorf("failed to CheckSignature, error %v", err.Error())
httpo.NewErrorResponse(http.StatusInternalServerError, "Unexpected error occured").SendD(c)
return
}
if isCorrect {
// update wallet address for that user_id
err = db.Model(&models.User{}).Where("user_id = ?", userId).Update("wallet_address", walletAddr).Error
if err != nil {
httpo.NewErrorResponse(http.StatusInternalServerError, "Unexpected error occured").SendD(c)
logwrapper.Errorf("failed to update wallet address, error %v", err.Error())
return
}

customClaims := claims.NewWithWallet(userId, &walletAddr)
pvKey, err := hex.DecodeString(envconfig.EnvVars.PASETO_PRIVATE_KEY[2:])
if err != nil {
httpo.NewErrorResponse(http.StatusInternalServerError, "Unexpected error occured").SendD(c)
logwrapper.Errorf("failed to generate token, error %v", err.Error())
return
}
pasetoToken, err := auth.GenerateToken(customClaims, pvKey)
if err != nil {
httpo.NewErrorResponse(http.StatusInternalServerError, "Unexpected error occured").SendD(c)
logwrapper.Errorf("failed to generate token, error %v", err.Error())
return
}
err = db.Where("flow_id = ?", req.FlowId).Delete(&models.FlowId{}).Error
if err != nil {
httpo.NewErrorResponse(http.StatusInternalServerError, "Unexpected error occured").SendD(c)
logwrapper.Errorf("failed to delete flowId, error %v", err.Error())
return
}
payload := AuthenticatePayload{
Token: pasetoToken,
UserId: userId,
}
httpo.NewSuccessResponseP(200, "Token generated successfully", payload).SendD(c)
} else {
httpo.NewErrorResponse(http.StatusForbidden, "Wallet Address is not correct").SendD(c)
return
}
}

// create api handler which will take
5 changes: 2 additions & 3 deletions api/client/client.go → api/v1/v1.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package client
package apiv1

import "github.com/gin-gonic/gin"

func ApplyRoutes(r *gin.RouterGroup) {
g := r.Group("/status")
v1 := r.Group("/v1.0")
{
g.GET("", GetStatus)
}
}
2 changes: 1 addition & 1 deletion app/app.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package app

import p2pnode "github.com/TheLazarusNetwork/erebrus-gateway/app/p2p-Node"
import p2pnode "github.com/NetSepio/erebrus-gateway/app/p2p-Node"

func Init() {
p2pnode.Init()
Expand Down
4 changes: 2 additions & 2 deletions app/p2p-Node/host/host.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"sync"
"time"

"github.com/TheLazarusNetwork/erebrus-gateway/app/p2p-Node/pkey"
"github.com/NetSepio/erebrus-gateway/app/p2p-Node/pkey"
"github.com/libp2p/go-libp2p"
dht "github.com/libp2p/go-libp2p-kad-dht"
"github.com/libp2p/go-libp2p/core/host"
Expand All @@ -26,7 +26,7 @@ const DiscoveryInterval = time.Second * 10

func getHostAddress(ha host.Host) string {
// Build host multiaddress
hostAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", ha.ID().Pretty()))
hostAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", ha.ID()))

// Now we can build a full multiaddress to reach this host
// by encapsulating both addresses:
Expand Down
4 changes: 2 additions & 2 deletions app/p2p-Node/p2p-node.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"context"
"time"

p2pHost "github.com/TheLazarusNetwork/erebrus-gateway/app/p2p-Node/host"
"github.com/TheLazarusNetwork/erebrus-gateway/app/p2p-Node/service"
p2pHost "github.com/NetSepio/erebrus-gateway/app/p2p-Node/host"
"github.com/NetSepio/erebrus-gateway/app/p2p-Node/service"
)

// DiscoveryInterval is how often we search for other peers via the DHT.
Expand Down
2 changes: 1 addition & 1 deletion app/p2p-Node/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"encoding/json"
"fmt"

p2pHost "github.com/TheLazarusNetwork/erebrus-gateway/app/p2p-Node/host"
p2pHost "github.com/NetSepio/erebrus-gateway/app/p2p-Node/host"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/host"
)
Expand Down
69 changes: 69 additions & 0 deletions config/dbconfig/dbconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package dbconfig

import (
"fmt"

log "github.com/sirupsen/logrus"
"gorm.io/gorm"

"github.com/NetSepio/erebrus-gateway/config/envconfig"

"gorm.io/driver/postgres"
)

var db *gorm.DB

// Return singleton instance of db, initiates it before if it is not initiated already
func GetDb() *gorm.DB {
if db != nil {
return db
}
var (
host = envconfig.EnvVars.DB_HOST
username = envconfig.EnvVars.DB_USERNAME
password = envconfig.EnvVars.DB_PASSWORD
dbname = envconfig.EnvVars.DB_NAME
port = envconfig.EnvVars.DB_PORT
)

dns := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable port=%d",
host, username, password, dbname, port)

var err error
db, err = gorm.Open(postgres.New(postgres.Config{
DSN: dns,
}))
if err != nil {
log.Fatal("failed to connect database", err)
}

sqlDb, err := db.DB()
if err != nil {
log.Fatal("failed to ping database", err)
}
if err = sqlDb.Ping(); err != nil {
log.Fatal("failed to ping database", err)
}

// if err := db.AutoMigrate(&models.User{}, &models.Role{}, &models.UserFeedback{}, &models.FlowId{}, &models.Review{}, &models.WaitList{}, &models.Domain{}, &models.DomainAdmin{}, &models.Sotreus{}, &models.Erebrus{}); err != nil {
// log.Fatal(err)
// }

// db.Exec(`create table if not exists user_roles (
// wallet_address text,
// role_id text,
// unique (wallet_address,role_id)
// )`)

// //Create flow id
// db.Exec(`
// DO $$ BEGIN
// CREATE TYPE flow_id_type AS ENUM (
// 'AUTH',
// 'ROLE');
// EXCEPTION
// WHEN duplicate_object THEN null;
// END $$;`)

return db.Debug()
}
56 changes: 56 additions & 0 deletions config/envconfig/envconfig.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package envconfig

import (
"log"
"time"

"github.com/caarlos0/env/v6"
_ "github.com/joho/godotenv/autoload"
)

type config struct {
PASETO_PRIVATE_KEY string `env:"PASETO_PRIVATE_KEY,required"`
PASETO_EXPIRATION time.Duration `env:"PASETO_EXPIRATION,required"`
APP_PORT int `env:"APP_PORT,required"`
AUTH_EULA string `env:"AUTH_EULA,required"`
APP_NAME string `env:"APP_NAME,required"`
GIN_MODE string `env:"GIN_MODE,required"`
DB_HOST string `env:"DB_HOST,required"`
DB_USERNAME string `env:"DB_USERNAME,required"`
DB_PASSWORD string `env:"DB_PASSWORD,required"`
DB_NAME string `env:"DB_NAME,required"`
DB_PORT int `env:"DB_PORT,required"`
ALLOWED_ORIGIN []string `env:"ALLOWED_ORIGIN,required" envSeparator:","`
PASETO_SIGNED_BY string `env:"PASETO_SIGNED_BY,required"`
APTOS_FUNCTION_ID string `env:"APTOS_FUNCTION_ID,required"`
APTOS_REPORT_FUNCTION_ID string `env:"APTOS_REPORT_FUNCTION_ID,required"`
GAS_UNITS int `env:"GAS_UNITS,required"`
GAS_PRICE int `env:"GAS_PRICE,required"`
NETWORK string `env:"NETWORK,required"`
NFT_STORAGE_KEY string `env:"NFT_STORAGE_KEY,required"`
VERSION string `env:"VERSION,notEmpty"`
VPN_DEPLOYER_API_US_EAST string `env:"VPN_DEPLOYER_API_US_EAST,notEmpty"`
VPN_DEPLOYER_API_SG string `env:"VPN_DEPLOYER_API_SG,notEmpty"`
EREBRUS_API_US_EAST string `env:"EREBRUS_API_US_EAST,notEmpty"`
EREBRUS_API_SG string `env:"EREBRUS_API_SG,notEmpty"`
GOOGLE_AUDIENCE string `env:"GOOGLE_AUDIENCE,notEmpty"`
OPENAI_API_KEY string `env:"OPENAI_API_KEY,notEmpty"`
EREBRUS_US string `env:"EREBRUS_US,notEmpty"`
EREBRUS_SG string `env:"EREBRUS_SG,notEmpty"`
EREBRUS_CA string `env:"EREBRUS_CA,notEmpty"`
EREBRUS_EU string `env:"EREBRUS_EU,notEmpty"`
EREBRUS_JP string `env:"EREBRUS_JP,notEmpty"`
SOTREUS_US string `env:"SOTREUS_US,notEmpty"`
SOTREUS_SG string `env:"SOTREUS_SG,notEmpty"`
STRIPE_WEBHOOK_SECRET string `env:"STRIPE_WEBHOOK_SECRET,notEmpty"`
STRIPE_SECRET_KEY string `env:"STRIPE_SECRET_KEY,notEmpty"`
}

var EnvVars config = config{}

func InitEnvVars() {

if err := env.Parse(&EnvVars); err != nil {
log.Fatalf("failed to parse EnvVars: %s", err)
}
}
Loading

0 comments on commit 36f4e0c

Please sign in to comment.