Compare commits
	
		
			87 Commits
		
	
	
		
			fcd6477ec3
			...
			enhanced_r
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 
						 | 
					783ddaf553 | ||
| 
						 | 
					b8b64968bb | ||
| 
						 | 
					aad9cdfaf5 | ||
| 
						 | 
					3738ba689e | ||
| 
						 | 
					65be302aa4 | ||
| 
						 | 
					8ab50cb37c | ||
| 
						 | 
					a833823ad6 | ||
| 
						 | 
					6d6aff50b3 | ||
| 
						 | 
					a6be73765a | ||
| 
						 | 
					ddc9e51831 | ||
| 
						 | 
					dc450e26dd | ||
| 
						 | 
					de4a217c5f | ||
| 
						 | 
					c4e83d06b9 | ||
| 
						 | 
					51da24be9b | ||
| 
						 | 
					e497f4d2f0 | ||
| 
						 | 
					b30af86e58 | ||
| 
						 | 
					3ffd548623 | ||
| 
						 | 
					cb4f10e0b4 | ||
| 
						 | 
					878ce01b29 | ||
| 
						 | 
					c82cdb4f13 | ||
| 
						 | 
					ce81c36e9f | ||
| 
						 | 
					ab1b82c680 | ||
| 
						 | 
					d8b1a5c999 | ||
| 
						 | 
					0f59a6eba9 | ||
| 
						 | 
					bb69c16cdf | ||
| 
						 | 
					e87f14bcbf | ||
| 
						 | 
					ed712a5344 | ||
| 
						 | 
					ee4c9f9199 | ||
| 
						 | 
					1d400efa19 | ||
| 
						 | 
					b36cbf4b9e | ||
| 
						 | 
					fa3165d317 | ||
| 
						 | 
					7cb36db3c2 | ||
| 
						 | 
					eda5344685 | ||
| 
						 | 
					9670b7d717 | ||
| 
						 | 
					a1438f4fe2 | ||
| 
						 | 
					052fa689c7 | ||
| 
						 | 
					f1fad7e4e3 | ||
| 
						 | 
					b475da66da | ||
| 
						 | 
					d0085ab2c3 | ||
| 
						 | 
					58514f4c5f | ||
| 
						 | 
					606f5df45a | ||
| 
						 | 
					2a32a1b3ce | ||
| 
						 | 
					eb36156c52 | ||
| 
						 | 
					bada24884a | ||
| 
						 | 
					05397c2b61 | ||
| 
						 | 
					3d80b95f55 | ||
| 
						 | 
					6da7d408f9 | ||
| 
						 | 
					e993bcf317 | ||
| 
						 | 
					9b231a73d6 | ||
| 
						 | 
					34acd0fa8d | ||
| 
						 | 
					71d3bd77d0 | ||
| 
						 | 
					1451abcca4 | ||
| 
						 | 
					53a780343f | ||
| 
						 | 
					8e4c5e3268 | ||
| 
						 | 
					f18f512fea | ||
| 
						 | 
					58328fe505 | ||
| 
						 | 
					10e7830349 | ||
| 
						 | 
					5f7e674d32 | ||
| 
						 | 
					ec9c1a8fb5 | ||
| 
						 | 
					242029f2e5 | ||
| 
						 | 
					b1c65f2ab1 | ||
| 
						 | 
					965139ea18 | ||
| 
						 | 
					cf8aea5115 | ||
| 
						 | 
					c510646c84 | ||
| 
						 | 
					a4366c7395 | ||
| 
						 | 
					073dfafb28 | ||
| 
						 | 
					3fa5cf46d2 | ||
| 
						 | 
					bd8b015f44 | ||
| 
						 | 
					5a1cd77676 | ||
| 
						 | 
					012906eee2 | ||
| 
						 | 
					2a705483d9 | ||
| 
						 | 
					be2c3ae178 | ||
| 
						 | 
					f32223f12c | ||
| 
						 | 
					eff740072d | ||
| 
						 | 
					75d8996cf9 | ||
| 
						 | 
					ac2b5262fd | ||
| 
						 | 
					b9ac6fbd5f | ||
| 
						 | 
					baa8eb2b93 | ||
| 
						 | 
					402c514970 | ||
| 
						 | 
					89d1b96400 | ||
| 
						 | 
					2b46385126 | ||
| 
						 | 
					0a77813360 | ||
| 
						 | 
					f7eb852c66 | ||
| 
						 | 
					5ae84c1995 | ||
| 
						 | 
					3336bd0b3f | ||
| 
						 | 
					f2a7336283 | ||
| 
						 | 
					204971d40a | 
							
								
								
									
										1
									
								
								.gitattributes
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								.gitattributes
									
									
									
									
										vendored
									
									
										Normal file
									
								
							@@ -0,0 +1 @@
 | 
				
			|||||||
 | 
					* text=auto eol=lf
 | 
				
			||||||
							
								
								
									
										22
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										22
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							@@ -1,4 +1,26 @@
 | 
				
			|||||||
 | 
					# GoWeb specific
 | 
				
			||||||
env.json
 | 
					env.json
 | 
				
			||||||
logs/
 | 
					logs/
 | 
				
			||||||
*.log
 | 
					*.log
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Binaries for programs and plugins
 | 
				
			||||||
 | 
					*.exe
 | 
				
			||||||
 | 
					*.exe~
 | 
				
			||||||
 | 
					*.dll
 | 
				
			||||||
 | 
					*.so
 | 
				
			||||||
 | 
					*.dylib
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Test binary, built with `go test -c`
 | 
				
			||||||
 | 
					*.test
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Output of the go coverage tool, specifically when used with LiteIDE
 | 
				
			||||||
 | 
					*.out
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Dependency directories
 | 
				
			||||||
 | 
					vendor/
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# Go workspace file
 | 
				
			||||||
 | 
					go.work
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					# IDE files
 | 
				
			||||||
/.idea
 | 
					/.idea
 | 
				
			||||||
							
								
								
									
										65
									
								
								README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										65
									
								
								README.md
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,65 @@
 | 
				
			|||||||
 | 
					# GoWeb 🌐
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					GoWeb is a simple Go web framework that aims to only use the standard library. The overall file structure and
 | 
				
			||||||
 | 
					development flow is inspired by larger frameworks like Laravel. It is partially ready for smaller projects if you are
 | 
				
			||||||
 | 
					fine with getting your hands dirty, but I plan on having it ready to go for more serious projects when it hits version
 | 
				
			||||||
 | 
					2.0.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					<hr>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## Current features 🚀
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- Routing/controllers
 | 
				
			||||||
 | 
					- Templating
 | 
				
			||||||
 | 
					- Simple database migration system
 | 
				
			||||||
 | 
					- Built in REST client
 | 
				
			||||||
 | 
					- CSRF protection
 | 
				
			||||||
 | 
					- Middleware
 | 
				
			||||||
 | 
					- Minimal user login/registration + sessions
 | 
				
			||||||
 | 
					- Config file handling
 | 
				
			||||||
 | 
					- Scheduled tasks
 | 
				
			||||||
 | 
					- Entire website compiles into a single binary (~10mb) (excluding env.json)
 | 
				
			||||||
 | 
					- Minimal dependencies (just standard library, postgres driver, and x/crypto for bcrypt)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					<hr>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## When to use 🙂
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- You need to build a dynamic web application with persistent data
 | 
				
			||||||
 | 
					- You need to build a dynamic website using Go and need a good starting point
 | 
				
			||||||
 | 
					- You need to build an API in Go and don't know where to start
 | 
				
			||||||
 | 
					- Pretty much any use-case where you would use Laravel, Django, or Flask
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## When not to use 🙃
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- You need a static website (see [Hugo](https://gohugo.io/))
 | 
				
			||||||
 | 
					- You need a simple blog (see [Hugo](https://gohugo.io/))
 | 
				
			||||||
 | 
					- You need a simple site for your projects' documentation (see [Hugo](https://gohugo.io/))
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## How to use 🤔
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					1. Clone
 | 
				
			||||||
 | 
					2. Delete the git folder, so you can start tracking in your own repo
 | 
				
			||||||
 | 
					3. Run `go get` to install dependencies
 | 
				
			||||||
 | 
					4. Copy env_example.json to env.json and fill in the values
 | 
				
			||||||
 | 
					5. Run `go run main.go` to start the server
 | 
				
			||||||
 | 
					6. Rename the occurences of "GoWeb" to your app name
 | 
				
			||||||
 | 
					7. Start building your app!
 | 
				
			||||||
 | 
					8. When you see useful changes to GoWeb you'd like in your project copy them over
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## How to contribute 👨💻
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- Open an issue on GitHub if you find a bug or have a feature request.
 | 
				
			||||||
 | 
					- [Email](mailto:contact@mpatterson.xyz) me a patch if you want to contribute code.
 | 
				
			||||||
 | 
					    - Please include a good description of what the patch does and why it is needed, also include how you want to be
 | 
				
			||||||
 | 
					      credited in the commit message.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					<hr>
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					### License and disclaimer 😤
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					- You are free to use this project under the terms of the MIT license. See LICENSE for more details.
 | 
				
			||||||
 | 
					- You are responsible for the security and everything else regarding your application.
 | 
				
			||||||
 | 
					- It is not required, but I ask that when you use this project you give me credit by linking to this repository.
 | 
				
			||||||
 | 
					- I also ask that when releasing self-hosted or other end-user applications that you release it under
 | 
				
			||||||
 | 
					  the [GPLv3](https://www.gnu.org/licenses/gpl-3.0.html) license. This too is not required, but I would appreciate it.
 | 
				
			||||||
@@ -8,7 +8,8 @@ import (
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
// App contains and supplies available configurations and connections
 | 
					// App contains and supplies available configurations and connections
 | 
				
			||||||
type App struct {
 | 
					type App struct {
 | 
				
			||||||
	Config config.Configuration // Configuration file
 | 
						Config         config.Configuration // Configuration file
 | 
				
			||||||
	Db     *sql.DB              // Database connection
 | 
						Db             *sql.DB              // Database connection
 | 
				
			||||||
	Res    *embed.FS            // Resources from the embedded filesystem
 | 
						Res            *embed.FS            // Resources from the embedded filesystem
 | 
				
			||||||
 | 
						ScheduledTasks Scheduled            // Scheduled contains a struct of all scheduled functions
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										71
									
								
								app/schedule.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										71
									
								
								app/schedule.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,71 @@
 | 
				
			|||||||
 | 
					package app
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"sync"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Scheduled struct {
 | 
				
			||||||
 | 
						EveryReboot []func(app *App)
 | 
				
			||||||
 | 
						EverySecond []func(app *App)
 | 
				
			||||||
 | 
						EveryMinute []func(app *App)
 | 
				
			||||||
 | 
						EveryHour   []func(app *App)
 | 
				
			||||||
 | 
						EveryDay    []func(app *App)
 | 
				
			||||||
 | 
						EveryWeek   []func(app *App)
 | 
				
			||||||
 | 
						EveryMonth  []func(app *App)
 | 
				
			||||||
 | 
						EveryYear   []func(app *App)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Task struct {
 | 
				
			||||||
 | 
						Funcs    []func(app *App)
 | 
				
			||||||
 | 
						Interval time.Duration
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
 | 
				
			||||||
 | 
						for _, f := range app.ScheduledTasks.EveryReboot {
 | 
				
			||||||
 | 
							f(app)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						tasks := []Task{
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EverySecond, Interval: time.Second},
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EveryMinute, Interval: time.Minute},
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EveryHour, Interval: time.Hour},
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EveryDay, Interval: 24 * time.Hour},
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EveryWeek, Interval: 7 * 24 * time.Hour},
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EveryMonth, Interval: 30 * 24 * time.Hour},
 | 
				
			||||||
 | 
							{Funcs: app.ScheduledTasks.EveryYear, Interval: 365 * 24 * time.Hour},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						var wg sync.WaitGroup
 | 
				
			||||||
 | 
						runners := make([]chan bool, len(tasks))
 | 
				
			||||||
 | 
						for i, task := range tasks {
 | 
				
			||||||
 | 
							runner := make(chan bool, poolSize)
 | 
				
			||||||
 | 
							runners[i] = runner
 | 
				
			||||||
 | 
							wg.Add(1)
 | 
				
			||||||
 | 
							go func(task Task, runner chan bool) {
 | 
				
			||||||
 | 
								defer wg.Done()
 | 
				
			||||||
 | 
								ticker := time.NewTicker(task.Interval)
 | 
				
			||||||
 | 
								defer ticker.Stop()
 | 
				
			||||||
 | 
								for {
 | 
				
			||||||
 | 
									select {
 | 
				
			||||||
 | 
									case <-ticker.C:
 | 
				
			||||||
 | 
										for _, f := range task.Funcs {
 | 
				
			||||||
 | 
											runner <- true
 | 
				
			||||||
 | 
											go func(f func(app *App)) {
 | 
				
			||||||
 | 
												defer func() { <-runner }()
 | 
				
			||||||
 | 
												f(app)
 | 
				
			||||||
 | 
											}(f)
 | 
				
			||||||
 | 
										}
 | 
				
			||||||
 | 
									case <-stop:
 | 
				
			||||||
 | 
										return
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							}(task, runner)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						wg.Wait()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, runner := range runners {
 | 
				
			||||||
 | 
							close(runner)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -3,7 +3,7 @@ package config
 | 
				
			|||||||
import (
 | 
					import (
 | 
				
			||||||
	"encoding/json"
 | 
						"encoding/json"
 | 
				
			||||||
	"flag"
 | 
						"flag"
 | 
				
			||||||
	"log"
 | 
						"log/slog"
 | 
				
			||||||
	"os"
 | 
						"os"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -23,7 +23,8 @@ type Configuration struct {
 | 
				
			|||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	Template struct {
 | 
						Template struct {
 | 
				
			||||||
		BaseName string `json:"BaseTemplateName"`
 | 
							BaseName    string `json:"BaseTemplateName"`
 | 
				
			||||||
 | 
							ContentPath string `json:"ContentPath"`
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -33,22 +34,21 @@ func LoadConfig() Configuration {
 | 
				
			|||||||
	flag.Parse()
 | 
						flag.Parse()
 | 
				
			||||||
	file, err := os.Open(*c)
 | 
						file, err := os.Open(*c)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Fatal("Unable to open JSON config file: ", err)
 | 
							panic("unable to open JSON config file: " + err.Error())
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	defer func(file *os.File) {
 | 
						defer func(file *os.File) {
 | 
				
			||||||
		err := file.Close()
 | 
							err := file.Close()
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			log.Fatal("Unable to close JSON config file: ", err)
 | 
								slog.Error("unable to close JSON config file: ", err)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
	}(file)
 | 
						}(file)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Decode json config file to Configuration struct named config
 | 
					 | 
				
			||||||
	decoder := json.NewDecoder(file)
 | 
						decoder := json.NewDecoder(file)
 | 
				
			||||||
	Config := Configuration{}
 | 
						Config := Configuration{}
 | 
				
			||||||
	err = decoder.Decode(&Config)
 | 
						err = decoder.Decode(&Config)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Fatal("Unable to decode JSON config file: ", err)
 | 
							panic("unable to decode JSON config file: " + err.Error())
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return Config
 | 
						return Config
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										84
									
								
								controllers/get.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										84
									
								
								controllers/get.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,84 @@
 | 
				
			|||||||
 | 
					package controllers
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"GoWeb/app"
 | 
				
			||||||
 | 
						"GoWeb/models"
 | 
				
			||||||
 | 
						"GoWeb/security"
 | 
				
			||||||
 | 
						"GoWeb/templating"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Get is a wrapper struct for the App struct
 | 
				
			||||||
 | 
					type Get struct {
 | 
				
			||||||
 | 
						App *app.App
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (g *Get) ShowHome(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						type dataStruct struct {
 | 
				
			||||||
 | 
							CsrfToken       string
 | 
				
			||||||
 | 
							IsAuthenticated bool
 | 
				
			||||||
 | 
							Test            string
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						CsrfToken, err := security.GenerateCsrfToken(w, r)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						isAuthenticated := true
 | 
				
			||||||
 | 
						user, err := models.CurrentUser(g.App, r)
 | 
				
			||||||
 | 
						if err != nil || user.Id == 0 {
 | 
				
			||||||
 | 
							isAuthenticated = false
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						data := dataStruct{
 | 
				
			||||||
 | 
							CsrfToken:       CsrfToken,
 | 
				
			||||||
 | 
							Test:            "Hello World!",
 | 
				
			||||||
 | 
							IsAuthenticated: isAuthenticated,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						templating.RenderTemplate(w, "templates/pages/home.html", data)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						type dataStruct struct {
 | 
				
			||||||
 | 
							CsrfToken       string
 | 
				
			||||||
 | 
							IsAuthenticated bool
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						CsrfToken, err := security.GenerateCsrfToken(w, r)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						isAuthenticated := true
 | 
				
			||||||
 | 
						user, err := models.CurrentUser(g.App, r)
 | 
				
			||||||
 | 
						if err != nil || user.Id == 0 {
 | 
				
			||||||
 | 
							isAuthenticated = false
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						data := dataStruct{
 | 
				
			||||||
 | 
							CsrfToken:       CsrfToken,
 | 
				
			||||||
 | 
							IsAuthenticated: isAuthenticated,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						templating.RenderTemplate(w, "templates/pages/register.html", data)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (g *Get) ShowLogin(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						type dataStruct struct {
 | 
				
			||||||
 | 
							CsrfToken       string
 | 
				
			||||||
 | 
							IsAuthenticated bool
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						CsrfToken, err := security.GenerateCsrfToken(w, r)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						data := dataStruct{
 | 
				
			||||||
 | 
							CsrfToken: CsrfToken,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						templating.RenderTemplate(w, "templates/pages/login.html", data)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,67 +0,0 @@
 | 
				
			|||||||
package controllers
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"GoWeb/app"
 | 
					 | 
				
			||||||
	"GoWeb/models"
 | 
					 | 
				
			||||||
	"GoWeb/security"
 | 
					 | 
				
			||||||
	"GoWeb/templating"
 | 
					 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// GetController is a wrapper struct for the App struct
 | 
					 | 
				
			||||||
type GetController struct {
 | 
					 | 
				
			||||||
	App *app.App
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (getController *GetController) ShowHome(w http.ResponseWriter, _ *http.Request) {
 | 
					 | 
				
			||||||
	type dataStruct struct {
 | 
					 | 
				
			||||||
		Test string
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	data := dataStruct{
 | 
					 | 
				
			||||||
		Test: "Hello World!",
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	templating.RenderTemplate(getController.App, w, "templates/pages/home.html", data)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (getController *GetController) ShowRegister(w http.ResponseWriter, r *http.Request) {
 | 
					 | 
				
			||||||
	type dataStruct struct {
 | 
					 | 
				
			||||||
		CsrfToken string
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Create csrf token
 | 
					 | 
				
			||||||
	CsrfToken, err := security.GenerateCsrfToken(w, r)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	data := dataStruct{
 | 
					 | 
				
			||||||
		CsrfToken: CsrfToken,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	templating.RenderTemplate(getController.App, w, "templates/pages/register.html", data)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (getController *GetController) ShowLogin(w http.ResponseWriter, r *http.Request) {
 | 
					 | 
				
			||||||
	type dataStruct struct {
 | 
					 | 
				
			||||||
		CsrfToken string
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Create csrf token
 | 
					 | 
				
			||||||
	CsrfToken, err := security.GenerateCsrfToken(w, r)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	data := dataStruct{
 | 
					 | 
				
			||||||
		CsrfToken: CsrfToken,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	templating.RenderTemplate(getController.App, w, "templates/pages/login.html", data)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (getController *GetController) Logout(w http.ResponseWriter, r *http.Request) {
 | 
					 | 
				
			||||||
	models.LogoutUser(getController.App, w, r)
 | 
					 | 
				
			||||||
	http.Redirect(w, r, "/", http.StatusFound)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
							
								
								
									
										57
									
								
								controllers/post.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										57
									
								
								controllers/post.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,57 @@
 | 
				
			|||||||
 | 
					package controllers
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"GoWeb/app"
 | 
				
			||||||
 | 
						"GoWeb/models"
 | 
				
			||||||
 | 
						"log/slog"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Post is a wrapper struct for the App struct
 | 
				
			||||||
 | 
					type Post struct {
 | 
				
			||||||
 | 
						App *app.App
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (p *Post) Login(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						username := r.FormValue("username")
 | 
				
			||||||
 | 
						password := r.FormValue("password")
 | 
				
			||||||
 | 
						remember := r.FormValue("remember") == "on"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if username == "" || password == "" {
 | 
				
			||||||
 | 
							http.Redirect(w, r, "/login", http.StatusUnauthorized)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						_, err := models.AuthenticateUser(p.App, w, username, password, remember)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							http.Redirect(w, r, "/login", http.StatusUnauthorized)
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						http.Redirect(w, r, "/", http.StatusFound)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (p *Post) Register(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						username := r.FormValue("username")
 | 
				
			||||||
 | 
						password := r.FormValue("password")
 | 
				
			||||||
 | 
						createdAt := time.Now()
 | 
				
			||||||
 | 
						updatedAt := time.Now()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if username == "" || password == "" {
 | 
				
			||||||
 | 
							http.Redirect(w, r, "/register", http.StatusUnauthorized)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						_, err := models.CreateUser(p.App, username, password, createdAt, updatedAt)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							// TODO: if err == bcrypt.ErrPasswordTooLong display error to user, this will require a flash message system with cookies
 | 
				
			||||||
 | 
							slog.Error("error creating user: " + err.Error())
 | 
				
			||||||
 | 
							http.Redirect(w, r, "/register", http.StatusInternalServerError)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						http.Redirect(w, r, "/login", http.StatusFound)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func (p *Post) Logout(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						models.LogoutUser(p.App, w, r)
 | 
				
			||||||
 | 
						http.Redirect(w, r, "/", http.StatusFound)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,70 +0,0 @@
 | 
				
			|||||||
package controllers
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"GoWeb/app"
 | 
					 | 
				
			||||||
	"GoWeb/models"
 | 
					 | 
				
			||||||
	"GoWeb/security"
 | 
					 | 
				
			||||||
	"log"
 | 
					 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
	"time"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// PostController is a wrapper struct for the App struct
 | 
					 | 
				
			||||||
type PostController struct {
 | 
					 | 
				
			||||||
	App *app.App
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (postController *PostController) Login(w http.ResponseWriter, r *http.Request) {
 | 
					 | 
				
			||||||
	// Validate csrf token
 | 
					 | 
				
			||||||
	_, err := security.VerifyCsrfToken(r)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error verifying csrf token")
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	username := r.FormValue("username")
 | 
					 | 
				
			||||||
	password := r.FormValue("password")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	if username == "" || password == "" {
 | 
					 | 
				
			||||||
		log.Println("Tried to login user with empty username or password")
 | 
					 | 
				
			||||||
		http.Redirect(w, r, "/login", http.StatusFound)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	_, err = models.AuthenticateUser(postController.App, w, username, password)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error authenticating user")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		http.Redirect(w, r, "/login", http.StatusFound)
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	http.Redirect(w, r, "/", http.StatusFound)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
func (postController *PostController) Register(w http.ResponseWriter, r *http.Request) {
 | 
					 | 
				
			||||||
	// Validate csrf token
 | 
					 | 
				
			||||||
	_, err := security.VerifyCsrfToken(r)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error verifying csrf token")
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	username := r.FormValue("username")
 | 
					 | 
				
			||||||
	password := r.FormValue("password")
 | 
					 | 
				
			||||||
	createdAt := time.Now()
 | 
					 | 
				
			||||||
	updatedAt := time.Now()
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	if username == "" || password == "" {
 | 
					 | 
				
			||||||
		log.Println("Tried to create user with empty username or password")
 | 
					 | 
				
			||||||
		http.Redirect(w, r, "/register", http.StatusFound)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	_, err = models.CreateUser(postController.App, username, password, createdAt, updatedAt)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error creating user")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	http.Redirect(w, r, "/login", http.StatusFound)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@@ -5,29 +5,26 @@ import (
 | 
				
			|||||||
	"database/sql"
 | 
						"database/sql"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	_ "github.com/lib/pq"
 | 
						_ "github.com/lib/pq"
 | 
				
			||||||
	"log"
 | 
						"log/slog"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// ConnectDB returns a new database connection
 | 
					// Connect returns a new database connection
 | 
				
			||||||
func ConnectDB(app *app.App) *sql.DB {
 | 
					func Connect(app *app.App) *sql.DB {
 | 
				
			||||||
	// Set connection parameters from config
 | 
					 | 
				
			||||||
	postgresConfig := fmt.Sprintf("host=%s port=%s user=%s "+
 | 
						postgresConfig := fmt.Sprintf("host=%s port=%s user=%s "+
 | 
				
			||||||
		"password=%s dbname=%s sslmode=disable",
 | 
							"password=%s dbname=%s sslmode=disable",
 | 
				
			||||||
		app.Config.Db.Ip, app.Config.Db.Port, app.Config.Db.User, app.Config.Db.Password, app.Config.Db.Name)
 | 
							app.Config.Db.Ip, app.Config.Db.Port, app.Config.Db.User, app.Config.Db.Password, app.Config.Db.Name)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Create connection
 | 
					 | 
				
			||||||
	db, err := sql.Open("postgres", postgresConfig)
 | 
						db, err := sql.Open("postgres", postgresConfig)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		panic(err)
 | 
							panic(err)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Test connection
 | 
					 | 
				
			||||||
	err = db.Ping()
 | 
						err = db.Ping()
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		panic(err)
 | 
							panic(err)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	log.Println("Connected to database successfully on " + app.Config.Db.Ip + ":" + app.Config.Db.Port + " using database " + app.Config.Db.Name)
 | 
						slog.Info("connected to database successfully on " + app.Config.Db.Ip + ":" + app.Config.Db.Port + " using database " + app.Config.Db.Name)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return db
 | 
						return db
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
@@ -5,11 +5,12 @@ import (
 | 
				
			|||||||
	"errors"
 | 
						"errors"
 | 
				
			||||||
	"fmt"
 | 
						"fmt"
 | 
				
			||||||
	"github.com/lib/pq"
 | 
						"github.com/lib/pq"
 | 
				
			||||||
	"log"
 | 
						"log/slog"
 | 
				
			||||||
	"reflect"
 | 
						"reflect"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Migrate given a dummy object of any type, it will create a table with the same name as the type and create columns with the same name as the fields of the object
 | 
					// Migrate given a dummy object of any type, it will create a table with the same name
 | 
				
			||||||
 | 
					// as the type and create columns with the same name as the fields of the object
 | 
				
			||||||
func Migrate(app *app.App, anyStruct interface{}) error {
 | 
					func Migrate(app *app.App, anyStruct interface{}) error {
 | 
				
			||||||
	valueOfStruct := reflect.ValueOf(anyStruct)
 | 
						valueOfStruct := reflect.ValueOf(anyStruct)
 | 
				
			||||||
	typeOfStruct := valueOfStruct.Type()
 | 
						typeOfStruct := valueOfStruct.Type()
 | 
				
			||||||
@@ -23,10 +24,15 @@ func Migrate(app *app.App, anyStruct interface{}) error {
 | 
				
			|||||||
	for i := 0; i < valueOfStruct.NumField(); i++ {
 | 
						for i := 0; i < valueOfStruct.NumField(); i++ {
 | 
				
			||||||
		fieldType := typeOfStruct.Field(i)
 | 
							fieldType := typeOfStruct.Field(i)
 | 
				
			||||||
		fieldName := fieldType.Name
 | 
							fieldName := fieldType.Name
 | 
				
			||||||
		if fieldName != "Id" && fieldName != "id" {
 | 
					
 | 
				
			||||||
			err := createColumn(app, tableName, fieldName, fieldType.Type.Name())
 | 
							// Create column if dummy for migration is NOT zero value
 | 
				
			||||||
			if err != nil {
 | 
							fieldValue := valueOfStruct.Field(i).Interface()
 | 
				
			||||||
				return err
 | 
							if !reflect.ValueOf(fieldValue).IsZero() {
 | 
				
			||||||
 | 
								if fieldName != "Id" && fieldName != "id" {
 | 
				
			||||||
 | 
									err := createColumn(app, tableName, fieldName, fieldType.Type.Name())
 | 
				
			||||||
 | 
									if err != nil {
 | 
				
			||||||
 | 
										return err
 | 
				
			||||||
 | 
									}
 | 
				
			||||||
			}
 | 
								}
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
@@ -36,56 +42,72 @@ func Migrate(app *app.App, anyStruct interface{}) error {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
// createTable creates a table with the given name if it doesn't exist, it is assumed that id will be the primary key
 | 
					// createTable creates a table with the given name if it doesn't exist, it is assumed that id will be the primary key
 | 
				
			||||||
func createTable(app *app.App, tableName string) error {
 | 
					func createTable(app *app.App, tableName string) error {
 | 
				
			||||||
	sanitizedTableQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS \"%s\" (\"Id\" serial primary key)", tableName)
 | 
						var tableExists bool
 | 
				
			||||||
 | 
						err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ $1 AND pg_catalog.pg_table_is_visible(c.oid))", "^"+tableName+"$").Scan(&tableExists)
 | 
				
			||||||
	_, err := app.Db.Query(sanitizedTableQuery)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error creating table: " + tableName)
 | 
							slog.Error("error checking if table exists: " + tableName)
 | 
				
			||||||
		return err
 | 
							return err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	log.Println("Table created successfully (or already exists): " + tableName)
 | 
						if tableExists {
 | 
				
			||||||
	return nil
 | 
							slog.Info("table already exists: " + tableName)
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							sanitizedTableQuery := fmt.Sprintf("CREATE TABLE IF NOT EXISTS \"%s\" (\"Id\" serial primary key)", tableName)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							_, err := app.Db.Query(sanitizedTableQuery)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								slog.Error("error creating table: " + tableName)
 | 
				
			||||||
 | 
								return err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							slog.Info("table created successfully: " + tableName)
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// createColumn creates a column with the given name and type if it doesn't exist
 | 
					// createColumn creates a column with the given name and type if it doesn't exist
 | 
				
			||||||
func createColumn(app *app.App, tableName, columnName, columnType string) error {
 | 
					func createColumn(app *app.App, tableName, columnName, columnType string) error {
 | 
				
			||||||
	postgresType, err := getPostgresType(columnType)
 | 
						var columnExists bool
 | 
				
			||||||
 | 
						err := app.Db.QueryRow("SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2)", tableName, columnName).Scan(&columnExists)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType)
 | 
							slog.Error("error checking if column exists: " + columnName + " in table: " + tableName)
 | 
				
			||||||
		return err
 | 
							return err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	sanitizedTableName := pq.QuoteIdentifier(tableName)
 | 
						if columnExists {
 | 
				
			||||||
	query := fmt.Sprintf("ALTER TABLE %s ADD COLUMN IF NOT EXISTS \"%s\" %s", sanitizedTableName, columnName, postgresType)
 | 
							slog.Info("column already exists: " + columnName + " in table: " + tableName)
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							postgresType, err := getPostgresType(columnType)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								slog.Error("error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType)
 | 
				
			||||||
 | 
								return err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	_, err = app.Db.Query(query)
 | 
							sanitizedTableName := pq.QuoteIdentifier(tableName)
 | 
				
			||||||
	if err != nil {
 | 
							query := fmt.Sprintf("ALTER TABLE %s ADD COLUMN IF NOT EXISTS \"%s\" %s", sanitizedTableName, columnName, postgresType)
 | 
				
			||||||
		log.Println("Error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType)
 | 
					
 | 
				
			||||||
		return err
 | 
							_, err = app.Db.Query(query)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								slog.Error("error creating column: " + columnName + " in table: " + tableName + " with type: " + postgresType)
 | 
				
			||||||
 | 
								return err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							slog.Info("column created successfully:", columnName)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							return nil
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					 | 
				
			||||||
	log.Println("Column created successfully (or already exists):", columnName)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return nil
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// Given a type in Go, return the corresponding type in Postgres
 | 
					// Given a type in Go, return the corresponding type in Postgres
 | 
				
			||||||
func getPostgresType(goType string) (string, error) {
 | 
					func getPostgresType(goType string) (string, error) {
 | 
				
			||||||
	switch goType {
 | 
						switch goType {
 | 
				
			||||||
	case "int":
 | 
						case "int", "int32", "uint", "uint32":
 | 
				
			||||||
	case "int32":
 | 
					 | 
				
			||||||
	case "uint":
 | 
					 | 
				
			||||||
	case "uint32":
 | 
					 | 
				
			||||||
		return "integer", nil
 | 
							return "integer", nil
 | 
				
			||||||
	case "int64":
 | 
						case "int64", "uint64":
 | 
				
			||||||
	case "uint64":
 | 
					 | 
				
			||||||
		return "bigint", nil
 | 
							return "bigint", nil
 | 
				
			||||||
	case "int16":
 | 
						case "int16", "int8", "uint16", "uint8", "byte":
 | 
				
			||||||
	case "int8":
 | 
					 | 
				
			||||||
	case "uint16":
 | 
					 | 
				
			||||||
	case "uint8":
 | 
					 | 
				
			||||||
	case "byte":
 | 
					 | 
				
			||||||
		return "smallint", nil
 | 
							return "smallint", nil
 | 
				
			||||||
	case "string":
 | 
						case "string":
 | 
				
			||||||
		return "text", nil
 | 
							return "text", nil
 | 
				
			||||||
@@ -93,12 +115,10 @@ func getPostgresType(goType string) (string, error) {
 | 
				
			|||||||
		return "double precision", nil
 | 
							return "double precision", nil
 | 
				
			||||||
	case "bool":
 | 
						case "bool":
 | 
				
			||||||
		return "boolean", nil
 | 
							return "boolean", nil
 | 
				
			||||||
	case "time.Time":
 | 
						case "Time":
 | 
				
			||||||
		return "timestamp", nil
 | 
							return "timestamp", nil
 | 
				
			||||||
	case "[]byte":
 | 
						case "[]byte":
 | 
				
			||||||
		return "bytea", nil
 | 
							return "bytea", nil
 | 
				
			||||||
	default:
 | 
					 | 
				
			||||||
		return "text", nil
 | 
					 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return "", errors.New("Unknown type: " + goType)
 | 
						return "", errors.New("Unknown type: " + goType)
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -5,13 +5,14 @@
 | 
				
			|||||||
    "DbName": "database",
 | 
					    "DbName": "database",
 | 
				
			||||||
    "DbUser": "user",
 | 
					    "DbUser": "user",
 | 
				
			||||||
    "DbPassword": "password",
 | 
					    "DbPassword": "password",
 | 
				
			||||||
    "AutoMigrate": true
 | 
					    "DbAutoMigrate": true
 | 
				
			||||||
  },
 | 
					  },
 | 
				
			||||||
  "Listen": {
 | 
					  "Listen": {
 | 
				
			||||||
    "HttpIp": "127.0.0.1",
 | 
					    "HttpIp": "127.0.0.1",
 | 
				
			||||||
    "HttpPort": "8090"
 | 
					    "HttpPort": "8090"
 | 
				
			||||||
  },
 | 
					  },
 | 
				
			||||||
  "Template": {
 | 
					  "Template": {
 | 
				
			||||||
    "BaseTemplateName": "templates/base.html"
 | 
					    "BaseTemplateName": "templates/base.html",
 | 
				
			||||||
 | 
					    "ContentPath": "templates"
 | 
				
			||||||
  }
 | 
					  }
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
							
								
								
									
										6
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										6
									
								
								go.mod
									
									
									
									
									
								
							@@ -1,8 +1,8 @@
 | 
				
			|||||||
module GoWeb
 | 
					module GoWeb
 | 
				
			||||||
 | 
					
 | 
				
			||||||
go 1.20
 | 
					go 1.22
 | 
				
			||||||
 | 
					
 | 
				
			||||||
require (
 | 
					require (
 | 
				
			||||||
	github.com/lib/pq v1.10.7
 | 
						github.com/lib/pq v1.10.9
 | 
				
			||||||
	golang.org/x/crypto v0.6.0
 | 
						golang.org/x/crypto v0.20.0
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										8
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										8
									
								
								go.sum
									
									
									
									
									
								
							@@ -1,4 +1,4 @@
 | 
				
			|||||||
github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw=
 | 
					github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
 | 
				
			||||||
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
 | 
					github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
 | 
				
			||||||
golang.org/x/crypto v0.6.0 h1:qfktjS5LUO+fFKeJXZ+ikTRijMmljikvG68fpMMruSc=
 | 
					golang.org/x/crypto v0.20.0 h1:jmAMJJZXr5KiCw05dfYK9QnqaqKLYXijU23lsEdcQqg=
 | 
				
			||||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
 | 
					golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ=
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										67
									
								
								main.go
									
									
									
									
									
								
							
							
						
						
									
										67
									
								
								main.go
									
									
									
									
									
								
							@@ -6,10 +6,15 @@ import (
 | 
				
			|||||||
	"GoWeb/database"
 | 
						"GoWeb/database"
 | 
				
			||||||
	"GoWeb/models"
 | 
						"GoWeb/models"
 | 
				
			||||||
	"GoWeb/routes"
 | 
						"GoWeb/routes"
 | 
				
			||||||
 | 
						"GoWeb/templating"
 | 
				
			||||||
 | 
						"context"
 | 
				
			||||||
	"embed"
 | 
						"embed"
 | 
				
			||||||
	"log"
 | 
						"errors"
 | 
				
			||||||
 | 
						"log/slog"
 | 
				
			||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
	"os"
 | 
						"os"
 | 
				
			||||||
 | 
						"os/signal"
 | 
				
			||||||
 | 
						"syscall"
 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -30,33 +35,69 @@ func main() {
 | 
				
			|||||||
	if _, err := os.Stat("logs"); os.IsNotExist(err) {
 | 
						if _, err := os.Stat("logs"); os.IsNotExist(err) {
 | 
				
			||||||
		err := os.Mkdir("logs", 0755)
 | 
							err := os.Mkdir("logs", 0755)
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			panic("Failed to create log directory")
 | 
								panic("failed to create log directory: " + err.Error())
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Create log file and set output
 | 
						// Create log file and set output
 | 
				
			||||||
	file, err := os.OpenFile("logs/"+time.Now().Format("2006-01-02")+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
 | 
						file, err := os.OpenFile("logs/"+time.Now().Format("2006-01-02")+".log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
 | 
				
			||||||
	log.SetOutput(file)
 | 
						if err != nil {
 | 
				
			||||||
 | 
							panic("error creating log file: " + err.Error())
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						logger := slog.New(slog.NewTextHandler(file, nil))
 | 
				
			||||||
 | 
						slog.SetDefault(logger) // Set structured logger globally
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Connect to database and run migrations
 | 
						// Connect to database and run migrations
 | 
				
			||||||
	appLoaded.Db = database.ConnectDB(&appLoaded)
 | 
						appLoaded.Db = database.Connect(&appLoaded)
 | 
				
			||||||
	if appLoaded.Config.Db.AutoMigrate {
 | 
						if appLoaded.Config.Db.AutoMigrate {
 | 
				
			||||||
		err = models.RunAllMigrations(&appLoaded)
 | 
							err = models.RunAllMigrations(&appLoaded)
 | 
				
			||||||
		if err != nil {
 | 
							if err != nil {
 | 
				
			||||||
			log.Println(err)
 | 
								slog.Error("error running migrations: " + err.Error())
 | 
				
			||||||
			return
 | 
								os.Exit(1)
 | 
				
			||||||
		}
 | 
							}
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Assign and run scheduled tasks
 | 
				
			||||||
 | 
						appLoaded.ScheduledTasks = app.Scheduled{
 | 
				
			||||||
 | 
							EveryReboot: []func(app *app.App){models.ScheduledSessionCleanup},
 | 
				
			||||||
 | 
							EveryMinute: []func(app *app.App){models.ScheduledSessionCleanup},
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Define Routes
 | 
						// Define Routes
 | 
				
			||||||
	routes.GetRoutes(&appLoaded)
 | 
						routes.Get(&appLoaded)
 | 
				
			||||||
	routes.PostRoutes(&appLoaded)
 | 
						routes.Post(&appLoaded)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Prepare templates
 | 
				
			||||||
 | 
						err = templating.BuildPages(&appLoaded)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error building templates: " + err.Error())
 | 
				
			||||||
 | 
							os.Exit(1)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Start server
 | 
						// Start server
 | 
				
			||||||
	log.Println("Starting server and listening on " + appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port)
 | 
						server := &http.Server{Addr: appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port}
 | 
				
			||||||
	err = http.ListenAndServe(appLoaded.Config.Listen.Ip+":"+appLoaded.Config.Listen.Port, nil)
 | 
						go func() {
 | 
				
			||||||
 | 
							slog.Info("starting server and listening on " + appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port)
 | 
				
			||||||
 | 
							err := server.ListenAndServe()
 | 
				
			||||||
 | 
							if err != nil && !errors.Is(err, http.ErrServerClosed) {
 | 
				
			||||||
 | 
								slog.Error("could not listen on %s: %v\n", appLoaded.Config.Listen.Ip+":"+appLoaded.Config.Listen.Port, err)
 | 
				
			||||||
 | 
								os.Exit(1)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Wait for interrupt signal and shut down the server
 | 
				
			||||||
 | 
						interrupt := make(chan os.Signal, 1)
 | 
				
			||||||
 | 
						signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
 | 
				
			||||||
 | 
						stop := make(chan struct{})
 | 
				
			||||||
 | 
						go app.RunScheduledTasks(&appLoaded, 100, stop)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						<-interrupt
 | 
				
			||||||
 | 
						slog.Info("interrupt signal received. Shutting down server...")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						err = server.Shutdown(context.Background())
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println(err)
 | 
							slog.Error("could not gracefully shutdown the server: %v\n", err)
 | 
				
			||||||
		return
 | 
							os.Exit(1)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										21
									
								
								middleware/csrf.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								middleware/csrf.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					package middleware
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"GoWeb/security"
 | 
				
			||||||
 | 
						"log/slog"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Csrf validates the CSRF token and returns the handler function if it succeeded
 | 
				
			||||||
 | 
					func Csrf(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						return func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
							_, err := security.VerifyCsrfToken(r)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								slog.Info("error verifying csrf token")
 | 
				
			||||||
 | 
								http.Error(w, "Forbidden", http.StatusForbidden)
 | 
				
			||||||
 | 
								return
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							f(w, r)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										5
									
								
								middleware/groups.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								middleware/groups.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,5 @@
 | 
				
			|||||||
 | 
					package middleware
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import "net/http"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type MiddlewareFunc func(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)
 | 
				
			||||||
							
								
								
									
										14
									
								
								middleware/wrapper.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								middleware/wrapper.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,14 @@
 | 
				
			|||||||
 | 
					package middleware
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import "net/http"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// ProcessGroup is a wrapper function for the http.HandleFunc function
 | 
				
			||||||
 | 
					// that takes the function you want to execute (f) and the middleware you want
 | 
				
			||||||
 | 
					// to execute (m) this should be used when processing multiple groups of middleware at a time
 | 
				
			||||||
 | 
					func ProcessGroup(f func(w http.ResponseWriter, r *http.Request), m []MiddlewareFunc) func(w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
 | 
						for _, middleware := range m {
 | 
				
			||||||
 | 
							_ = middleware(f)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return f
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -3,6 +3,7 @@ package models
 | 
				
			|||||||
import (
 | 
					import (
 | 
				
			||||||
	"GoWeb/app"
 | 
						"GoWeb/app"
 | 
				
			||||||
	"GoWeb/database"
 | 
						"GoWeb/database"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// RunAllMigrations defines the structs that should be represented in the database
 | 
					// RunAllMigrations defines the structs that should be represented in the database
 | 
				
			||||||
@@ -12,10 +13,25 @@ func RunAllMigrations(app *app.App) error {
 | 
				
			|||||||
		Id:        1, // Id is handled automatically, but it is added here to show it will be skipped during column creation
 | 
							Id:        1, // Id is handled automatically, but it is added here to show it will be skipped during column creation
 | 
				
			||||||
		Username:  "migrate",
 | 
							Username:  "migrate",
 | 
				
			||||||
		Password:  "migrate",
 | 
							Password:  "migrate",
 | 
				
			||||||
		AuthToken: "migrate",
 | 
							CreatedAt: time.Now(),
 | 
				
			||||||
		CreatedAt: "2021-01-01 00:00:00",
 | 
							UpdatedAt: time.Now(),
 | 
				
			||||||
		UpdatedAt: "2021-01-01 00:00:00",
 | 
						}
 | 
				
			||||||
 | 
						err := database.Migrate(app, user)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return database.Migrate(app, user)
 | 
						session := Session{
 | 
				
			||||||
 | 
							Id:         1,
 | 
				
			||||||
 | 
							UserId:     1,
 | 
				
			||||||
 | 
							AuthToken:  "migrate",
 | 
				
			||||||
 | 
							RememberMe: true, // Booleans must be true to migrate properly
 | 
				
			||||||
 | 
							CreatedAt:  time.Now(),
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						err = database.Migrate(app, session)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										153
									
								
								models/session.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										153
									
								
								models/session.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,153 @@
 | 
				
			|||||||
 | 
					package models
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"GoWeb/app"
 | 
				
			||||||
 | 
						"crypto/rand"
 | 
				
			||||||
 | 
						"encoding/hex"
 | 
				
			||||||
 | 
						"log/slog"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
						"time"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					type Session struct {
 | 
				
			||||||
 | 
						Id         int64
 | 
				
			||||||
 | 
						UserId     int64
 | 
				
			||||||
 | 
						AuthToken  string
 | 
				
			||||||
 | 
						RememberMe bool
 | 
				
			||||||
 | 
						CreatedAt  time.Time
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const sessionColumnsNoId = "\"UserId\", \"AuthToken\", \"RememberMe\", \"CreatedAt\""
 | 
				
			||||||
 | 
					const sessionColumns = "\"Id\", " + sessionColumnsNoId
 | 
				
			||||||
 | 
					const sessionTable = "public.\"Session\""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						selectSessionByAuthToken      = "SELECT " + sessionColumns + " FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
 | 
				
			||||||
 | 
						selectAuthTokenIfExists       = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)"
 | 
				
			||||||
 | 
						insertSession                 = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
 | 
				
			||||||
 | 
						deleteSessionByAuthToken      = "DELETE FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
 | 
				
			||||||
 | 
						deleteSessionsOlderThan30Days = "DELETE FROM " + sessionTable + " WHERE \"CreatedAt\" < NOW() - INTERVAL '30 days'"
 | 
				
			||||||
 | 
						deleteSessionsOlderThan6Hours = "DELETE FROM " + sessionTable + " WHERE \"CreatedAt\" < NOW() - INTERVAL '6 hours' AND \"RememberMe\" = false"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// CreateSession creates a new session for a user
 | 
				
			||||||
 | 
					func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember bool) (Session, error) {
 | 
				
			||||||
 | 
						session := Session{}
 | 
				
			||||||
 | 
						session.UserId = userId
 | 
				
			||||||
 | 
						session.AuthToken = generateAuthToken(app)
 | 
				
			||||||
 | 
						session.RememberMe = remember
 | 
				
			||||||
 | 
						session.CreatedAt = time.Now()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// If the AuthToken column for any user matches the token, set existingAuthToken to true
 | 
				
			||||||
 | 
						var existingAuthToken bool
 | 
				
			||||||
 | 
						err := app.Db.QueryRow(selectAuthTokenIfExists, session.AuthToken).Scan(&existingAuthToken)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error checking for existing auth token" + err.Error())
 | 
				
			||||||
 | 
							return Session{}, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// If duplicate token found, recursively call function until unique token is generated
 | 
				
			||||||
 | 
						if existingAuthToken {
 | 
				
			||||||
 | 
							slog.Warn("duplicate token found in sessions table, generating new token...")
 | 
				
			||||||
 | 
							return CreateSession(app, w, userId, remember)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.RememberMe, session.CreatedAt).Scan(&session.Id)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error inserting session into database")
 | 
				
			||||||
 | 
							return Session{}, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						createSessionCookie(app, w, session)
 | 
				
			||||||
 | 
						return session, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func SessionByAuthToken(app *app.App, authToken string) (Session, error) {
 | 
				
			||||||
 | 
						session := Session{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						err := app.Db.QueryRow(selectSessionByAuthToken, authToken).Scan(&session.Id, &session.UserId, &session.AuthToken, &session.RememberMe, &session.CreatedAt)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return Session{}, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return session, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// generateAuthToken generates a random 64-byte string
 | 
				
			||||||
 | 
					func generateAuthToken(app *app.App) string {
 | 
				
			||||||
 | 
						b := make([]byte, 64)
 | 
				
			||||||
 | 
						_, err := rand.Read(b)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error generating random bytes for auth token")
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return hex.EncodeToString(b)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// createSessionCookie creates a new session cookie
 | 
				
			||||||
 | 
					func createSessionCookie(app *app.App, w http.ResponseWriter, session Session) {
 | 
				
			||||||
 | 
						cookie := &http.Cookie{}
 | 
				
			||||||
 | 
						if session.RememberMe {
 | 
				
			||||||
 | 
							cookie = &http.Cookie{
 | 
				
			||||||
 | 
								Name:     "session",
 | 
				
			||||||
 | 
								Value:    session.AuthToken,
 | 
				
			||||||
 | 
								Path:     "/",
 | 
				
			||||||
 | 
								MaxAge:   2592000 * 1000, // 30 days in ms
 | 
				
			||||||
 | 
								HttpOnly: true,
 | 
				
			||||||
 | 
								Secure:   true,
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						} else {
 | 
				
			||||||
 | 
							cookie = &http.Cookie{
 | 
				
			||||||
 | 
								Name:     "session",
 | 
				
			||||||
 | 
								Value:    session.AuthToken,
 | 
				
			||||||
 | 
								Path:     "/",
 | 
				
			||||||
 | 
								MaxAge:   21600 * 1000, // 6 hours in ms
 | 
				
			||||||
 | 
								HttpOnly: true,
 | 
				
			||||||
 | 
								Secure:   true,
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						http.SetCookie(w, cookie)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// deleteSessionCookie deletes the session cookie
 | 
				
			||||||
 | 
					func deleteSessionCookie(app *app.App, w http.ResponseWriter) {
 | 
				
			||||||
 | 
						cookie := &http.Cookie{
 | 
				
			||||||
 | 
							Name:   "session",
 | 
				
			||||||
 | 
							Value:  "",
 | 
				
			||||||
 | 
							Path:   "/",
 | 
				
			||||||
 | 
							MaxAge: -1,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						http.SetCookie(w, cookie)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// DeleteSessionByAuthToken deletes a session from the database by AuthToken
 | 
				
			||||||
 | 
					func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken string) error {
 | 
				
			||||||
 | 
						_, err := app.Db.Exec(deleteSessionByAuthToken, authToken)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error deleting session from database")
 | 
				
			||||||
 | 
							return err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						deleteSessionCookie(app, w)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// ScheduledSessionCleanup deletes expired sessions from the database
 | 
				
			||||||
 | 
					func ScheduledSessionCleanup(app *app.App) {
 | 
				
			||||||
 | 
						// Delete sessions older than 30 days (remember me sessions)
 | 
				
			||||||
 | 
						_, err := app.Db.Exec(deleteSessionsOlderThan30Days)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error deleting 30 day expired sessions from database" + err.Error())
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Delete sessions older than 6 hours
 | 
				
			||||||
 | 
						_, err = app.Db.Exec(deleteSessionsOlderThan6Hours)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error deleting 6 hour expired sessions from database" + err.Error())
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						slog.Info("deleted expired sessions from database")
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										218
									
								
								models/user.go
									
									
									
									
									
								
							
							
						
						
									
										218
									
								
								models/user.go
									
									
									
									
									
								
							@@ -2,13 +2,10 @@ package models
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"GoWeb/app"
 | 
						"GoWeb/app"
 | 
				
			||||||
	"crypto/rand"
 | 
						"crypto/sha256"
 | 
				
			||||||
	"database/sql"
 | 
					 | 
				
			||||||
	"encoding/hex"
 | 
						"encoding/hex"
 | 
				
			||||||
	"log"
 | 
						"log/slog"
 | 
				
			||||||
	"math"
 | 
					 | 
				
			||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
	"strconv"
 | 
					 | 
				
			||||||
	"time"
 | 
						"time"
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	"golang.org/x/crypto/bcrypt"
 | 
						"golang.org/x/crypto/bcrypt"
 | 
				
			||||||
@@ -18,207 +15,116 @@ type User struct {
 | 
				
			|||||||
	Id        int64
 | 
						Id        int64
 | 
				
			||||||
	Username  string
 | 
						Username  string
 | 
				
			||||||
	Password  string
 | 
						Password  string
 | 
				
			||||||
	AuthToken string
 | 
						CreatedAt time.Time
 | 
				
			||||||
	CreatedAt string
 | 
						UpdatedAt time.Time
 | 
				
			||||||
	UpdatedAt string
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// GetCurrentUser finds the currently logged-in user by session cookie
 | 
					const userColumnsNoId = "\"Username\", \"Password\", \"CreatedAt\", \"UpdatedAt\""
 | 
				
			||||||
func GetCurrentUser(app *app.App, r *http.Request) (User, error) {
 | 
					const userColumns = "\"Id\", " + userColumnsNoId
 | 
				
			||||||
 | 
					const userTable = "public.\"User\""
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					const (
 | 
				
			||||||
 | 
						selectUserById       = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Id\" = $1"
 | 
				
			||||||
 | 
						selectUserByUsername = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Username\" = $1"
 | 
				
			||||||
 | 
						insertUser           = "INSERT INTO " + userTable + " (" + userColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// CurrentUser finds the currently logged-in user by session cookie
 | 
				
			||||||
 | 
					func CurrentUser(app *app.App, r *http.Request) (User, error) {
 | 
				
			||||||
	cookie, err := r.Cookie("session")
 | 
						cookie, err := r.Cookie("session")
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error getting session cookie")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return User{}, err
 | 
							return User{}, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	var userId int64
 | 
						session, err := SessionByAuthToken(app, cookie.Value)
 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Query row by session cookie
 | 
					 | 
				
			||||||
	err = app.Db.QueryRow("SELECT Id FROM User WHERE session = $1", cookie.Value).Scan(&userId)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error querying session row with session: " + cookie.Value)
 | 
					 | 
				
			||||||
		return User{}, err
 | 
							return User{}, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return GetUserById(app, userId)
 | 
						return UserById(app, session.UserId)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// GetUserById finds a users table row in the database by id and returns a struct representing this row
 | 
					// UserById finds a User table row in the database by id and returns a struct representing this row
 | 
				
			||||||
func GetUserById(app *app.App, id int64) (User, error) {
 | 
					func UserById(app *app.App, id int64) (User, error) {
 | 
				
			||||||
	user := User{}
 | 
						user := User{}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Query row by id
 | 
						err := app.Db.QueryRow(selectUserById, id).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
 | 
				
			||||||
	row, err := app.Db.Query("SELECT Id, Username, Password, AuthToken, CreatedAt, UpdatedAt FROM User WHERE Id = $1", id)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error querying user row with id: " + strconv.FormatInt(id, 10))
 | 
					 | 
				
			||||||
		return User{}, err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	defer func(row *sql.Rows) {
 | 
					 | 
				
			||||||
		err := row.Close()
 | 
					 | 
				
			||||||
		if err != nil {
 | 
					 | 
				
			||||||
			log.Println("Error closing database row")
 | 
					 | 
				
			||||||
			log.Println(err)
 | 
					 | 
				
			||||||
		}
 | 
					 | 
				
			||||||
	}(row)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Feed row data into user struct
 | 
					 | 
				
			||||||
	row.Next()
 | 
					 | 
				
			||||||
	err = row.Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error reading queried row from database")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return User{}, err
 | 
							return User{}, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return user, nil
 | 
						return user, nil
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// CreateUser creates a users table row in the database
 | 
					// UserByUsername finds a User table row in the database by username and returns a struct representing this row
 | 
				
			||||||
func CreateUser(app *app.App, username string, password string, createdAt time.Time, updatedAt time.Time) (User, error) {
 | 
					func UserByUsername(app *app.App, username string) (User, error) {
 | 
				
			||||||
	// Hash password
 | 
						user := User{}
 | 
				
			||||||
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
 | 
					
 | 
				
			||||||
 | 
						err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error hashing password when creating user")
 | 
							return User{}, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return user, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// CreateUser creates a User table row in the database
 | 
				
			||||||
 | 
					func CreateUser(app *app.App, username string, password string, createdAt time.Time, updatedAt time.Time) (User, error) {
 | 
				
			||||||
 | 
						// Get sha256 hash of password then get bcrypt hash to store
 | 
				
			||||||
 | 
						hash256 := sha256.New()
 | 
				
			||||||
 | 
						hash256.Write([]byte(password))
 | 
				
			||||||
 | 
						hashSum := hash256.Sum(nil)
 | 
				
			||||||
 | 
						hashString := hex.EncodeToString(hashSum)
 | 
				
			||||||
 | 
						hash, err := bcrypt.GenerateFromPassword([]byte(hashString), bcrypt.DefaultCost)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error("error hashing password: " + err.Error())
 | 
				
			||||||
		return User{}, err
 | 
							return User{}, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	var lastInsertId int64
 | 
						var lastInsertId int64
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	sqlStatement := "INSERT INTO User (Username, Password, CreatedAt, UpdatedAt) VALUES ($1, $2, $3, $4) RETURNING Id"
 | 
						err = app.Db.QueryRow(insertUser, username, string(hash), createdAt, updatedAt).Scan(&lastInsertId)
 | 
				
			||||||
	err = app.Db.QueryRow(sqlStatement, username, string(hash), createdAt, updatedAt).Scan(&lastInsertId)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error creating user row")
 | 
							slog.Error("error creating user row: " + err.Error())
 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return User{}, err
 | 
							return User{}, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	return GetUserById(app, lastInsertId)
 | 
						return UserById(app, lastInsertId)
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// AuthenticateUser validates the password for the specified user if it matches a session cookie is created and returned
 | 
					// AuthenticateUser validates the password for the specified user
 | 
				
			||||||
func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string) (string, error) {
 | 
					func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string, remember bool) (Session, error) {
 | 
				
			||||||
	var hashedPassword []byte
 | 
						var user User
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Query row by username, scan password column
 | 
						err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
 | 
				
			||||||
	err := app.Db.QueryRow("SELECT Password FROM User WHERE Username = $1", username).Scan(&hashedPassword)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Unable to find row with username: " + username)
 | 
							slog.Info("user not found: " + username)
 | 
				
			||||||
		log.Println(err)
 | 
							return Session{}, err
 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Validate password
 | 
						// Get sha256 hash of password then check bcrypt
 | 
				
			||||||
	err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))
 | 
						hash256 := sha256.New()
 | 
				
			||||||
 | 
						hash256.Write([]byte(password))
 | 
				
			||||||
 | 
						hashSum := hash256.Sum(nil)
 | 
				
			||||||
 | 
						hashString := hex.EncodeToString(hashSum)
 | 
				
			||||||
 | 
						err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(hashString))
 | 
				
			||||||
	if err != nil { // Failed to validate password, doesn't match
 | 
						if err != nil { // Failed to validate password, doesn't match
 | 
				
			||||||
		log.Println("Authentication error (incorrect password) for user:" + username)
 | 
							slog.Info("incorrect password:" + username)
 | 
				
			||||||
		log.Println(err)
 | 
							return Session{}, err
 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	} else {
 | 
						} else {
 | 
				
			||||||
		return createSessionCookie(app, w, username)
 | 
							return CreateSession(app, w, user.Id, remember)
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// createSessionCookie creates a new session token and cookie and returns the token value
 | 
					// LogoutUser deletes the session cookie and AuthToken from the database
 | 
				
			||||||
func createSessionCookie(app *app.App, w http.ResponseWriter, username string) (string, error) {
 | 
					 | 
				
			||||||
	// Generate random 64 character string (alpha-numeric)
 | 
					 | 
				
			||||||
	buff := make([]byte, int(math.Ceil(float64(64)/2)))
 | 
					 | 
				
			||||||
	_, err := rand.Read(buff)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error creating random buffer for session token value")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
	str := hex.EncodeToString(buff)
 | 
					 | 
				
			||||||
	token := str[:64]
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// If the auth_token column for any user matches the token, set existingAuthToken to true
 | 
					 | 
				
			||||||
	var existingAuthToken bool
 | 
					 | 
				
			||||||
	err = app.Db.QueryRow("SELECT EXISTS(SELECT 1 FROM User WHERE AuthToken = $1)", token).Scan(&existingAuthToken)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error checking for existing auth token")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// If duplicate token found, recursively call function until unique token is generated
 | 
					 | 
				
			||||||
	if existingAuthToken == true {
 | 
					 | 
				
			||||||
		log.Println("Duplicate token found in sessions table")
 | 
					 | 
				
			||||||
		return createSessionCookie(app, w, username)
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Store token in auth_token column of the users table
 | 
					 | 
				
			||||||
	_, err = app.Db.Exec("UPDATE User SET AuthToken = $1 WHERE Username = $2", token, username)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error setting auth_token column in users table")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Create session cookie, containing token
 | 
					 | 
				
			||||||
	cookie := &http.Cookie{
 | 
					 | 
				
			||||||
		Name:     "session",
 | 
					 | 
				
			||||||
		Value:    token,
 | 
					 | 
				
			||||||
		Path:     "/",
 | 
					 | 
				
			||||||
		MaxAge:   86400,
 | 
					 | 
				
			||||||
		HttpOnly: true,
 | 
					 | 
				
			||||||
		Secure:   true,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	http.SetCookie(w, cookie)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return token, nil
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// ValidateSessionCookie validates the session cookie and returns the username of the user if valid
 | 
					 | 
				
			||||||
func ValidateSessionCookie(app *app.App, r *http.Request) (string, error) {
 | 
					 | 
				
			||||||
	// Get cookie from request
 | 
					 | 
				
			||||||
	cookie, err := r.Cookie("session")
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error getting cookie from request")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Query row by token
 | 
					 | 
				
			||||||
	var username string
 | 
					 | 
				
			||||||
	err = app.Db.QueryRow("SELECT Username FROM User WHERE AuthToken = $1", cookie.Value).Scan(&username)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println("Error querying row by token")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return "", err
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	return username, nil
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// LogoutUser deletes the session cookie and token from the database
 | 
					 | 
				
			||||||
func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) {
 | 
					func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) {
 | 
				
			||||||
	// Get cookie from request
 | 
					 | 
				
			||||||
	cookie, err := r.Cookie("session")
 | 
						cookie, err := r.Cookie("session")
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error getting cookie from request")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return
 | 
							return
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Set token to empty string
 | 
						err = DeleteSessionByAuthToken(app, w, cookie.Value)
 | 
				
			||||||
	sqlStatement := "UPDATE User SET AuthToken = $1 WHERE AuthToken = $2"
 | 
					 | 
				
			||||||
	_, err = app.Db.Exec(sqlStatement, "", cookie.Value)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error setting auth_token column in users table")
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return
 | 
							return
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Delete cookie
 | 
					 | 
				
			||||||
	cookie = &http.Cookie{
 | 
					 | 
				
			||||||
		Name:   "session",
 | 
					 | 
				
			||||||
		Value:  "",
 | 
					 | 
				
			||||||
		Path:   "/",
 | 
					 | 
				
			||||||
		MaxAge: -1,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	http.SetCookie(w, cookie)
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										65
									
								
								restclient/client.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										65
									
								
								restclient/client.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,65 @@
 | 
				
			|||||||
 | 
					package restclient
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"bytes"
 | 
				
			||||||
 | 
						"encoding/json"
 | 
				
			||||||
 | 
						"mime/multipart"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// SendRequest sends an HTTP request to a URL and includes the specified headers and body.
 | 
				
			||||||
 | 
					// A body can be nil for GET requests, a map[string]string for multipart/form-data requests,
 | 
				
			||||||
 | 
					// or a struct for JSON requests
 | 
				
			||||||
 | 
					func SendRequest(url string, method string, headers map[string]string, body interface{}) (http.Response, error) {
 | 
				
			||||||
 | 
						var reqBody *bytes.Buffer
 | 
				
			||||||
 | 
						var contentType string
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						switch v := body.(type) {
 | 
				
			||||||
 | 
						case nil:
 | 
				
			||||||
 | 
							reqBody = bytes.NewBuffer([]byte(""))
 | 
				
			||||||
 | 
						case map[string]string:
 | 
				
			||||||
 | 
							reqBody = &bytes.Buffer{}
 | 
				
			||||||
 | 
							writer := multipart.NewWriter(reqBody)
 | 
				
			||||||
 | 
							for key, value := range v {
 | 
				
			||||||
 | 
								err := writer.WriteField(key, value)
 | 
				
			||||||
 | 
								if err != nil {
 | 
				
			||||||
 | 
									return http.Response{}, err
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							err := writer.Close()
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								return http.Response{}, err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							contentType = writer.FormDataContentType()
 | 
				
			||||||
 | 
						default:
 | 
				
			||||||
 | 
							jsonBody, err := json.Marshal(body)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								return http.Response{}, err
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
							reqBody = bytes.NewBuffer(jsonBody)
 | 
				
			||||||
 | 
							contentType = "application/json"
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						req, err := http.NewRequest(method, url, reqBody)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return http.Response{}, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						if contentType != "" {
 | 
				
			||||||
 | 
							req.Header.Set("Content-Type", contentType)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for key, value := range headers {
 | 
				
			||||||
 | 
							req.Header.Add(key, value)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						client := &http.Client{}
 | 
				
			||||||
 | 
						resp, err := client.Do(req)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return http.Response{}, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return *resp, nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										32
									
								
								routes/get.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										32
									
								
								routes/get.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,32 @@
 | 
				
			|||||||
 | 
					package routes
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"GoWeb/app"
 | 
				
			||||||
 | 
						"GoWeb/controllers"
 | 
				
			||||||
 | 
						"io/fs"
 | 
				
			||||||
 | 
						"log/slog"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Get defines all project get routes
 | 
				
			||||||
 | 
					func Get(app *app.App) {
 | 
				
			||||||
 | 
						// Get controller struct initialize
 | 
				
			||||||
 | 
						getController := controllers.Get{
 | 
				
			||||||
 | 
							App: app,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Serve static files
 | 
				
			||||||
 | 
						staticFS, err := fs.Sub(app.Res, "static")
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							slog.Error(err.Error())
 | 
				
			||||||
 | 
							return
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
						staticHandler := http.FileServer(http.FS(staticFS))
 | 
				
			||||||
 | 
						http.Handle("GET /static/", http.StripPrefix("/static/", staticHandler))
 | 
				
			||||||
 | 
						slog.Info("serving static files from embedded file system /static")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Pages
 | 
				
			||||||
 | 
						http.HandleFunc("GET /", getController.ShowHome)
 | 
				
			||||||
 | 
						http.HandleFunc("GET /login", getController.ShowLogin)
 | 
				
			||||||
 | 
						http.HandleFunc("GET /register", getController.ShowRegister)
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,26 +0,0 @@
 | 
				
			|||||||
package routes
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"GoWeb/app"
 | 
					 | 
				
			||||||
	"GoWeb/controllers"
 | 
					 | 
				
			||||||
	"log"
 | 
					 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// GetRoutes defines all project get routes
 | 
					 | 
				
			||||||
func GetRoutes(app *app.App) {
 | 
					 | 
				
			||||||
	// Get controller struct initialize
 | 
					 | 
				
			||||||
	getController := controllers.GetController{
 | 
					 | 
				
			||||||
		App: app,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Serve static files
 | 
					 | 
				
			||||||
	http.Handle("/file/", http.FileServer(http.Dir("./static")))
 | 
					 | 
				
			||||||
	log.Println("Serving static files from: ./static")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// Pages
 | 
					 | 
				
			||||||
	http.HandleFunc("/", getController.ShowHome)
 | 
					 | 
				
			||||||
	http.HandleFunc("/login", getController.ShowLogin)
 | 
					 | 
				
			||||||
	http.HandleFunc("/register", getController.ShowRegister)
 | 
					 | 
				
			||||||
	http.HandleFunc("/logout", getController.Logout)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
							
								
								
									
										21
									
								
								routes/post.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								routes/post.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,21 @@
 | 
				
			|||||||
 | 
					package routes
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					import (
 | 
				
			||||||
 | 
						"GoWeb/app"
 | 
				
			||||||
 | 
						"GoWeb/controllers"
 | 
				
			||||||
 | 
						"GoWeb/middleware"
 | 
				
			||||||
 | 
						"net/http"
 | 
				
			||||||
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					// Post defines all project post routes
 | 
				
			||||||
 | 
					func Post(app *app.App) {
 | 
				
			||||||
 | 
						// Post controller struct initialize
 | 
				
			||||||
 | 
						postController := controllers.Post{
 | 
				
			||||||
 | 
							App: app,
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// User authentication
 | 
				
			||||||
 | 
						http.HandleFunc("POST /register-handle", middleware.Csrf(postController.Register))
 | 
				
			||||||
 | 
						http.HandleFunc("POST /login-handle", middleware.Csrf(postController.Login))
 | 
				
			||||||
 | 
						http.HandleFunc("POST /logout", middleware.Csrf(postController.Logout))
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -1,19 +0,0 @@
 | 
				
			|||||||
package routes
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
import (
 | 
					 | 
				
			||||||
	"GoWeb/app"
 | 
					 | 
				
			||||||
	"GoWeb/controllers"
 | 
					 | 
				
			||||||
	"net/http"
 | 
					 | 
				
			||||||
)
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
// PostRoutes defines all project post routes
 | 
					 | 
				
			||||||
func PostRoutes(app *app.App) {
 | 
					 | 
				
			||||||
	// Post controller struct initialize
 | 
					 | 
				
			||||||
	postController := controllers.PostController{
 | 
					 | 
				
			||||||
		App: app,
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	// User authentication
 | 
					 | 
				
			||||||
	http.HandleFunc("/register-handle", postController.Register)
 | 
					 | 
				
			||||||
	http.HandleFunc("/login-handle", postController.Login)
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
@@ -3,25 +3,22 @@ package security
 | 
				
			|||||||
import (
 | 
					import (
 | 
				
			||||||
	"crypto/rand"
 | 
						"crypto/rand"
 | 
				
			||||||
	"encoding/hex"
 | 
						"encoding/hex"
 | 
				
			||||||
	"log"
 | 
						"log/slog"
 | 
				
			||||||
	"math"
 | 
						"math"
 | 
				
			||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// GenerateCsrfToken generates a csrf token and assigns it to a cookie for double submit cookie csrf protection
 | 
					// GenerateCsrfToken generates a csrf token and assigns it to a cookie for double submit cookie csrf protection
 | 
				
			||||||
func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
 | 
					func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
 | 
				
			||||||
	// Generate random 64 character string (alpha-numeric)
 | 
					 | 
				
			||||||
	buff := make([]byte, int(math.Ceil(float64(64)/2)))
 | 
						buff := make([]byte, int(math.Ceil(float64(64)/2)))
 | 
				
			||||||
	_, err := rand.Read(buff)
 | 
						_, err := rand.Read(buff)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error creating random buffer for csrf token value")
 | 
							slog.Error("error creating random buffer for csrf token value" + err.Error())
 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return "", err
 | 
							return "", err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	str := hex.EncodeToString(buff)
 | 
						str := hex.EncodeToString(buff)
 | 
				
			||||||
	token := str[:64]
 | 
						token := str[:64]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Create session cookie, containing token
 | 
					 | 
				
			||||||
	cookie := &http.Cookie{
 | 
						cookie := &http.Cookie{
 | 
				
			||||||
		Name:     "csrf_token",
 | 
							Name:     "csrf_token",
 | 
				
			||||||
		Value:    token,
 | 
							Value:    token,
 | 
				
			||||||
@@ -38,18 +35,14 @@ func GenerateCsrfToken(w http.ResponseWriter, _ *http.Request) (string, error) {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
// VerifyCsrfToken verifies the csrf token
 | 
					// VerifyCsrfToken verifies the csrf token
 | 
				
			||||||
func VerifyCsrfToken(r *http.Request) (bool, error) {
 | 
					func VerifyCsrfToken(r *http.Request) (bool, error) {
 | 
				
			||||||
	// Get csrf cookie
 | 
					 | 
				
			||||||
	cookie, err := r.Cookie("csrf_token")
 | 
						cookie, err := r.Cookie("csrf_token")
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println("Error getting csrf_token cookie")
 | 
							slog.Info("unable to get csrf_token cookie" + err.Error())
 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		return false, err
 | 
							return false, err
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Get csrf token from form
 | 
					 | 
				
			||||||
	token := r.FormValue("csrf_token")
 | 
						token := r.FormValue("csrf_token")
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	// Compare csrf cookie and csrf token
 | 
					 | 
				
			||||||
	if cookie.Value == token {
 | 
						if cookie.Value == token {
 | 
				
			||||||
		return true, nil
 | 
							return true, nil
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										75
									
								
								static/css/style.css
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										75
									
								
								static/css/style.css
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,75 @@
 | 
				
			|||||||
 | 
					body {
 | 
				
			||||||
 | 
					    font-family: Arial, sans-serif;
 | 
				
			||||||
 | 
					    background-color: lightblue;
 | 
				
			||||||
 | 
					    color: #333;
 | 
				
			||||||
 | 
					    margin: 0;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					.container {
 | 
				
			||||||
 | 
					    display: flex;
 | 
				
			||||||
 | 
					    justify-content: center;
 | 
				
			||||||
 | 
					    align-items: center;
 | 
				
			||||||
 | 
					    width: 80%;
 | 
				
			||||||
 | 
					    padding: 20px;
 | 
				
			||||||
 | 
					    margin: 0 auto;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					.footer-container {
 | 
				
			||||||
 | 
					    display: flex;
 | 
				
			||||||
 | 
					    justify-content: center;
 | 
				
			||||||
 | 
					    align-items: center;
 | 
				
			||||||
 | 
					    height: 80px;
 | 
				
			||||||
 | 
					    background-color: lightblue;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					footer {
 | 
				
			||||||
 | 
					    color: #0077be;
 | 
				
			||||||
 | 
					    font-size: 14px;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					form label {
 | 
				
			||||||
 | 
					    display: block;
 | 
				
			||||||
 | 
					    font-weight: bold;
 | 
				
			||||||
 | 
					    margin-bottom: 5px;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					form input[type="text"],
 | 
				
			||||||
 | 
					form input[type="password"] {
 | 
				
			||||||
 | 
					    padding: 10px;
 | 
				
			||||||
 | 
					    font-size: 16px;
 | 
				
			||||||
 | 
					    border-radius: 5px;
 | 
				
			||||||
 | 
					    border: none;
 | 
				
			||||||
 | 
					    margin-bottom: 10px;
 | 
				
			||||||
 | 
					    width: 100%;
 | 
				
			||||||
 | 
					    box-sizing: border-box;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					form input[type="submit"] {
 | 
				
			||||||
 | 
					    display: inline-block;
 | 
				
			||||||
 | 
					    padding: 10px 20px;
 | 
				
			||||||
 | 
					    background-color: #0077be;
 | 
				
			||||||
 | 
					    color: #fff;
 | 
				
			||||||
 | 
					    border-radius: 5px;
 | 
				
			||||||
 | 
					    text-decoration: none;
 | 
				
			||||||
 | 
					    border: none;
 | 
				
			||||||
 | 
					    cursor: pointer;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					form input[type="submit"]:hover {
 | 
				
			||||||
 | 
					    background-color: #005fa3;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					h1, h2, h3, h4, h5, h6 {
 | 
				
			||||||
 | 
					    font-weight: bold;
 | 
				
			||||||
 | 
					    color: #333;
 | 
				
			||||||
 | 
					    text-align: center;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					a {
 | 
				
			||||||
 | 
					    color: #0077be;
 | 
				
			||||||
 | 
					    text-decoration: none;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					a:hover {
 | 
				
			||||||
 | 
					    text-decoration: underline;
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
@@ -3,11 +3,29 @@
 | 
				
			|||||||
<head>
 | 
					<head>
 | 
				
			||||||
    <meta charset="UTF-8">
 | 
					    <meta charset="UTF-8">
 | 
				
			||||||
    <title>SiteName - {{ template "pageTitle" }}</title>
 | 
					    <title>SiteName - {{ template "pageTitle" }}</title>
 | 
				
			||||||
 | 
					    <link href="/static/css/style.css" rel="stylesheet">
 | 
				
			||||||
</head>
 | 
					</head>
 | 
				
			||||||
<body>
 | 
					<body>
 | 
				
			||||||
 | 
					<div class="navbar">
 | 
				
			||||||
 | 
					    {{ if .IsAuthenticated }}
 | 
				
			||||||
 | 
					    <form action="/logout" method="post">
 | 
				
			||||||
 | 
					        <input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
 | 
				
			||||||
 | 
					        <input type="submit" value="Logout">
 | 
				
			||||||
 | 
					    </form>
 | 
				
			||||||
 | 
					    {{ else }}
 | 
				
			||||||
 | 
					    <form action="/login" method="get">
 | 
				
			||||||
 | 
					        <input type="submit" value="Login">
 | 
				
			||||||
 | 
					    </form>
 | 
				
			||||||
 | 
					    <form action="/register" method="get">
 | 
				
			||||||
 | 
					        <input type="submit" value="Register">
 | 
				
			||||||
 | 
					    </form>
 | 
				
			||||||
 | 
					    {{ end }}
 | 
				
			||||||
 | 
					</div>
 | 
				
			||||||
{{ template "content" . }}
 | 
					{{ template "content" . }}
 | 
				
			||||||
 | 
					<div class="footer-container">
 | 
				
			||||||
 | 
					    <footer>
 | 
				
			||||||
 | 
					        <p>SiteName - Powered by GoWeb!</p>
 | 
				
			||||||
 | 
					    </footer>
 | 
				
			||||||
 | 
					</div>
 | 
				
			||||||
</body>
 | 
					</body>
 | 
				
			||||||
<footer>
 | 
					 | 
				
			||||||
    <p>SiteName - Powered by Go!</p>
 | 
					 | 
				
			||||||
</footer>
 | 
					 | 
				
			||||||
</html>
 | 
					</html>
 | 
				
			||||||
@@ -1,13 +1,18 @@
 | 
				
			|||||||
{{ define "pageTitle" }}Login{{ end }}
 | 
					{{ define "pageTitle" }}Login{{ end }}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
{{ define "content" }}
 | 
					{{ define "content" }}
 | 
				
			||||||
<form action="/login-handle" method="post">
 | 
					<h1>Login</h1>
 | 
				
			||||||
    <input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
 | 
					<div class="container">
 | 
				
			||||||
 | 
					    <form action="/login-handle" method="post">
 | 
				
			||||||
 | 
					        <input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    <label for="username">Username:</label><br>
 | 
					        <label for="username">Username:</label><br>
 | 
				
			||||||
    <input id="username" name="username" type="text" value="John"><br><br>
 | 
					        <input id="username" name="username" placeholder="John" type="text"><br><br>
 | 
				
			||||||
    <label for="password">Password:</label><br>
 | 
					        <label for="password">Password:</label><br>
 | 
				
			||||||
    <input id="password" name="password" type="password"><br><br>
 | 
					        <input id="password" name="password" type="password"><br><br>
 | 
				
			||||||
    <input type="submit" value="Submit">
 | 
					        <label for="remember">Remember Me:</label>
 | 
				
			||||||
</form>
 | 
					        <input id="remember" name="remember" type="checkbox"><br><br>
 | 
				
			||||||
 | 
					        <input type="submit" value="Submit">
 | 
				
			||||||
 | 
					    </form>
 | 
				
			||||||
 | 
					</div>
 | 
				
			||||||
{{ end }}
 | 
					{{ end }}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -1,13 +1,16 @@
 | 
				
			|||||||
{{ define "pageTitle" }}Register{{ end }}
 | 
					{{ define "pageTitle" }}Register{{ end }}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
{{ define "content" }}
 | 
					{{ define "content" }}
 | 
				
			||||||
<form action="/register-handle" method="post">
 | 
					<h1>Register</h1>
 | 
				
			||||||
    <input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
 | 
					<div class="container">
 | 
				
			||||||
 | 
					    <form action="/register-handle" method="post">
 | 
				
			||||||
 | 
					        <input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    <label for="username">Username:</label><br>
 | 
					        <label for="username">Username:</label><br>
 | 
				
			||||||
    <input id="username" name="username" type="text" value="John"><br><br>
 | 
					        <input id="username" name="username" placeholder="John" type="text"><br><br>
 | 
				
			||||||
    <label for="password">Password:</label><br>
 | 
					        <label for="password">Password:</label><br>
 | 
				
			||||||
    <input id="password" name="password" type="password"><br><br>
 | 
					        <input id="password" name="password" type="password"><br><br>
 | 
				
			||||||
    <input type="submit" value="Submit">
 | 
					        <input type="submit" value="Submit">
 | 
				
			||||||
</form>
 | 
					    </form>
 | 
				
			||||||
 | 
					</div>
 | 
				
			||||||
{{ end }}
 | 
					{{ end }}
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -2,46 +2,83 @@ package templating
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
import (
 | 
					import (
 | 
				
			||||||
	"GoWeb/app"
 | 
						"GoWeb/app"
 | 
				
			||||||
 | 
						"fmt"
 | 
				
			||||||
	"html/template"
 | 
						"html/template"
 | 
				
			||||||
	"log"
 | 
						"io/fs"
 | 
				
			||||||
 | 
						"log/slog"
 | 
				
			||||||
	"net/http"
 | 
						"net/http"
 | 
				
			||||||
)
 | 
					)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// RenderTemplate renders and serves a template from the embedded filesystem optionally with given data
 | 
					var templates = make(map[string]*template.Template) // This is only used here, does not need to be in app.App
 | 
				
			||||||
func RenderTemplate(app *app.App, w http.ResponseWriter, contentPath string, data any) {
 | 
					 | 
				
			||||||
	templatePath := app.Config.Template.BaseName
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
	templateContent, err := app.Res.ReadFile(templatePath)
 | 
					func BuildPages(app *app.App) error {
 | 
				
			||||||
 | 
						basePath := app.Config.Template.BaseName
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						baseContent, err := app.Res.ReadFile(basePath)
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println(err)
 | 
							return fmt.Errorf("error reading base file: %w", err)
 | 
				
			||||||
		http.Error(w, err.Error(), 500)
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						base, err := template.New(basePath).Parse(string(baseContent)) // Sets filepath as name and parses content
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return fmt.Errorf("error parsing base file: %w", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						readFilesRecursively := func(fsys fs.FS, root string) ([]string, error) {
 | 
				
			||||||
 | 
							var files []string
 | 
				
			||||||
 | 
							err := fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {
 | 
				
			||||||
 | 
								if err != nil {
 | 
				
			||||||
 | 
									return fmt.Errorf("error walking the path %q: %w", path, err)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								if !d.IsDir() {
 | 
				
			||||||
 | 
									files = append(files, path)
 | 
				
			||||||
 | 
								}
 | 
				
			||||||
 | 
								return nil
 | 
				
			||||||
 | 
							})
 | 
				
			||||||
 | 
							return files, err
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						// Get all file paths in the directory tree
 | 
				
			||||||
 | 
						filePaths, err := readFilesRecursively(app.Res, app.Config.Template.ContentPath)
 | 
				
			||||||
 | 
						if err != nil {
 | 
				
			||||||
 | 
							return fmt.Errorf("error reading files recursively: %w", err)
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						for _, contentPath := range filePaths { // Create a new template base + content for each page
 | 
				
			||||||
 | 
							content, err := app.Res.ReadFile(contentPath)
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								return fmt.Errorf("error reading content file %s: %w", contentPath, err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							t, err := base.Clone()
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								return fmt.Errorf("error cloning base template: %w", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							_, err = t.Parse(string(content))
 | 
				
			||||||
 | 
							if err != nil {
 | 
				
			||||||
 | 
								return fmt.Errorf("error parsing content: %w", err)
 | 
				
			||||||
 | 
							}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
							templates[contentPath] = t
 | 
				
			||||||
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
						return nil
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					func RenderTemplate(w http.ResponseWriter, contentPath string, data any) {
 | 
				
			||||||
 | 
						t, ok := templates[contentPath]
 | 
				
			||||||
 | 
						if !ok {
 | 
				
			||||||
 | 
							err := fmt.Errorf("template not found for path: %s", contentPath)
 | 
				
			||||||
 | 
							slog.Error(err.Error())
 | 
				
			||||||
 | 
							http.Error(w, "Template not found", 404)
 | 
				
			||||||
		return
 | 
							return
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
	t, err := template.New(templatePath).Parse(string(templateContent))
 | 
						err := t.Execute(w, data) // Execute prebuilt template with dynamic data
 | 
				
			||||||
	if err != nil {
 | 
						if err != nil {
 | 
				
			||||||
		log.Println(err)
 | 
							err = fmt.Errorf("error executing template: %w", err)
 | 
				
			||||||
		http.Error(w, err.Error(), 500)
 | 
							slog.Error(err.Error())
 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	content, err := app.Res.ReadFile(contentPath)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		http.Error(w, err.Error(), 500)
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	t, err = t.Parse(string(content))
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		http.Error(w, err.Error(), 500)
 | 
					 | 
				
			||||||
		return
 | 
					 | 
				
			||||||
	}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
	err = t.Execute(w, data)
 | 
					 | 
				
			||||||
	if err != nil {
 | 
					 | 
				
			||||||
		log.Println(err)
 | 
					 | 
				
			||||||
		http.Error(w, err.Error(), 500)
 | 
							http.Error(w, err.Error(), 500)
 | 
				
			||||||
		return
 | 
							return
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user