25 Commits

Author SHA1 Message Date
gawells 791dd3b0c4 place resize anchors 2026-06-14 08:52:59 -04:00
gawells 3d6a853be0 Update ReadME.md 2026-06-14 08:17:18 -04:00
gawells 7d1be226b6 move some stuff to a new JS file 2026-06-14 08:13:30 -04:00
gawells 65ed53c5d1 grab picture when moving it around 2026-06-14 07:58:29 -04:00
gawells ff5d9724d6 simple cursor controller 2026-06-14 07:58:17 -04:00
gawells 8859449be5 add boundies for moving image around 2026-06-13 13:41:39 -04:00
gawells f0ace2b43f unblur background on error 2026-06-12 13:23:50 -04:00
gawells 07f78510ed display profile picture image 2026-06-12 13:16:14 -04:00
gawells 4870318148 add a cursor helper 2026-06-11 18:58:57 -04:00
gawells c9f9f3ef6c add in confirm change button 2026-06-11 18:38:37 -04:00
gawells d82d2bba20 redo in memory sesisons to have TTLs 2026-06-11 18:13:31 -04:00
gawells 22c4666fa7 update session stores to decide TTLs 2026-06-09 12:31:27 -04:00
gawells e41a81c487 get a cropped square to exist 2026-06-08 21:36:10 -04:00
gawells 600c3abf20 make new photo pop up in box before changing 2026-06-08 21:09:12 -04:00
Gregory Wells 4cce7b7454 have user data persist between restarts in redis session 2026-06-08 19:21:08 -04:00
Gregory Wells 109199ea45 move redis config over to config file 2026-06-08 18:54:31 -04:00
Gregory Wells 40429d7618 add in config variable for redis sessions 2026-06-08 18:44:20 -04:00
Gregory Wells 11c40a75ac handle cleanup 2026-06-08 18:37:51 -04:00
Gregory Wells d162c32a57 begin handling cleanup of session tokens 2026-06-08 18:37:42 -04:00
Gregory Wells 2a97ec72be convert over in memory store 2026-06-08 18:29:19 -04:00
Gregory Wells 09e0683ae0 fully convert redis over to custom key value store type 2026-06-08 18:24:59 -04:00
Gregory Wells f6016bbdb1 start to move session stores into there own key value in memory store 2026-06-08 18:16:07 -04:00
Gregory Wells 3b31adf3e2 fix server from crashing after restart not having user data 2026-06-08 17:56:04 -04:00
Gregory Wells efdf9fdade remove old comment 2026-06-08 17:47:31 -04:00
Gregory Wells 4474986909 store extra key infront of session tokens 2026-06-07 20:42:09 -04:00
22 changed files with 599 additions and 276 deletions
+1 -1
View File
@@ -13,7 +13,7 @@ A simple, lightweight web application for managing user profile photos in a Free
## Prerequisites ## Prerequisites
* **Go 1.26+** installed on your machine. * **Go 1.26+** installed on your machine.
* Access to a **FreeIPA Server**. * Access to a **FreeIPA Server**.
* A Service Account with permission to search and modify the `jpegPhoto` attribute. * A Service Account with permission to search and modify the `jpegPhoto` attribute and read the `krbPasswordExpiration` attribute.
## Setup & Installation ## Setup & Installation
+6 -1
View File
@@ -13,7 +13,12 @@
}, },
"server_config": { "server_config": {
"port": 8080, "port": 8080,
"base_url": "https://profile.example.com" "base_url": "https://profile.example.com",
"session_store": "redis",
"redis_config": {
"redis_url": "redis://localhost:6379/0",
"prefix": ""
}
}, },
"email_config": { "email_config": {
"username": "noreply", "username": "noreply",
+7
View File
@@ -21,9 +21,16 @@ type StyleConfig struct {
LogoPath string `json:"logo_path"` LogoPath string `json:"logo_path"`
} }
type RedisConfig struct {
RedisURL string `json:"redis_url"`
Prefix string `json:"prefix"`
}
type WebserverConfig struct { type WebserverConfig struct {
Port int `json:"port"` Port int `json:"port"`
BaseURL string `json:"base_url"` BaseURL string `json:"base_url"`
SessionStore string `json:"session_store"`
RedisConfigInfo RedisConfig `json:"redis_config"`
} }
type EmailConfig struct { type EmailConfig struct {
+10 -3
View File
@@ -6,6 +6,7 @@ import (
"strings" "strings"
"astraltech.xyz/accountmanager/src/logging" "astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/store"
) )
type LoginPageData struct { type LoginPageData struct {
@@ -32,9 +33,15 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
logging.Infof("New Login request for %s\n", username) logging.Infof("New Login request for %s\n", username)
newUserData, err := authenticateUser(username, password) newUserData, err := authenticateUser(username, password)
userDataMutex.Lock()
userData[username] = newUserData userDataErr := userData.Create(username, newUserData)
userDataMutex.Unlock() if userDataErr == store.ErrKeyAlreadyExists {
userData.Update(username, newUserData)
} else if userDataErr != nil {
logging.Error(userDataErr.Error())
return
}
if err == ErrPasswordExpired { if err == ErrPasswordExpired {
http.Redirect(w, r, "/reset-password?token=this_is_the_only_token_that_works", http.StatusFound) http.Redirect(w, r, "/reset-password?token=this_is_the_only_token_that_works", http.StatusFound)
} else if err != nil { } else if err != nil {
+29 -11
View File
@@ -7,7 +7,6 @@ import (
"log" "log"
"net/http" "net/http"
"strings" "strings"
"sync"
"astraltech.xyz/accountmanager/src/components" "astraltech.xyz/accountmanager/src/components"
"astraltech.xyz/accountmanager/src/email" "astraltech.xyz/accountmanager/src/email"
@@ -15,6 +14,7 @@ import (
"astraltech.xyz/accountmanager/src/ldap" "astraltech.xyz/accountmanager/src/ldap"
"astraltech.xyz/accountmanager/src/logging" "astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/session" "astraltech.xyz/accountmanager/src/session"
"astraltech.xyz/accountmanager/src/store"
) )
var ( var (
@@ -31,8 +31,7 @@ type UserData struct {
} }
var ( var (
userData = make(map[string]*UserData) userData store.KeyValueStore[*UserData]
userDataMutex sync.RWMutex
) )
var ErrPasswordExpired = errors.New("Password expired") var ErrPasswordExpired = errors.New("Password expired")
@@ -94,16 +93,22 @@ func profileHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
data, err := userData.Get(sessionData.UserID)
if err != nil {
logging.Error(err.Error())
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if r.Method == http.MethodGet { if r.Method == http.MethodGet {
tmpl := template.Must(template.ParseFiles("src/pages/profile_page.html")) tmpl := template.Must(template.ParseFiles("src/pages/profile_page.html"))
userDataMutex.RLock()
tmpl.Execute(w, ProfileData{ tmpl.Execute(w, ProfileData{
Username: sessionData.UserID, Username: sessionData.UserID,
Email: userData[sessionData.UserID].Email, Email: data.Email,
DisplayName: userData[sessionData.UserID].DisplayName, DisplayName: data.DisplayName,
CSRFToken: sessionData.CSRFToken, CSRFToken: sessionData.CSRFToken,
}) })
userDataMutex.RUnlock()
return return
} }
} }
@@ -198,8 +203,10 @@ func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"success": true}`)) w.Write([]byte(`{"success": true}`))
user_data, err := userData.Get(sessionData.UserID)
data := map[string]any{ data := map[string]any{
"Username": userData[sessionData.UserID].DisplayName, "Username": user_data.DisplayName,
"ServiceName": "Astral Tech", "ServiceName": "Astral Tech",
} }
@@ -207,13 +214,11 @@ func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
logging.Errorf("Failed to load email template: %s", err.Error()) logging.Errorf("Failed to load email template: %s", err.Error())
} }
noReplyEmail.SendEmail([]string{userData[sessionData.UserID].Email}, "Password expired", email_template) noReplyEmail.SendEmail([]string{user_data.Email}, "Password expired", email_template)
} }
func main() { func main() {
logging.Info("Starting the server") logging.Info("Starting the server")
sessionManager = session.GetSessionManager()
sessionManager.SetStoreType(session.Redis)
var err error var err error
serverConfig, err = loadServerConfig("./data/config.json") serverConfig, err = loadServerConfig("./data/config.json")
@@ -221,6 +226,19 @@ func main() {
log.Fatal("Could not load server config") log.Fatal("Could not load server config")
} }
sessionManager = session.GetSessionManager()
if serverConfig.WebserverConfig.SessionStore == "in_memory" {
sessionManager.SetStoreType(session.InMemory)
userData = store.NewMemoryStore[*UserData]()
} else if serverConfig.WebserverConfig.SessionStore == "redis" {
sessionManager.SetStoreType(session.Redis, serverConfig.WebserverConfig.RedisConfigInfo.RedisURL, serverConfig.WebserverConfig.RedisConfigInfo.Prefix)
userData = store.NewRedisStore[*UserData](serverConfig.WebserverConfig.RedisConfigInfo.RedisURL, serverConfig.WebserverConfig.RedisConfigInfo.Prefix)
} else {
logging.Warnf("'%s' is an unknown session store type defaulting to in memory", serverConfig.WebserverConfig.SessionStore)
sessionManager.SetStoreType(session.InMemory)
userData = store.NewMemoryStore[*UserData]()
}
noReplyEmail = email.CreateEmailAccount(email.EmailAccountData{ noReplyEmail = email.CreateEmailAccount(email.EmailAccountData{
Username: serverConfig.EmailConfig.Username, Username: serverConfig.EmailConfig.Username,
Password: serverConfig.EmailConfig.Password, Password: serverConfig.EmailConfig.Password,
+59 -15
View File
@@ -10,6 +10,7 @@
<link rel="stylesheet" href="static/error/error.css" /> <link rel="stylesheet" href="static/error/error.css" />
<link rel="stylesheet" href="static/profile_page.css" /> <link rel="stylesheet" href="static/profile_page.css" />
<link rel="stylesheet" href="static/progress_bar.css" /> <link rel="stylesheet" href="static/progress_bar.css" />
<link rel="stylesheet" href="static/cursor.css" />
<div id="popup_background" class="blocked hidden"></div> <div id="popup_background" class="blocked hidden"></div>
@@ -87,18 +88,21 @@
></div> ></div>
</div> </div>
</div> </div>
<button id="final_change_password_button">Change Password</button>
<!--<div id="password_errors">
<div class="password_error">Error 1</div>
<div class="password_error">Error 2</div>
</div> </div>
<div id="password_warnings"> <div id="resize_photo_dialouge" class="card static_center hidden">
<div class="password_error">Error 1</div> <div id="image_container">
<div class="password_error">Error 2</div> <img id="new_profile_image" alt="new-profile-image" />
</div>--> <div id="darken_part"></div>
</div>
<button id="final_change_password_button">Change Password</button> <div id="resize_photo_box">
<div id="top_left_resize" class="resize_anchor"></div>
<div id="top_right_resize" class="resize_anchor"></div>
<div id="bottom_left_resize" class="resize_anchor"></div>
<div id="bottom_right_resize" class="resize_anchor"></div>
</div>
<button id="confirm_change">Confirm Change</button>
</div> </div>
<img id="logo_image" alt="logo" src="/logo" /> <img id="logo_image" alt="logo" src="/logo" />
@@ -168,28 +172,68 @@
</div> </div>
</div> </div>
<script src="/static/javascript/cursor.js" type="text/javascript"></script>
<script
src="/static/javascript/resize_photo_dialouge.js"
type="text/javascript"
></script>
<script type="text/javascript"> <script type="text/javascript">
const button = document.getElementById("edit_picture_button"); const button = document.getElementById("edit_picture_button");
const fileInput = document.getElementById("file_input"); const fileInput = document.getElementById("file_input");
const confirm_change = document.getElementById("confirm_change");
const new_profile_image = document.getElementById("new_profile_image");
button.addEventListener("click", () => { button.addEventListener("click", () => {
fileInput.click(); // opens file picker fileInput.click();
}); });
</script> </script>
<script type="text/javascript"> <script type="text/javascript">
var currentPreviewURL = null; var currentPreviewURL = null,
image = null,
file = null;
var x_start = 0,
y_start = 0;
var bitmap;
fileInput.addEventListener("change", async () => { fileInput.addEventListener("change", async () => {
document.getElementById("popup_background").classList.remove("hidden"); document.getElementById("popup_background").classList.remove("hidden");
const file = fileInput.files[0]; file = fileInput.files[0];
if (!file) return; if (!file) return;
if (file.type !== "image/jpeg") { if (file.type !== "image/jpeg") {
alert("Only JPEG images are allowed."); alert("Only JPEG images are allowed.");
fileInput.value = ""; fileInput.value = "";
document.getElementById("popup_background").classList.add("hidden");
return; return;
} }
document
.getElementById("resize_photo_dialouge")
.classList.remove("hidden");
image = URL.createObjectURL(file);
bitmap = await createImageBitmap(file);
new_profile_image.src = image;
resize_photo_box.style.setProperty(
"--image-width",
bitmap.width + "px",
);
new_profile_image.style.setProperty("--x-offset", "0px");
new_profile_image.style.setProperty("--y-offset", "0px");
});
confirm_change.addEventListener("click", async () => {
document
.getElementById("resize_photo_dialouge")
.classList.add("hidden");
const formData = new FormData(); const formData = new FormData();
formData.append("photo", file); formData.append("photo", file);
formData.append( formData.append(
@@ -211,8 +255,8 @@
URL.revokeObjectURL(currentPreviewURL); URL.revokeObjectURL(currentPreviewURL);
} }
img.src = URL.createObjectURL(file); img.src = image;
currentPreviewURL = img.src; currentPreviewURL = image;
}); });
</script> </script>
-8
View File
@@ -1,8 +0,0 @@
package session
import "errors"
var ErrSessionNotFound = errors.New("session not found")
var ErrSessionAlreadyExists = errors.New("session already exists")
var ErrSessionExpired = errors.New("session expired")
var ErrSessionBackend = errors.New("session backend")
-7
View File
@@ -2,7 +2,6 @@ package session
import ( import (
"crypto/rand" "crypto/rand"
"crypto/sha256"
"encoding/base64" "encoding/base64"
) )
@@ -16,9 +15,3 @@ func GenerateSessionToken(length int) (string, error) {
token := base64.RawURLEncoding.EncodeToString(b) token := base64.RawURLEncoding.EncodeToString(b)
return token, nil return token, nil
} }
// more helper
func hashSession(session_id string) string {
tokenEncoded := sha256.Sum256([]byte(session_id))
return base64.RawURLEncoding.EncodeToString(tokenEncoded[:])
}
-94
View File
@@ -1,94 +0,0 @@
package session
import (
"sync"
"time"
"astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/worker"
)
type MemoryStore struct {
sessions map[string]*SessionData
lock sync.RWMutex
}
func NewMemoryStore() *MemoryStore {
logging.Debug("Creating new in memory session store")
store := &MemoryStore{
sessions: make(map[string]*SessionData),
}
worker.CreateWorker(time.Minute*5, store.cleanup)
return store
}
func (m *MemoryStore) Create(sessionID string, session *SessionData) (err error) {
hashedSession := hashSession(sessionID)
m.lock.Lock()
defer m.lock.Unlock()
_, exist := m.sessions[hashedSession]
if exist {
return ErrSessionAlreadyExists
}
m.sessions[hashedSession] = session
return nil
}
func (m *MemoryStore) Get(sessionID string) (*SessionData, error) {
m.lock.RLock()
hashed := hashSession(sessionID)
data, exists := m.sessions[hashed]
m.lock.RUnlock()
if exists == false {
return nil, ErrSessionNotFound
}
if time.Now().After(data.ExpiresAt) {
_ = m.Delete(sessionID) // ignore error
return nil, ErrSessionExpired
}
copy := *data
return &copy, nil
}
func (m *MemoryStore) Update(sessionID string, session *SessionData) error {
hashedSession := hashSession(sessionID)
m.lock.Lock()
defer m.lock.Unlock()
_, exist := m.sessions[hashedSession]
if !exist {
return ErrSessionNotFound
}
m.sessions[hashedSession] = session
return nil
}
func (m *MemoryStore) cleanup() {
logging.Debug("Cleaning up memory store sessions")
now := time.Now()
m.lock.Lock()
defer m.lock.Unlock()
deleted := 0
for id, session := range m.sessions {
if now.After(session.ExpiresAt) {
delete(m.sessions, id)
deleted = deleted + 1
}
}
logging.Infof("Cleaned up %d stale sessions", deleted)
}
func (m *MemoryStore) Delete(sessionID string) error {
hashedSession := hashSession(sessionID)
m.lock.Lock()
defer m.lock.Unlock()
_, exist := m.sessions[hashedSession]
if !exist {
return ErrSessionNotFound
}
delete(m.sessions, hashedSession)
return nil
}
+17 -8
View File
@@ -6,12 +6,13 @@ import (
"time" "time"
"astraltech.xyz/accountmanager/src/logging" "astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/store"
) )
const SessionCookieName = "session_token" const SessionCookieName = "session_token"
type SessionManager struct { type SessionManager struct {
store SessionStore store store.KeyValueStore[*SessionData]
} }
var instance *SessionManager var instance *SessionManager
@@ -31,17 +32,19 @@ func GetSessionManager() *SessionManager {
return instance return instance
} }
func (manager *SessionManager) SetStoreType(storeType StoreType) { func (manager *SessionManager) SetStoreType(storeType StoreType, params ...any) {
logging.Infof("Changing session manager store type") logging.Infof("Changing session manager store type")
switch storeType { switch storeType {
case InMemory: case InMemory:
{ {
manager.store = NewMemoryStore() manager.store = store.NewMemoryStore[*SessionData]()
break break
} }
case Redis: case Redis:
{ {
manager.store = NewRedisStore() url, _ := params[0].(string)
prefix, _ := params[1].(string)
manager.store = store.NewRedisStore[*SessionData](url, prefix)
break break
} }
} }
@@ -62,7 +65,7 @@ func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie
CSRFToken: CSRFToken, CSRFToken: CSRFToken,
ExpiresAt: time.Now().Add(time.Hour), ExpiresAt: time.Now().Add(time.Hour),
} }
err = manager.store.Create(token, &newSessionData) err = manager.store.CreateExpiring(token, &newSessionData, time.Hour)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -71,10 +74,10 @@ func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie
Name: SessionCookieName, Name: SessionCookieName,
Value: token, Value: token,
Path: "/", Path: "/",
HttpOnly: true, // Essential: prevents JS access HttpOnly: true,
Secure: true, // Set to TRUE in production (HTTPS) Secure: true,
SameSite: http.SameSiteLaxMode, SameSite: http.SameSiteLaxMode,
MaxAge: 3600, // 1 hour MaxAge: 3600,
} }
return newCookie, nil return newCookie, nil
} }
@@ -93,6 +96,12 @@ func (manager *SessionManager) GetSession(r *http.Request) (*SessionData, error)
if err != nil { if err != nil {
return nil, ErrSessionNotFound return nil, ErrSessionNotFound
} }
if time.Now().After(data.ExpiresAt) {
_ = manager.store.Delete(token)
return nil, ErrSessionExpired
}
return data, nil return data, nil
} }
-117
View File
@@ -1,117 +0,0 @@
package session
import (
"context"
"encoding/json"
"time"
"astraltech.xyz/accountmanager/src/logging"
"github.com/redis/go-redis/v9"
)
type RedisStore struct {
client *redis.Client
ctx context.Context
}
func NewRedisStore() *RedisStore {
logging.Debug("Creating new redis session store")
// this will be replaced with a URL that can be parsed in the config file
redis_server := "redis://localhost:6379/0"
opts, err := redis.ParseURL(redis_server)
if err != nil {
logging.Errorf("Failed to parse redis url %s", err.Error())
}
rdb := redis.NewClient(opts)
ctx := context.Background()
if err := rdb.Ping(ctx).Err(); err != nil {
logging.Errorf("Failed to connect to redis server %s", redis_server)
} else {
logging.Infof("Successfully connected to redis server %s", redis_server)
}
store := &RedisStore{
client: rdb,
ctx: ctx,
}
return store
}
// return rdb.Set(ctx, key, data, 0).Err()
func (m *RedisStore) Create(sessionID string, session *SessionData) (err error) {
hashedSession := hashSession(sessionID)
data, err := json.Marshal(*session)
if err != nil {
return ErrSessionBackend
}
created, err := m.client.SetNX(m.ctx, hashedSession, data, time.Hour).Result()
if err != nil {
logging.Error(err.Error())
return ErrSessionBackend
}
if !created {
return ErrSessionAlreadyExists
}
return nil
}
func (m *RedisStore) Get(sessionID string) (*SessionData, error) {
hashed := hashSession(sessionID)
data, err := m.client.Get(m.ctx, hashed).Bytes()
if err == redis.Nil {
return nil, ErrSessionNotFound
} else if err != nil {
logging.Error(err.Error())
return nil, ErrSessionBackend
}
var session_data SessionData
if err := json.Unmarshal(data, &session_data); err != nil {
logging.Error(err.Error())
return nil, ErrSessionBackend
}
if time.Now().After(session_data.ExpiresAt) {
_ = m.Delete(sessionID)
return nil, ErrSessionBackend
}
return &session_data, nil
}
func (m *RedisStore) Update(sessionID string, session *SessionData) error {
hashedSession := hashSession(sessionID)
data, err := json.Marshal(*session)
if err != nil {
return ErrSessionBackend
}
updated, err := m.client.SetXX(m.ctx, hashedSession, data, time.Hour).Result()
if err != nil {
logging.Error(err.Error())
return ErrSessionBackend
}
if !updated {
return ErrSessionNotFound
}
return nil
}
func (m *RedisStore) Delete(sessionID string) error {
hashedSession := hashSession(sessionID)
err := m.client.Del(m.ctx, hashedSession).Err()
if err != nil {
logging.Error(err.Error())
return ErrSessionBackend
}
return nil
}
+9 -8
View File
@@ -1,16 +1,17 @@
package session package session
import "time" import (
"errors"
"time"
)
var ErrSessionNotFound = errors.New("Session not found")
var ErrSessionAlreadyExists = errors.New("Session already exists")
var ErrSessionExpired = errors.New("Session expired")
var ErrSessionBackend = errors.New("Session backend")
type SessionData struct { type SessionData struct {
UserID string `json:"userid"` UserID string `json:"userid"`
CSRFToken string `json:"csrftoken"` CSRFToken string `json:"csrftoken"`
ExpiresAt time.Time `json:"expiresat"` ExpiresAt time.Time `json:"expiresat"`
} }
type SessionStore interface {
Create(sessionID string, session *SessionData) error
Get(sessionID string) (*SessionData, error)
Update(sessionID string, session *SessionData) error
Delete(sessionID string) error
}
+15
View File
@@ -0,0 +1,15 @@
package store
import (
"time"
)
// A simple key value store that can either just be single instance in memory or a redis server (for now)
type KeyValueStore[Value any] interface {
Create(key string, value Value) error
CreateExpiring(key string, value Value, ttl time.Duration) error
Get(key string) (Value, error)
Update(key string, session Value) error
Delete(key string) error
}
+8
View File
@@ -0,0 +1,8 @@
package store
import "errors"
var ErrKeyNotFound = errors.New("Key not found")
var ErrKeyAlreadyExists = errors.New("Key already exists")
var ErrKeyExpired = errors.New("Key expired")
var ErrKeyBackend = errors.New("Key backend")
+11
View File
@@ -0,0 +1,11 @@
package store
import (
"crypto/sha256"
"encoding/base64"
)
func HashKey(key string) string {
tokenEncoded := sha256.Sum256([]byte(key))
return base64.RawURLEncoding.EncodeToString(tokenEncoded[:])
}
+158
View File
@@ -0,0 +1,158 @@
package store
import (
"sync"
"time"
"astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/worker"
)
type KeyValue[Value any] struct {
value Value
expireTime time.Time
}
type ExpireTime struct {
expiryTime time.Time
key string
}
type MemoryStore[Value any] struct {
Keys map[string]KeyValue[Value]
Lock sync.RWMutex
ExpireTimes []ExpireTime
}
func NewMemoryStore[Value any]() *MemoryStore[Value] {
logging.Debug("Creating new in memory session store")
store := &MemoryStore[Value]{
Keys: make(map[string]KeyValue[Value]),
Lock: sync.RWMutex{},
ExpireTimes: []ExpireTime{},
}
worker.CreateWorker(time.Minute*5, store.CleanupExpired)
return store
}
func (m *MemoryStore[Value]) CreateExpiring(key string, value Value, duration time.Duration) error {
var expiry time.Time
if duration != 0 {
expiry = time.Now().Add(duration)
}
m.Lock.Lock()
defer m.Lock.Unlock()
hashedkey := HashKey(key)
_, exist := m.Keys[hashedkey]
if exist {
return ErrKeyAlreadyExists
}
m.Keys[hashedkey] = KeyValue[Value]{
value: value,
expireTime: expiry,
}
if duration != 0 {
low := 0
high := len(m.ExpireTimes)
for low < high {
mid := (low + high) / 2
if m.ExpireTimes[mid].expiryTime.Before(expiry) {
low = mid + 1
} else {
high = mid
}
}
insertIndex := low
m.ExpireTimes = append(m.ExpireTimes, ExpireTime{})
copy(m.ExpireTimes[insertIndex+1:], m.ExpireTimes[insertIndex:])
m.ExpireTimes[insertIndex] = ExpireTime{
key: key,
expiryTime: expiry,
}
}
return nil
}
func (m *MemoryStore[Value]) CleanupExpired() {
m.Lock.Lock()
defer m.Lock.Unlock()
now := time.Now()
for len(m.ExpireTimes) > 0 && !now.Before(m.ExpireTimes[0].expiryTime) {
key, exists := m.Keys[HashKey(m.ExpireTimes[0].key)]
if exists && key.expireTime.Equal(m.ExpireTimes[0].expiryTime) {
m.deleteWithoutLock(m.ExpireTimes[0].key)
}
m.ExpireTimes = m.ExpireTimes[1:]
}
}
func (m *MemoryStore[Value]) Create(key string, session Value) error {
return m.CreateExpiring(key, session, 0)
}
func (m *MemoryStore[Value]) Get(key string) (Value, error) {
var data KeyValue[Value]
var zeroValue Value
hashedkey := HashKey(key)
m.Lock.RLock()
data, exists := m.Keys[hashedkey]
m.Lock.RUnlock()
if !exists {
return zeroValue, ErrKeyNotFound
}
if !data.expireTime.IsZero() && !time.Now().Before(data.expireTime) {
m.Lock.Lock()
if current, ok := m.Keys[hashedkey]; ok && current.expireTime.Equal(data.expireTime) {
delete(m.Keys, hashedkey)
}
m.Lock.Unlock()
return zeroValue, ErrKeyNotFound
}
return data.value, nil
}
func (m *MemoryStore[Value]) Update(sessionID string, value Value) error {
hashedkey := HashKey(sessionID)
m.Lock.Lock()
defer m.Lock.Unlock()
old_key, exist := m.Keys[hashedkey]
if !exist {
return ErrKeyNotFound
}
m.Keys[hashedkey] = KeyValue[Value]{
value: value,
expireTime: old_key.expireTime,
}
return nil
}
func (m *MemoryStore[Value]) deleteWithoutLock(key string) error {
hashedkey := HashKey(key)
_, exist := m.Keys[hashedkey]
if !exist {
return ErrKeyNotFound
}
delete(m.Keys, hashedkey)
return nil
}
func (m *MemoryStore[Value]) Delete(key string) error {
m.Lock.Lock()
defer m.Lock.Unlock()
return m.deleteWithoutLock(key)
}
+116
View File
@@ -0,0 +1,116 @@
package store
import (
"context"
"encoding/json"
"time"
"astraltech.xyz/accountmanager/src/logging"
"github.com/redis/go-redis/v9"
)
type RedisStore[Value any] struct {
client *redis.Client
ctx context.Context
prefix string
}
func (m *RedisStore[Value]) RedisHash(value_to_hash string) string {
return m.prefix + HashKey(value_to_hash)
}
func NewRedisStore[Value any](redis_server string, prefix string) *RedisStore[Value] {
logging.Debug("Creating new redis session store")
opts, err := redis.ParseURL(redis_server)
if err != nil {
logging.Errorf("Failed to parse redis url %s", err.Error())
}
rdb := redis.NewClient(opts)
ctx := context.Background()
if err := rdb.Ping(ctx).Err(); err != nil {
logging.Errorf("Failed to connect to redis server %s", redis_server)
} else {
logging.Infof("Successfully connected to redis server %s", redis_server)
}
store := &RedisStore[Value]{
client: rdb,
ctx: ctx,
prefix: prefix,
}
return store
}
func (m *RedisStore[Value]) CreateExpiring(key string, value Value, ttl time.Duration) error {
hashedSession := m.RedisHash(key)
data, err := json.Marshal(value)
if err != nil {
return ErrKeyBackend
}
created, err := m.client.SetNX(m.ctx, hashedSession, data, ttl).Result()
if err != nil {
logging.Error(err.Error())
return ErrKeyBackend
}
if !created {
return ErrKeyAlreadyExists
}
return nil
}
func (m *RedisStore[Value]) Create(key string, value Value) error {
return m.CreateExpiring(key, value, 0)
}
func (m *RedisStore[Value]) Get(sessionID string) (Value, error) {
hashed := m.RedisHash(sessionID)
var session_data Value
data, err := m.client.Get(m.ctx, hashed).Bytes()
if err == redis.Nil {
return session_data, ErrKeyNotFound
} else if err != nil {
logging.Error(err.Error())
return session_data, ErrKeyBackend
}
if err := json.Unmarshal(data, &session_data); err != nil {
logging.Error(err.Error())
return session_data, ErrKeyBackend
}
return session_data, nil
}
func (m *RedisStore[Value]) Update(key string, value Value) error {
hashedSession := m.RedisHash(key)
data, err := json.Marshal(value)
if err != nil {
return ErrKeyBackend
}
updated, err := m.client.SetXX(m.ctx, hashedSession, data, time.Hour).Result()
if err != nil {
logging.Error(err.Error())
return ErrKeyBackend
}
if !updated {
return ErrKeyNotFound
}
return nil
}
func (m *RedisStore[Value]) Delete(sessionID string) error {
hashedSession := m.RedisHash(sessionID)
err := m.client.Del(m.ctx, hashedSession).Err()
if err != nil {
logging.Error(err.Error())
return ErrKeyBackend
}
return nil
}
+1
View File
@@ -9,6 +9,7 @@
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 15px; gap: 15px;
overflow: hidden;
} }
.static_center { .static_center {
+3
View File
@@ -0,0 +1,3 @@
.cursor_grabbing {
cursor: grabbing;
}
+20
View File
@@ -0,0 +1,20 @@
var currentX, currentY;
document.addEventListener("mousemove", (e) => {
const rect = document.body.getBoundingClientRect();
currentX = e.clientX;
currentY = e.clientY;
});
const CURSOR_NORMAL = "cursor_normal";
const CURSOR_GRABBING = "cursor_grabbing";
document.body.classList.remove(CURSOR_NORMAL);
let current_cursor_state = CURSOR_NORMAL;
function set_cursor_state(new_cursor_state) {
document.body.classList.remove(current_cursor_state);
document.body.classList.add(new_cursor_state);
current_cursor_state = new_cursor_state;
}
@@ -0,0 +1,52 @@
const resize_photo_box = document.getElementById("resize_photo_box");
// Drag handling
var startXOffset = 0,
startYOffset = 0;
function calculateOffsets() {
const yOffset = startYOffset + (currentY - y_start);
const xOffset = startXOffset + (currentX - x_start);
var top = bitmap.height / 2 - yOffset - 175;
if (top > 0) top = 0;
var bottom = -(bitmap.height / 2) - yOffset + 10 + 175;
if (bottom < 0) bottom = 0;
var left = bitmap.width / 2 - xOffset - 175;
if (left > 0) left = 0;
var right = -(bitmap.width / 2) - xOffset + 10 + 175;
if (right < 0) right = 0;
return { x: xOffset + left + right, y: yOffset + top + bottom };
}
var mouseClicked = false;
resize_photo_box.addEventListener("mousemove", () => {
if (!mouseClicked) return;
offsets = calculateOffsets();
y_top = new_profile_image.style.setProperty("--x-offset", offsets.x + "px");
new_profile_image.style.setProperty("--y-offset", offsets.y + "px");
});
resize_photo_box.addEventListener("mousedown", () => {
x_start = currentX;
y_start = currentY;
mouseClicked = true;
set_cursor_state(CURSOR_GRABBING);
});
resize_photo_box.addEventListener("mouseup", () => {
offsets = calculateOffsets();
startXOffset = offsets.x;
startYOffset = offsets.y;
});
document.body.addEventListener("mouseup", () => {
mouseClicked = false;
set_cursor_state(CURSOR_NORMAL);
});
+74
View File
@@ -116,6 +116,10 @@
position: fixed; position: fixed;
} }
#resize_photo_dialouge {
z-index: 10000;
}
#change_password_dialogue input { #change_password_dialogue input {
width: 350px; width: 350px;
} }
@@ -149,3 +153,73 @@
border-style: solid; border-style: solid;
color: var(--text-main); color: var(--text-main);
} }
#image_container {
position: absolute;
}
#darken_part {
/*background-color: black;*/
z-index: 3;
width: 100vw;
height: 100vh;
}
#confirm_change {
z-index: 2;
}
#new_profile_image {
z-index: 1;
transform: translateX(calc(-50% + var(--x-offset)))
translateY(calc(-50% + var(--y-offset)));
position: absolute;
left: calc(350px / 2);
top: calc(350px / 2);
}
#resize_photo_box {
background-color: rgba(0, 0, 0, 0);
width: 350px;
aspect-ratio: 1 / 1;
border-style: dashed;
border-color: black;
border-width: 5px;
z-index: 4;
}
#resize_photo_box:hover {
background-color: rgba(0, 0, 0, 0);
width: 350px;
aspect-ratio: 1 / 1;
border-style: dashed;
border-color: black;
border-width: 5px;
z-index: 4;
}
.resize_anchor {
background-color: red;
width: 20px;
height: 20px;
position: absolute;
pointer-events: none;
}
#top_left_resize {
transform: translateX(-50%) translateY(-50%);
}
#top_right_resize {
transform: translateX(340px) translateY(-50%);
}
#bottom_left_resize {
transform: translateY(340px) translateX(-50%);
}
#bottom_right_resize {
transform: translateX(340px) translateY(340px);
}