Skip to content

Commit

Permalink
refactor: consolidate utility functions into AWS Lambda Layer for ide…
Browse files Browse the repository at this point in the history
…ntity service
  • Loading branch information
rishirishhh committed Jul 22, 2024
1 parent a68d5ce commit c0bf5a0
Show file tree
Hide file tree
Showing 11 changed files with 155 additions and 457 deletions.
2 changes: 1 addition & 1 deletion call-profile/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import (
"net/http"
"time"

utils "github.com/Real-Dev-Squad/identity-service/layer/utils"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
utils "github.com/rishirishhh/identity-service/layer/utils"
)

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
Expand Down
76 changes: 8 additions & 68 deletions call-profiles/main.go
Original file line number Diff line number Diff line change
@@ -1,84 +1,24 @@
package main

import (
"bytes"
"context"
"fmt"
"log"
"os"
"net/http"
"bytes"
"os"
"sync"
"time"

"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"

"github.com/Real-Dev-Squad/identity-service/layer/utils"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"

"google.golang.org/api/iterator"
"google.golang.org/api/option"
)

var wg sync.WaitGroup

/*
Setting Constants Map
*/
var Constants map[string]string = map[string]string{
"ENV_DEVELOPMENT": "DEVELOPMENT",
"ENV_PRODUCTION": "PRODUCTION",
"FIRE_STORE_CRED": "firestoreCred",
}

/*
Setting Firestore Key for development/production
*/
func getFirestoreKey() string {
if os.Getenv(("environment")) == Constants["ENV_DEVELOPMENT"] {
return os.Getenv(Constants["FIRE_STORE_CRED"])
} else if os.Getenv(("environment")) == Constants["ENV_PRODUCTION"] {
var parameterName string = Constants["FIRE_STORE_CRED"]

sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))

svc := ssm.New(sess)

results, err := svc.GetParameter(&ssm.GetParameterInput{
Name: &parameterName,
})
if err != nil {
log.Fatalf(err.Error())
}

return *results.Parameter.Value
} else {
return ""
}
}

/*
Function to initialize the firestore client
*/
func initializeFirestoreClient(ctx context.Context) (*firestore.Client, error) {
sa := option.WithCredentialsJSON([]byte(getFirestoreKey()))
app, err := firebase.NewApp(ctx, nil, sa)
if err != nil {
return nil, err
}

client, err := app.Firestore(ctx)
if err != nil {
return nil, err
}

return client, nil
}

func callProfile(userId string, sessionId string) {

defer wg.Done()
Expand All @@ -97,17 +37,17 @@ func callProfile(userId string, sessionId string) {

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
ctx := context.Background()
client, err := initializeFirestoreClient(ctx)
client, err := utils.InitializeFirestoreClient(ctx)

if err != nil {
return events.APIGatewayProxyResponse{}, err
}

docRef ,_ ,sessionIdErr := client.Collection("identitySessionIds").Add(ctx, map[string]interface{}{
docRef, _, sessionIdErr := client.Collection("identitySessionIds").Add(ctx, map[string]interface{}{
"Timestamp": time.Now(),
})

if(sessionIdErr != nil) {
if sessionIdErr != nil {
return events.APIGatewayProxyResponse{}, sessionIdErr
}

Expand All @@ -124,7 +64,7 @@ func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyRespo
}
totalProfilesCalled += 1
wg.Add(1)
go callProfile(doc.Ref.ID, docRef.ID)
go callProfile(doc.Ref.ID, docRef.ID)
}

wg.Wait()
Expand All @@ -138,4 +78,4 @@ func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyRespo

func main() {
lambda.Start(handler)
}
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module github.com/rishirishhh/identity-service
module github.com/Real-Dev-Squad/identity-service

go 1.22.5

Expand Down
67 changes: 3 additions & 64 deletions health-check/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,80 +4,19 @@ import (
"context"
"fmt"
"log"
"os"
"net/http"
"sync"
"time"

"cloud.google.com/go/firestore"
firebase "firebase.google.com/go"

"github.com/Real-Dev-Squad/identity-service/layer/utils"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ssm"

"google.golang.org/api/iterator"
"google.golang.org/api/option"
)

var wg sync.WaitGroup

/*
Setting Constants Map
*/
var Constants map[string]string = map[string]string{
"ENV_DEVELOPMENT": "DEVELOPMENT",
"ENV_PRODUCTION": "PRODUCTION",
"FIRE_STORE_CRED": "firestoreCred",
}

/*
Setting Firestore Key for development/production
*/
func getFirestoreKey() string {
if os.Getenv(("environment")) == Constants["ENV_DEVELOPMENT"] {
return os.Getenv(Constants["FIRE_STORE_CRED"])
} else if os.Getenv(("environment")) == Constants["ENV_PRODUCTION"] {
var parameterName string = Constants["FIRE_STORE_CRED"]

sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))

svc := ssm.New(sess)

results, err := svc.GetParameter(&ssm.GetParameterInput{
Name: &parameterName,
})
if err != nil {
log.Fatalf(err.Error())
}

return *results.Parameter.Value
} else {
return ""
}
}

/*
Function to initialize the firestore client
*/
func initializeFirestoreClient(ctx context.Context) (*firestore.Client, error) {
sa := option.WithCredentialsJSON([]byte(getFirestoreKey()))
app, err := firebase.NewApp(ctx, nil, sa)
if err != nil {
return nil, err
}

client, err := app.Firestore(ctx)
if err != nil {
return nil, err
}

return client, nil
}

func callProfileHealth(userUrl string) {

defer wg.Done()
Expand All @@ -99,7 +38,7 @@ func callProfileHealth(userUrl string) {

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
ctx := context.Background()
client, err := initializeFirestoreClient(ctx)
client, err := utils.InitializeFirestoreClient(ctx)

if err != nil {
return events.APIGatewayProxyResponse{}, err
Expand Down Expand Up @@ -135,4 +74,4 @@ func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyRespo

func main() {
lambda.Start(handler)
}
}
2 changes: 1 addition & 1 deletion health/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package main

import (
utils "github.com/Real-Dev-Squad/identity-service/layer/utils"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/rishirishhh/identity-service/layer/utils"
)

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
Expand Down
88 changes: 88 additions & 0 deletions layer/utils/firestore.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
Expand Down Expand Up @@ -206,3 +207,90 @@ func GetDataFromBody(body []byte) (string, string) {
func GenerateHealthMessage() string {
return "Awesome, Server health is good!!!"
}

/*
Function to extract userId from the request body
*/

func GetUserIdFromBody(body []byte) string {
type extractedBody struct {
UserId string `json:"userId"`
}

var e extractedBody
json.Unmarshal(body, &e)
return e.UserId
}

/*
Function to get the userData using userId
*/

func GetUserData(client *firestore.Client, ctx context.Context, userId string) (string, string, string, error) {
dsnap, err := client.Collection("users").Doc(userId).Get(ctx)
var profileURL string
var profileStatus string
var chaincode string
if err != nil {
return "", "", "", err
}
if str, ok := dsnap.Data()["profileURL"].(string); ok {
profileURL = str
} else {
return "", "", "", errors.New("profile url is not a string")
}
if str, ok := dsnap.Data()["profileStatus"].(string); ok {
profileStatus = str
} else {
profileStatus = ""
}

if str, ok := dsnap.Data()["chaincode"].(string); ok {
if str != "" {
chaincode = str
} else {
newLog := Log{
Type: "VERIFICATION_BLOCKED",
Timestamp: time.Now(),
Meta: map[string]interface{}{
"userId": userId,
},
Body: map[string]interface{}{
"userId": userId,
"reason": "Chaincode is empty. Generate new one.",
},
}
client.Collection("logs").Add(ctx, newLog)
return "", "", "", errors.New("chaincode is blocked")
}
} else {
return "", "", "", errors.New("chaincode is not a string")
}

return profileURL, profileStatus, chaincode, nil
}

/*
Function for setting the profileStatus in user object in firestore
*/
func SetProfileStatus(client *firestore.Client, ctx context.Context, id string, status string) error {
var newData = map[string]interface{}{
"profileStatus": status,
}

if status == "BLOCKED" {
newData = map[string]interface{}{
"profileStatus": status,
"chaincode": "",
"updated_at": time.Now().UnixMilli(),
}
}

_, err := client.Collection("users").Doc(id).Set(ctx, newData, firestore.MergeAll)

if err != nil {
return errors.New("unable to set profile status")
}

return nil
}
27 changes: 27 additions & 0 deletions layer/utils/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,30 @@ func LogHealth(client *firestore.Client, ctx context.Context, userId string, isS

client.Collection("logs").Add(ctx, newLog)
}

func LogVerification(client *firestore.Client, ctx context.Context, status string, profileURL string, userId string) {
var logtype string
var logbody map[string]interface{}
if status == "VERIFIED" {
logtype = "PROFILE_VERIFIED"
logbody = map[string]interface{}{
"userId": userId,
"profileURL": profileURL,
}
} else if status == "BLOCKED" {
logtype = "PROFILE_BLOCKED"
logbody = map[string]interface{}{
"userId": userId,
"reason": "Chaincode not linked. Hash sent by service is not verified.",
}
}
newLog := Log{
Type: logtype,
Timestamp: time.Now(),
Meta: map[string]interface{}{
"userId": userId,
},
Body: logbody,
}
client.Collection("logs").Add(ctx, newLog)
}
3 changes: 1 addition & 2 deletions scripts/test.sh
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
cd health
go mod tidy
cd health
go test -v
npx kill-port 8090
cd ../verify
go mod tidy
npm install -g firebase-tools
if (firebase --project="test" emulators:exec "go test"); then
echo "Exited Success"
Expand Down
Loading

0 comments on commit c0bf5a0

Please sign in to comment.