Skip to content

Commit

Permalink
current user working, changed way class id is displayed
Browse files Browse the repository at this point in the history
  • Loading branch information
PeanutBrrutter committed Jul 15, 2024
1 parent fc8276b commit 02603e3
Show file tree
Hide file tree
Showing 10 changed files with 166 additions and 115 deletions.
Binary file modified EduSync.exe
Binary file not shown.
4 changes: 2 additions & 2 deletions adminHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func AdminHandler(router *mux.Router) {

currentUser, err := GetCurrentUser(req)
if err != nil {
http.Error(res, "Unauthorized", http.StatusUnauthorized)
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}

Expand All @@ -69,7 +69,7 @@ func AdminHandler(router *mux.Router) {

currentUser, err := GetCurrentUser(req)
if err != nil {
http.Error(res, "Unauthorized", http.StatusUnauthorized)
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}

Expand Down
89 changes: 60 additions & 29 deletions authHandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,20 @@ func AuthHandler(router *mux.Router, config *Config) {
maxAge := 86400 * 30 // 30 days
isProd := true // Set to true when serving over https

store := sessions.NewCookieStore([]byte(config.SessionSecret))
store = sessions.NewCookieStore(
[]byte(config.AuthKey),
[]byte(config.EncryptKey),
)
store.MaxAge(maxAge)
store.Options.Path = "/"
store.Options.HttpOnly = true // HttpOnly should always be enabled
store.Options.Secure = isProd
store.Options = &sessions.Options{
Path: "/",
MaxAge: 3600, // 1 hour
HttpOnly: true,
Secure: true, // This should be true if your application is served over HTTPS
}

gothic.Store = store
goth.UseProviders(google.New(config.GoogleClientID, config.GoogleClientSecret, "https://localhost:8080/auth/google/callback", "email", "profile"))
Expand All @@ -43,36 +52,38 @@ func AuthHandler(router *mux.Router, config *Config) {

// Only store the user object into the session if userRole is not an empty string
if userRole != "" {
// Create a User object with the user role
currentUser := User{
GoogleID: user.UserID,
Name: user.Name,
Email: user.Email,
ContactNumber: userObj.ContactNumber, // Use contact number from the retrieved user object
Role: userObj.Role,
CreatedAt: userObj.CreatedAt,
UpdatedAt: userObj.UpdatedAt,
}
// // Create a User object with the user role
// currentUser := User{
// GoogleID: user.UserID,
// Name: user.Name,
// Email: user.Email,
// ContactNumber: userObj.ContactNumber, // Use contact number from the retrieved user object
// Role: userObj.Role,
// CreatedAt: userObj.CreatedAt,
// UpdatedAt: userObj.UpdatedAt,
// }

// Serialize the user object to JSON
userData, err := json.Marshal(currentUser)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
// // Serialize the user object to JSON
// userData, err := json.Marshal(currentUser)
// if err != nil {
// http.Error(res, err.Error(), http.StatusInternalServerError)
// return
// }

// Get the session and store the user data
session, err := store.Get(req, "auth-session")
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
session.Values["user"] = userData
err = session.Save(req, res)
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return
}
// // Get the session and store the user data
// session, err := store.Get(req, "auth-session")
// if err != nil {
// http.Error(res, err.Error(), http.StatusInternalServerError)
// return
// }
// session.Values["user"] = userData
// err = session.Save(req, res)
// if err != nil {
// http.Error(res, err.Error(), http.StatusInternalServerError)
// return
// }

SetCurrentUser(res, req, userObj)

// Redirect based on user role
if userRole == "Admin" {
Expand Down Expand Up @@ -106,3 +117,23 @@ func AuthHandler(router *mux.Router, config *Config) {
t.Execute(res, false)
}).Methods("GET")
}

func SetCurrentUser(res http.ResponseWriter, req *http.Request, user User) error {
session, err := store.Get(req, "auth-session")
if err != nil {
return fmt.Errorf("error retrieving session: %v", err)
}

userData, err := json.Marshal(user)
if err != nil {
return fmt.Errorf("error marshalling user data: %v", err)
}

session.Values["user"] = userData
err = session.Save(req, res)
if err != nil {
return fmt.Errorf("error saving session: %v", err)
}

return nil
}
2 changes: 2 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ type Config struct {
GoogleClientID string `json:"google_client_id"`
GoogleClientSecret string `json:"google_client_secret"`
SessionSecret string `json:"session_secret"`
AuthKey string `json:"auth_key"`
EncryptKey string `json:"encrypt_key"`
}

// LoadConfig reads the configuration from a file
Expand Down
4 changes: 2 additions & 2 deletions database.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func initDB(app *firebase.App) error {
func GetCurrentUser(req *http.Request) (User, error) {
session, err := store.Get(req, "auth-session")
if err != nil {
return User{}, err
return User{}, fmt.Errorf("error retrieving session: %v", err)
}

userData, ok := session.Values["user"].([]byte)
Expand All @@ -41,7 +41,7 @@ func GetCurrentUser(req *http.Request) (User, error) {
var user User
err = json.Unmarshal(userData, &user)
if err != nil {
return User{}, err
return User{}, fmt.Errorf("error unmarshalling user data: %v", err)
}

return user, nil
Expand Down
4 changes: 2 additions & 2 deletions database_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ var students = []Student{
User: User{
GoogleID: "test-student",
Name: "John Doe",
Email: "jeyvianangjieen@gmail.com",
Email: "jeyvianang112462@gmail.com",
ContactNumber: "91234567",
Role: "Student",
},
Expand Down Expand Up @@ -43,7 +43,7 @@ var admin = Admin{
GoogleID: "test-admin",
Name: "Awesomeness",
ContactNumber: "99999999",
Email: "awesome_admin@nk.com",
Email: "jeyvianangjieen@gmail.com",
Role: "Admin",
},
BasePay: 15,
Expand Down
38 changes: 19 additions & 19 deletions firebase.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,41 @@ import (
"log"
"os"

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

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

// Use godot package to load/read the .env file and
// return the value of the key (for local env)
// 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")
// }
if err != nil {
log.Fatalf("Error loading .env file")
}

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

// InitializeFirebase initializes the Firebase app and sets the global firebaseClient variable
func initializeFirebase() error {
ctx := context.Background()

databaseURL, found := os.LookupEnv("DATABASE_URL")
if !found {
log.Fatalf("DATABASE_URL is not set in the environment variables")
}
opt := option.WithCredentialsFile("edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json")

// databaseURL := goDotEnvVariable("DATABASE_URL")
// if databaseURL == "" {
// return fmt.Errorf("DATABASE_URL is not set in the environment variables")
// databaseURL, found := os.LookupEnv("DATABASE_URL")
// if !found {
// log.Fatalf("DATABASE_URL is not set in the environment variables")
// }
// opt := option.WithCredentialsFile("edusync-test-firebase-adminsdk-hk5kl-9af0162b09.json")
// opt := option.WithCredentialsFile("edusync-7bd5e-firebase-adminsdk-x49uh-af084a6314.json")

databaseURL := goDotEnvVariable("DATABASE_URL")
if databaseURL == "" {
return fmt.Errorf("DATABASE_URL is not set in the environment variables")
}
opt := option.WithCredentialsFile("edusync-test-firebase-adminsdk-hk5kl-9af0162b09.json")

conf := &firebase.Config{DatabaseURL: databaseURL}

Expand Down
1 change: 0 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ func main() {
// Set up authentication routes
AuthHandler(router, config)
MainHandler(router)
AdminHandler(router)

log.Println("listening on localhost:8080")
err = http.ListenAndServeTLS(":8080", "cert.pem", "key.pem", router)
Expand Down
Loading

0 comments on commit 02603e3

Please sign in to comment.