Begin refactoring structure
This commit is contained in:
65
app/controllers/get.go
Normal file
65
app/controllers/get.go
Normal file
@ -0,0 +1,65 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/app/models"
|
||||
"GoWeb/security"
|
||||
"GoWeb/templating"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Get is a wrapper struct for the App struct
|
||||
type Get struct {
|
||||
App *app.Deps
|
||||
}
|
||||
|
||||
func (g *Get) ShowHome(w http.ResponseWriter, _ *http.Request) {
|
||||
type dataStruct struct {
|
||||
Test string
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
Test: "Hello World!",
|
||||
}
|
||||
|
||||
templating.RenderTemplate(w, "templates/pages/home.html", data)
|
||||
}
|
||||
|
||||
func (g *Get) ShowRegister(w http.ResponseWriter, r *http.Request) {
|
||||
type dataStruct struct {
|
||||
CsrfToken string
|
||||
}
|
||||
|
||||
CsrfToken, err := security.GenerateCsrfToken(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
CsrfToken: CsrfToken,
|
||||
}
|
||||
|
||||
templating.RenderTemplate(w, "templates/pages/register.html", data)
|
||||
}
|
||||
|
||||
func (g *Get) ShowLogin(w http.ResponseWriter, r *http.Request) {
|
||||
type dataStruct struct {
|
||||
CsrfToken string
|
||||
}
|
||||
|
||||
CsrfToken, err := security.GenerateCsrfToken(w, r)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := dataStruct{
|
||||
CsrfToken: CsrfToken,
|
||||
}
|
||||
|
||||
templating.RenderTemplate(w, "templates/pages/login.html", data)
|
||||
}
|
||||
|
||||
func (g *Get) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
models.LogoutUser(g.App, w, r)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
52
app/controllers/post.go
Normal file
52
app/controllers/post.go
Normal file
@ -0,0 +1,52 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/app/models"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Post is a wrapper struct for the App struct
|
||||
type Post struct {
|
||||
App *app.Deps
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
75
app/frontend/static/css/style.css
Normal file
75
app/frontend/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;
|
||||
}
|
16
app/frontend/templates/base.html
Normal file
16
app/frontend/templates/base.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>SiteName - {{ template "pageTitle" }}</title>
|
||||
<link href="/app/frontend/staticyle.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
{{ template "content" . }}
|
||||
<div class="footer-container">
|
||||
<footer>
|
||||
<p>SiteName - Powered by GoWeb!</p>
|
||||
</footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
5
app/frontend/templates/pages/home.html
Normal file
5
app/frontend/templates/pages/home.html
Normal file
@ -0,0 +1,5 @@
|
||||
{{ define "pageTitle" }}Home{{ end }}
|
||||
|
||||
{{ define "content" }}
|
||||
{{ .Test }}
|
||||
{{ end }}
|
18
app/frontend/templates/pages/login.html
Normal file
18
app/frontend/templates/pages/login.html
Normal file
@ -0,0 +1,18 @@
|
||||
{{ define "pageTitle" }}Login{{ end }}
|
||||
|
||||
{{ define "content" }}
|
||||
<h1>Login</h1>
|
||||
<div class="container">
|
||||
<form action="/login-handle" method="post">
|
||||
<input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
|
||||
|
||||
<label for="username">Username:</label><br>
|
||||
<input id="username" name="username" placeholder="John" type="text"><br><br>
|
||||
<label for="password">Password:</label><br>
|
||||
<input id="password" name="password" type="password"><br><br>
|
||||
<label for="remember">Remember Me:</label>
|
||||
<input id="remember" name="remember" type="checkbox"><br><br>
|
||||
<input type="submit" value="Submit">
|
||||
</form>
|
||||
</div>
|
||||
{{ end }}
|
16
app/frontend/templates/pages/register.html
Normal file
16
app/frontend/templates/pages/register.html
Normal file
@ -0,0 +1,16 @@
|
||||
{{ define "pageTitle" }}Register{{ end }}
|
||||
|
||||
{{ define "content" }}
|
||||
<h1>Register</h1>
|
||||
<div class="container">
|
||||
<form action="/register-handle" method="post">
|
||||
<input name="csrf_token" type="hidden" value="{{ .CsrfToken }}">
|
||||
|
||||
<label for="username">Username:</label><br>
|
||||
<input id="username" name="username" placeholder="John" type="text"><br><br>
|
||||
<label for="password">Password:</label><br>
|
||||
<input id="password" name="password" type="password"><br><br>
|
||||
<input type="submit" value="Submit">
|
||||
</form>
|
||||
</div>
|
||||
{{ end }}
|
@ -6,8 +6,8 @@ import (
|
||||
"embed"
|
||||
)
|
||||
|
||||
// App contains and supplies available configurations and connections
|
||||
type App struct {
|
||||
// Deps contains and supplies available configurations and connections
|
||||
type Deps struct {
|
||||
Config config.Configuration // Configuration file
|
||||
Db *sql.DB // Database connection
|
||||
Res *embed.FS // Resources from the embedded filesystem
|
21
app/middleware/csrf.go
Normal file
21
app/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)
|
||||
}
|
||||
}
|
16
app/middleware/wrapper.go
Normal file
16
app/middleware/wrapper.go
Normal file
@ -0,0 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
type MiddlewareFunc func(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
// 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
|
||||
}
|
37
app/models/migrations.go
Normal file
37
app/models/migrations.go
Normal file
@ -0,0 +1,37 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/database"
|
||||
"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
app/models/session.go
Normal file
153
app/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.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
app/models/user.go
Normal file
130
app/models/user.go
Normal file
@ -0,0 +1,130 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"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
|
||||
}
|
||||
}
|
33
app/routes/get.go
Normal file
33
app/routes/get.go
Normal file
@ -0,0 +1,33 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/app/controllers"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Get defines all project get routes
|
||||
func Get(app *app.Deps) {
|
||||
// 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("/static/", http.StripPrefix("/static/", staticHandler))
|
||||
slog.Info("serving static files from embedded file system /static")
|
||||
|
||||
// Pages
|
||||
http.HandleFunc("/", getController.ShowHome)
|
||||
http.HandleFunc("/login", getController.ShowLogin)
|
||||
http.HandleFunc("/register", getController.ShowRegister)
|
||||
http.HandleFunc("/logout", getController.Logout)
|
||||
}
|
20
app/routes/post.go
Normal file
20
app/routes/post.go
Normal file
@ -0,0 +1,20 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/app/controllers"
|
||||
"GoWeb/app/middleware"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Post defines all project post routes
|
||||
func Post(app *app.Deps) {
|
||||
// Post controller struct initialize
|
||||
postController := controllers.Post{
|
||||
App: app,
|
||||
}
|
||||
|
||||
// User authentication
|
||||
http.HandleFunc("/register-handle", middleware.Csrf(postController.Register))
|
||||
http.HandleFunc("/login-handle", middleware.Csrf(postController.Login))
|
||||
}
|
@ -6,22 +6,22 @@ import (
|
||||
)
|
||||
|
||||
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)
|
||||
EveryReboot []func(app *Deps)
|
||||
EverySecond []func(app *Deps)
|
||||
EveryMinute []func(app *Deps)
|
||||
EveryHour []func(app *Deps)
|
||||
EveryDay []func(app *Deps)
|
||||
EveryWeek []func(app *Deps)
|
||||
EveryMonth []func(app *Deps)
|
||||
EveryYear []func(app *Deps)
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
Funcs []func(app *App)
|
||||
Funcs []func(app *Deps)
|
||||
Interval time.Duration
|
||||
}
|
||||
|
||||
func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||
func RunScheduledTasks(app *Deps, poolSize int, stop <-chan struct{}) {
|
||||
for _, f := range app.ScheduledTasks.EveryReboot {
|
||||
f(app)
|
||||
}
|
||||
@ -51,7 +51,7 @@ func RunScheduledTasks(app *App, poolSize int, stop <-chan struct{}) {
|
||||
case <-ticker.C:
|
||||
for _, f := range task.Funcs {
|
||||
runner <- true
|
||||
go func(f func(app *App)) {
|
||||
go func(f func(app *Deps)) {
|
||||
defer func() { <-runner }()
|
||||
f(app)
|
||||
}(f)
|
Reference in New Issue
Block a user