Skip to content

Commit

Permalink
making code more modular, add geolocation button
Browse files Browse the repository at this point in the history
  • Loading branch information
baditaflorin committed May 20, 2024
1 parent e601d45 commit 038eb0e
Show file tree
Hide file tree
Showing 10 changed files with 299 additions and 194 deletions.
48 changes: 26 additions & 22 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 17 additions & 12 deletions drinking_water/config/config.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// config/config.go
package config

import (
Expand All @@ -8,12 +9,14 @@ import (
)

type Config struct {
ClientID string
ClientSecret string
RedirectURI string
AuthURL string
TokenURL string
Query string
ClientID string
ClientSecret string
RedirectURI string
AuthURL string
TokenURL string
Query string
ChangesetComment string
CreatedBy string
}

func LoadConfig() *Config {
Expand All @@ -23,11 +26,13 @@ func LoadConfig() *Config {
}

return &Config{
ClientID: os.Getenv("CLIENT_ID"),
ClientSecret: os.Getenv("CLIENT_SECRET"),
RedirectURI: os.Getenv("REDIRECT_URI"),
AuthURL: os.Getenv("AUTH_URL"),
TokenURL: os.Getenv("TOKEN_URL"),
Query: os.Getenv("QUERY"),
ClientID: os.Getenv("CLIENT_ID"),
ClientSecret: os.Getenv("CLIENT_SECRET"),
RedirectURI: os.Getenv("REDIRECT_URI"),
AuthURL: os.Getenv("AUTH_URL"),
TokenURL: os.Getenv("TOKEN_URL"),
Query: os.Getenv("QUERY"),
ChangesetComment: os.Getenv("CHANGESET_COMMENT"),
CreatedBy: os.Getenv("CREATED_BY"),
}
}
120 changes: 66 additions & 54 deletions drinking_water/handlers/handlers.go
Original file line number Diff line number Diff line change
@@ -1,80 +1,92 @@
package handlers

import (
"drinking_water/config"
"drinking_water/oauth"
"drinking_water/osm"
"encoding/json"
"fmt"
"golang.org/x/oauth2"
"log"
"net/http"

"golang.org/x/oauth2"
)

func HandleData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(osm.WaterNodes.Elements)
func HandleData(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(osm.Nodes.Elements)
}
}

func HandleMap(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/map.html")
func HandleMap(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/map.html")
}
}

func HandleLogin(w http.ResponseWriter, r *http.Request) {
url := oauth.Oauth2Config.AuthCodeURL("state", oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
func HandleLogin(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
url := oauth.Oauth2Config.AuthCodeURL("state", oauth2.AccessTypeOffline)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
}

func HandleCallback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
token, err := oauth.Oauth2Config.Exchange(oauth2.NoContext, code)
if err != nil {
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}
func HandleCallback(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
token, err := oauth.Oauth2Config.Exchange(oauth2.NoContext, code)
if err != nil {
http.Error(w, "Failed to exchange token: "+err.Error(), http.StatusInternalServerError)
return
}

// Store the token in the session
session, _ := oauth.Store.Get(r, "session-name")
session.Values["oauth-token"] = token
err = session.Save(r, w)
if err != nil {
http.Error(w, "Failed to save session: "+err.Error(), http.StatusInternalServerError)
return
}
log.Printf("OAuth token saved in session: %v", token)
// Store the token in the session
session, _ := oauth.Store.Get(r, "session-name")
session.Values["oauth-token"] = token
err = session.Save(r, w)
if err != nil {
http.Error(w, "Failed to save session: "+err.Error(), http.StatusInternalServerError)
return
}
log.Printf("OAuth token saved in session: %v", token)

// Redirect back to the main map page
http.Redirect(w, r, "/", http.StatusSeeOther)
// Redirect back to the main map page
http.Redirect(w, r, "/", http.StatusSeeOther)
}
}

func HandleAddNode(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}
func HandleAddNode(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
return
}

// Parse the incoming request to get node details
var node struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Tags map[string]string `json:"tags"`
}
if err := json.NewDecoder(r.Body).Decode(&node); err != nil {
http.Error(w, "Failed to parse request body: "+err.Error(), http.StatusBadRequest)
return
}
// Parse the incoming request to get node details
var node struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
Tags map[string]string `json:"tags"`
}
if err := json.NewDecoder(r.Body).Decode(&node); err != nil {
http.Error(w, "Failed to parse request body: "+err.Error(), http.StatusBadRequest)
return
}

// Retrieve the OAuth token from the session
session, _ := oauth.Store.Get(r, "session-name")
token, ok := session.Values["oauth-token"].(*oauth2.Token)
if !ok {
http.Error(w, "You are not authenticated. Please log in to add a new source.", http.StatusUnauthorized)
log.Println("No OAuth token found in session")
return
}
log.Printf("Retrieved OAuth token from session: %v", token)
// Retrieve the OAuth token from the session
session, _ := oauth.Store.Get(r, "session-name")
token, ok := session.Values["oauth-token"].(*oauth2.Token)
if !ok {
http.Error(w, "You are not authenticated. Please log in to add a new source.", http.StatusUnauthorized)
log.Println("No OAuth token found in session")
return
}
log.Printf("Retrieved OAuth token from session: %v", token)

// Create the map node using the OAuth token
oauth.CreateMapNode(token, node.Lat, node.Lon, node.Tags)
// Create the map node using the OAuth token
oauth.CreateMapNode(cfg, token, node.Lat, node.Lon, node.Tags)

fmt.Fprintf(w, "Node created successfully")
fmt.Fprintf(w, "Node created successfully")
}
}
19 changes: 9 additions & 10 deletions drinking_water/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,24 @@ import (
)

func main() {
// Load configuration
cfg := config.LoadConfig()

// Initialize OAuth with configuration
// Initialize OAuth and Cookie Store
oauth.Init(cfg)

// Fetch water nodes on server start
osm.FetchWaterNodes(cfg.Query)
// Fetch nodes on server start
osm.FetchNodes(cfg)

// Static file server
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

// Setting up HTTP server routes
http.HandleFunc("/", handlers.HandleMap)
http.HandleFunc("/data", handlers.HandleData)
http.HandleFunc("/login", handlers.HandleLogin)
http.HandleFunc("/callback", handlers.HandleCallback)
http.HandleFunc("/addnode", handlers.HandleAddNode)
// Setting up HTTP server routes with injected config
http.HandleFunc("/", handlers.HandleMap(cfg))
http.HandleFunc("/data", handlers.HandleData(cfg))
http.HandleFunc("/login", handlers.HandleLogin(cfg))
http.HandleFunc("/callback", handlers.HandleCallback(cfg))
http.HandleFunc("/addnode", handlers.HandleAddNode(cfg))

fmt.Println("Server starting on :8080...")
err := http.ListenAndServe(":8080", nil)
Expand Down
Loading

0 comments on commit 038eb0e

Please sign in to comment.