17 Commits

Author SHA1 Message Date
Gregory Wells
074b3f8f31 stale sessions not deleting 2026-03-25 14:05:27 -04:00
Gregory Wells
f8b3c10933 final cleanups 2026-03-25 14:02:53 -04:00
Gregory Wells
c11425dde7 Finish logging 2026-03-25 14:01:46 -04:00
Gregory Wells
bcaa023d3c add log levels in to logger 2026-03-25 13:55:37 -04:00
Gregory Wells
f491c80fa0 fixed a bug that stopped sessions from being deleted 2026-03-25 10:20:20 -04:00
Gregory Wells
ffb4077f24 debugging session 2026-03-25 09:40:50 -04:00
Gregory Wells
8adca50b91 Logging for LDAP server 2026-03-24 20:26:22 -04:00
Gregory Wells
8928b3c1fc Debug email class (even though no used) 2026-03-24 20:11:52 -04:00
Gregory Wells
92f7c0f127 implemented more logging functionality 2026-03-24 20:06:06 -04:00
Gregory Wells
d4512e9cce Debug worker 2026-03-24 18:38:47 -04:00
Gregory Wells
ffb9600089 some more changes to the Logger 2026-03-24 18:09:49 -04:00
Gregory Wells
d62e1f7b8f Debug connecting to the LDAP server 2026-03-24 18:08:36 -04:00
Gregory Wells
5aa2ce47c7 Fatalf and FatalFileRead 2026-03-24 17:51:59 -04:00
Gregory Wells
8d0cd0fd1b use read file helper function everywhere 2026-03-24 17:10:56 -04:00
Gregory Wells
35ec6678f8 implement and use first logging event (ReadFile) 2026-03-24 17:09:30 -04:00
Gregory Wells
ac20f9172d implement the first log message 2026-03-24 16:57:28 -04:00
Gregory Wells
b96f65c294 Redo File structure 2026-03-24 16:52:22 -04:00
9 changed files with 299 additions and 65 deletions

View File

@@ -20,7 +20,7 @@ A simple, lightweight web application for managing user profile photos in a Free
1. **Clone the Repository**
```bash
git clone https://git.astraltech.xyz/gawells/Self-Service-Dashboard
cd account-manager
cd Self-Service-Dashboard
```
2. **Configure the Application**
@@ -39,7 +39,7 @@ A simple, lightweight web application for managing user profile photos in a Free
5. **Run the Server**
```bash
go run src/*.go
go run ./src/main/
```
The application will be available at `http://<host>:<port>`.

120
src/logging/logging.go Normal file
View File

@@ -0,0 +1,120 @@
package logging
import (
"log"
)
type EventType int
const (
ReadFile EventType = iota
AuthenticateUser
)
type LogLevel int
const (
InfoLevel LogLevel = iota
EventLevel
DebugLevel
WarnLevel
ErrorLevel
FatalLevel
)
var (
currentLevel LogLevel = InfoLevel
)
func Info(message string) {
if currentLevel > InfoLevel {
return
}
log.Printf("Info: %s", message)
}
func Infof(message string, v ...any) {
if currentLevel > InfoLevel {
return
}
log.Printf("Info: "+message, v...)
}
func Debug(message string) {
if currentLevel > DebugLevel {
return
}
log.Printf("Debug: %s", message)
}
func Debugf(message string, v ...any) {
if currentLevel > DebugLevel {
return
}
log.Printf("Debug: "+message, v...)
}
func Warn(message string) {
if currentLevel > WarnLevel {
return
}
log.Printf("Warn: %s", message)
}
func Warnf(message string, v ...any) {
if currentLevel > WarnLevel {
return
}
log.Printf("Warn: "+message, v...)
}
func Error(message string) {
if currentLevel > ErrorLevel {
return
}
log.Printf("Error: %s", message)
}
func Errorf(message string, v ...any) {
if currentLevel > ErrorLevel {
return
}
log.Printf("Error: "+message, v...)
}
func Fatal(message string) {
if currentLevel > FatalLevel {
return
}
log.Fatal(message)
}
func Fatalf(message string, v ...any) {
if currentLevel > FatalLevel {
return
}
log.Fatalf(message, v...)
}
func Event(eventType EventType, eventData ...any) {
if currentLevel > EventLevel {
return
}
switch eventType {
case ReadFile:
{
log.Printf("Reading file %s", eventData[0])
break
}
case AuthenticateUser:
{
log.Printf("Authenticating user %s", eventData[0])
break
}
}
}
func SetLogLovel(level LogLevel) {
currentLevel = level
}

View File

@@ -3,6 +3,8 @@ package main
import (
"encoding/json"
"os"
"astraltech.xyz/accountmanager/src/logging"
)
type LDAPConfig struct {
@@ -30,12 +32,20 @@ type ServerConfig struct {
}
func loadServerConfig(path string) (*ServerConfig, error) {
logging.Debugf("Loading server config file: %s", path)
file, err := os.ReadFile(path)
if err != nil {
logging.Errorf("Failed to load server config")
logging.Error(err.Error())
return nil, err
}
var cfg ServerConfig
logging.Debugf("Unmarshaling JSON data")
err = json.Unmarshal(file, &cfg)
return &cfg, err
if err != nil {
logging.Error("Failed to read JSON data")
logging.Error(err.Error())
}
return &cfg, nil
}

View File

@@ -1,9 +1,11 @@
package main
import (
"log"
"net/smtp"
"strconv"
"strings"
"astraltech.xyz/accountmanager/src/logging"
)
type EmailAccount struct {
@@ -20,6 +22,7 @@ type EmailAccountData struct {
}
func createEmailAccount(accountData EmailAccountData, smtpHost string, smtpPort int) EmailAccount {
logging.Debugf("Creating Email Account: \n\tUsername: %s\n\tEmail: %s\n\tSMTP Host: %s:%d", accountData.username, accountData.email, smtpHost, smtpPort)
account := EmailAccount{
email: accountData.email,
smtpHost: smtpHost,
@@ -30,13 +33,9 @@ func createEmailAccount(accountData EmailAccountData, smtpHost string, smtpPort
}
func sendEmail(account EmailAccount, toEmail []string, subject string, message string) {
ToEmailList := ""
for i := 0; i < len(toEmail); i++ {
ToEmailList += toEmail[i]
if i+1 < len(toEmail) {
ToEmailList += ", "
}
}
logging.Debugf("Sending an email from %s to %s", account.email, strings.Join(toEmail, ""))
ToEmailList := strings.Join(toEmail, "")
messageData := []byte(
"From: " + account.email + "\r\n" +
@@ -47,6 +46,7 @@ func sendEmail(account EmailAccount, toEmail []string, subject string, message s
)
err := smtp.SendMail(account.smtpHost+":"+account.smtpPort, account.auth, account.email, toEmail, messageData)
if err != nil {
log.Print(err)
logging.Error("Failed to send email")
logging.Error(err.Error())
}
}

58
src/main/helpers.go Normal file
View File

@@ -0,0 +1,58 @@
package main
import (
"net/http"
"os"
"astraltech.xyz/accountmanager/src/logging"
)
// Reads a file, if fails just returns an error
func ReadFile(path string) ([]byte, error) {
logging.Event(logging.ReadFile, "static/blank_profile.jpg")
data, err := os.ReadFile(path)
if err != nil {
logging.Infof("Could not read file at %s", path)
logging.Infof("Error code: %e", err)
return nil, err
}
logging.Infof("Successfully read file at %s", path)
return data, err
}
func ReadRequiredFile(path string) []byte {
logging.Event(logging.ReadFile, "static/blank_profile.jpg")
data, err := os.ReadFile(path)
if err != nil {
logging.Fatalf("Could not read file at %s", path)
return nil
}
logging.Infof("Successfully read file at %s", path)
return data
}
func Mkdir(path string, perm os.FileMode) error {
logging.Infof("Making directory %s", path)
err := os.Mkdir(path, perm)
if err != nil {
logging.Errorf("Failed to make %s directory", path)
logging.Error(err.Error())
return err
}
return nil
}
func CreateFile(path string) (*os.File, error) {
logging.Infof("Creating %s", path)
file, err := os.Create(path)
if err != nil {
logging.Errorf("Faile to create %s", path)
logging.Error(err.Error())
}
return file, nil
}
func HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) {
logging.Infof("Handling %s", path)
http.HandleFunc(path, handler)
}

View File

@@ -2,9 +2,10 @@ package main
import (
"crypto/tls"
"errors"
"log"
"fmt"
"strings"
"astraltech.xyz/accountmanager/src/logging"
"github.com/go-ldap/ldap/v3"
)
@@ -20,16 +21,21 @@ type LDAPSearch struct {
LDAPSearch *ldap.SearchResult
}
func connectToLDAPServer(URL string, starttls bool, ignore_cert bool) (*LDAPServer, error) {
func connectToLDAPServer(URL string, starttls bool, ignore_cert bool) *LDAPServer {
logging.Debugf("Connecting to LDAP server %s", URL)
l, err := ldap.DialURL(URL)
if err != nil {
return nil, err
logging.Fatal("Failed to connect to LDAP server")
logging.Fatal(err.Error())
}
logging.Infof("Connected to LDAP server")
if starttls {
logging.Debugf("Enabling StartTLS")
if err := l.StartTLS(&tls.Config{InsecureSkipVerify: ignore_cert}); err != nil {
log.Println("StartTLS failed:", err)
logging.Errorf("StartTLS failed %s", err.Error())
}
logging.Infof("StartTLS enabled")
}
return &LDAPServer{
@@ -37,44 +43,58 @@ func connectToLDAPServer(URL string, starttls bool, ignore_cert bool) (*LDAPServ
URL: URL,
StartTLS: starttls,
IgnoreInsecureCert: ignore_cert,
}, nil
}
}
func reconnectToLDAPServer(server *LDAPServer) {
func reconnectToLDAPServer(server *LDAPServer) error {
logging.Debugf("Reconnecting to %s LDAP server", server.URL)
if server == nil {
log.Println("Cannot reconnect: server is nil")
return
logging.Errorf("Cannot reconnect: server is nil")
return fmt.Errorf("Server is nil")
}
l, err := ldap.DialURL(server.URL)
if err != nil {
log.Print(err)
return
logging.Errorf("Failed to connect to LDAP server (has server gone down)")
return err
}
if server.StartTLS {
logging.Debugf("StartTLS enabling")
if err := l.StartTLS(&tls.Config{InsecureSkipVerify: server.IgnoreInsecureCert}); err != nil {
log.Println("StartTLS failed:", err)
logging.Error("StartTLS failed")
return err
}
logging.Debugf("Successfully Started TLS")
}
server.Connection = l
return nil
}
func connectAsLDAPUser(server *LDAPServer, bindDN, password string) error {
logging.Debugf("Connecting to %s LDAP server with %s BindDN", server.URL, bindDN)
if server == nil {
return errors.New("LDAP server is nil")
logging.Errorf("Failed to connect as user, LDAP server is NULL")
return fmt.Errorf("LDAP server is null")
}
// Reconnect if needed
if server.Connection == nil || server.Connection.IsClosing() {
reconnectToLDAPServer(server)
err := reconnectToLDAPServer(server)
return err
}
return server.Connection.Bind(bindDN, password)
err := server.Connection.Bind(bindDN, password)
if err != nil {
logging.Errorf("Failed to bind to LDAP as user %s", err.Error())
return err
}
return nil
}
func searchLDAPServer(server *LDAPServer, baseDN string, searchFilter string, attributes []string) LDAPSearch {
logging.Debugf("Searching %s LDAP server\n\tBase DN: %s\n\tSearch Filter %s\n\tAttributes: %s", server.URL, baseDN, searchFilter, strings.Join(attributes, ","))
if server == nil {
logging.Errorf("Server is nil, failed to search LDAP server")
return LDAPSearch{false, nil}
}
@@ -94,6 +114,7 @@ func searchLDAPServer(server *LDAPServer, baseDN string, searchFilter string, at
sr, err := server.Connection.Search(searchRequest)
if err != nil {
logging.Errorf("Failed to search LDAP server %s\n", err.Error())
return LDAPSearch{false, nil}
}
@@ -101,10 +122,12 @@ func searchLDAPServer(server *LDAPServer, baseDN string, searchFilter string, at
}
func modifyLDAPAttribute(server *LDAPServer, userDN string, attribute string, data []string) error {
logging.Infof("Modifing LDAP attribute %s", attribute)
modify := ldap.NewModifyRequest(userDN, nil)
modify.Replace(attribute, data)
err := server.Connection.Modify(modify)
if err != nil {
logging.Errorf("Failed to modify %s", err.Error())
return err
}
return nil
@@ -112,7 +135,11 @@ func modifyLDAPAttribute(server *LDAPServer, userDN string, attribute string, da
func closeLDAPServer(server *LDAPServer) {
if server != nil && server.Connection != nil {
server.Connection.Close()
logging.Debug("Closing connection to LDAP server")
err := server.Connection.Close()
if err != nil {
logging.Errorf("Failed to close LDAP server %s", err.Error())
}
}
}

View File

@@ -11,6 +11,8 @@ import (
"strings"
"sync"
"time"
"astraltech.xyz/accountmanager/src/logging"
)
var (
@@ -33,20 +35,20 @@ var (
)
func createUserPhoto(username string, photoData []byte) error {
os.Mkdir("./avatars", os.ModePerm)
Mkdir("./avatars", os.ModePerm)
path := fmt.Sprintf("./avatars/%s.jpeg", username)
cleaned := filepath.Clean(path)
dst, err := os.Create(cleaned)
dst, err := CreateFile(cleaned)
if err != nil {
fmt.Printf("Not saving file\n")
return fmt.Errorf("Could not save file")
}
photoCreatedMutex.Lock()
photoCreatedTimestamp[username] = time.Now()
photoCreatedMutex.Unlock()
defer dst.Close()
logging.Info("Writing to avarar file")
_, err = dst.Write(photoData)
if err != nil {
return err
@@ -55,6 +57,7 @@ func createUserPhoto(username string, photoData []byte) error {
}
func authenticateUser(username, password string) (UserData, error) {
logging.Event(logging.AuthenticateUser, username)
ldapServerMutex.Lock()
defer ldapServerMutex.Unlock()
if ldapServer.Connection == nil {
@@ -96,9 +99,12 @@ type LoginPageData struct {
}
func loginHandler(w http.ResponseWriter, r *http.Request) {
logging.Info("Handing login page")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl := template.Must(template.ParseFiles("src/pages/login_page.html"))
if r.Method == http.MethodGet {
logging.Info("Rending login page")
tmpl.Execute(w, LoginPageData{IsHiddenClassList: "hidden"})
return
}
@@ -109,10 +115,9 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
if strings.Contains(username, "/") {
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
}
password := r.FormValue("password")
log.Printf("New Login request for %s\n", username)
logging.Infof("New Login request for %s\n", username)
userData, err := authenticateUser(username, password)
if err != nil {
log.Print(err)
@@ -170,7 +175,7 @@ func avatarHandler(w http.ResponseWriter, r *http.Request) {
filePath := fmt.Sprintf("./avatars/%s.jpeg", username)
cleaned := filepath.Clean(filePath)
value, err := os.ReadFile(cleaned)
value, err := ReadFile(cleaned)
if err == nil {
photoCreatedMutex.Lock()
@@ -187,7 +192,6 @@ func avatarHandler(w http.ResponseWriter, r *http.Request) {
connected := connectAsLDAPUser(ldapServer, serverConfig.LDAPConfig.BindDN, serverConfig.LDAPConfig.BindPassword)
if connected != nil {
w.Write(blankPhotoData)
fmt.Println("Returned blank avatar because couldnt connect as user")
return
}
@@ -199,13 +203,11 @@ func avatarHandler(w http.ResponseWriter, r *http.Request) {
)
if !userSearch.Succeeded || len(userSearch.LDAPSearch.Entries) == 0 {
w.Write(blankPhotoData)
fmt.Println("Returned blank avatar because we couldnt find the user")
return
}
entry := userSearch.LDAPSearch.Entries[0]
bytes := entry.GetRawAttributeValue("jpegphoto")
if len(bytes) == 0 {
fmt.Println("Returned blank avatar because we just don't have an avatar")
w.Write(blankPhotoData)
return
} else {
@@ -226,14 +228,13 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) {
if exist {
if r.FormValue("csrf_token") != sessionData.CSRFToken {
http.Error(w, "Unable to log user out", http.StatusForbidden)
log.Printf("%s attempted to logout with invalid csrf token", sessionData.data.Username)
logging.Debugf("%s attempted to logout with invalid csrf token", sessionData.data.Username)
return
}
}
logging.Infof("handling logout event for %s", sessionData.data.Username)
sessionMutex.Lock()
delete(sessions, token)
sessionMutex.Unlock()
deleteSession(token)
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
@@ -279,17 +280,19 @@ func uploadPhotoHandler(w http.ResponseWriter, r *http.Request) {
}
func faviconHandler(w http.ResponseWriter, r *http.Request) {
logging.Info("Requesting Favicon")
http.ServeFile(w, r, serverConfig.StyleConfig.FaviconPath)
}
func logoHandler(w http.ResponseWriter, r *http.Request) {
logging.Info("Requesting Logo")
http.ServeFile(w, r, serverConfig.StyleConfig.LogoPath)
}
func cleanupSessions() {
sessionMutex.Lock()
defer sessionMutex.Unlock()
logging.Debug("Cleaning up stale session\n")
sessionMutex.Lock()
sessions_to_delete := []string{}
for session_token, session_data := range sessions {
timeUntilRemoval := time.Minute * 5
@@ -300,17 +303,19 @@ func cleanupSessions() {
sessions_to_delete = append(sessions_to_delete, session_token)
}
}
sessionMutex.Unlock()
for _, session_id := range sessions_to_delete {
delete(sessions, session_id)
deleteSession(session_id)
}
}
func main() {
var err error = nil
logging.Info("Starting the server")
blankPhotoData, err = os.ReadFile("static/blank_profile.jpg")
var err error = nil
blankPhotoData, err = ReadFile("static/blank_profile.jpg")
if err != nil {
log.Fatal("Could not load blank profile image")
logging.Fatal("Could not load blank profile image")
}
serverConfig, err = loadServerConfig("./data/config.json")
if err != nil {
@@ -318,31 +323,27 @@ func main() {
}
ldapServerMutex.Lock()
server, err := connectToLDAPServer(serverConfig.LDAPConfig.LDAPURL, serverConfig.LDAPConfig.Security == "tls", serverConfig.LDAPConfig.IgnoreInvalidCert)
server := connectToLDAPServer(serverConfig.LDAPConfig.LDAPURL, serverConfig.LDAPConfig.Security == "tls", serverConfig.LDAPConfig.IgnoreInvalidCert)
ldapServer = server
ldapServerMutex.Unlock()
if err != nil {
log.Fatal(err)
return
}
defer closeLDAPServer(ldapServer)
createWorker(time.Minute*5, cleanupSessions)
http.HandleFunc("/favicon.ico", faviconHandler)
http.HandleFunc("/logo", logoHandler)
HandleFunc("/favicon.ico", faviconHandler)
HandleFunc("/logo", logoHandler)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/profile", profileHandler)
http.HandleFunc("/logout", logoutHandler)
HandleFunc("/login", loginHandler)
HandleFunc("/profile", profileHandler)
HandleFunc("/logout", logoutHandler)
http.HandleFunc("/avatar", avatarHandler)
http.HandleFunc("/change-photo", uploadPhotoHandler)
HandleFunc("/avatar", avatarHandler)
HandleFunc("/change-photo", uploadPhotoHandler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/profile", http.StatusFound) // 302 redirect
})
serverAddress := fmt.Sprintf(":%d", serverConfig.WebserverConfig.Port)
log.Fatal(http.ListenAndServe(serverAddress, nil))
logging.Fatal(http.ListenAndServe(serverAddress, nil).Error())
}

View File

@@ -4,10 +4,11 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"log"
"net/http"
"sync"
"time"
"astraltech.xyz/accountmanager/src/logging"
)
type SessionData struct {
@@ -33,14 +34,15 @@ func GenerateSessionToken(length int) (string, error) {
}
func createSession(userData *UserData) *http.Cookie {
logging.Debugf("Creating a new session for %s", userData.Username)
token, err := GenerateSessionToken(32) // Use crypto/rand for this
if err != nil {
log.Print(err)
logging.Error(err.Error())
return nil
}
CSRFToken, err := GenerateSessionToken(32)
if err != nil {
log.Print(err)
logging.Error(err.Error())
return nil
}
@@ -72,8 +74,10 @@ func createSession(userData *UserData) *http.Cookie {
}
func validateSession(r *http.Request) (bool, *SessionData) {
logging.Debugf("Validating session")
cookie, err := r.Cookie("session_token")
if err != nil {
logging.Error(err.Error())
return false, &SessionData{}
}
token := cookie.Value
@@ -87,5 +91,16 @@ func validateSession(r *http.Request) (bool, *SessionData) {
if !exists || !sessionData.loggedIn {
return false, &SessionData{}
}
logging.Infof("Validated session for %s", sessionData.data.Username)
return true, &sessionData
}
func deleteSession(session_id string) {
sessionMutex.Lock()
tokenEncoded := sha256.Sum256([]byte(session_id))
tokenEncodedString := string(tokenEncoded[:])
delete(sessions, tokenEncodedString)
sessionMutex.Unlock()
}

View File

@@ -2,9 +2,12 @@ package main
import (
"time"
"astraltech.xyz/accountmanager/src/logging"
)
func createWorker(interval time.Duration, task func()) {
logging.Debugf("Creating worker that runs on a %s interval", interval.String())
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()