10 Commits

Author SHA1 Message Date
Maximilian
b475da66da Fix nil error for GET requests 2023-07-26 13:09:01 -05:00
Maximilian
d0085ab2c3 Update crypto dependency 2023-07-25 15:36:25 -05:00
Maximilian
58514f4c5f Update client to handle GET (no body) requests, multipart requests, and JSON requests 2023-07-25 15:34:11 -05:00
Maximilian
2a32a1b3ce Add restclient package, and a simple function to send HTTP requests 2023-07-21 16:35:18 -05:00
Maximilian
6da7d408f9 Add .gitattributes to force LF line endings 2023-05-05 12:19:17 -05:00
max
e993bcf317 Update dependency versions 2023-05-04 09:00:35 -05:00
Maximilian
9b231a73d6 Update README.md 2023-04-07 21:32:39 -05:00
Maximilian
34acd0fa8d Remove old session query 2023-04-07 21:27:14 -05:00
Maximilian
71d3bd77d0 Add ability to get session given an AuthToken, fix GetCurrentUser() 2023-04-07 21:23:46 -05:00
Maximilian
1451abcca4 Formatting 2023-04-06 12:01:29 -05:00
8 changed files with 84 additions and 16 deletions

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto eol=lf

View File

@@ -15,6 +15,7 @@ fine with getting your hands dirty, but I plan on having it ready to go for more
- CSRF protection
- 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 experimental package for bcrypt)

4
go.mod
View File

@@ -3,6 +3,6 @@ module GoWeb
go 1.20
require (
github.com/lib/pq v1.10.7
golang.org/x/crypto v0.7.0
github.com/lib/pq v1.10.9
golang.org/x/crypto v0.11.0
)

8
go.sum
View File

@@ -1,4 +1,4 @@
github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw=
github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA=
golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio=

View File

@@ -78,6 +78,7 @@ func main() {
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
stop := make(chan struct{})
go app.RunScheduledTasks(&appLoaded, 100, stop)
<-interrupt
log.Println("Interrupt signal received. Shutting down server...")

View File

@@ -64,6 +64,18 @@ func CreateSession(app *app.App, w http.ResponseWriter, userId int64, remember b
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
func generateAuthToken(app *app.App) string {
// Generate random bytes

View File

@@ -23,10 +23,9 @@ const userColumns = "\"Id\", " + userColumnsNoId
const userTable = "public.\"User\""
const (
selectSessionIdByAuthToken = "SELECT \"Id\" FROM public.\"Session\" WHERE \"AuthToken\" = $1"
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\""
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\""
)
// GetCurrentUser finds the currently logged-in user by session cookie
@@ -37,16 +36,13 @@ func GetCurrentUser(app *app.App, r *http.Request) (User, error) {
return User{}, err
}
var userId int64
// Query row by AuthToken
err = app.Db.QueryRow(selectSessionIdByAuthToken, cookie.Value).Scan(&userId)
session, err := GetSessionByAuthToken(app, cookie.Value)
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 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

57
restclient/client.go Normal file
View 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
}