Compare commits
28 Commits
Author | SHA1 | Date | |
---|---|---|---|
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 |
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
* text=auto eol=lf
|
@ -12,9 +12,12 @@ fine with getting your hands dirty, but I plan on having it ready to go for more
|
|||||||
- Routing/controllers
|
- Routing/controllers
|
||||||
- Templating
|
- Templating
|
||||||
- Simple database migration system
|
- Simple database migration system
|
||||||
|
- Built in REST client
|
||||||
- CSRF protection
|
- CSRF protection
|
||||||
|
- Middleware
|
||||||
- Minimal user login/registration + sessions
|
- Minimal user login/registration + sessions
|
||||||
- Config file handling
|
- Config file handling
|
||||||
|
- Scheduled tasks
|
||||||
- Entire website compiles into a single binary (~10mb) (excluding env.json)
|
- Entire website compiles into a single binary (~10mb) (excluding env.json)
|
||||||
- Minimal dependencies (just standard library, postgres driver, and experimental package for bcrypt)
|
- Minimal dependencies (just standard library, postgres driver, and experimental package for bcrypt)
|
||||||
|
|
||||||
|
@ -11,4 +11,5 @@ 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
|
||||||
}
|
}
|
||||||
|
75
app/schedule.go
Normal file
75
app/schedule.go
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
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 {
|
||||||
|
Interval time.Duration
|
||||||
|
Funcs []func(app *App)
|
||||||
|
}
|
||||||
|
|
||||||
|
func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||||
|
// Run every time the server starts
|
||||||
|
for _, f := range app.ScheduledTasks.EveryReboot {
|
||||||
|
f(app)
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks := []Task{
|
||||||
|
{Interval: time.Second, Funcs: app.ScheduledTasks.EverySecond},
|
||||||
|
{Interval: time.Minute, Funcs: app.ScheduledTasks.EveryMinute},
|
||||||
|
{Interval: time.Hour, Funcs: app.ScheduledTasks.EveryHour},
|
||||||
|
{Interval: 24 * time.Hour, Funcs: app.ScheduledTasks.EveryDay},
|
||||||
|
{Interval: 7 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryWeek},
|
||||||
|
{Interval: 30 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryMonth},
|
||||||
|
{Interval: 365 * 24 * time.Hour, Funcs: app.ScheduledTasks.EveryYear},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set up task runners
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all goroutines to finish
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
// Close channels
|
||||||
|
for _, runner := range runners {
|
||||||
|
close(runner)
|
||||||
|
}
|
||||||
|
}
|
@ -3,7 +3,6 @@ package controllers
|
|||||||
import (
|
import (
|
||||||
"GoWeb/app"
|
"GoWeb/app"
|
||||||
"GoWeb/models"
|
"GoWeb/models"
|
||||||
"GoWeb/security"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
@ -15,22 +14,16 @@ type PostController struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (postController *PostController) Login(w http.ResponseWriter, r *http.Request) {
|
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")
|
username := r.FormValue("username")
|
||||||
password := r.FormValue("password")
|
password := r.FormValue("password")
|
||||||
|
remember := r.FormValue("remember") == "on"
|
||||||
|
|
||||||
if username == "" || password == "" {
|
if username == "" || password == "" {
|
||||||
log.Println("Tried to login user with empty username or password")
|
log.Println("Tried to login user with empty username or password")
|
||||||
http.Redirect(w, r, "/login", http.StatusFound)
|
http.Redirect(w, r, "/login", http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = models.AuthenticateUser(postController.App, w, username, password)
|
_, err := models.AuthenticateUser(postController.App, w, username, password, remember)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Error authenticating user")
|
log.Println("Error authenticating user")
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
@ -42,13 +35,6 @@ func (postController *PostController) Login(w http.ResponseWriter, r *http.Reque
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (postController *PostController) Register(w http.ResponseWriter, r *http.Request) {
|
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")
|
username := r.FormValue("username")
|
||||||
password := r.FormValue("password")
|
password := r.FormValue("password")
|
||||||
createdAt := time.Now()
|
createdAt := time.Now()
|
||||||
@ -59,7 +45,7 @@ func (postController *PostController) Register(w http.ResponseWriter, r *http.Re
|
|||||||
http.Redirect(w, r, "/register", http.StatusFound)
|
http.Redirect(w, r, "/register", http.StatusFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = models.CreateUser(postController.App, username, password, createdAt, updatedAt)
|
_, err := models.CreateUser(postController.App, username, password, createdAt, updatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Error creating user")
|
log.Println("Error creating user")
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
|
4
go.mod
4
go.mod
@ -3,6 +3,6 @@ module GoWeb
|
|||||||
go 1.20
|
go 1.20
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/lib/pq v1.10.7
|
github.com/lib/pq v1.10.9
|
||||||
golang.org/x/crypto v0.7.0
|
golang.org/x/crypto v0.11.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.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
|
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
|
||||||
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
|
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=
|
||||||
|
9
main.go
9
main.go
@ -53,6 +53,12 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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.GetRoutes(&appLoaded)
|
||||||
routes.PostRoutes(&appLoaded)
|
routes.PostRoutes(&appLoaded)
|
||||||
@ -70,6 +76,9 @@ func main() {
|
|||||||
// Wait for interrupt signal and shut down the server
|
// Wait for interrupt signal and shut down the server
|
||||||
interrupt := make(chan os.Signal, 1)
|
interrupt := make(chan os.Signal, 1)
|
||||||
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
|
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
|
||||||
|
stop := make(chan struct{})
|
||||||
|
go app.RunScheduledTasks(&appLoaded, 100, stop)
|
||||||
|
|
||||||
<-interrupt
|
<-interrupt
|
||||||
log.Println("Interrupt signal received. Shutting down server...")
|
log.Println("Interrupt signal received. Shutting down server...")
|
||||||
|
|
||||||
|
22
middleware/csrf.go
Normal file
22
middleware/csrf.go
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"GoWeb/security"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Csrf validates the CSRF token and returns the handler function if it succeded
|
||||||
|
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) {
|
||||||
|
// Verify csrf token
|
||||||
|
_, err := security.VerifyCsrfToken(r)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("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
|
||||||
|
}
|
@ -25,6 +25,7 @@ func RunAllMigrations(app *app.App) error {
|
|||||||
Id: 1,
|
Id: 1,
|
||||||
UserId: 1,
|
UserId: 1,
|
||||||
AuthToken: "migrate",
|
AuthToken: "migrate",
|
||||||
|
RememberMe: false,
|
||||||
CreatedAt: time.Now(),
|
CreatedAt: time.Now(),
|
||||||
}
|
}
|
||||||
err = database.Migrate(app, session)
|
err = database.Migrate(app, session)
|
||||||
|
@ -13,25 +13,29 @@ type Session struct {
|
|||||||
Id int64
|
Id int64
|
||||||
UserId int64
|
UserId int64
|
||||||
AuthToken string
|
AuthToken string
|
||||||
|
RememberMe bool
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionColumnsNoId = "\"UserId\", \"AuthToken\", \"CreatedAt\""
|
const sessionColumnsNoId = "\"UserId\", \"AuthToken\",\"RememberMe\", \"CreatedAt\""
|
||||||
const sessionColumns = "\"Id\", " + sessionColumnsNoId
|
const sessionColumns = "\"Id\", " + sessionColumnsNoId
|
||||||
const sessionTable = "public.\"Session\""
|
const sessionTable = "public.\"Session\""
|
||||||
|
|
||||||
const (
|
const (
|
||||||
selectSessionByAuthToken = "SELECT " + sessionColumns + " FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
selectSessionByAuthToken = "SELECT " + sessionColumns + " FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
||||||
selectAuthTokenIfExists = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)"
|
selectAuthTokenIfExists = "SELECT EXISTS(SELECT 1 FROM " + sessionTable + " WHERE \"AuthToken\" = $1)"
|
||||||
insertSession = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3) RETURNING \"Id\""
|
insertSession = "INSERT INTO " + sessionTable + " (" + sessionColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
|
||||||
deleteSessionByAuthToken = "DELETE FROM " + sessionTable + " WHERE \"AuthToken\" = $1"
|
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
|
// CreateSession creates a new session for a user
|
||||||
func CreateSession(app *app.App, w http.ResponseWriter, userId int64) (Session, error) {
|
func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember bool) (Session, error) {
|
||||||
session := Session{}
|
session := Session{}
|
||||||
session.UserId = userId
|
session.UserId = userId
|
||||||
session.AuthToken = generateAuthToken(app)
|
session.AuthToken = generateAuthToken(app)
|
||||||
|
session.RememberMe = remember
|
||||||
session.CreatedAt = time.Now()
|
session.CreatedAt = time.Now()
|
||||||
|
|
||||||
// If the AuthToken column for any user matches the token, set existingAuthToken to true
|
// If the AuthToken column for any user matches the token, set existingAuthToken to true
|
||||||
@ -46,11 +50,11 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64) (Session,
|
|||||||
// If duplicate token found, recursively call function until unique token is generated
|
// If duplicate token found, recursively call function until unique token is generated
|
||||||
if existingAuthToken == true {
|
if existingAuthToken == true {
|
||||||
log.Println("Duplicate token found in sessions table, generating new token...")
|
log.Println("Duplicate token found in sessions table, generating new token...")
|
||||||
return CreateSession(app, w, userId)
|
return CreateSession(app, w, userId, remember)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Insert session into database
|
// Insert session into database
|
||||||
err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.CreatedAt).Scan(&session.Id)
|
err = app.Db.QueryRow(insertSession, session.UserId, session.AuthToken, session.RememberMe, session.CreatedAt).Scan(&session.Id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Error inserting session into database")
|
log.Println("Error inserting session into database")
|
||||||
return Session{}, err
|
return Session{}, err
|
||||||
@ -60,6 +64,18 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64) (Session,
|
|||||||
return session, nil
|
return session, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetSessionByAuthToken(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 {
|
||||||
|
log.Println("Error getting session by auth token")
|
||||||
|
return Session{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return session, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Generates a random 64-byte string
|
// Generates a random 64-byte string
|
||||||
func generateAuthToken(app *app.App) string {
|
func generateAuthToken(app *app.App) string {
|
||||||
// Generate random bytes
|
// Generate random bytes
|
||||||
@ -75,14 +91,26 @@ func generateAuthToken(app *app.App) string {
|
|||||||
|
|
||||||
// createSessionCookie creates a new session cookie
|
// createSessionCookie creates a new session cookie
|
||||||
func createSessionCookie(app *app.App, w http.ResponseWriter, session Session) {
|
func createSessionCookie(app *app.App, w http.ResponseWriter, session Session) {
|
||||||
cookie := &http.Cookie{
|
cookie := &http.Cookie{}
|
||||||
|
if session.RememberMe {
|
||||||
|
cookie = &http.Cookie{
|
||||||
Name: "session",
|
Name: "session",
|
||||||
Value: session.AuthToken,
|
Value: session.AuthToken,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
MaxAge: 86400,
|
MaxAge: 2592000 * 1000, // 30 days in ms
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Secure: 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)
|
http.SetCookie(w, cookie)
|
||||||
}
|
}
|
||||||
@ -112,3 +140,22 @@ func DeleteSessionByAuthToken(app *app.App, w http.ResponseWriter, authToken str
|
|||||||
|
|
||||||
return nil
|
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 {
|
||||||
|
log.Println("Error deleting 30 day expired sessions from database")
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete sessions older than 6 hours
|
||||||
|
_, err = app.Db.Exec(deleteSessionsOlderThan6Hours)
|
||||||
|
if err != nil {
|
||||||
|
log.Println("Error deleting 6 hour expired sessions from database")
|
||||||
|
log.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Println("Deleted expired sessions from database")
|
||||||
|
}
|
||||||
|
@ -23,7 +23,6 @@ const userColumns = "\"Id\", " + userColumnsNoId
|
|||||||
const userTable = "public.\"User\""
|
const userTable = "public.\"User\""
|
||||||
|
|
||||||
const (
|
const (
|
||||||
selectSessionIdByAuthToken = "SELECT \"Id\" FROM public.\"Session\" WHERE \"AuthToken\" = $1"
|
|
||||||
selectUserById = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Id\" = $1"
|
selectUserById = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Id\" = $1"
|
||||||
selectUserByUsername = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Username\" = $1"
|
selectUserByUsername = "SELECT " + userColumns + " FROM " + userTable + " WHERE \"Username\" = $1"
|
||||||
insertUser = "INSERT INTO " + userTable + " (" + userColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
|
insertUser = "INSERT INTO " + userTable + " (" + userColumnsNoId + ") VALUES ($1, $2, $3, $4) RETURNING \"Id\""
|
||||||
@ -37,16 +36,13 @@ func GetCurrentUser(app *app.App, r *http.Request) (User, error) {
|
|||||||
return User{}, err
|
return User{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var userId int64
|
session, err := GetSessionByAuthToken(app, cookie.Value)
|
||||||
|
|
||||||
// Query row by AuthToken
|
|
||||||
err = app.Db.QueryRow(selectSessionIdByAuthToken, cookie.Value).Scan(&userId)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Error querying session row with session: " + cookie.Value)
|
log.Println("Error getting session by auth token")
|
||||||
return User{}, err
|
return User{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return GetUserById(app, userId)
|
return GetUserById(app, session.UserId)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetUserById finds a User table row in the database by id and returns a struct representing this row
|
// GetUserById finds a User table row in the database by id and returns a struct representing this row
|
||||||
@ -98,7 +94,7 @@ func CreateUser(app *app.App, username string, password string, createdAt time.T
|
|||||||
}
|
}
|
||||||
|
|
||||||
// AuthenticateUser validates the password for the specified user
|
// AuthenticateUser validates the password for the specified user
|
||||||
func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string) (Session, error) {
|
func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, password string, remember bool) (Session, error) {
|
||||||
var user User
|
var user User
|
||||||
|
|
||||||
// Query row by username
|
// Query row by username
|
||||||
@ -114,7 +110,7 @@ func AuthenticateUser(app *app.App, w http.ResponseWriter, username string, pass
|
|||||||
log.Println("Authentication error (incorrect password) for user:" + username)
|
log.Println("Authentication error (incorrect password) for user:" + username)
|
||||||
return Session{}, err
|
return Session{}, err
|
||||||
} else {
|
} else {
|
||||||
return CreateSession(app, w, user.Id)
|
return CreateSession(app, w, user.Id, remember)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -133,14 +129,4 @@ func LogoutUser(app *app.App, w http.ResponseWriter, r *http.Request) {
|
|||||||
log.Println("Error deleting session by AuthToken")
|
log.Println("Error deleting session by AuthToken")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete cookie
|
|
||||||
cookie = &http.Cookie{
|
|
||||||
Name: "session",
|
|
||||||
Value: "",
|
|
||||||
Path: "/",
|
|
||||||
MaxAge: -1,
|
|
||||||
}
|
|
||||||
|
|
||||||
http.SetCookie(w, cookie)
|
|
||||||
}
|
}
|
||||||
|
57
restclient/client.go
Normal file
57
restclient/client.go
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
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 {
|
||||||
|
writer.WriteField(key, value)
|
||||||
|
}
|
||||||
|
writer.Close()
|
||||||
|
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
|
||||||
|
}
|
@ -3,6 +3,7 @@ package routes
|
|||||||
import (
|
import (
|
||||||
"GoWeb/app"
|
"GoWeb/app"
|
||||||
"GoWeb/controllers"
|
"GoWeb/controllers"
|
||||||
|
"GoWeb/middleware"
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -14,6 +15,6 @@ func PostRoutes(app *app.App) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// User authentication
|
// User authentication
|
||||||
http.HandleFunc("/register-handle", postController.Register)
|
http.HandleFunc("/register-handle", middleware.Csrf(postController.Register))
|
||||||
http.HandleFunc("/login-handle", postController.Login)
|
http.HandleFunc("/login-handle", middleware.Csrf(postController.Login))
|
||||||
}
|
}
|
||||||
|
@ -10,6 +10,8 @@
|
|||||||
<input id="username" name="username" type="text" placeholder="John"><br><br>
|
<input id="username" name="username" type="text" placeholder="John"><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>
|
||||||
|
<label for="remember">Remember Me:</label>
|
||||||
|
<input id="remember" type="checkbox" name="remember"><br><br>
|
||||||
<input type="submit" value="Submit">
|
<input type="submit" value="Submit">
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
Reference in New Issue
Block a user