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

Database #25

Merged
merged 37 commits into from
Jun 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
457aecb
successfully added data to database, test successful, renamed model file
APandamonium1 Jun 11, 2024
0e5a98c
Added instructor CRUD
APandamonium1 Jun 11, 2024
05b436a
minor changes, added parent's name for student
APandamonium1 Jun 11, 2024
f2e47aa
added parents
APandamonium1 Jun 12, 2024
2eaa630
moved over from test database, added testing
APandamonium1 Jun 17, 2024
32ffca5
testing change env to repo secrets
APandamonium1 Jun 18, 2024
c4fe446
hopefully this fixes env error
APandamonium1 Jun 18, 2024
82d4fc6
rectifying secrets issue
APandamonium1 Jun 18, 2024
9af6262
let's try again
APandamonium1 Jun 18, 2024
82f111d
test print
APandamonium1 Jun 18, 2024
f58eccf
what about now
APandamonium1 Jun 18, 2024
85ab6c1
so butter fingers today
APandamonium1 Jun 18, 2024
bad70ae
try harder
APandamonium1 Jun 18, 2024
93bc699
let's try another way
APandamonium1 Jun 18, 2024
70e55cc
let's see what's the error
APandamonium1 Jun 18, 2024
8d5bcfb
6th diff error?
APandamonium1 Jun 18, 2024
029c0e5
json formatting error?
APandamonium1 Jun 18, 2024
ed17338
hmmmmmm
APandamonium1 Jun 18, 2024
c4d2c98
huh
APandamonium1 Jun 18, 2024
15fc6ff
test nth
APandamonium1 Jun 18, 2024
7649cde
Fixing github treating {} as secrets try 1
APandamonium1 Jun 18, 2024
7eaecc9
Fixing github treating {} as secrets try 2
APandamonium1 Jun 18, 2024
95cfadd
try with encrypt/decrypt instead
APandamonium1 Jun 18, 2024
e4c029a
chmod +x using git, will it work?
APandamonium1 Jun 18, 2024
7b45510
forgot abt this
APandamonium1 Jun 18, 2024
e057ce9
silly me
APandamonium1 Jun 18, 2024
3794584
what if chmod in workflow
APandamonium1 Jun 18, 2024
ff6cb93
hmmm identifying new error
APandamonium1 Jun 18, 2024
d242c63
changed file path
APandamonium1 Jun 18, 2024
11cdf40
changed file path in database code, omg workflow finally proceeded
APandamonium1 Jun 18, 2024
6ceaca9
changed 1 path and forgot the others lmaopain
APandamonium1 Jun 18, 2024
87eba54
removing potential error to see if that's the error
APandamonium1 Jun 18, 2024
de02aaa
swapping env code over
APandamonium1 Jun 18, 2024
830de37
try again
APandamonium1 Jun 18, 2024
3fc0c65
lets try this
APandamonium1 Jun 18, 2024
7c38fcb
reverting some changes to see progress
APandamonium1 Jun 18, 2024
d4bd35c
removing testing for test database
APandamonium1 Jun 18, 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
36 changes: 30 additions & 6 deletions .github/workflows/example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ on:
pull_request:
branches: [main]

env:
DATABASE_URL: ${{secrets.DATABASE_URL}}
# FIREBASE_ADMIN_PASSPHRASE: ${{secrets.FIREBASE_ADMIN_PASSPHRASE}}

jobs:
example:
name: Create Ubuntu OS
Expand All @@ -27,6 +31,26 @@ jobs:
go mod tidy
go get github.com/franela/goblin
ls

# - name: Setup Firebase JSON file
# run: echo "{${{ secrets.FIREBASE_JSON }}}" > edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json

# - name: Build and run JSON validator
# run: |
# go run json_validator.go edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json

- name: Decrypt Firebase JSON
run: |
chmod +x decrypt_secret.sh
./decrypt_secret.sh
env:
FIREBASE_ADMIN_PASSPHRASE: ${{secrets.FIREBASE_ADMIN_PASSPHRASE}}

- name: Testing, to be removed
run: |
ls
# cat $HOME/secrets/edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json
cat edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json

- name: Go Test
run: |
Expand All @@ -36,30 +60,30 @@ jobs:
name: Success Message (Discord)
uses: discord-actions/message@v2
with:
webhookUrl: https://discord.com/api/webhooks/1237964301201965127/ZYe3gYTeweYEfA_Q0I-JWFVXA2dVMp7Pw7jeNNd2UlFCtvIS8ZvIN_CRQ-gUwSgl7eD2
webhookUrl: ${{secrets.DISCORD_WEBHOOK}}
message: SUCCESSFULLLL in branch ${{github.ref}} by ${{github.actor}}

- if: ${{success()}}
name: Success Message (Telegram)
uses: akeylimepie/[email protected]
with:
token: 6795256205:AAHm19-9zOM4jMtEtVOSDGExXAtg5J67rKc
chat_id: -4244340354
token: ${{secrets.TELEGRAM_TOKEN}}
chat_id: ${{secrets.TELEGRAM_CHAT_ID}}
text: SUCCESSFULLLL in branch ${{github.ref}} by ${{github.actor}}

- if: ${{failure()}}
name: Failure Message (Discord)
uses: discord-actions/message@v2
with:
webhookUrl: https://discord.com/api/webhooks/1237964301201965127/ZYe3gYTeweYEfA_Q0I-JWFVXA2dVMp7Pw7jeNNd2UlFCtvIS8ZvIN_CRQ-gUwSgl7eD2
webhookUrl: ${{secrets.DISCORD_WEBHOOK}}
message: FAILUREEEE in branch ${{github.ref}} by ${{github.actor}}

- if: ${{failure()}}
name: Failure Message (Telegram)
uses: akeylimepie/[email protected]
with:
token: 6795256205:AAHm19-9zOM4jMtEtVOSDGExXAtg5J67rKc
chat_id: -4244340354
token: ${{secrets.TELEGRAM_TOKEN}}
chat_id: ${{secrets.TELEGRAM_CHAT_ID}}
text: FAILUREEEE in branch ${{github.ref}} by ${{github.actor}}

#- name: Setup Python
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
*.crt
*.key
*.pem
edusync-firebase.json
edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json
edusync-test-firebase-adminsdk-hk5kl-9af0162b09.json
.env
Binary file modified EduSync.exe
Binary file not shown.
253 changes: 186 additions & 67 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,117 +3,236 @@ package main
import (
"context"
"fmt"
"time"

"log"
"os"

"github.com/joho/godotenv"
// "github.com/joho/godotenv"

firebase "firebase.google.com/go"
"firebase.google.com/go/db"
"google.golang.org/api/option"
)

// use godot package to load/read the .env file and
// Use godot package to load/read the .env file and
// return the value of the key
func goDotEnvVariable(key string) string {
// func goDotEnvVariable(key string) string {

// load .env file
err := godotenv.Load(".env")
// // load .env file
// err := godotenv.Load(".env")

// if err != nil {
// log.Fatalf("Error loading .env file")
// }

// return os.Getenv(key)
// }

func database() {
// Find home directory.
// home, err := os.Getwd()
// if err != nil {
// return err
// }

ctx := context.Background()

// configure database URL
// databaseURL := goDotEnvVariable("DATABASE_URL")
// if databaseURL == "" {
// return fmt.Errorf("DATABASE_URL is not set in the .env file")
// }
databaseURL, found := os.LookupEnv("DATABASE_URL")
if !found {
log.Fatalf("DATABASE_URL is not set in the environment variables")
}
conf := &firebase.Config{DatabaseURL: databaseURL}

// conf := &firebase.Config{
// DatabaseURL: "https://edusync-test-default-rtdb.firebaseio.com/",
// }

// Set up the Firebase app with the provided JSON file containing the service account key.
// opt := option.WithCredentialsFile(home + "edusync-test-firebase-adminsdk-hk5kl-9af0162b09.json")

// fetch service account key
// opt := option.WithCredentialsFile("edusync-test-firebase-adminsdk-hk5kl-9af0162b09.json")
opt := option.WithCredentialsFile("edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json")
// opt := option.WithCredentialsFile("$HOME/secrets/edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json")

app, err := firebase.NewApp(ctx, conf, opt)
if err != nil {
log.Fatalf("Error loading .env file")
log.Fatalln("error in initializing firebase app: ", err)
}

return os.Getenv(key)
}
client, err := app.Database(ctx)
if err != nil {
log.Fatalln("error in creating firebase DB client: ", err)
}

type FireDB struct {
*db.Client
}
// Student operations
student := NewStudent("Jane Doe", 7, 119.5, "[email protected]", "91234567", "Tech Explorer", "Scott Smith", "Jackie Doe")
err = createStudent(client, student.ID.String(), student)
if err != nil {
log.Fatal(err)
}
fmt.Println("Student added/updated successfully!")

var fireDB FireDB
readStudent, err := readStudent(client, student.ID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("Student read successfully:", readStudent)

// Connect initializes and connects to the Firebase Realtime Database.
// It uses the provided JSON file containing the service account key to authenticate with Firebase.
// The DatabaseURL is set to the Firebase project's Realtime Database URL.
// The function returns an error if any step fails during the initialization or connection process.
func (db *FireDB) Connect() error {
// Find home directory.
home, err := os.Getwd()
studentUpdates := map[string]interface{}{
"class": "Tech Explorer 2",
"updated_at": time.Now(),
}
err = updateStudent(client, student.ID.String(), studentUpdates)
if err != nil {
return err
log.Fatal(err)
}
fmt.Println("Student updated successfully!")

// Create a context for the Firebase app.
ctx := context.Background()
err = deleteStudent(client, student.ID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("Student deleted successfully!")

// Set up the Firebase app with the provided JSON file containing the service account key.
opt := option.WithCredentialsFile(home + "edusync-firebase.json")
dotenv := goDotEnvVariable("DATABASE_URL")
config := &firebase.Config{DatabaseURL: dotenv}
// Instructor operations
instructor := NewInstructor("Scott Smith", "123-456-7890", "[email protected]", 50000.00, 10)
err = createInstructor(client, instructor.ID.String(), instructor)
if err != nil {
log.Fatal(err)
}
fmt.Println("Instructor added/updated successfully!")

app, err := firebase.NewApp(ctx, config, opt)
// opt := option.WithCredentialsFile("edusync-firebase.json")
// app, err := firebase.NewApp(context.Background(), nil, opt)
readInstructor, err := readInstructor(client, instructor.ID.String())
if err != nil {
return fmt.Errorf("error initializing app: %v", err)
log.Fatal(err)
}
fmt.Println("Instructor read successfully:", readInstructor)

// Initialize the Firebase Realtime Database client.
client, err := app.Database(ctx)
instructorUpdates := map[string]interface{}{
"base_pay": 55000.00,
"updated_at": time.Now(),
}
err = updateInstructor(client, instructor.ID.String(), instructorUpdates)
if err != nil {
return fmt.Errorf("error initializing database: %v", err)
log.Fatal(err)
}
fmt.Println("Instructor updated successfully!")

// Assign the Firebase Realtime Database client to the FireDB struct.
db.Client = client
return nil
}
err = deleteInstructor(client, instructor.ID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("Instructor deleted successfully!")

func FirebaseDB() *FireDB {
return &fireDB
}
// Parent operations
parent := NewParent("Jackie Doe", "[email protected]", "98765432")
err = createParent(client, parent.ID.String(), parent)
if err != nil {
log.Fatal(err)
}
fmt.Println("Parent added/updated successfully!")

func connectToFirebase() error {
fireDB := FirebaseDB()
err := fireDB.Connect()
readParent, err := readParent(client, parent.ID.String())
if err != nil {
return err
log.Fatal(err)
}
fmt.Println("Parent read successfully:", readParent)

ref := fireDB.NewRef("/")
err = ref.Set(context.Background(), map[string]string{
"name": "Jane Doe",
"age": "7",
"class": "Tech Explorer",
"instructor": "Scott Smith",
})
parentUpdates := map[string]interface{}{
"email": "[email protected]",
"updated_at": time.Now(),
}
err = updateParent(client, parent.ID.String(), parentUpdates)
if err != nil {
return err
log.Fatal(err)
}
return nil
fmt.Println("Parent updated successfully!")

err = deleteParent(client, parent.ID.String())
if err != nil {
log.Fatal(err)
}
fmt.Println("Parent deleted successfully!")
}

// CRUD operations
func (db *FireDB) Create(refPath string, data interface{}) error {
ref := db.NewRef(refPath)
return ref.Set(context.Background(), data)
// Student CRUD
func createStudent(client *db.Client, userId string, student Student) error {
ref := client.NewRef("students/" + userId)
return ref.Set(context.TODO(), student)
}

func (db *FireDB) Read(refPath string, dest interface{}) error {
ref := db.NewRef(refPath)
return ref.Get(context.Background(), dest)
func readStudent(client *db.Client, userId string) (Student, error) {
ref := client.NewRef("students/" + userId)
var student Student
if err := ref.Get(context.TODO(), &student); err != nil {
return Student{}, err
}
return student, nil
}

func (db *FireDB) Update(refPath string, data map[string]interface{}) error {
ref := db.NewRef(refPath)
return ref.Update(context.Background(), data)
func updateStudent(client *db.Client, userId string, updates map[string]interface{}) error {
ref := client.NewRef("students/" + userId)
return ref.Update(context.TODO(), updates)
}

func (db *FireDB) Delete(refPath string) error {
ref := db.NewRef(refPath)
return ref.Delete(context.Background())
func deleteStudent(client *db.Client, userId string) error {
ref := client.NewRef("students/" + userId)
return ref.Delete(context.TODO())
}

//todo: set up firebase, finish connecting to database
// Instructor CRUD
func createInstructor(client *db.Client, userId string, instructor Instructor) error {
ref := client.NewRef("instructors/" + userId)
return ref.Set(context.TODO(), instructor)
}

func readInstructor(client *db.Client, userId string) (Instructor, error) {
ref := client.NewRef("instructors/" + userId)
var instructor Instructor
if err := ref.Get(context.TODO(), &instructor); err != nil {
return Instructor{}, err
}
return instructor, nil
}

func updateInstructor(client *db.Client, userId string, updates map[string]interface{}) error {
ref := client.NewRef("instructors/" + userId)
return ref.Update(context.TODO(), updates)
}

func deleteInstructor(client *db.Client, userId string) error {
ref := client.NewRef("instructors/" + userId)
return ref.Delete(context.TODO())
}

// Parent CRUD
func createParent(client *db.Client, userId string, parent Parent) error {
ref := client.NewRef("parents/" + userId)
return ref.Set(context.TODO(), parent)
}

func readParent(client *db.Client, userId string) (Parent, error) {
ref := client.NewRef("parents/" + userId)
var parent Parent
if err := ref.Get(context.TODO(), &parent); err != nil {
return Parent{}, err
}
return parent, nil
}

func updateParent(client *db.Client, userId string, updates map[string]interface{}) error {
ref := client.NewRef("parents/" + userId)
return ref.Update(context.TODO(), updates)
}

func deleteParent(client *db.Client, userId string) error {
ref := client.NewRef("parents/" + userId)
return ref.Delete(context.TODO())
}
6 changes: 0 additions & 6 deletions database.rules.json

This file was deleted.

Loading
Loading