42 Commits

Author SHA1 Message Date
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
gawells 6a985c1a84 send simple test email to my email on server startup 2026-04-13 09:32:22 -04:00
gawells 590ea73a92 send all emails as HTML 2026-04-13 09:22:57 -04:00
gawells 8de145adbc add email config to config file 2026-04-13 09:19:35 -04:00
gawells 8f0291bb8a make small changes to the email package 2026-04-13 09:13:49 -04:00
gawells cde41b82b2 base URL param for config 2026-04-09 16:45:02 -04:00
gawells 37c6978d1b move all files to images folder 2026-04-08 10:18:07 -04:00
gawells 9389df28e4 add show password buttons to all password inputs 2026-04-08 10:17:01 -04:00
gawells b94bc612c3 implement logic for a show password button 2026-04-08 10:14:33 -04:00
gawells 25e61c553f hide the warnings because I dont like the UI 2026-04-07 12:36:17 -04:00
gawells a31d21456c warnings box 2026-04-06 18:56:58 -04:00
gawells a1f58e817e build sample error box 2026-04-06 18:49:01 -04:00
gawells 387bd2d0ae Update README.md 2026-04-06 18:41:30 -04:00
gawells 0ab1e95690 blur background when changing password 2026-04-06 18:15:07 -04:00
gawells d7727e9b0d remove block 2026-04-06 16:14:43 -04:00
gawells 72dfaf5da1 reset password boxes on close 2026-04-06 16:14:11 -04:00
gawells 5e0771d482 add a couple stylistic changes to the password dialouge 2026-04-06 16:02:34 -04:00
gawells b9ed00c127 password strength meter 2026-04-06 15:48:27 -04:00
gawells 8b74cab34e move password changing to seperate file 2026-04-06 11:50:40 -04:00
gawells dbb91fac62 add in simple password progress bar 2026-04-06 11:48:31 -04:00
gawells 8cb1fff36b password strength function 2026-04-06 11:46:49 -04:00
gawells d0524f901c bug where a users profile photo would not display if the user had not
logged in
2026-04-06 09:30:15 -04:00
gawells 384ef90ea8 move errors to a different file 2026-04-05 11:37:00 -04:00
36 changed files with 1032 additions and 246 deletions
+10 -15
View File
@@ -6,20 +6,20 @@ A simple, lightweight web application for managing user profile photos in a Free
* **LDAP Authentication**: Secure login with existing FreeIPA credentials. * **LDAP Authentication**: Secure login with existing FreeIPA credentials.
* **Profile Management**: View user details (Display Name, Email). * **Profile Management**: View user details (Display Name, Email).
* **Photo Upload**: Users can upload and update their profile picture (`jpegPhoto` attribute). * **Photo Upload**: Users can upload and update their profile picture (`jpegPhoto` attribute).
* **Change Password**: Users can change there password once logged in
* **Session Management**: Secure, cookie-based sessions with CSRF protection. * **Session Management**: Secure, cookie-based sessions with CSRF protection.
* **Customizable**: Configurable styling (logo, favicon) and LDAP settings. * **Customizable**: Configurable styling (logo, favicon) and LDAP settings.
## Prerequisites ## Prerequisites
* **Go 1.26+** installed on your machine.
* **Go 1.20+** installed on your machine. * Access to a **FreeIPA Server**.
* Access to an **FreeIPA Server**. * A Service Account with permission to search and modify the `jpegPhoto` attribute.
* A Service Account (Bind DN) with permission to search users and modify the `jpegPhoto` attribute.
## Setup & Installation ## Setup & Installation
1. **Clone the Repository** 1. **Clone the Repository**
```bash ```bash
git clone https://git.astraltech.xyz/gawells/Self-Service-Dashboard git clone https://git.astraltech.xyz/gawells/Self-Service-Dashboard.git
cd Self-Service-Dashboard cd Self-Service-Dashboard
``` ```
@@ -30,7 +30,10 @@ A simple, lightweight web application for managing user profile photos in a Free
``` ```
5. **Edit config** 5. **Edit config**
put in your config values for ldap, and whatevery styling guidelines you would want to use Edit the config file
```bash
nvim data/config.json
```
4. **Install Dependencies** 4. **Install Dependencies**
```bash ```bash
@@ -41,15 +44,7 @@ A simple, lightweight web application for managing user profile photos in a Free
```bash ```bash
go run ./src/main/ go run ./src/main/
``` ```
The application will be available at `http://<host>:<port>`. The application will be available at `http://localhost:<port>`.
## Directory Structure
* `src/`: Go source code (`main.go`, `ldap.go`, `session.go`, etc.).
* `src/pages/`: HTML templates for login and profile pages.
* `static/`: CSS files, images, and other static assets.
* `data/`: Configuration files and local assets (logos).
* `avatars/`: Stores cached user profile photos.
## License ## License
+9 -1
View File
@@ -12,6 +12,14 @@
"logo_path": "./data/astraltech_logo_large.png" "logo_path": "./data/astraltech_logo_large.png"
}, },
"server_config": { "server_config": {
"port": 8080 "port": 8080,
"base_url": "https://profile.example.com"
},
"email_config": {
"username": "noreply",
"email": "noreply@example.com",
"password": "",
"smtp_url": "mx.example.com",
"smtp_port": 587
} }
} }
@@ -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>
+112
View File
@@ -0,0 +1,112 @@
<!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 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>
</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=
+30 -11
View File
@@ -33,7 +33,7 @@ var (
) )
func ReadBlankPhoto() { func ReadBlankPhoto() {
blank, err := helpers.ReadFile("static/blank_profile.jpg") blank, err := helpers.ReadFile("static/images/blank_profile.jpg")
if err != nil { if err != nil {
logging.Fatal("Could not load blank profile image") logging.Fatal("Could not load blank profile image")
} }
@@ -98,7 +98,11 @@ func UploadPhotoHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", sessionData.UserID, BaseDN) userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", sessionData.UserID, BaseDN)
LDAPServer.ModifyAttribute(ServiceUserBindDN, ServiceUserPassword, userDN, "jpegphoto", []string{string(data)}) err = LDAPServer.ModifyAttribute(ServiceUserBindDN, ServiceUserPassword, userDN, "jpegphoto", []string{string(data)})
if err != nil {
logging.Error(err.Error())
return
}
CreateUserPhoto(sessionData.UserID, data) CreateUserPhoto(sessionData.UserID, data)
} }
@@ -112,17 +116,25 @@ func AvatarHandler(w http.ResponseWriter, r *http.Request) {
filePath := fmt.Sprintf("./avatars/%s.jpeg", username) filePath := fmt.Sprintf("./avatars/%s.jpeg", username)
cleaned := filepath.Clean(filePath) cleaned := filepath.Clean(filePath)
value, err := helpers.ReadFile(cleaned) fileExist, err := helpers.DoesFileExist(cleaned)
if err != nil {
if err == nil { w.Write(blankPhotoData)
photoCreatedMutex.Lock() logging.Error(err.Error())
if time.Since(photoCreatedTimestamp[username]) <= 5*time.Minute { return
photoCreatedMutex.Unlock() }
w.Write(value) photoCreatedMutex.Lock()
if fileExist && time.Since(photoCreatedTimestamp[username]) <= 5*time.Minute {
photoCreatedMutex.Unlock()
val, err := helpers.ReadFile(cleaned)
if err != nil {
logging.Error(err.Error())
w.Write(blankPhotoData)
return return
} }
photoCreatedMutex.Unlock() w.Write(val)
return
} }
photoCreatedMutex.Unlock()
userSearch, err := LDAPServer.SerchServer( userSearch, err := LDAPServer.SerchServer(
ServiceUserBindDN, ServiceUserPassword, ServiceUserBindDN, ServiceUserPassword,
@@ -130,10 +142,16 @@ func AvatarHandler(w http.ResponseWriter, r *http.Request) {
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldap.LDAPEscapeFilter(username)), fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldap.LDAPEscapeFilter(username)),
[]string{"jpegphoto"}, []string{"jpegphoto"},
) )
if err == nil || userSearch.EntryCount() == 0 { if err != nil {
logging.Error(err.Error())
w.Write(blankPhotoData) w.Write(blankPhotoData)
return return
} }
if userSearch.EntryCount() == 0 {
w.Write(blankPhotoData)
return
}
entry := userSearch.GetEntry(0) entry := userSearch.GetEntry(0)
bytes := entry.GetRawAttributeValue("jpegphoto") bytes := entry.GetRawAttributeValue("jpegphoto")
if len(bytes) == 0 { if len(bytes) == 0 {
@@ -142,5 +160,6 @@ func AvatarHandler(w http.ResponseWriter, r *http.Request) {
} else { } else {
w.Write(bytes) w.Write(bytes)
CreateUserPhoto(username, bytes) CreateUserPhoto(username, bytes)
return
} }
} }
+16 -11
View File
@@ -16,37 +16,42 @@ type EmailAccount struct {
} }
type EmailAccountData struct { type EmailAccountData struct {
username string Username string
password string Password string
email string Email string
} }
func createEmailAccount(accountData EmailAccountData, smtpHost string, smtpPort int) EmailAccount { func CreateEmailAccount(accountData EmailAccountData, smtpHost string, smtpPort int) EmailAccount {
logging.Debugf("Creating Email Account: \n\tUsername: %s\n\tEmail: %s\n\tSMTP Host: %s:%d", accountData.username, accountData.email, smtpHost, smtpPort) logging.Debugf("Creating Email Account: \n\tUsername: %s\n\tEmail: %s\n\tSMTP Host: %s:%d", accountData.Username, accountData.Email, smtpHost, smtpPort)
account := EmailAccount{ account := EmailAccount{
email: accountData.email, email: accountData.Email,
smtpHost: smtpHost, smtpHost: smtpHost,
smtpPort: strconv.Itoa(smtpPort), smtpPort: strconv.Itoa(smtpPort),
} }
account.auth = smtp.PlainAuth("", accountData.username, accountData.password, smtpHost) account.auth = smtp.PlainAuth("", accountData.Username, accountData.Password, smtpHost)
return account return account
} }
func sendEmail(account EmailAccount, toEmail []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(toEmail, "")) logging.Debugf("Sending an email from %s to %s", account.email, strings.Join(toEmails, ", "))
ToEmailList := strings.Join(toEmail, "") ToEmailList := strings.Join(toEmails, ", ")
mime := "MIME-version: 1.0;\r\nContent-Type: text/html; charset=\"UTF-8\";\r\n\r\n"
messageData := []byte( messageData := []byte(
"From: " + account.email + "\r\n" + "From: " + account.email + "\r\n" +
"To: " + ToEmailList + "\r\n" + "To: " + ToEmailList + "\r\n" +
"Subject: " + subject + "\r\n" + "Subject: " + subject + "\r\n" +
mime +
"\r\n" + "\r\n" +
message, message,
) )
err := smtp.SendMail(account.smtpHost+":"+account.smtpPort, account.auth, account.email, toEmail, messageData) err := smtp.SendMail(account.smtpHost+":"+account.smtpPort, account.auth, account.email, toEmails, messageData)
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")
} }
+28
View File
@@ -0,0 +1,28 @@
package email
import (
"bytes"
"path/filepath"
"text/template"
)
func RenderTemplate(path string, data any, funcMap template.FuncMap) (string, error) {
tmpl := template.New("")
if funcMap != nil {
tmpl = tmpl.Funcs(funcMap)
}
tmpl, err := tmpl.ParseFiles(path)
if err != nil {
return "", err
}
var buf bytes.Buffer
err = tmpl.ExecuteTemplate(&buf, filepath.Base(path), data)
if err != nil {
return "", err
}
return buf.String(), nil
}
+11
View File
@@ -52,6 +52,17 @@ func CreateFile(path string) (*os.File, error) {
return file, nil return file, nil
} }
func DoesFileExist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) { func HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) {
logging.Infof("Handling %s", path) logging.Infof("Handling %s", path)
http.HandleFunc(path, handler) http.HandleFunc(path, handler)
+11 -1
View File
@@ -22,13 +22,23 @@ type StyleConfig struct {
} }
type WebserverConfig struct { type WebserverConfig struct {
Port int `json:"port"` Port int `json:"port"`
BaseURL string `json:"base_url"`
}
type EmailConfig struct {
Username string `json:"username"`
Email string `json:"email"`
Password string `json:"password"`
SMTPURL string `json:"smtp_url"`
SMTPPort int `json:"smtp_port"`
} }
type ServerConfig struct { type ServerConfig struct {
LDAPConfig LDAPConfig `json:"ldap_config"` LDAPConfig LDAPConfig `json:"ldap_config"`
StyleConfig StyleConfig `json:"style_config"` StyleConfig StyleConfig `json:"style_config"`
WebserverConfig WebserverConfig `json:"server_config"` WebserverConfig WebserverConfig `json:"server_config"`
EmailConfig EmailConfig `json:"email_config"`
} }
func loadServerConfig(path string) (*ServerConfig, error) { func loadServerConfig(path string) (*ServerConfig, error) {
+58
View File
@@ -0,0 +1,58 @@
package main
import (
"html/template"
"net/http"
"strings"
"astraltech.xyz/accountmanager/src/logging"
)
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)
userDataMutex.Lock()
userData[username] = newUserData
userDataMutex.Unlock()
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: ""})
}
}
}
}
+29 -49
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"errors"
"fmt" "fmt"
"html/template" "html/template"
"log" "log"
@@ -9,6 +10,7 @@ import (
"sync" "sync"
"astraltech.xyz/accountmanager/src/components" "astraltech.xyz/accountmanager/src/components"
"astraltech.xyz/accountmanager/src/email"
"astraltech.xyz/accountmanager/src/helpers" "astraltech.xyz/accountmanager/src/helpers"
"astraltech.xyz/accountmanager/src/ldap" "astraltech.xyz/accountmanager/src/ldap"
"astraltech.xyz/accountmanager/src/logging" "astraltech.xyz/accountmanager/src/logging"
@@ -19,6 +21,7 @@ var (
ldapServer ldap.LDAPServer ldapServer ldap.LDAPServer
serverConfig *ServerConfig serverConfig *ServerConfig
sessionManager *session.SessionManager sessionManager *session.SessionManager
noReplyEmail email.EmailAccount
) )
type UserData struct { type UserData struct {
@@ -32,12 +35,17 @@ var (
userDataMutex sync.RWMutex 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 {
@@ -70,54 +78,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
@@ -237,12 +197,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}`))
data := map[string]any{
"Username": userData[sessionData.UserID].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{userData[sessionData.UserID].Email}, "Password expired", email_template)
} }
func main() { func main() {
logging.Info("Starting the server") logging.Info("Starting the server")
sessionManager = session.GetSessionManager() sessionManager = session.GetSessionManager()
sessionManager.SetStoreType(session.InMemory) sessionManager.SetStoreType(session.Redis)
var err error var err error
serverConfig, err = loadServerConfig("./data/config.json") serverConfig, err = loadServerConfig("./data/config.json")
@@ -250,6 +221,12 @@ func main() {
log.Fatal("Could not load server config") log.Fatal("Could not load server config")
} }
noReplyEmail = email.CreateEmailAccount(email.EmailAccountData{
Username: serverConfig.EmailConfig.Username,
Password: serverConfig.EmailConfig.Password,
Email: serverConfig.EmailConfig.Email,
}, serverConfig.EmailConfig.SMTPURL, serverConfig.EmailConfig.SMTPPort)
ldapServer = ldap.LDAPServer{ ldapServer = ldap.LDAPServer{
URL: serverConfig.LDAPConfig.LDAPURL, URL: serverConfig.LDAPConfig.LDAPURL,
StartTLS: serverConfig.LDAPConfig.Security == "tls", StartTLS: serverConfig.LDAPConfig.Security == "tls",
@@ -269,6 +246,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)
@@ -276,6 +255,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
}
}
+8 -1
View File
@@ -28,9 +28,16 @@
<div> <div>
<label class="input_label">Password</label><br /> <label class="input_label">Password</label><br />
<input type="password" name="password" placeholder="" required /> <div class="password_box">
<input type="password" name="password" placeholder="" required />
<button type="button" class="show_password_toggle closed"></button>
</div>
</div> </div>
<button type="submit">Login</button> <button type="submit">Login</button>
</form> </form>
<script src="/static/error/error.js" type="text/javascript"></script> <script src="/static/error/error.js" type="text/javascript"></script>
<script
src="/static/javascript/show_password.js"
type="text/javascript"
></script>
+79 -126
View File
@@ -9,14 +9,24 @@
<link rel="stylesheet" href="static/card.css" /> <link rel="stylesheet" href="static/card.css" />
<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" />
<div id="popup_background" class="blocked hidden"></div> <div id="popup_background" class="blocked hidden"></div>
<div id="change_password_dialogue" class="hidden card static_center"> <div id="change_password_dialogue" class="card static_center hidden">
Change Password <div class="dialouge_title">Change Password</div>
<button id="close_password_dialogue">X</button> <button id="close_password_dialogue">X</button>
<hr
style="
border: 0;
border-top: 1px solid var(--border-subtle);
margin: 20px 0;
margin-bottom: 0px;
margin-top: 0px;
"
/>
<div id="password_error" class="error hidden"> <div id="password_error" class="error hidden">
<div id="password_text"></div> <div id="password_text"></div>
<button id="password_error_close_button" class="close_error_button"> <button id="password_error_close_button" class="close_error_button">
@@ -26,37 +36,68 @@
<div> <div>
<label class="input_label">Current password</label><br /> <label class="input_label">Current password</label><br />
<input <div class="password_box">
type="password" <input
id="current_password" type="password"
name="current_password" id="current_password"
placeholder="" name="current_password"
required placeholder=""
/> required
/>
<button type="button" class="show_password_toggle closed"></button>
</div>
</div> </div>
<div> <div>
<label class="input_label">New password</label><br /> <label class="input_label">New password</label><br />
<input <div class="password_box">
type="password" <input
id="new_password" type="password"
name="new_password" id="new_password"
placeholder="" name="new_password"
required placeholder=""
/> required
/>
<button type="button" class="show_password_toggle closed"></button>
</div>
</div> </div>
<div> <div>
<label class="input_label">New password (repeat)</label><br /> <label class="input_label">New password (repeat)</label><br />
<input <div class="password_box">
type="password" <input
id="new_password_repeat" type="password"
name="new_password_repeat" id="new_password_repeat"
placeholder="" name="new_password_repeat"
required placeholder=""
/> required
/>
<button type="button" class="show_password_toggle closed"></button>
</div>
</div> </div>
<div>
<label class="input_label" id="strengh-label">Strength: Weak</label
><br />
<div class="progress-bar">
<div
class="progress-bar-progress"
id="password-progress"
style="width: 0%"
></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>
@@ -80,7 +121,7 @@
<button id="edit_picture_button"> <button id="edit_picture_button">
<img <img
src="/static/crayon_icon.png" src="/static/images/crayon_icon.png"
id="edit_picture_image" id="edit_picture_image"
/> />
</button> </button>
@@ -136,96 +177,6 @@
}); });
</script> </script>
<script type="text/javascript">
const popup_botton = document.getElementById("change_password_button");
popup_botton.addEventListener("click", () => {
document.getElementById("popup_background").classList.remove("hidden");
document
.getElementById("change_password_dialogue")
.classList.remove("hidden");
});
</script>
<script type="text/javascript">
const changePasswordButton = document.getElementById(
"final_change_password_button",
);
function displayError(errorText) {
document.getElementById("password_error").classList.remove("hidden");
document.getElementById("password_text").innerText =
"⚠️ " + errorText + ".";
return;
}
changePasswordButton.addEventListener("click", () => {
if (document.getElementById("current_password").value === "") {
displayError("Please enter current password");
return;
}
if (document.getElementById("new_password").value === "") {
displayError("No value for new password");
return;
}
if (document.getElementById("new_password_repeat").value === "") {
displayError("Please repeat new password");
return;
}
if (
document.getElementById("new_password").value !==
document.getElementById("new_password_repeat").value
) {
displayError("New password and new password repeat do not match");
return;
}
const formData = new FormData();
formData.append(
"csrf_token",
document.getElementById("csrf_token_storage").value,
);
formData.append(
"old_password",
document.getElementById("current_password").value,
);
formData.append(
"new_password",
document.getElementById("new_password").value,
);
formData.append(
"new_password_repeat",
document.getElementById("new_password_repeat").value,
);
fetch("/change-password", {
method: "POST",
body: formData,
})
.then(async (res) => {
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Request failed");
}
return data;
})
.then((data) => {
document
.getElementById("change_password_dialogue")
.classList.add("hidden");
document
.getElementById("popup_background")
.classList.add("hidden");
})
.catch((err) => {
displayError(err.message);
});
});
</script>
<script type="text/javascript"> <script type="text/javascript">
var currentPreviewURL = null; var currentPreviewURL = null;
@@ -265,15 +216,17 @@
}); });
</script> </script>
<script type="text/javascript">
document
.getElementById("close_password_dialogue")
.addEventListener("click", () => {
document
.getElementById("change_password_dialogue")
.classList.add("hidden");
document.getElementById("popup_background").classList.add("hidden");
});
</script>
<script src="/static/error/error.js" type="text/javascript"></script> <script src="/static/error/error.js" type="text/javascript"></script>
<script
src="/static/javascript/password_strength.js"
type="text/javascript"
></script>
<script
src="/static/javascript/handle_password_change.js"
type="text/javascript"
></script>
<script
src="/static/javascript/show_password.js"
type="text/javascript"
></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>
+8
View File
@@ -0,0 +1,8 @@
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")
-5
View File
@@ -1,7 +1,6 @@
package session package session
import ( import (
"errors"
"sync" "sync"
"time" "time"
@@ -9,10 +8,6 @@ import (
"astraltech.xyz/accountmanager/src/worker" "astraltech.xyz/accountmanager/src/worker"
) )
var ErrSessionNotFound = errors.New("session not found")
var ErrSessionAlreadyExists = errors.New("session already exists")
var ErrSessionExpired = errors.New("session expired")
type MemoryStore struct { type MemoryStore struct {
sessions map[string]*SessionData sessions map[string]*SessionData
lock sync.RWMutex lock sync.RWMutex
+6
View File
@@ -21,6 +21,7 @@ type StoreType int
const ( const (
InMemory StoreType = iota InMemory StoreType = iota
Redis
) )
func GetSessionManager() *SessionManager { func GetSessionManager() *SessionManager {
@@ -38,6 +39,11 @@ func (manager *SessionManager) SetStoreType(storeType StoreType) {
manager.store = NewMemoryStore() manager.store = NewMemoryStore()
break break
} }
case Redis:
{
manager.store = NewRedisStore()
break
}
} }
} }
+117
View File
@@ -0,0 +1,117 @@
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
}
+3 -3
View File
@@ -3,9 +3,9 @@ package session
import "time" import "time"
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 { type SessionStore interface {
+1 -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;

Before

Width:  |  Height:  |  Size: 21 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

+106
View File
@@ -0,0 +1,106 @@
document
.getElementById("close_password_dialogue")
.addEventListener("click", () => {
document.getElementById("change_password_dialogue").classList.add("hidden");
document.getElementById("popup_background").classList.add("hidden");
});
const popup_botton = document.getElementById("change_password_button");
const currentPasswordButton = document.getElementById("current_password"),
newPasswordButton = document.getElementById("new_password"),
newPasswordRepeatButton = document.getElementById("new_password_repeat");
const strengh_label = document.getElementById("strengh-label");
const password_progress = document.getElementById("password-progress");
popup_botton.addEventListener("click", () => {
document.getElementById("popup_background").classList.remove("hidden");
document
.getElementById("change_password_dialogue")
.classList.remove("hidden");
currentPasswordButton.value = "";
newPasswordButton.value = "";
newPasswordRepeatButton.value = "";
strengh_label.innerText = "Strength: Weak";
password_progress.style.width = "0%";
});
const changePasswordButton = document.getElementById(
"final_change_password_button",
);
function displayError(errorText) {
document.getElementById("password_error").classList.remove("hidden");
document.getElementById("password_text").innerText = "⚠️ " + errorText + ".";
return;
}
changePasswordButton.addEventListener("click", () => {
if (currentPasswordButton.value === "") {
displayError("Please enter current password");
return;
}
if (newPasswordButton.value === "") {
displayError("No value for new password");
return;
}
if (newPasswordRepeatButton.value === "") {
displayError("Please repeat new password");
return;
}
if (newPasswordButton.value !== newPasswordRepeatButton.value) {
displayError("New passwords do not match");
return;
}
const formData = new FormData();
formData.append(
"csrf_token",
document.getElementById("csrf_token_storage").value,
);
formData.append("old_password", currentPasswordButton.value);
formData.append("new_password", newPasswordButton.value);
formData.append("new_password_repeat", newPasswordRepeatButton.value);
fetch("/change-password", {
method: "POST",
body: formData,
})
.then(async (res) => {
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || "Request failed");
}
return data;
})
.then((data) => {
document
.getElementById("change_password_dialogue")
.classList.add("hidden");
document.getElementById("popup_background").classList.add("hidden");
})
.catch((err) => {
displayError(err.message);
});
});
document.getElementById("new_password").addEventListener("input", () => {
score = EvaluatePassword(document.getElementById("new_password").value).score;
password_progress.style.width = score + "%";
if (score <= 40) {
strengh_label.innerText = "Strength: Weak";
password_progress.style.backgroundColor = "var(--password-strength-weak)";
} else if (score > 40 && score <= 70) {
strengh_label.innerText = "Strength: Medium";
password_progress.style.backgroundColor = "var(--password-strength-medium)";
} else if (score > 40 && score >= 70) {
strengh_label.innerText = "Strength: Strong";
password_progress.style.backgroundColor = "var(--password-strength-strong)";
}
});
+51
View File
@@ -0,0 +1,51 @@
// build in evaluate password function
// Errors: reasons why the FreeIPA server would reject the password
// Suggestions: reasons the password should be made stronger
// You can change this code to change how complexity is rated
// Return values
// Score: 0-100
// Errors: A list of errors that would cause the server to reject the password
// Suggestions: A list of suggestions to make the password stronger
function EvaluatePassword(password) {
let score = 0;
let errors = [];
let suggestions = [];
const hasUpper = /[A-Z]/.test(password);
const hasLower = /[a-z]/.test(password);
const hasNumber = /[0-9]/.test(password);
const hasSpecial = /[^A-Za-z0-9]/.test(password);
const isLongEnough = password.length >= 8;
if (!isLongEnough) {
errors.push("Password must be at least 8 characters long.");
}
score += Math.min(password.length * 3, 60);
if (hasUpper) score += 10;
if (hasLower) score += 10;
if (hasNumber) score += 10;
if (hasSpecial) score += 10;
if (score < 100) {
if (password.length < 20) {
suggestions.push(
`Add ${20 - password.length} more characters to reach maximum length points.`,
);
}
if (!hasUpper) suggestions.push("Add an uppercase letter.");
if (!hasLower) suggestions.push("Add a lowercase letter.");
if (!hasNumber) suggestions.push("Add a number.");
if (!hasSpecial)
suggestions.push("Add a special character (e.g., !, @, #).");
if (score > 70 && score < 100) {
suggestions.push(
"Pro-tip: Use a full sentence (passphrase) to make it easier to remember and harder to crack.",
);
}
}
return {
score: Math.min(score, 100),
errors: errors,
suggestions: suggestions,
};
}
+22
View File
@@ -0,0 +1,22 @@
const showPasswordButtons = document.getElementsByClassName(
"show_password_toggle",
);
for (const button of showPasswordButtons) {
button.addEventListener("click", function () {
const input = this.parentElement.querySelector(
"input[type='password'], input[type='text']",
);
if (!input) return;
const isHidden = input.type === "password";
input.type = isHidden ? "text" : "password";
if (isHidden) {
this.classList.add("open");
this.classList.remove("closed");
} else {
this.classList.remove("open");
this.classList.add("closed");
}
});
}
-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%;
+25 -8
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;
@@ -128,7 +121,31 @@
} }
#close_password_dialogue { #close_password_dialogue {
width: fit-content; display: inline-block;
aspect-ratio: 1 / 1;
position: absolute; position: absolute;
right: 2.5rem; right: 2.5rem;
padding: 0px;
margin: 0px;
width: 30px;
}
#password_errors {
background-color: var(--error-red);
border-radius: 8px;
padding: 20px;
border-color: var(--error-border-red);
border-width: 2px;
border-style: solid;
color: var(--text-main);
}
#password_warnings {
background-color: var(--warning-yellow);
border-radius: 8px;
padding: 20px;
border-color: var(--warning-border-yellow);
border-width: 2px;
border-style: solid;
color: var(--text-main);
} }
+16
View File
@@ -0,0 +1,16 @@
:root {
--progress-top: #becbd8;
}
.progress-bar {
width: 100%;
background-color: var(--bg-input);
height: 20px;
border-radius: 10px;
}
.progress-bar-progress {
background-color: var(--progress-top);
height: 20px;
border-radius: 10px;
}
+7
View File
@@ -0,0 +1,7 @@
#reset_password_card {
width: 350px;
}
#reset_password_card input {
width: 324px;
}
+69 -2
View File
@@ -16,6 +16,13 @@
--error-red: #ef4444; /* Professional Red */ --error-red: #ef4444; /* Professional Red */
--error-border-red: #e22d2d; --error-border-red: #e22d2d;
--warning-yellow: #fef08a;
--warning-border-yellow: #fde047;
--password-strength-weak: var(--error-red);
--password-strength-medium: var(--warning-border-yellow);
--password-strength-strong: #43ef6b;
font-family: "Inter", sans-serif; font-family: "Inter", sans-serif;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
} }
@@ -39,6 +46,10 @@ button:hover {
background-color: var(--primary-hover); background-color: var(--primary-hover);
} }
button:focus {
outline: 2px solid var(--primary-accent);
}
input { input {
padding: 12px; padding: 12px;
background-color: var(--bg-input); background-color: var(--bg-input);
@@ -47,6 +58,10 @@ input {
border-radius: 6px; border-radius: 6px;
} }
input:focus {
outline: 2px solid var(--primary-accent);
}
input::placeholder { input::placeholder {
color: var(--text-muted); color: var(--text-muted);
} }
@@ -70,6 +85,58 @@ input::placeholder {
height: 100%; height: 100%;
z-index: 9999; /* higher = on top */ z-index: 9999; /* higher = on top */
background-color: black; backdrop-filter: blur(4px);
opacity: 10%; background-color: rgba(0, 0, 0, 0.3);
pointer-events: all;
}
.dialouge_title {
font-size: 20px;
margin-bottom: 0px;
color: var(--text-main) !important;
}
.password_box {
position: relative;
display: inline-block;
}
.show_password_toggle {
width: 10px;
height: 10px;
position: absolute;
right: 5px;
bottom: 50%;
transform: translateY(50%);
background-size: contain;
background-repeat: no-repeat;
background-position: center;
background-color: rgba(0, 0, 0, 0);
}
.show_password_toggle.closed {
background-image: url("/static/images/closed_eye.png");
}
.show_password_toggle.open {
background-image: url("/static/images/filled_eye.png");
}
.show_password_toggle:hover {
background-color: rgba(0, 0, 0, 0);
}
.show_password_toggle:focus {
outline: none !important;
}
#logo_image {
position: fixed;
width: 300px;
left: 50%;
transform: translateX(-50%);
}
.subtext {
color: var(--text-muted);
} }