Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge dev to prod #179

Merged
merged 36 commits into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
5aa299b
Adding automigration in dev netsepio
p-shubh Apr 16, 2024
31efe25
Merge branch 'main' into gorm_migrate
p-shubh Apr 16, 2024
84b1e11
Merge branch 'main' into gorm_migrate
p-shubh Apr 16, 2024
b5e5235
Merge branch 'main' into gorm_migrate
p-shubh May 2, 2024
5ac33e3
main: remove dotenv load
inciner8r May 2, 2024
3835863
db: remove unnecessary query
inciner8r May 2, 2024
749108a
Bug fixing over user constraints
p-shubh May 2, 2024
0a5acad
Bug Fix over constraints removing automigration
p-shubh May 2, 2024
149e3f2
Authentication: refactor for multichain (#165)
inciner8r May 2, 2024
9e858a3
authenticate: pubkey optional
inciner8r May 3, 2024
2d88362
Handled Unique Constraints
p-shubh May 4, 2024
00256c5
authenticate: add sui signature check (#166)
inciner8r May 6, 2024
21e9304
authenticate: remove public key input for sui
inciner8r May 6, 2024
89ee97a
authenticate: remove message for sui
inciner8r May 6, 2024
2583bde
chacksign: define curve for pubkey
inciner8r May 6, 2024
a5fa5b2
account/subscription: add trial and stripe subscriptions (#167)
inciner8r May 6, 2024
214bd08
authenticare: add solana signature verification (#168)
surajhub255 May 6, 2024
3829824
added nonsign for wallet zk login (#169)
Rushikeshnimkar May 13, 2024
9f01514
fix zk wallet login (#171)
Rushikeshnimkar May 13, 2024
43a11d7
api: added summary api for terms of use and privacy policy
vaibhavvvvv May 25, 2024
2b7e032
Merge pull request #172 from NetSepio/vaibhavvvvv/dev
p-shubh May 26, 2024
051b22d
api: update summary api to stream response
vaibhavvvvv May 29, 2024
c845c60
Merge pull request #173 from NetSepio/vaibhavvvvv/dev
p-shubh May 29, 2024
c8c4698
summary: scraping urls from web to find terms of use and privacy poli…
vaibhavvvvv May 30, 2024
ec24d08
summary: OpenAI Model Update to gpt-4-turbo
vaibhavvvvv May 30, 2024
dc430d1
Merge pull request #174 from NetSepio/vaibhavvvvv/dev
vaibhavvvvv May 30, 2024
ee9abf4
summary: openai methods updated according to gpt-4-turbo
vaibhavvvvv May 31, 2024
1532c03
Merge pull request #175 from NetSepio/vaibhavvvvv/dev
p-shubh May 31, 2024
72bdaa1
summary: reduced response time + reduced prompt size
vaibhavvvvv Jun 3, 2024
468addf
Merge pull request #176 from NetSepio/vaibhavvvvv/dev
p-shubh Jun 4, 2024
ebb63d2
scrape_urls : handling routes as urls and change in chromdp task
vaibhavvvvv Jun 4, 2024
f124bbe
Merge pull request #177 from NetSepio/vaibhavvvvv/dev
p-shubh Jun 4, 2024
d880715
User struct: unique constraint remove to fix evm auth
vaibhavvvvv Jun 11, 2024
1c945d8
Merge pull request #178 from NetSepio/vaibhavvvvv/dev
vaibhavvvvv Jun 11, 2024
f05ec7a
Removing paseto from google authentication
p-shubh Jun 14, 2024
734803a
adding mobile google auth
p-shubh Jun 15, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion api/v1/account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ func ApplyRoutes(r *gin.RouterGroup) {
g := r.Group("/account")
{
g.POST("generate-auth-id", GenerateAuthId)
g.POST("auth-google", authGoogle)
g.POST("auth-google/app", authGoogleApp)
g.Use(paseto.PASETO(true))
g.POST("paseto-from-magic-link", PasetoFromMagicLink)
g.POST("auth-google", authGoogle)
g.Use(paseto.PASETO(false))
g.DELETE("remove-mail", removeMail)
}
Expand Down
94 changes: 94 additions & 0 deletions api/v1/account/auth-google.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,97 @@
}
httpo.NewSuccessResponseP(200, "Token generated successfully", payload).SendD(c)
}
func authGoogleApp(c *gin.Context) {
userId := c.GetString(paseto.CTX_USER_ID)
db := dbconfig.GetDb()
var request AppAccountRequest
err := c.BindJSON(&request)
if err != nil {
httpo.NewErrorResponse(http.StatusBadRequest, fmt.Sprintf("payload is invalid %s", err)).SendD(c)
return
}

// ctx := context.Background()
// tokenValidationRes, err := verifyIDToken(ctx, request.IdToken)
// if err != nil {
// httpo.NewErrorResponse(http.StatusBadRequest, "failed to validate ").SendD(c)
// return
// }

// response := map[string]interface{}{
// "email": payload.Claims["email"],
// "name": payload.Claims["name"],
// }
// if !tokenValidationRes.Claims["email_verified"].(bool) {
// httpo.NewErrorResponse(http.StatusForbidden, "email not verified").SendD(c)
// return
// }

// email := tokenValidationRes.Claims["email"].(string)
var user models.User
err = db.Model(&models.User{}).Where("email_id = ?", request.Email).First(&user).Error
if err == nil && userId != "" {
httpo.NewErrorResponse(http.StatusBadRequest, "another user with this email already exist").SendD(c)
return
}
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
if userId != "" {
err = db.Model(&models.User{}).Where("user_id = ?", userId).Update("email_id", request.Email).Error
if err != nil {
logwrapper.Errorf("failed to update user email: %s", err)
httpo.NewErrorResponse(http.StatusInternalServerError, "internal server error").SendD(c)
return
}
httpo.NewSuccessResponse(200, "email linked successfully").SendD(c)
return
}

// User does not exist, so create a new user
user = models.User{
EmailId: &request.Email,
UserId: uuid.NewString(),
}
err = db.Model(&models.User{}).Create(&user).Error
if err != nil {
logwrapper.Errorf("failed to create user: %s", err)
httpo.NewErrorResponse(http.StatusInternalServerError, "internal server error").SendD(c)
return
}
} else {
// Other error occurred
logwrapper.Errorf("failed to retrieve user: %s", err)
httpo.NewErrorResponse(http.StatusInternalServerError, "internal server error").SendD(c)
return
}
}

customClaims := claims.NewWithEmail(user.UserId, user.EmailId)
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 {
logwrapper.Errorf("failed to create paseto token: %s", err)
httpo.NewErrorResponse(http.StatusInternalServerError, "internal server error").SendD(c)
return
}

payload := CreateAccountResponse{
Token: pasetoToken,
UserId: user.UserId,
}
httpo.NewSuccessResponseP(200, "Token generated successfully", payload).SendD(c)
}

func verifyIDToken(ctx context.Context, idToken string) (*idtoken.Payload, error) {

Check failure on line 195 in api/v1/account/auth-google.go

View workflow job for this annotation

GitHub Actions / Run go vet and staticcheck

func verifyIDToken is unused (U1000)
payload, err := idtoken.Validate(ctx, idToken, "699954671747-i1mqa1d7k3nh8bo9arv58pq8j4osl642.apps.googleusercontent.com")
if err != nil {
return nil, err
}
return payload, nil
}
98 changes: 91 additions & 7 deletions api/v1/account/subscription/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package subscription
import (
"math"
"net/http"
"time"

"github.com/NetSepio/gateway/api/middleware/auth/paseto"
"github.com/NetSepio/gateway/config/dbconfig"
Expand All @@ -14,6 +15,7 @@ import (
"github.com/google/uuid"
"github.com/stripe/stripe-go/v76"
"github.com/stripe/stripe-go/v76/paymentintent"
"gorm.io/gorm"
)

func Buy111NFT(c *gin.Context) {
Expand Down Expand Up @@ -48,13 +50,6 @@ func Buy111NFT(c *gin.Context) {
return
}

// type UsersStripePi struct {
// Id string `gorm:"primary_key" json:"id,omitempty"`
// UserId string `json:"userId,omitempty"`
// StripePiId string `json:"stripePiId,omitempty"`
// StripePiType string `json:"stripePiType,omitempty"`
// }

// insert in above table
err = db.Create(&models.UserStripePi{
Id: uuid.NewString(),
Expand All @@ -70,3 +65,92 @@ func Buy111NFT(c *gin.Context) {

httpo.NewSuccessResponseP(http.StatusOK, "payment intent created", BuyErebrusNFTResponse{ClientSecret: pi.ClientSecret}).SendD(c)
}

func TrialSubscription(c *gin.Context) {
userId := c.GetString(paseto.CTX_USER_ID)

// Check if there is already an active trial subscription for the user
var existingSubscription models.Subscription
db := dbconfig.GetDb()
if err := db.Where("user_id = ? AND type = ? AND end_time > ?", userId, "trial", time.Now()).First(&existingSubscription).Error; err == nil {
// There is already an active trial subscription for the user
c.JSON(http.StatusBadRequest, gin.H{"error": "You already have an active trial subscription"})
return
}

// Create a new trial subscription
subscription := models.Subscription{
UserId: userId,
StartTime: time.Now(),
EndTime: time.Now().AddDate(0, 0, 7),
Type: "TrialSubscription",
}

// Save the new trial subscription to the database
if err := db.Model(models.Subscription{}).Create(&subscription).Error; err != nil {
logwrapper.Errorf("Error creating subscription: %v", err)
c.Status(http.StatusInternalServerError)
return
}

c.JSON(http.StatusOK, gin.H{"status": "subscription created"})
}

func CheckSubscription(c *gin.Context) {
userId := c.GetString(paseto.CTX_USER_ID)

db := dbconfig.GetDb()
var subscription *models.Subscription
err := db.Where("user_id = ?", userId).Order("end_time DESC").First(&subscription).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
res := SubscriptionResponse{
Status: "notFound",
}
c.JSON(http.StatusNotFound, res)
}
logwrapper.Errorf("Error fetching subscriptions: %v", err)
c.Status(http.StatusInternalServerError)
return
}
var status = "expired"
if time.Now().Before(subscription.EndTime) {
status = "active"
}
res := SubscriptionResponse{
Subscription: subscription,
Status: status,
}
c.JSON(http.StatusOK, res)
}

func CreatePaymentIntent(c *gin.Context) {
userId := c.GetString(paseto.CTX_USER_ID)
db := dbconfig.GetDb()
params := &stripe.PaymentIntentParams{
Amount: stripe.Int64(1000),
Currency: stripe.String(string(stripe.CurrencyUSD)),
Description: stripe.String("Payment to purchase 3 month subscription"),
}
pi, err := paymentintent.New(params)
if err != nil {
logwrapper.Errorf("failed to create new payment intent: %s", err)
httpo.NewErrorResponse(http.StatusInternalServerError, err.Error()).SendD(c)
return
}

// insert in above table
err = db.Create(&models.UserStripePi{
Id: uuid.NewString(),
UserId: userId,
StripePiId: pi.ID,
StripePiType: models.ThreeMonthSubscription,
}).Error
if err != nil {
logwrapper.Errorf("failed to insert into users_stripe_pi: %v", err)
httpo.NewErrorResponse(http.StatusInternalServerError, "internal server error").SendD(c)
return
}

httpo.NewSuccessResponseP(200, "Created new charge", gin.H{"clientSecret": pi.ClientSecret}).SendD(c)
}
3 changes: 3 additions & 0 deletions api/v1/account/subscription/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ func ApplyRoutes(r *gin.RouterGroup) {
{
g.POST("payment-webhook", StripeWebhookHandler)
g.Use(paseto.PASETO(false))
g.POST("/trial", TrialSubscription)
g.POST("/create-payment", CreatePaymentIntent)
g.GET("", CheckSubscription)
g.POST("erebrus", Buy111NFT)
}
}
7 changes: 7 additions & 0 deletions api/v1/account/subscription/type.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package subscription

import "github.com/NetSepio/gateway/models"

type BuyErebrusNFTResponse struct {
ClientSecret string `json:"clientSecret"`
}

type SubscriptionResponse struct {
Subscription *models.Subscription `json:"subscription,omitempty"`
Status string `json:"status"`
}
35 changes: 26 additions & 9 deletions api/v1/account/subscription/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"net/http"
"os"
"time"

"github.com/NetSepio/gateway/config/dbconfig"
"github.com/NetSepio/gateway/config/envconfig"
Expand Down Expand Up @@ -37,6 +38,7 @@ func StripeWebhookHandler(c *gin.Context) {
c.Status(http.StatusBadRequest)
return
}

switch event.Type {
case stripe.EventTypePaymentIntentSucceeded:
var paymentIntent stripe.PaymentIntent
Expand All @@ -47,11 +49,11 @@ func StripeWebhookHandler(c *gin.Context) {
return
}

// get user with stripe_pi_id
// Get user with stripe_pi_id
var userStripePi models.UserStripePi
if err := db.Where("stripe_pi_id = ?", paymentIntent.ID).First(&userStripePi).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
//warn and return success
// Warn and return success
logwrapper.Warnf("No user found with stripe_pi_id: %v", err)
c.JSON(http.StatusOK, gin.H{"status": "received"})
return
Expand All @@ -61,20 +63,36 @@ func StripeWebhookHandler(c *gin.Context) {
return
}

// get user with user_id
// Get user with user_id
var user models.User
if err := db.Where("user_id = ?", userStripePi.UserId).First(&user).Error; err != nil {
logwrapper.Errorf("Error getting user with user_id: %v", err)
c.Status(http.StatusInternalServerError)
return
}

if _, err = aptos.DelegateMintNft(*user.WalletAddress); err != nil {
logwrapper.Errorf("Error minting nft: %v", err)
c.Status(http.StatusInternalServerError)
return
if userStripePi.StripePiType == models.ThreeMonthSubscription {
// Handle ThreeMonthSubscription payment intent
subscription := models.Subscription{
UserId: user.UserId,
StartTime: time.Now(),
EndTime: time.Now().AddDate(0, 3, 0),
Type: "ThreeMonthSubscription",
}
if err = db.Model(models.Subscription{}).Create(&subscription).Error; err != nil {
logwrapper.Errorf("Error creating subscription: %v", err)
c.Status(http.StatusInternalServerError)
return
}
} else if userStripePi.StripePiType == models.Erebrus111NFT {
// Handle Erebrus111NFT payment intent
if _, err = aptos.DelegateMintNft(*user.WalletAddress); err != nil {
logwrapper.Errorf("Error minting nft: %v", err)
c.Status(http.StatusInternalServerError)
return
}
fmt.Println("minting nft -- 111NFT")
}
fmt.Println("minting nft -- 111NFT")

case stripe.EventTypePaymentIntentCanceled:
err := HandleCanceledOrFailedPaymentIntent(event.Data.Raw)
Expand All @@ -88,7 +106,6 @@ func StripeWebhookHandler(c *gin.Context) {

c.JSON(http.StatusOK, gin.H{"status": "received"})
}

func HandleCanceledOrFailedPaymentIntent(eventDataRaw json.RawMessage) error {
var paymentIntent stripe.PaymentIntent
err := json.Unmarshal(eventDataRaw, &paymentIntent)
Expand Down
3 changes: 3 additions & 0 deletions api/v1/account/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package account
type CreateAccountRequest struct {
IdToken string `json:"idToken" binding:"required"`
}
type AppAccountRequest struct {
Email string `json:"email" binding:"required"`
}

type CreateAccountResponse struct {
Token string `json:"token"`
Expand Down
Loading
Loading