Rename app->internal
This commit is contained in:
37
internal/models/migrations.go
Normal file
37
internal/models/migrations.go
Normal file
@ -0,0 +1,37 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"GoWeb/database"
|
||||
"GoWeb/internal"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RunAllMigrations defines the structs that should be represented in the database
|
||||
func RunAllMigrations(app *app.Deps) error {
|
||||
// Declare new dummy user for reflection
|
||||
user := User{
|
||||
Id: 1, // Id is handled automatically, but it is added here to show it will be skipped during column creation
|
||||
Username: "migrate",
|
||||
Password: "migrate",
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
err := database.Migrate(app, user)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
session := Session{
|
||||
Id: 1,
|
||||
UserId: 1,
|
||||
AuthToken: "migrate",
|
||||
RememberMe: false,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
err = database.Migrate(app, session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
153
internal/models/session.go
Normal file
153
internal/models/session.go
Normal file
@ -0,0 +1,153 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"GoWeb/internal"
|
||||
"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.Deps, 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.Deps, 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.Deps) 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.Deps, 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.Deps, 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.Deps, 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.Deps) {
|
||||
// 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")
|
||||
}
|
130
internal/models/user.go
Normal file
130
internal/models/user.go
Normal file
@ -0,0 +1,130 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"GoWeb/internal"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id int64
|
||||
Username string
|
||||
Password string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
const userColumnsNoId = "\"Username\", \"Password\", \"CreatedAt\", \"UpdatedAt\""
|
||||
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.Deps, r *http.Request) (User, error) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
session, err := SessionByAuthToken(app, cookie.Value)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
return UserById(app, session.UserId)
|
||||
}
|
||||
|
||||
// UserById finds a User table row in the database by id and returns a struct representing this row
|
||||
func UserById(app *app.Deps, id int64) (User, error) {
|
||||
user := User{}
|
||||
|
||||
err := app.Db.QueryRow(selectUserById, id).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UserByUsername finds a User table row in the database by username and returns a struct representing this row
|
||||
func UserByUsername(app *app.Deps, username string) (User, error) {
|
||||
user := User{}
|
||||
|
||||
err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// CreateUser creates a User table row in the database
|
||||
func CreateUser(app *app.Deps, 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
|
||||
}
|
||||
|
||||
var lastInsertId int64
|
||||
|
||||
err = app.Db.QueryRow(insertUser, username, string(hash), createdAt, updatedAt).Scan(&lastInsertId)
|
||||
if err != nil {
|
||||
slog.Error("error creating user row: " + err.Error())
|
||||
return User{}, err
|
||||
}
|
||||
|
||||
return UserById(app, lastInsertId)
|
||||
}
|
||||
|
||||
// AuthenticateUser validates the password for the specified user
|
||||
func AuthenticateUser(app *app.Deps, w http.ResponseWriter, username string, password string, remember bool) (Session, error) {
|
||||
var user User
|
||||
|
||||
err := app.Db.QueryRow(selectUserByUsername, username).Scan(&user.Id, &user.Username, &user.Password, &user.CreatedAt, &user.UpdatedAt)
|
||||
if err != nil {
|
||||
slog.Info("user not found: " + username)
|
||||
return Session{}, err
|
||||
}
|
||||
|
||||
// Get sha256 hash of password then check bcrypt
|
||||
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
|
||||
slog.Info("incorrect password:" + username)
|
||||
return Session{}, err
|
||||
} else {
|
||||
return CreateSession(app, w, user.Id, remember)
|
||||
}
|
||||
}
|
||||
|
||||
// LogoutUser deletes the session cookie and AuthToken from the database
|
||||
func LogoutUser(app *app.Deps, w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = DeleteSessionByAuthToken(app, w, cookie.Value)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user