Compare commits
25 Commits
a7b302b74b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 791dd3b0c4 | |||
| 3d6a853be0 | |||
| 7d1be226b6 | |||
| 65ed53c5d1 | |||
| ff5d9724d6 | |||
| 8859449be5 | |||
| f0ace2b43f | |||
| 07f78510ed | |||
| 4870318148 | |||
| c9f9f3ef6c | |||
| d82d2bba20 | |||
| 22c4666fa7 | |||
| e41a81c487 | |||
| 600c3abf20 | |||
| 4cce7b7454 | |||
| 109199ea45 | |||
| 40429d7618 | |||
| 11c40a75ac | |||
| d162c32a57 | |||
| 2a97ec72be | |||
| 09e0683ae0 | |||
| f6016bbdb1 | |||
| 3b31adf3e2 | |||
| efdf9fdade | |||
| 4474986909 |
@@ -13,7 +13,7 @@ A simple, lightweight web application for managing user profile photos in a Free
|
||||
## Prerequisites
|
||||
* **Go 1.26+** installed on your machine.
|
||||
* 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
|
||||
|
||||
|
||||
@@ -13,7 +13,12 @@
|
||||
},
|
||||
"server_config": {
|
||||
"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": {
|
||||
"username": "noreply",
|
||||
|
||||
@@ -21,9 +21,16 @@ type StyleConfig struct {
|
||||
LogoPath string `json:"logo_path"`
|
||||
}
|
||||
|
||||
type RedisConfig struct {
|
||||
RedisURL string `json:"redis_url"`
|
||||
Prefix string `json:"prefix"`
|
||||
}
|
||||
|
||||
type WebserverConfig struct {
|
||||
Port int `json:"port"`
|
||||
BaseURL string `json:"base_url"`
|
||||
SessionStore string `json:"session_store"`
|
||||
RedisConfigInfo RedisConfig `json:"redis_config"`
|
||||
}
|
||||
|
||||
type EmailConfig struct {
|
||||
|
||||
+10
-3
@@ -6,6 +6,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"astraltech.xyz/accountmanager/src/store"
|
||||
)
|
||||
|
||||
type LoginPageData struct {
|
||||
@@ -32,9 +33,15 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
logging.Infof("New Login request for %s\n", username)
|
||||
newUserData, err := authenticateUser(username, password)
|
||||
userDataMutex.Lock()
|
||||
userData[username] = newUserData
|
||||
userDataMutex.Unlock()
|
||||
|
||||
userDataErr := userData.Create(username, newUserData)
|
||||
if userDataErr == store.ErrKeyAlreadyExists {
|
||||
userData.Update(username, newUserData)
|
||||
} else if userDataErr != nil {
|
||||
logging.Error(userDataErr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err == ErrPasswordExpired {
|
||||
http.Redirect(w, r, "/reset-password?token=this_is_the_only_token_that_works", http.StatusFound)
|
||||
} else if err != nil {
|
||||
|
||||
+29
-11
@@ -7,7 +7,6 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/components"
|
||||
"astraltech.xyz/accountmanager/src/email"
|
||||
@@ -15,6 +14,7 @@ import (
|
||||
"astraltech.xyz/accountmanager/src/ldap"
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"astraltech.xyz/accountmanager/src/session"
|
||||
"astraltech.xyz/accountmanager/src/store"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -31,8 +31,7 @@ type UserData struct {
|
||||
}
|
||||
|
||||
var (
|
||||
userData = make(map[string]*UserData)
|
||||
userDataMutex sync.RWMutex
|
||||
userData store.KeyValueStore[*UserData]
|
||||
)
|
||||
|
||||
var ErrPasswordExpired = errors.New("Password expired")
|
||||
@@ -94,16 +93,22 @@ func profileHandler(w http.ResponseWriter, r *http.Request) {
|
||||
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 {
|
||||
tmpl := template.Must(template.ParseFiles("src/pages/profile_page.html"))
|
||||
userDataMutex.RLock()
|
||||
|
||||
tmpl.Execute(w, ProfileData{
|
||||
Username: sessionData.UserID,
|
||||
Email: userData[sessionData.UserID].Email,
|
||||
DisplayName: userData[sessionData.UserID].DisplayName,
|
||||
Email: data.Email,
|
||||
DisplayName: data.DisplayName,
|
||||
CSRFToken: sessionData.CSRFToken,
|
||||
})
|
||||
userDataMutex.RUnlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -198,8 +203,10 @@ func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"success": true}`))
|
||||
|
||||
user_data, err := userData.Get(sessionData.UserID)
|
||||
|
||||
data := map[string]any{
|
||||
"Username": userData[sessionData.UserID].DisplayName,
|
||||
"Username": user_data.DisplayName,
|
||||
"ServiceName": "Astral Tech",
|
||||
}
|
||||
|
||||
@@ -207,13 +214,11 @@ func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil {
|
||||
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() {
|
||||
logging.Info("Starting the server")
|
||||
sessionManager = session.GetSessionManager()
|
||||
sessionManager.SetStoreType(session.Redis)
|
||||
|
||||
var err error
|
||||
serverConfig, err = loadServerConfig("./data/config.json")
|
||||
@@ -221,6 +226,19 @@ func main() {
|
||||
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{
|
||||
Username: serverConfig.EmailConfig.Username,
|
||||
Password: serverConfig.EmailConfig.Password,
|
||||
|
||||
+60
-16
@@ -10,6 +10,7 @@
|
||||
<link rel="stylesheet" href="static/error/error.css" />
|
||||
<link rel="stylesheet" href="static/profile_page.css" />
|
||||
<link rel="stylesheet" href="static/progress_bar.css" />
|
||||
<link rel="stylesheet" href="static/cursor.css" />
|
||||
|
||||
<div id="popup_background" class="blocked hidden"></div>
|
||||
|
||||
@@ -87,20 +88,23 @@
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!--<div id="password_errors">
|
||||
<div class="password_error">Error 1</div>
|
||||
<div class="password_error">Error 2</div>
|
||||
</div>
|
||||
|
||||
<div id="password_warnings">
|
||||
<div class="password_error">Error 1</div>
|
||||
<div class="password_error">Error 2</div>
|
||||
</div>-->
|
||||
|
||||
<button id="final_change_password_button">Change Password</button>
|
||||
</div>
|
||||
|
||||
<div id="resize_photo_dialouge" class="card static_center hidden">
|
||||
<div id="image_container">
|
||||
<img id="new_profile_image" alt="new-profile-image" />
|
||||
<div id="darken_part"></div>
|
||||
</div>
|
||||
<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>
|
||||
|
||||
<img id="logo_image" alt="logo" src="/logo" />
|
||||
<div id="main_content">
|
||||
<div class="cards">
|
||||
@@ -168,28 +172,68 @@
|
||||
</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">
|
||||
const button = document.getElementById("edit_picture_button");
|
||||
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", () => {
|
||||
fileInput.click(); // opens file picker
|
||||
fileInput.click();
|
||||
});
|
||||
</script>
|
||||
|
||||
<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 () => {
|
||||
document.getElementById("popup_background").classList.remove("hidden");
|
||||
|
||||
const file = fileInput.files[0];
|
||||
file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
if (file.type !== "image/jpeg") {
|
||||
alert("Only JPEG images are allowed.");
|
||||
fileInput.value = "";
|
||||
document.getElementById("popup_background").classList.add("hidden");
|
||||
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();
|
||||
formData.append("photo", file);
|
||||
formData.append(
|
||||
@@ -211,8 +255,8 @@
|
||||
URL.revokeObjectURL(currentPreviewURL);
|
||||
}
|
||||
|
||||
img.src = URL.createObjectURL(file);
|
||||
currentPreviewURL = img.src;
|
||||
img.src = image;
|
||||
currentPreviewURL = image;
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -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")
|
||||
@@ -2,7 +2,6 @@ package session
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
@@ -16,9 +15,3 @@ func GenerateSessionToken(length int) (string, error) {
|
||||
token := base64.RawURLEncoding.EncodeToString(b)
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// more helper
|
||||
func hashSession(session_id string) string {
|
||||
tokenEncoded := sha256.Sum256([]byte(session_id))
|
||||
return base64.RawURLEncoding.EncodeToString(tokenEncoded[:])
|
||||
}
|
||||
|
||||
@@ -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 ©, 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
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import (
|
||||
"time"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"astraltech.xyz/accountmanager/src/store"
|
||||
)
|
||||
|
||||
const SessionCookieName = "session_token"
|
||||
|
||||
type SessionManager struct {
|
||||
store SessionStore
|
||||
store store.KeyValueStore[*SessionData]
|
||||
}
|
||||
|
||||
var instance *SessionManager
|
||||
@@ -31,17 +32,19 @@ func GetSessionManager() *SessionManager {
|
||||
return instance
|
||||
}
|
||||
|
||||
func (manager *SessionManager) SetStoreType(storeType StoreType) {
|
||||
func (manager *SessionManager) SetStoreType(storeType StoreType, params ...any) {
|
||||
logging.Infof("Changing session manager store type")
|
||||
switch storeType {
|
||||
case InMemory:
|
||||
{
|
||||
manager.store = NewMemoryStore()
|
||||
manager.store = store.NewMemoryStore[*SessionData]()
|
||||
break
|
||||
}
|
||||
case Redis:
|
||||
{
|
||||
manager.store = NewRedisStore()
|
||||
url, _ := params[0].(string)
|
||||
prefix, _ := params[1].(string)
|
||||
manager.store = store.NewRedisStore[*SessionData](url, prefix)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -62,7 +65,7 @@ func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie
|
||||
CSRFToken: CSRFToken,
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
}
|
||||
err = manager.store.Create(token, &newSessionData)
|
||||
err = manager.store.CreateExpiring(token, &newSessionData, time.Hour)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,10 +74,10 @@ func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie
|
||||
Name: SessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true, // Essential: prevents JS access
|
||||
Secure: true, // Set to TRUE in production (HTTPS)
|
||||
HttpOnly: true,
|
||||
Secure: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 3600, // 1 hour
|
||||
MaxAge: 3600,
|
||||
}
|
||||
return newCookie, nil
|
||||
}
|
||||
@@ -93,6 +96,12 @@ func (manager *SessionManager) GetSession(r *http.Request) (*SessionData, error)
|
||||
if err != nil {
|
||||
return nil, ErrSessionNotFound
|
||||
}
|
||||
|
||||
if time.Now().After(data.ExpiresAt) {
|
||||
_ = manager.store.Delete(token)
|
||||
return nil, ErrSessionExpired
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
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 {
|
||||
UserID string `json:"userid"`
|
||||
CSRFToken string `json:"csrftoken"`
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
@@ -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[:])
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.static_center {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.cursor_grabbing {
|
||||
cursor: grabbing;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -116,6 +116,10 @@
|
||||
position: fixed;
|
||||
}
|
||||
|
||||
#resize_photo_dialouge {
|
||||
z-index: 10000;
|
||||
}
|
||||
|
||||
#change_password_dialogue input {
|
||||
width: 350px;
|
||||
}
|
||||
@@ -149,3 +153,73 @@
|
||||
border-style: solid;
|
||||
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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user