45 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
Gregory Wells a7b302b74b redis sessions 2026-06-07 20:38:35 -04:00
Gregory Wells f8b37d9836 update session info 2026-06-07 20:36:23 -04:00
Gregory Wells 4256e5ba8a create redis session 2026-06-07 20:34:10 -04:00
Gregory Wells 5386b64648 finish session getting code 2026-06-07 20:27:42 -04:00
Gregory Wells 78d259ea3b fix crash on load from nil session info 2026-06-07 20:17:51 -04:00
Gregory Wells 1e87b8239b connect to redis session 2026-06-07 20:07:20 -04:00
Gregory Wells e1862ca8eb allow redis to be selected as session store type 2026-06-07 20:02:12 -04:00
Gregory Wells 9c984fefaf create redis session go file 2026-06-07 19:58:59 -04:00
Gregory Wells 10900093e0 log that email has sent successfully 2026-06-02 11:44:35 -04:00
Gregory Wells e151e11123 send email on successful password change 2026-06-02 11:44:17 -04:00
gawells 1ddc4daf02 bold name text 2026-04-17 08:32:53 -04:00
gawells e2fe714029 reset password page design 2026-04-16 14:53:02 -04:00
gawells 3e2541b411 add subtext modifier 2026-04-16 14:52:55 -04:00
gawells 561c33b1a9 move logo page to the master style.css file 2026-04-16 14:44:34 -04:00
gawells 33afca200d reset password page 2026-04-16 14:42:40 -04:00
gawells 812a40492f password expiry email 2026-04-16 14:23:07 -04:00
gawells 093b33db0d add more logging into the password expiry checks 2026-04-16 09:12:46 -04:00
gawells 8633309968 send password expired emails every 12 hours from the program start 2026-04-15 09:43:38 -04:00
gawells 093b258b84 expried password email template 2026-04-13 10:24:12 -04:00
gawells 5a80d61d9b remove old comment 2026-04-13 09:40:24 -04:00
32 changed files with 1009 additions and 261 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",
@@ -0,0 +1,69 @@
<!doctype html>
<html>
<head>
<!-- Tell iOS we support light mode -->
<meta name="color-scheme" content="light" />
<meta name="supported-color-schemes" content="light" />
</head>
<body
style="margin: 0; padding: 0; background-color: #f7fff7; color: #000000"
>
<table
width="100%"
cellpadding="0"
cellspacing="0"
border="0"
style="background-color: #f7fff7"
>
<tr>
<td align="center">
<!-- Outer container -->
<table
width="600"
cellpadding="0"
cellspacing="0"
border="0"
style="
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
margin-top: 25px;
"
>
<tr>
<td
style="
padding: 30px;
font-family: Arial, sans-serif;
color: #000000;
"
>
<p style="margin: 0 0 15px 0">
Hi <strong>{{.Username}}</strong>,
</p>
<p style="margin: 0 0 15px 0">
Your account password has been successfully
changed. If you made this change, you can
safely disregard this email.
</p>
<p style="margin: 20px 0 15px 0">
If you did not change your password, please
contact your system administrator
immediately to secure your account.
</p>
<p style="margin: 0">
Thanks,<br />
<strong>{{.ServiceName}}</strong>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
+106 -19
View File
@@ -1,25 +1,112 @@
<!doctype html> <!doctype html>
<html lang="en"> <html>
<head> <head>
<meta charset="UTF-8" /> <!-- Tell iOS we support light mode -->
<title>Hi</title> <meta name="color-scheme" content="light" />
<style> <meta name="supported-color-schemes" content="light" />
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
img {
margin-top: 20px;
width: 150px;
height: 150px;
border-radius: 50%;
}
</style>
</head> </head>
<body>
<h1>Hi {{.Username}}</h1>
<img src="{{avatar .Username}}" alt="Profile Picture" /> <body
style="margin: 0; padding: 0; background-color: #f7fff7; color: #000000"
>
<table
width="100%"
cellpadding="0"
cellspacing="0"
border="0"
style="background-color: #f7fff7"
>
<tr>
<td align="center">
<!-- Outer container -->
<table
width="600"
cellpadding="0"
cellspacing="0"
border="0"
style="
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 12px;
margin-top: 25px;
"
>
<tr>
<td
style="
padding: 30px;
font-family: Arial, sans-serif;
color: #000000;
"
>
<p style="margin: 0 0 15px 0">
Hi <strong>{{.Username}}</strong>,
</p>
<p style="margin: 0 0 15px 0">
Your account password has expired and needs
to be updated to continue accessing your
account.
</p>
<p style="margin: 0 0 15px 0">
<strong>Expiration Date:</strong><br />
{{.ExpiredAt}}
</p>
<p style="margin: 0 0 20px 0">
For security reasons, passwords must be
updated periodically. Please reset your
password as soon as possible.
</p>
<!-- Button -->
<table
align="center"
cellpadding="0"
cellspacing="0"
border="0"
>
<tr>
<td
bgcolor="#1a535c"
style="border-radius: 6px"
>
<a
href="{{.ResetURL}}"
style="
display: inline-block;
padding: 12px 20px;
font-weight: bold;
font-family:
Arial, sans-serif;
color: #ffffff;
text-decoration: none;
background-color: #1a535c;
border-radius: 6px;
-webkit-text-fill-color: #ffffff;
"
>
Reset Password
</a>
</td>
</tr>
</table>
<p style="margin: 20px 0 15px 0">
If you did not expect this, please contact
your system administrator.
</p>
<p style="margin: 0">
Thanks,<br />
<strong>{{.ServiceName}}</strong>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body> </body>
</html> </html>
+3
View File
@@ -6,7 +6,10 @@ require github.com/go-ldap/ldap/v3 v3.4.13
require ( require (
github.com/Azure/go-ntlmssp v0.1.0 // indirect github.com/Azure/go-ntlmssp v0.1.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
github.com/google/uuid v1.6.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/redis/go-redis/v9 v9.20.0 // indirect
go.uber.org/atomic v1.11.0 // indirect
golang.org/x/crypto v0.48.0 // indirect golang.org/x/crypto v0.48.0 // indirect
) )
+6
View File
@@ -2,6 +2,8 @@ github.com/Azure/go-ntlmssp v0.1.0 h1:DjFo6YtWzNqNvQdrwEyr/e4nhU3vRiwenz5QX7sFz+
github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI= github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI=
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo= github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 h1:BP4M0CvQ4S3TGls2FvczZtj5Re/2ZzkV9VwqPHH/3Bo=
@@ -30,8 +32,12 @@ github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZ
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.20.0 h1:WnQYxLkgO2xiXTCJY0ldIiI8dNqCDlQAG+AtaH7a2a0=
github.com/redis/go-redis/v9 v9.20.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60= golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
+4 -2
View File
@@ -33,9 +33,9 @@ func CreateEmailAccount(accountData EmailAccountData, smtpHost string, smtpPort
} }
func (account *EmailAccount) SendEmail(toEmails []string, subject string, message string) { func (account *EmailAccount) SendEmail(toEmails []string, subject string, message string) {
logging.Debugf("Sending an email from %s to %s", account.email, strings.Join(toEmails, "")) logging.Debugf("Sending an email from %s to %s", account.email, strings.Join(toEmails, ", "))
ToEmailList := strings.Join(toEmails, "") ToEmailList := strings.Join(toEmails, ", ")
mime := "MIME-version: 1.0;\r\nContent-Type: text/html; charset=\"UTF-8\";\r\n\r\n" mime := "MIME-version: 1.0;\r\nContent-Type: text/html; charset=\"UTF-8\";\r\n\r\n"
@@ -51,5 +51,7 @@ func (account *EmailAccount) SendEmail(toEmails []string, subject string, messag
if err != nil { if err != nil {
logging.Error("Failed to send email") logging.Error("Failed to send email")
logging.Error(err.Error()) logging.Error(err.Error())
return
} }
logging.Info("Successfully sent email")
} }
+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 {
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"html/template"
"net/http"
"strings"
"astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/store"
)
type LoginPageData struct {
IsHiddenClassList string
}
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
}
if r.Method == http.MethodPost {
username := r.FormValue("username")
if strings.Contains(username, "/") {
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
}
password := r.FormValue("password")
logging.Infof("New Login request for %s\n", username)
newUserData, err := authenticateUser(username, password)
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 {
logging.Error(err.Error())
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
} else {
if newUserData.isAuth == true {
cookie, err := sessionManager.CreateSession(username)
if err != nil {
logging.Error(err.Error())
http.Error(w, "Session error", http.StatusInternalServerError)
return
}
http.SetCookie(w, cookie)
http.Redirect(w, r, "/profile", http.StatusFound)
} else {
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
}
}
}
}
+47 -74
View File
@@ -1,13 +1,12 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"net/url"
"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,16 +31,20 @@ type UserData struct {
} }
var ( var (
userData = make(map[string]*UserData) userData store.KeyValueStore[*UserData]
userDataMutex sync.RWMutex
) )
var ErrPasswordExpired = errors.New("Password expired")
func authenticateUser(username, password string) (*UserData, error) { func authenticateUser(username, password string) (*UserData, error) {
logging.Event(logging.AuthenticateUser, username) logging.Event(logging.AuthenticateUser, username)
userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", username, serverConfig.LDAPConfig.BaseDN) userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", username, serverConfig.LDAPConfig.BaseDN)
connected, err := ldapServer.AuthenticateUser(userDN, password) connected, err := ldapServer.AuthenticateUser(userDN, password)
if err != nil { if err != nil {
if strings.Contains(err.Error(), "Password is expired") {
return nil, ErrPasswordExpired
}
return nil, err return nil, err
} }
if connected == false { if connected == false {
@@ -73,54 +77,6 @@ func authenticateUser(username, password string) (*UserData, error) {
return &user, nil return &user, nil
} }
type LoginPageData struct {
IsHiddenClassList string
}
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
}
// 2. Logic for processing the form
if r.Method == http.MethodPost {
username := r.FormValue("username")
if strings.Contains(username, "/") {
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
}
password := r.FormValue("password")
logging.Infof("New Login request for %s\n", username)
newUserData, err := authenticateUser(username, password)
userDataMutex.Lock()
userData[username] = newUserData
userDataMutex.Unlock()
if err != nil {
logging.Error(err.Error())
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
} else {
if newUserData.isAuth == true {
cookie, err := sessionManager.CreateSession(username)
if err != nil {
logging.Error(err.Error())
http.Error(w, "Session error", http.StatusInternalServerError)
return
}
http.SetCookie(w, cookie)
http.Redirect(w, r, "/profile", http.StatusFound)
} else {
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
}
}
}
}
type ProfileData struct { type ProfileData struct {
Username string Username string
Email string Email string
@@ -137,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
} }
} }
@@ -240,12 +202,23 @@ 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{
"Username": user_data.DisplayName,
"ServiceName": "Astral Tech",
}
email_template, err := email.RenderTemplate("./data/email-templates/changed-password.html", data, nil)
if err != nil {
logging.Errorf("Failed to load email template: %s", err.Error())
}
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.InMemory)
var err error var err error
serverConfig, err = loadServerConfig("./data/config.json") serverConfig, err = loadServerConfig("./data/config.json")
@@ -253,28 +226,25 @@ 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,
Email: serverConfig.EmailConfig.Email, Email: serverConfig.EmailConfig.Email,
}, serverConfig.EmailConfig.SMTPURL, serverConfig.EmailConfig.SMTPPort) }, serverConfig.EmailConfig.SMTPURL, serverConfig.EmailConfig.SMTPPort)
funcs := template.FuncMap{
"avatar": func(username string) string {
return serverConfig.WebserverConfig.BaseURL + "/avatar?user=" + url.QueryEscape(username)
},
}
data := map[string]any{
"Username": "gawells",
}
email_template, err := email.RenderTemplate("./data/email-templates/expired-password.html", data, funcs)
if err != nil {
logging.Errorf("Failed to load email template: %s", err.Error())
}
noReplyEmail.SendEmail([]string{"gawells@astraltech.xyz"}, "Test", email_template)
ldapServer = ldap.LDAPServer{ ldapServer = ldap.LDAPServer{
URL: serverConfig.LDAPConfig.LDAPURL, URL: serverConfig.LDAPConfig.LDAPURL,
StartTLS: serverConfig.LDAPConfig.Security == "tls", StartTLS: serverConfig.LDAPConfig.Security == "tls",
@@ -294,6 +264,8 @@ func main() {
logging.Fatal("Failed to connect to LDAP server") logging.Fatal("Failed to connect to LDAP server")
} }
InitPasswordExpiry()
helpers.HandleFunc("/favicon.ico", faviconHandler) helpers.HandleFunc("/favicon.ico", faviconHandler)
helpers.HandleFunc("/logo", logoHandler) helpers.HandleFunc("/logo", logoHandler)
@@ -301,6 +273,7 @@ func main() {
helpers.HandleFunc("/login", loginHandler) helpers.HandleFunc("/login", loginHandler)
helpers.HandleFunc("/profile", profileHandler) helpers.HandleFunc("/profile", profileHandler)
helpers.HandleFunc("/logout", logoutHandler) helpers.HandleFunc("/logout", logoutHandler)
helpers.HandleFunc("/reset-password", resetPasswordHandler)
helpers.HandleFunc("/avatar", components.AvatarHandler) helpers.HandleFunc("/avatar", components.AvatarHandler)
helpers.HandleFunc("/change-photo", components.UploadPhotoHandler) helpers.HandleFunc("/change-photo", components.UploadPhotoHandler)
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"fmt"
"time"
"astraltech.xyz/accountmanager/src/email"
"astraltech.xyz/accountmanager/src/logging"
"astraltech.xyz/accountmanager/src/worker"
)
func InitPasswordExpiry() {
go func() {
CheckPasswordExpriy()
}()
worker.CreateWorker(time.Hour*12, CheckPasswordExpriy)
}
func CheckPasswordExpriy() {
logging.Infof("Starting password expiry check")
now := time.Now().UTC()
formatted := now.Format("20060102150405Z")
search, err := ldapServer.SerchServer(serverConfig.LDAPConfig.BindDN, serverConfig.LDAPConfig.BindPassword, serverConfig.LDAPConfig.BaseDN, fmt.Sprintf("(&(objectclass=person)(krbPasswordExpiration<=%s))", formatted), []string{"cn", "mail", "krbPasswordExpiration"})
if err != nil {
logging.Warn(err.Error())
}
logging.Infof("%d users with expired passwords", search.EntryCount())
for i := range search.EntryCount() {
emailAddr := search.GetEntry(i).GetAttributeValue("mail")
if len(emailAddr) <= 0 {
continue
}
t, err := time.Parse("20060102150405Z", search.GetEntry(i).GetAttributeValue("krbPasswordExpiration"))
if err != nil {
panic(err)
}
formatted := t.Format("January 2, 2006 at 3:04 PM MST")
data := map[string]any{
"Username": search.GetEntry(i).GetAttributeValue("cn"),
"ExpiredAt": formatted,
"ResetURL": fmt.Sprintf("%s", serverConfig.WebserverConfig.BaseURL),
"ServiceName": "Astral Tech",
}
email_template, err := email.RenderTemplate("./data/email-templates/expired-password.html", data, nil)
if err != nil {
logging.Errorf("Failed to load email template: %s", err.Error())
}
noReplyEmail.SendEmail([]string{emailAddr}, "Password expired", email_template)
}
}
+21
View File
@@ -0,0 +1,21 @@
package main
import (
"html/template"
"net/http"
"astraltech.xyz/accountmanager/src/logging"
)
func resetPasswordHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
token := r.URL.Query().Get("token")
logging.Infof("Token: %s\n", token)
tmpl := template.Must(template.ParseFiles("src/pages/reset_password.html"))
if r.Method == http.MethodGet {
tmpl.Execute(w, nil)
return
}
}
+60 -16
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,20 +88,23 @@
></div> ></div>
</div> </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> <button id="final_change_password_button">Change Password</button>
</div> </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" /> <img id="logo_image" alt="logo" src="/logo" />
<div id="main_content"> <div id="main_content">
<div class="cards"> <div class="cards">
@@ -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>
+44
View File
@@ -0,0 +1,44 @@
<!doctype html>
<title>Astral Tech - Reset Password</title>
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="static/style.css" />
<link rel="stylesheet" href="static/error/error.css" />
<link rel="stylesheet" href="static/card.css" />
<link rel="stylesheet" href="static/reset_password.css" />
<img id="logo_image" alt="logo" src="/logo" />
<div id="reset_password_card" class="card static_center">
<div>
<div>
Welcome
<b>{{.Name}}</b>
</div>
<div class="subtext">
Your password needs to be reset, please enter your new password
below
</div>
</div>
<div>
<label class="input_label">New password</label><br />
<div class="password_box">
<input type="password" name="password" placeholder="" required />
<button type="button" class="show_password_toggle closed"></button>
</div>
</div>
<div>
<label class="input_label">New password (repeated)</label><br />
<div class="password_box">
<input type="password" name="password" placeholder="" required />
<button type="button" class="show_password_toggle closed"></button>
</div>
</div>
<button>Reset Password</button>
</div>
-7
View File
@@ -1,7 +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")
-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
}
+22 -7
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
@@ -21,6 +22,7 @@ type StoreType int
const ( const (
InMemory StoreType = iota InMemory StoreType = iota
Redis
) )
func GetSessionManager() *SessionManager { func GetSessionManager() *SessionManager {
@@ -30,12 +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
}
case Redis:
{
url, _ := params[0].(string)
prefix, _ := params[1].(string)
manager.store = store.NewRedisStore[*SessionData](url, prefix)
break break
} }
} }
@@ -56,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
} }
@@ -65,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
} }
@@ -87,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
} }
+12 -11
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 UserID string `json:"userid"`
CSRFToken string CSRFToken string `json:"csrftoken"`
ExpiresAt time.Time 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
}
+2 -6
View File
@@ -1,10 +1,5 @@
.card { .card {
background: rgba( background: rgba(255, 255, 255, 1);
255,
255,
255,
1
); /* Semi-transparent white for light theme */
border: 1px solid var(--border-subtle); border: 1px solid var(--border-subtle);
border-radius: 12px; border-radius: 12px;
padding: 2.5rem; padding: 2.5rem;
@@ -14,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);
});
-7
View File
@@ -1,10 +1,3 @@
#logo_image {
position: fixed;
width: 300px;
left: 50%;
transform: translateX(-50%);
}
#login_card { #login_card {
position: fixed; position: fixed;
top: 50%; top: 50%;
+74 -7
View File
@@ -1,10 +1,3 @@
#logo_image {
position: fixed;
width: 300px;
left: 50%;
transform: translateX(-50%);
}
#main_content { #main_content {
position: fixed; position: fixed;
top: 100px; top: 100px;
@@ -123,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;
} }
@@ -156,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);
}
+7
View File
@@ -0,0 +1,7 @@
#reset_password_card {
width: 350px;
}
#reset_password_card input {
width: 324px;
}
+11
View File
@@ -129,3 +129,14 @@ input::placeholder {
.show_password_toggle:focus { .show_password_toggle:focus {
outline: none !important; outline: none !important;
} }
#logo_image {
position: fixed;
width: 300px;
left: 50%;
transform: translateX(-50%);
}
.subtext {
color: var(--text-muted);
}