Compare commits
36 Commits
074b3f8f31
...
v0.0.4
| Author | SHA1 | Date | |
|---|---|---|---|
| a315161ed3 | |||
| e2531e3021 | |||
| a2602f74f0 | |||
| 1c1ba99080 | |||
| ad21d50ce5 | |||
| 3a3fab08f6 | |||
| bb649aef48 | |||
| f204069392 | |||
| ac663f21e1 | |||
| d1992ec466 | |||
| 46db63e62a | |||
| 33ea56fb0c | |||
| f651894a0f | |||
| d70e679a01 | |||
| a058804603 | |||
| c9c352204c | |||
| 0402a6ff9c | |||
| 737a1908e0 | |||
| c628c688f7 | |||
| d283ad0a0a | |||
| a8c8feeb3e | |||
| 939a55c44b | |||
| ffcaee7170 | |||
| 3a69c04c25 | |||
| cacddd16e2 | |||
| 2f6ff081f3 | |||
| 59bc23bdc2 | |||
| a7c33392ce | |||
| 05e01f4b23 | |||
| e2f4a0692c | |||
| efd7d15722 | |||
| 4e412e9c18 | |||
| 6220021953 | |||
|
|
01ca68e16b | ||
|
|
6c435e6135 | ||
|
|
e1f992e052 |
146
src/components/profile_photo.go
Normal file
146
src/components/profile_photo.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package components
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/helpers"
|
||||
"astraltech.xyz/accountmanager/src/ldap"
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"astraltech.xyz/accountmanager/src/session"
|
||||
)
|
||||
|
||||
var (
|
||||
photoCreatedTimestamp = make(map[string]time.Time)
|
||||
photoCreatedMutex sync.Mutex
|
||||
blankPhotoData []byte
|
||||
)
|
||||
|
||||
var (
|
||||
sessionManager = session.GetSessionManager()
|
||||
LDAPServer *ldap.LDAPServer
|
||||
|
||||
BaseDN string
|
||||
|
||||
ServiceUserBindDN string
|
||||
ServiceUserPassword string
|
||||
)
|
||||
|
||||
func ReadBlankPhoto() {
|
||||
blank, err := helpers.ReadFile("static/blank_profile.jpg")
|
||||
if err != nil {
|
||||
logging.Fatal("Could not load blank profile image")
|
||||
}
|
||||
blankPhotoData = blank
|
||||
}
|
||||
|
||||
func CreateUserPhoto(username string, photoData []byte) error {
|
||||
helpers.Mkdir("./avatars", os.ModePerm)
|
||||
|
||||
path := fmt.Sprintf("./avatars/%s.jpeg", username)
|
||||
cleaned := filepath.Clean(path)
|
||||
dst, err := helpers.CreateFile(cleaned)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not save file")
|
||||
}
|
||||
photoCreatedMutex.Lock()
|
||||
photoCreatedTimestamp[username] = time.Now()
|
||||
photoCreatedMutex.Unlock()
|
||||
defer dst.Close()
|
||||
logging.Info("Writing to avarar file")
|
||||
_, err = dst.Write(photoData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func UploadPhotoHandler(w http.ResponseWriter, r *http.Request) {
|
||||
sessionData, err := sessionManager.GetSession(r)
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
err = r.ParseMultipartForm(10 << 20) // 10MB limit
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if r.FormValue("csrf_token") != sessionData.CSRFToken {
|
||||
http.Error(w, "CSRF Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("photo")
|
||||
if err != nil {
|
||||
http.Error(w, "File not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
if header.Size > (10 * 1024 * 1024) {
|
||||
http.Error(w, "File is to large (limit is 10 MB)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Read file into memory
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", sessionData.UserID, BaseDN)
|
||||
LDAPServer.ModifyAttribute(ServiceUserBindDN, ServiceUserPassword, userDN, "jpegphoto", []string{string(data)})
|
||||
CreateUserPhoto(sessionData.UserID, data)
|
||||
}
|
||||
|
||||
func AvatarHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
username := r.URL.Query().Get("user")
|
||||
if strings.Contains(username, "/") {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
}
|
||||
|
||||
filePath := fmt.Sprintf("./avatars/%s.jpeg", username)
|
||||
cleaned := filepath.Clean(filePath)
|
||||
value, err := helpers.ReadFile(cleaned)
|
||||
|
||||
if err == nil {
|
||||
photoCreatedMutex.Lock()
|
||||
if time.Since(photoCreatedTimestamp[username]) <= 5*time.Minute {
|
||||
photoCreatedMutex.Unlock()
|
||||
w.Write(value)
|
||||
return
|
||||
}
|
||||
photoCreatedMutex.Unlock()
|
||||
}
|
||||
|
||||
userSearch, err := LDAPServer.SerchServer(
|
||||
ServiceUserBindDN, ServiceUserPassword,
|
||||
BaseDN,
|
||||
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldap.LDAPEscapeFilter(username)),
|
||||
[]string{"jpegphoto"},
|
||||
)
|
||||
if err == nil || userSearch.EntryCount() == 0 {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
}
|
||||
entry := userSearch.GetEntry(0)
|
||||
bytes := entry.GetRawAttributeValue("jpegphoto")
|
||||
if len(bytes) == 0 {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
} else {
|
||||
w.Write(bytes)
|
||||
CreateUserPhoto(username, bytes)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package email
|
||||
|
||||
import (
|
||||
"net/smtp"
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
7
src/ldap/ldap_helpers.go
Normal file
7
src/ldap/ldap_helpers.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
func LDAPEscapeFilter(input string) string { return ldap.EscapeFilter(input) }
|
||||
29
src/ldap/ldap_search.go
Normal file
29
src/ldap/ldap_search.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
type LDAPSearch struct {
|
||||
search *ldap.SearchResult
|
||||
}
|
||||
|
||||
type LDAPEntry struct {
|
||||
entry *ldap.Entry
|
||||
}
|
||||
|
||||
func (s *LDAPSearch) EntryCount() int {
|
||||
return len(s.search.Entries)
|
||||
}
|
||||
|
||||
func (s *LDAPSearch) GetEntry(number int) *LDAPEntry {
|
||||
return &LDAPEntry{s.search.Entries[number]}
|
||||
}
|
||||
|
||||
func (e *LDAPEntry) GetRawAttributeValue(name string) []byte {
|
||||
return e.entry.GetRawAttributeValue(name)
|
||||
}
|
||||
|
||||
func (e *LDAPEntry) GetAttributeValue(name string) string {
|
||||
return e.entry.GetAttributeValue(name)
|
||||
}
|
||||
130
src/ldap/ldap_server.go
Normal file
130
src/ldap/ldap_server.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"strings"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
type LDAPServer struct {
|
||||
URL string
|
||||
StartTLS bool
|
||||
IgnoreInsecureCert bool
|
||||
}
|
||||
|
||||
func (s *LDAPServer) TestConnection() (bool, error) {
|
||||
l, err := ldap.DialURL(s.URL)
|
||||
l.Close()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// internal connect, should not be used regularly
|
||||
func (s *LDAPServer) connect() (*ldap.Conn, error) {
|
||||
l, err := ldap.DialURL(s.URL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if s.StartTLS {
|
||||
err = l.StartTLS(&tls.Config{
|
||||
InsecureSkipVerify: s.IgnoreInsecureCert,
|
||||
})
|
||||
if err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return l, nil
|
||||
}
|
||||
func (s *LDAPServer) connectAsUser(userDN, password string) (*ldap.Conn, error) {
|
||||
conn, err := s.connect()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = conn.Bind(userDN, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (s *LDAPServer) AuthenticateUser(userDN, password string) (bool, error) {
|
||||
conn, err := s.connectAsUser(userDN, password)
|
||||
if err != nil || conn == nil {
|
||||
return false, err
|
||||
}
|
||||
conn.Close()
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *LDAPServer) SerchServer(
|
||||
userDN string, password string,
|
||||
baseDN string,
|
||||
searchFilter string, attributes []string,
|
||||
) (*LDAPSearch, error) {
|
||||
logging.Debugf("Searching %s LDAP server\n\tBase DN: %s\n\tSearch Filter %s\n\tAttributes: %s", s.URL, baseDN, searchFilter, strings.Join(attributes, ","))
|
||||
conn, err := s.connectAsUser(userDN, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
searchRequest := ldap.NewSearchRequest(
|
||||
baseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
searchFilter, attributes,
|
||||
nil,
|
||||
)
|
||||
sr, err := conn.Search(searchRequest)
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to search LDAP server %s\n", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
return &LDAPSearch{sr}, nil
|
||||
}
|
||||
|
||||
func (s *LDAPServer) ChangePassword(userDN string, oldPassword string, newPassword string) error {
|
||||
conn, err := s.connectAsUser(userDN, oldPassword)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
// Perform password modify extended operation
|
||||
_, err = conn.PasswordModify(&ldap.PasswordModifyRequest{
|
||||
UserIdentity: userDN,
|
||||
OldPassword: oldPassword,
|
||||
NewPassword: newPassword,
|
||||
})
|
||||
if err != nil {
|
||||
logging.Errorf("Password modify failed: %s", err.Error())
|
||||
return err
|
||||
}
|
||||
logging.Infof("Password successfully changed for %s", userDN)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *LDAPServer) ModifyAttribute(bindUserDN string, password string, userDN string, attribute string, data []string) error {
|
||||
logging.Infof("Modifing LDAP attribute %s", attribute)
|
||||
|
||||
conn, err := s.connectAsUser(bindUserDN, password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
modify := ldap.NewModifyRequest(userDN, nil)
|
||||
modify.Replace(attribute, data)
|
||||
err = conn.Modify(modify)
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to modify %s", err.Error())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
146
src/main/ldap.go
146
src/main/ldap.go
@@ -1,146 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
)
|
||||
|
||||
type LDAPServer struct {
|
||||
URL string
|
||||
StartTLS bool
|
||||
IgnoreInsecureCert bool
|
||||
Connection *ldap.Conn
|
||||
}
|
||||
|
||||
type LDAPSearch struct {
|
||||
Succeeded bool
|
||||
LDAPSearch *ldap.SearchResult
|
||||
}
|
||||
|
||||
func connectToLDAPServer(URL string, starttls bool, ignore_cert bool) *LDAPServer {
|
||||
logging.Debugf("Connecting to LDAP server %s", URL)
|
||||
l, err := ldap.DialURL(URL)
|
||||
if err != nil {
|
||||
logging.Fatal("Failed to connect to LDAP server")
|
||||
logging.Fatal(err.Error())
|
||||
}
|
||||
logging.Infof("Connected to LDAP server")
|
||||
|
||||
if starttls {
|
||||
logging.Debugf("Enabling StartTLS")
|
||||
if err := l.StartTLS(&tls.Config{InsecureSkipVerify: ignore_cert}); err != nil {
|
||||
logging.Errorf("StartTLS failed %s", err.Error())
|
||||
}
|
||||
logging.Infof("StartTLS enabled")
|
||||
}
|
||||
|
||||
return &LDAPServer{
|
||||
Connection: l,
|
||||
URL: URL,
|
||||
StartTLS: starttls,
|
||||
IgnoreInsecureCert: ignore_cert,
|
||||
}
|
||||
}
|
||||
|
||||
func reconnectToLDAPServer(server *LDAPServer) error {
|
||||
logging.Debugf("Reconnecting to %s LDAP server", server.URL)
|
||||
if server == nil {
|
||||
logging.Errorf("Cannot reconnect: server is nil")
|
||||
return fmt.Errorf("Server is nil")
|
||||
}
|
||||
|
||||
l, err := ldap.DialURL(server.URL)
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to connect to LDAP server (has server gone down)")
|
||||
return err
|
||||
}
|
||||
|
||||
if server.StartTLS {
|
||||
logging.Debugf("StartTLS enabling")
|
||||
if err := l.StartTLS(&tls.Config{InsecureSkipVerify: server.IgnoreInsecureCert}); err != nil {
|
||||
logging.Error("StartTLS failed")
|
||||
return err
|
||||
}
|
||||
logging.Debugf("Successfully Started TLS")
|
||||
}
|
||||
|
||||
server.Connection = l
|
||||
return nil
|
||||
}
|
||||
|
||||
func connectAsLDAPUser(server *LDAPServer, bindDN, password string) error {
|
||||
logging.Debugf("Connecting to %s LDAP server with %s BindDN", server.URL, bindDN)
|
||||
if server == nil {
|
||||
logging.Errorf("Failed to connect as user, LDAP server is NULL")
|
||||
return fmt.Errorf("LDAP server is null")
|
||||
}
|
||||
|
||||
if server.Connection == nil || server.Connection.IsClosing() {
|
||||
err := reconnectToLDAPServer(server)
|
||||
return err
|
||||
}
|
||||
err := server.Connection.Bind(bindDN, password)
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to bind to LDAP as user %s", err.Error())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func searchLDAPServer(server *LDAPServer, baseDN string, searchFilter string, attributes []string) LDAPSearch {
|
||||
logging.Debugf("Searching %s LDAP server\n\tBase DN: %s\n\tSearch Filter %s\n\tAttributes: %s", server.URL, baseDN, searchFilter, strings.Join(attributes, ","))
|
||||
if server == nil {
|
||||
logging.Errorf("Server is nil, failed to search LDAP server")
|
||||
return LDAPSearch{false, nil}
|
||||
}
|
||||
|
||||
if server.Connection == nil {
|
||||
reconnectToLDAPServer(server)
|
||||
if server.Connection == nil {
|
||||
return LDAPSearch{false, nil}
|
||||
}
|
||||
}
|
||||
|
||||
searchRequest := ldap.NewSearchRequest(
|
||||
baseDN,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
searchFilter, attributes,
|
||||
nil,
|
||||
)
|
||||
|
||||
sr, err := server.Connection.Search(searchRequest)
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to search LDAP server %s\n", err.Error())
|
||||
return LDAPSearch{false, nil}
|
||||
}
|
||||
|
||||
return LDAPSearch{true, sr}
|
||||
}
|
||||
|
||||
func modifyLDAPAttribute(server *LDAPServer, userDN string, attribute string, data []string) error {
|
||||
logging.Infof("Modifing LDAP attribute %s", attribute)
|
||||
modify := ldap.NewModifyRequest(userDN, nil)
|
||||
modify.Replace(attribute, data)
|
||||
err := server.Connection.Modify(modify)
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to modify %s", err.Error())
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func closeLDAPServer(server *LDAPServer) {
|
||||
if server != nil && server.Connection != nil {
|
||||
logging.Debug("Closing connection to LDAP server")
|
||||
err := server.Connection.Close()
|
||||
if err != nil {
|
||||
logging.Errorf("Failed to close LDAP server %s", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ldapEscapeFilter(input string) string { return ldap.EscapeFilter(input) }
|
||||
331
src/main/main.go
331
src/main/main.go
@@ -3,95 +3,71 @@ package main
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/components"
|
||||
"astraltech.xyz/accountmanager/src/helpers"
|
||||
"astraltech.xyz/accountmanager/src/ldap"
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"astraltech.xyz/accountmanager/src/session"
|
||||
)
|
||||
|
||||
var (
|
||||
ldapServer *LDAPServer
|
||||
ldapServerMutex sync.Mutex
|
||||
serverConfig *ServerConfig
|
||||
ldapServer ldap.LDAPServer
|
||||
serverConfig *ServerConfig
|
||||
sessionManager *session.SessionManager
|
||||
)
|
||||
|
||||
type UserData struct {
|
||||
isAuth bool
|
||||
Username string
|
||||
DisplayName string
|
||||
Email string
|
||||
}
|
||||
|
||||
var (
|
||||
photoCreatedTimestamp = make(map[string]time.Time)
|
||||
photoCreatedMutex sync.Mutex
|
||||
blankPhotoData []byte
|
||||
userData = make(map[string]*UserData)
|
||||
userDataMutex sync.RWMutex
|
||||
)
|
||||
|
||||
func createUserPhoto(username string, photoData []byte) error {
|
||||
Mkdir("./avatars", os.ModePerm)
|
||||
|
||||
path := fmt.Sprintf("./avatars/%s.jpeg", username)
|
||||
cleaned := filepath.Clean(path)
|
||||
dst, err := CreateFile(cleaned)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("Could not save file")
|
||||
}
|
||||
photoCreatedMutex.Lock()
|
||||
photoCreatedTimestamp[username] = time.Now()
|
||||
photoCreatedMutex.Unlock()
|
||||
defer dst.Close()
|
||||
logging.Info("Writing to avarar file")
|
||||
_, err = dst.Write(photoData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func authenticateUser(username, password string) (UserData, error) {
|
||||
func authenticateUser(username, password string) (*UserData, error) {
|
||||
logging.Event(logging.AuthenticateUser, username)
|
||||
ldapServerMutex.Lock()
|
||||
defer ldapServerMutex.Unlock()
|
||||
if ldapServer.Connection == nil {
|
||||
return UserData{isAuth: false}, fmt.Errorf("LDAP server not connected")
|
||||
}
|
||||
userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", username, serverConfig.LDAPConfig.BaseDN)
|
||||
connected := connectAsLDAPUser(ldapServer, userDN, password)
|
||||
if connected != nil {
|
||||
return UserData{isAuth: false}, connected
|
||||
}
|
||||
|
||||
userSearch := searchLDAPServer(
|
||||
ldapServer,
|
||||
connected, err := ldapServer.AuthenticateUser(userDN, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if connected == false {
|
||||
logging.Debug("Failed to authenticate user")
|
||||
return nil, fmt.Errorf("Failed to authenticate user %s", username)
|
||||
}
|
||||
logging.Info("User authenticated successfully")
|
||||
|
||||
userSearch, err := ldapServer.SerchServer(
|
||||
userDN, password,
|
||||
serverConfig.LDAPConfig.BaseDN,
|
||||
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldapEscapeFilter(username)),
|
||||
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldap.LDAPEscapeFilter(username)),
|
||||
[]string{"displayName", "mail", "jpegphoto"},
|
||||
)
|
||||
if !userSearch.Succeeded {
|
||||
return UserData{isAuth: false}, fmt.Errorf("user metadata not found")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entry := userSearch.LDAPSearch.Entries[0]
|
||||
entry := userSearch.GetEntry(0)
|
||||
user := UserData{
|
||||
isAuth: true,
|
||||
Username: username,
|
||||
DisplayName: entry.GetAttributeValue("displayName"),
|
||||
Email: entry.GetAttributeValue("mail"),
|
||||
}
|
||||
|
||||
photoData := entry.GetRawAttributeValue("jpegphoto")
|
||||
if len(photoData) > 0 {
|
||||
createUserPhoto(user.Username, photoData)
|
||||
components.CreateUserPhoto(username, photoData)
|
||||
}
|
||||
return user, nil
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
type LoginPageData struct {
|
||||
@@ -118,15 +94,19 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
|
||||
password := r.FormValue("password")
|
||||
|
||||
logging.Infof("New Login request for %s\n", username)
|
||||
userData, err := authenticateUser(username, password)
|
||||
newUserData, err := authenticateUser(username, password)
|
||||
userDataMutex.Lock()
|
||||
userData[username] = newUserData
|
||||
userDataMutex.Unlock()
|
||||
if err != nil {
|
||||
log.Print(err)
|
||||
logging.Error(err.Error())
|
||||
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
|
||||
} else {
|
||||
if userData.isAuth == true {
|
||||
cookie := createSession(&userData)
|
||||
if cookie == nil {
|
||||
http.Error(w, "Session error", 500)
|
||||
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)
|
||||
@@ -147,75 +127,27 @@ type ProfileData struct {
|
||||
|
||||
func profileHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
exist, sessionData := validateSession(r)
|
||||
if !exist {
|
||||
sessionData, err := sessionManager.GetSession(r)
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == http.MethodGet {
|
||||
tmpl := template.Must(template.ParseFiles("src/pages/profile_page.html"))
|
||||
userDataMutex.RLock()
|
||||
tmpl.Execute(w, ProfileData{
|
||||
Username: sessionData.data.Username,
|
||||
Email: sessionData.data.Email,
|
||||
DisplayName: sessionData.data.DisplayName,
|
||||
Username: sessionData.UserID,
|
||||
Email: userData[sessionData.UserID].Email,
|
||||
DisplayName: userData[sessionData.UserID].DisplayName,
|
||||
CSRFToken: sessionData.CSRFToken,
|
||||
})
|
||||
userDataMutex.RUnlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func avatarHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/jpeg")
|
||||
username := r.URL.Query().Get("user")
|
||||
if strings.Contains(username, "/") {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
}
|
||||
|
||||
filePath := fmt.Sprintf("./avatars/%s.jpeg", username)
|
||||
cleaned := filepath.Clean(filePath)
|
||||
value, err := ReadFile(cleaned)
|
||||
|
||||
if err == nil {
|
||||
photoCreatedMutex.Lock()
|
||||
if time.Since(photoCreatedTimestamp[username]) <= 5*time.Minute {
|
||||
photoCreatedMutex.Unlock()
|
||||
w.Write(value)
|
||||
return
|
||||
}
|
||||
photoCreatedMutex.Unlock()
|
||||
}
|
||||
|
||||
ldapServerMutex.Lock()
|
||||
defer ldapServerMutex.Unlock()
|
||||
connected := connectAsLDAPUser(ldapServer, serverConfig.LDAPConfig.BindDN, serverConfig.LDAPConfig.BindPassword)
|
||||
if connected != nil {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
}
|
||||
|
||||
userSearch := searchLDAPServer(
|
||||
ldapServer,
|
||||
serverConfig.LDAPConfig.BaseDN,
|
||||
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldapEscapeFilter(username)),
|
||||
[]string{"jpegphoto"},
|
||||
)
|
||||
if !userSearch.Succeeded || len(userSearch.LDAPSearch.Entries) == 0 {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
}
|
||||
entry := userSearch.LDAPSearch.Entries[0]
|
||||
bytes := entry.GetRawAttributeValue("jpegphoto")
|
||||
if len(bytes) == 0 {
|
||||
w.Write(blankPhotoData)
|
||||
return
|
||||
} else {
|
||||
w.Write(bytes)
|
||||
createUserPhoto(username, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
func logoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err != nil {
|
||||
@@ -224,59 +156,19 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
token := cookie.Value
|
||||
|
||||
exist, sessionData := validateSession(r)
|
||||
if exist {
|
||||
if r.FormValue("csrf_token") != sessionData.CSRFToken {
|
||||
http.Error(w, "Unable to log user out", http.StatusForbidden)
|
||||
logging.Debugf("%s attempted to logout with invalid csrf token", sessionData.data.Username)
|
||||
return
|
||||
}
|
||||
}
|
||||
logging.Infof("handling logout event for %s", sessionData.data.Username)
|
||||
|
||||
deleteSession(token)
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func uploadPhotoHandler(w http.ResponseWriter, r *http.Request) {
|
||||
exist, sessionData := validateSession(r)
|
||||
if !exist {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
err := r.ParseMultipartForm(10 << 20) // 10MB limit
|
||||
sessionData, err := sessionManager.GetSession(r)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
logging.Error(err.Error())
|
||||
}
|
||||
|
||||
if r.FormValue("csrf_token") != sessionData.CSRFToken {
|
||||
http.Error(w, "CSRF Forbidden", http.StatusForbidden)
|
||||
http.Error(w, "Unable to log user out", http.StatusForbidden)
|
||||
logging.Debugf("%s attempted to logout with invalid csrf token", sessionData.UserID)
|
||||
return
|
||||
}
|
||||
logging.Infof("handling logout event for %s", sessionData.UserID)
|
||||
|
||||
file, header, err := r.FormFile("photo")
|
||||
if err != nil {
|
||||
http.Error(w, "File not found", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
if header.Size > (10 * 1024 * 1024) {
|
||||
http.Error(w, "File is to large (limit is 10 MB)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Read file into memory
|
||||
data, err := io.ReadAll(file)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
userDN := fmt.Sprintf("uid=%s,cn=users,cn=accounts,%s", sessionData.data.Username, serverConfig.LDAPConfig.BaseDN)
|
||||
ldapServerMutex.Lock()
|
||||
defer ldapServerMutex.Unlock()
|
||||
modifyLDAPAttribute(ldapServer, userDN, "jpegphoto", []string{string(data)})
|
||||
createUserPhoto(sessionData.data.Username, data)
|
||||
sessionManager.DeleteSession(token)
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func faviconHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -289,58 +181,107 @@ func logoHandler(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, serverConfig.StyleConfig.LogoPath)
|
||||
}
|
||||
|
||||
func cleanupSessions() {
|
||||
logging.Debug("Cleaning up stale session\n")
|
||||
func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
sessionMutex.Lock()
|
||||
sessions_to_delete := []string{}
|
||||
for session_token, session_data := range sessions {
|
||||
timeUntilRemoval := time.Minute * 5
|
||||
if session_data.loggedIn {
|
||||
timeUntilRemoval = time.Hour
|
||||
}
|
||||
if time.Since(session_data.timeCreated) > timeUntilRemoval {
|
||||
sessions_to_delete = append(sessions_to_delete, session_token)
|
||||
}
|
||||
sessionData, err := sessionManager.GetSession(r)
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
w.Write([]byte(`{"success": false, "error": "Not authenticated"}`))
|
||||
return
|
||||
}
|
||||
sessionMutex.Unlock()
|
||||
for _, session_id := range sessions_to_delete {
|
||||
deleteSession(session_id)
|
||||
|
||||
err = r.ParseMultipartForm(10 << 20)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"success": false, "error": "Bad request"}`))
|
||||
return
|
||||
}
|
||||
|
||||
if r.FormValue("csrf_token") != sessionData.CSRFToken {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"success": false, "error": "CSRF Forbidden"}`))
|
||||
return
|
||||
}
|
||||
|
||||
oldPassword := r.FormValue("old_password")
|
||||
newPassword := r.FormValue("new_password")
|
||||
newPasswordRepeat := r.FormValue("new_password_repeat")
|
||||
|
||||
if newPassword != newPasswordRepeat {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"success": false, "error": "Passwords do not match"}`))
|
||||
return
|
||||
}
|
||||
|
||||
userDN := fmt.Sprintf(
|
||||
"uid=%s,cn=users,cn=accounts,%s",
|
||||
sessionData.UserID,
|
||||
serverConfig.LDAPConfig.BaseDN,
|
||||
)
|
||||
|
||||
err = ldapServer.ChangePassword(userDN, oldPassword, newPassword)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
if strings.Contains(err.Error(), "Invalid Credentials") {
|
||||
w.Write([]byte(`{"success": false, "error": "Current password incorrect"}`))
|
||||
} else if strings.Contains(err.Error(), "Too soon to change password") {
|
||||
w.Write([]byte(`{"success": false, "error": "Too soon to change password"}`))
|
||||
} else {
|
||||
w.Write([]byte(`{"success": false, "error": "Internal error"}`))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"success": true}`))
|
||||
}
|
||||
|
||||
func main() {
|
||||
logging.Info("Starting the server")
|
||||
sessionManager = session.GetSessionManager()
|
||||
sessionManager.SetStoreType(session.InMemory)
|
||||
|
||||
var err error = nil
|
||||
blankPhotoData, err = ReadFile("static/blank_profile.jpg")
|
||||
if err != nil {
|
||||
logging.Fatal("Could not load blank profile image")
|
||||
}
|
||||
var err error
|
||||
serverConfig, err = loadServerConfig("./data/config.json")
|
||||
if err != nil {
|
||||
log.Fatal("Could not load server config")
|
||||
}
|
||||
|
||||
ldapServerMutex.Lock()
|
||||
server := connectToLDAPServer(serverConfig.LDAPConfig.LDAPURL, serverConfig.LDAPConfig.Security == "tls", serverConfig.LDAPConfig.IgnoreInvalidCert)
|
||||
ldapServer = server
|
||||
ldapServerMutex.Unlock()
|
||||
defer closeLDAPServer(ldapServer)
|
||||
ldapServer = ldap.LDAPServer{
|
||||
URL: serverConfig.LDAPConfig.LDAPURL,
|
||||
StartTLS: serverConfig.LDAPConfig.Security == "tls",
|
||||
IgnoreInsecureCert: serverConfig.LDAPConfig.IgnoreInvalidCert,
|
||||
}
|
||||
|
||||
createWorker(time.Minute*5, cleanupSessions)
|
||||
HandleFunc("/favicon.ico", faviconHandler)
|
||||
HandleFunc("/logo", logoHandler)
|
||||
components.LDAPServer = &ldapServer
|
||||
components.BaseDN = serverConfig.LDAPConfig.BaseDN
|
||||
components.ServiceUserBindDN = serverConfig.LDAPConfig.BindDN
|
||||
components.ServiceUserPassword = serverConfig.LDAPConfig.BindPassword
|
||||
|
||||
connected, err := ldapServer.TestConnection()
|
||||
if connected != true || err != nil {
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
}
|
||||
logging.Fatal("Failed to connect to LDAP server")
|
||||
}
|
||||
|
||||
helpers.HandleFunc("/favicon.ico", faviconHandler)
|
||||
helpers.HandleFunc("/logo", logoHandler)
|
||||
|
||||
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
|
||||
HandleFunc("/login", loginHandler)
|
||||
HandleFunc("/profile", profileHandler)
|
||||
HandleFunc("/logout", logoutHandler)
|
||||
helpers.HandleFunc("/login", loginHandler)
|
||||
helpers.HandleFunc("/profile", profileHandler)
|
||||
helpers.HandleFunc("/logout", logoutHandler)
|
||||
|
||||
HandleFunc("/avatar", avatarHandler)
|
||||
HandleFunc("/change-photo", uploadPhotoHandler)
|
||||
helpers.HandleFunc("/avatar", components.AvatarHandler)
|
||||
helpers.HandleFunc("/change-photo", components.UploadPhotoHandler)
|
||||
helpers.HandleFunc("/change-password", changePasswordHandler)
|
||||
|
||||
HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
helpers.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/profile", http.StatusFound) // 302 redirect
|
||||
})
|
||||
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
)
|
||||
|
||||
type SessionData struct {
|
||||
loggedIn bool
|
||||
data *UserData
|
||||
timeCreated time.Time
|
||||
CSRFToken string
|
||||
}
|
||||
|
||||
var (
|
||||
sessions = make(map[string]SessionData)
|
||||
sessionMutex sync.Mutex
|
||||
)
|
||||
|
||||
func GenerateSessionToken(length int) (string, error) {
|
||||
b := make([]byte, length)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(b)
|
||||
return token, nil
|
||||
}
|
||||
|
||||
func createSession(userData *UserData) *http.Cookie {
|
||||
logging.Debugf("Creating a new session for %s", userData.Username)
|
||||
token, err := GenerateSessionToken(32) // Use crypto/rand for this
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
return nil
|
||||
}
|
||||
CSRFToken, err := GenerateSessionToken(32)
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
return nil
|
||||
}
|
||||
|
||||
tokenEncoded := sha256.Sum256([]byte(token))
|
||||
tokenEncodedString := string(tokenEncoded[:])
|
||||
|
||||
sessionMutex.Lock()
|
||||
defer sessionMutex.Unlock()
|
||||
loggedIn := false
|
||||
if userData != nil {
|
||||
loggedIn = true
|
||||
}
|
||||
sessions[tokenEncodedString] = SessionData{
|
||||
data: userData,
|
||||
timeCreated: time.Now(),
|
||||
CSRFToken: CSRFToken,
|
||||
loggedIn: loggedIn,
|
||||
}
|
||||
cookie := &http.Cookie{
|
||||
Name: "session_token",
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true, // Essential: prevents JS access
|
||||
Secure: true, // Set to TRUE in production (HTTPS)
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 3600, // 1 hour
|
||||
}
|
||||
return cookie
|
||||
}
|
||||
|
||||
func validateSession(r *http.Request) (bool, *SessionData) {
|
||||
logging.Debugf("Validating session")
|
||||
cookie, err := r.Cookie("session_token")
|
||||
if err != nil {
|
||||
logging.Error(err.Error())
|
||||
return false, &SessionData{}
|
||||
}
|
||||
token := cookie.Value
|
||||
|
||||
tokenEncoded := sha256.Sum256([]byte(token))
|
||||
tokenEncodedString := string(tokenEncoded[:])
|
||||
|
||||
sessionMutex.Lock()
|
||||
sessionData, exists := sessions[tokenEncodedString]
|
||||
sessionMutex.Unlock()
|
||||
if !exists || !sessionData.loggedIn {
|
||||
return false, &SessionData{}
|
||||
}
|
||||
logging.Infof("Validated session for %s", sessionData.data.Username)
|
||||
return true, &sessionData
|
||||
}
|
||||
|
||||
func deleteSession(session_id string) {
|
||||
sessionMutex.Lock()
|
||||
|
||||
tokenEncoded := sha256.Sum256([]byte(session_id))
|
||||
tokenEncodedString := string(tokenEncoded[:])
|
||||
|
||||
delete(sessions, tokenEncodedString)
|
||||
sessionMutex.Unlock()
|
||||
}
|
||||
@@ -6,37 +6,31 @@
|
||||
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/login_page.css" />
|
||||
|
||||
<img id="logo_image" alt="logo" src="/logo" />
|
||||
<form id="login_card" method="POST">
|
||||
<form id="login_card" class="card" method="POST">
|
||||
<div id="welcome_text">
|
||||
Welcome to Astral Tech, Please Sign in to your account below
|
||||
</div>
|
||||
|
||||
<div id="incorrect_password_text" class="{{.IsHiddenClassList}}">
|
||||
<div class="error {{.IsHiddenClassList}}">
|
||||
⚠️ Invalid username or password.
|
||||
<button id="incorrect_password_close_button">X</button>
|
||||
<button class="close_error_button">X</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="login_text">Username</label><br />
|
||||
<label class="input_label">Username</label><br />
|
||||
<input type="text" name="username" placeholder="" required />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="login_text">Password</label><br />
|
||||
<label class="input_label">Password</label><br />
|
||||
<input type="password" name="password" placeholder="" required />
|
||||
</div>
|
||||
<button type="submit">Login</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
document
|
||||
.getElementById("incorrect_password_close_button")
|
||||
.addEventListener("click", function () {
|
||||
document
|
||||
.getElementById("incorrect_password_text")
|
||||
.classList.add("hidden");
|
||||
});
|
||||
</script>
|
||||
<script src="/static/error/error.js" type="text/javascript"></script>
|
||||
|
||||
@@ -7,8 +7,59 @@
|
||||
/>
|
||||
<link rel="stylesheet" href="static/style.css" />
|
||||
<link rel="stylesheet" href="static/card.css" />
|
||||
<link rel="stylesheet" href="static/error/error.css" />
|
||||
<link rel="stylesheet" href="static/profile_page.css" />
|
||||
|
||||
<div id="popup_background" class="blocked hidden"></div>
|
||||
|
||||
<div id="change_password_dialogue" class="hidden card static_center">
|
||||
Change Password
|
||||
|
||||
<button id="close_password_dialogue">X</button>
|
||||
|
||||
<div id="password_error" class="error hidden">
|
||||
<div id="password_text"></div>
|
||||
<button id="password_error_close_button" class="close_error_button">
|
||||
X
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="input_label">Current password</label><br />
|
||||
<input
|
||||
type="password"
|
||||
id="current_password"
|
||||
name="current_password"
|
||||
placeholder=""
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="input_label">New password</label><br />
|
||||
<input
|
||||
type="password"
|
||||
id="new_password"
|
||||
name="new_password"
|
||||
placeholder=""
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="input_label">New password (repeat)</label><br />
|
||||
<input
|
||||
type="password"
|
||||
id="new_password_repeat"
|
||||
name="new_password_repeat"
|
||||
placeholder=""
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button id="final_change_password_button">Change Password</button>
|
||||
</div>
|
||||
|
||||
<img id="logo_image" alt="logo" src="/logo" />
|
||||
<div id="main_content">
|
||||
<div class="cards">
|
||||
@@ -51,28 +102,18 @@
|
||||
<div class="data-value">{{.Email}}</div>
|
||||
</div>
|
||||
|
||||
<form
|
||||
action="/logout"
|
||||
method="POST"
|
||||
style="
|
||||
color: var(--primary-accent);
|
||||
text-decoration: none;
|
||||
font-weight: bold;
|
||||
margin-top: 20px;
|
||||
display: inline-block;
|
||||
"
|
||||
>
|
||||
<button
|
||||
style="
|
||||
background: none;
|
||||
border-style: none;
|
||||
color: var(--primary-accent);
|
||||
text-decoration: none;
|
||||
font-weight: bold;
|
||||
font-size: 20px;
|
||||
"
|
||||
id="signout_button"
|
||||
>
|
||||
<button class="bottom_button" id="change_password_button">
|
||||
<input
|
||||
id="csrf_token_storage"
|
||||
type="hidden"
|
||||
name="csrf_token"
|
||||
value="{{.CSRFToken}}"
|
||||
/>
|
||||
Change Password
|
||||
</button>
|
||||
|
||||
<form action="/logout" method="POST" style="display: inline-block">
|
||||
<button class="bottom_button" id="signout_button">
|
||||
<input
|
||||
id="csrf_token_storage"
|
||||
type="hidden"
|
||||
@@ -95,10 +136,102 @@
|
||||
});
|
||||
</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">
|
||||
var currentPreviewURL = null;
|
||||
|
||||
fileInput.addEventListener("change", async () => {
|
||||
document.getElementById("popup_background").classList.remove("hidden");
|
||||
|
||||
const file = fileInput.files[0];
|
||||
if (!file) return;
|
||||
if (file.type !== "image/jpeg") {
|
||||
@@ -118,7 +251,9 @@
|
||||
credentials: "include",
|
||||
});
|
||||
const text = await res.text();
|
||||
// show the picture (so we don't need to re render the whole page)
|
||||
|
||||
document.getElementById("popup_background").classList.add("hidden");
|
||||
|
||||
const img = document.querySelector(".profile-pic");
|
||||
|
||||
if (currentPreviewURL != null) {
|
||||
@@ -129,3 +264,16 @@
|
||||
currentPreviewURL = img.src;
|
||||
});
|
||||
</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>
|
||||
|
||||
24
src/session/session_helpers.go
Normal file
24
src/session/session_helpers.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
// helper function for secure session storage
|
||||
func GenerateSessionToken(length int) (string, error) {
|
||||
b := make([]byte, length)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(b)
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// more helper
|
||||
func hashSession(session_id string) string {
|
||||
tokenEncoded := sha256.Sum256([]byte(session_id))
|
||||
return base64.RawURLEncoding.EncodeToString(tokenEncoded[:])
|
||||
}
|
||||
99
src/session/session_in_memory.go
Normal file
99
src/session/session_in_memory.go
Normal file
@@ -0,0 +1,99 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
"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 {
|
||||
sessions map[string]*SessionData
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
logging.Debug("Creating new in memory session store")
|
||||
store := &MemoryStore{
|
||||
sessions: make(map[string]*SessionData),
|
||||
}
|
||||
worker.CreateWorker(time.Minute*5, store.cleanup)
|
||||
return store
|
||||
}
|
||||
|
||||
func (m *MemoryStore) Create(sessionID string, session *SessionData) (err error) {
|
||||
hashedSession := hashSession(sessionID)
|
||||
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
_, exist := m.sessions[hashedSession]
|
||||
if exist {
|
||||
return ErrSessionAlreadyExists
|
||||
}
|
||||
|
||||
m.sessions[hashedSession] = session
|
||||
return nil
|
||||
}
|
||||
func (m *MemoryStore) Get(sessionID string) (*SessionData, error) {
|
||||
m.lock.RLock()
|
||||
hashed := hashSession(sessionID)
|
||||
data, exists := m.sessions[hashed]
|
||||
m.lock.RUnlock()
|
||||
if exists == false {
|
||||
return nil, ErrSessionNotFound
|
||||
}
|
||||
if time.Now().After(data.ExpiresAt) {
|
||||
_ = m.Delete(sessionID) // ignore error
|
||||
return nil, ErrSessionExpired
|
||||
}
|
||||
copy := *data
|
||||
return ©, nil
|
||||
}
|
||||
func (m *MemoryStore) Update(sessionID string, session *SessionData) error {
|
||||
hashedSession := hashSession(sessionID)
|
||||
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
_, exist := m.sessions[hashedSession]
|
||||
if !exist {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
m.sessions[hashedSession] = session
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemoryStore) cleanup() {
|
||||
logging.Debug("Cleaning up memory store sessions")
|
||||
now := time.Now()
|
||||
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
|
||||
deleted := 0
|
||||
for id, session := range m.sessions {
|
||||
if now.After(session.ExpiresAt) {
|
||||
delete(m.sessions, id)
|
||||
deleted = deleted + 1
|
||||
}
|
||||
}
|
||||
logging.Infof("Cleaned up %d stale sessions", deleted)
|
||||
}
|
||||
|
||||
func (m *MemoryStore) Delete(sessionID string) error {
|
||||
hashedSession := hashSession(sessionID)
|
||||
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
_, exist := m.sessions[hashedSession]
|
||||
if !exist {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
delete(m.sessions, hashedSession)
|
||||
return nil
|
||||
}
|
||||
95
src/session/session_manager.go
Normal file
95
src/session/session_manager.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
)
|
||||
|
||||
const SessionCookieName = "session_token"
|
||||
|
||||
type SessionManager struct {
|
||||
store SessionStore
|
||||
}
|
||||
|
||||
var instance *SessionManager
|
||||
var once sync.Once
|
||||
|
||||
type StoreType int
|
||||
|
||||
const (
|
||||
InMemory StoreType = iota
|
||||
)
|
||||
|
||||
func GetSessionManager() *SessionManager {
|
||||
once.Do(func() {
|
||||
instance = &SessionManager{}
|
||||
})
|
||||
return instance
|
||||
}
|
||||
|
||||
func (manager *SessionManager) SetStoreType(storeType StoreType) {
|
||||
logging.Infof("Changing session manager store type")
|
||||
switch storeType {
|
||||
case InMemory:
|
||||
{
|
||||
manager.store = NewMemoryStore()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie, err error) {
|
||||
logging.Debugf("Creating a new session for %s", userID)
|
||||
token, err := GenerateSessionToken(32) // Use crypto/rand for this
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
CSRFToken, err := GenerateSessionToken(32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newSessionData := SessionData{
|
||||
UserID: userID,
|
||||
CSRFToken: CSRFToken,
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
}
|
||||
err = manager.store.Create(token, &newSessionData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newCookie := &http.Cookie{
|
||||
Name: SessionCookieName,
|
||||
Value: token,
|
||||
Path: "/",
|
||||
HttpOnly: true, // Essential: prevents JS access
|
||||
Secure: true, // Set to TRUE in production (HTTPS)
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
MaxAge: 3600, // 1 hour
|
||||
}
|
||||
return newCookie, nil
|
||||
}
|
||||
|
||||
func (manager *SessionManager) GetSession(r *http.Request) (*SessionData, error) {
|
||||
logging.Debug("Validating session from request")
|
||||
cookie, err := r.Cookie(SessionCookieName)
|
||||
if err != nil {
|
||||
return nil, ErrSessionNotFound
|
||||
}
|
||||
token := cookie.Value
|
||||
if token == "" {
|
||||
return nil, ErrSessionNotFound
|
||||
}
|
||||
data, err := manager.store.Get(token)
|
||||
if err != nil {
|
||||
return nil, ErrSessionNotFound
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (manager *SessionManager) DeleteSession(sessionId string) error {
|
||||
return manager.store.Delete(sessionId)
|
||||
}
|
||||
16
src/session/session_store.go
Normal file
16
src/session/session_store.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package session
|
||||
|
||||
import "time"
|
||||
|
||||
type SessionData struct {
|
||||
UserID string
|
||||
CSRFToken string
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Create(sessionID string, session *SessionData) error
|
||||
Get(sessionID string) (*SessionData, error)
|
||||
Update(sessionID string, session *SessionData) error
|
||||
Delete(sessionID string) error
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package main
|
||||
package worker
|
||||
|
||||
import (
|
||||
"time"
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"astraltech.xyz/accountmanager/src/logging"
|
||||
)
|
||||
|
||||
func createWorker(interval time.Duration, task func()) {
|
||||
func CreateWorker(interval time.Duration, task func()) {
|
||||
logging.Debugf("Creating worker that runs on a %s interval", interval.String())
|
||||
go func() {
|
||||
ticker := time.NewTicker(interval)
|
||||
@@ -3,11 +3,22 @@
|
||||
255,
|
||||
255,
|
||||
255,
|
||||
0.8
|
||||
1
|
||||
); /* Semi-transparent white for light theme */
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 12px;
|
||||
padding: 24px;
|
||||
padding: 2.5rem;
|
||||
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.03);
|
||||
transition: transform 0.2s ease;
|
||||
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 15px;
|
||||
}
|
||||
|
||||
.static_center {
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translateX(-50%) translateY(-50%);
|
||||
}
|
||||
|
||||
30
static/error/error.css
Normal file
30
static/error/error.css
Normal file
@@ -0,0 +1,30 @@
|
||||
.error {
|
||||
background-color: var(--error-red) !important;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
border-style: solid;
|
||||
border-color: var(--error-border-red);
|
||||
border-width: 1px;
|
||||
box-sizing: border-box;
|
||||
font-size: 12px;
|
||||
position: relative;
|
||||
color: white;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.close_error_button {
|
||||
position: absolute !important;
|
||||
background-color: rgba(0, 0, 0, 0) !important;
|
||||
padding: 0px !important;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
color: black !important;
|
||||
font-weight: normal !important;
|
||||
border: none;
|
||||
width: fit-content !important;
|
||||
}
|
||||
|
||||
.close_error_button:hover {
|
||||
cursor: default;
|
||||
font-weight: bold !important;
|
||||
}
|
||||
7
static/error/error.js
Normal file
7
static/error/error.js
Normal file
@@ -0,0 +1,7 @@
|
||||
var error_close_buttons = document.getElementsByClassName("close_error_button");
|
||||
|
||||
for (const close_button of error_close_buttons) {
|
||||
close_button.addEventListener("click", function () {
|
||||
this.parentElement.classList.add("hidden");
|
||||
});
|
||||
}
|
||||
@@ -6,51 +6,17 @@
|
||||
}
|
||||
|
||||
#login_card {
|
||||
/* The Magic Three */
|
||||
display: flex;
|
||||
flex-direction: column; /* Stack vertically */
|
||||
gap: 15px; /* Space between inputs */
|
||||
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translateX(-50%) translateY(-50%);
|
||||
|
||||
background-color: var(--bg-card);
|
||||
border: 1px solid var(--border-subtle);
|
||||
padding: 2.5rem;
|
||||
border-radius: 8px;
|
||||
width: 350px;
|
||||
|
||||
/* Soft shadow for depth in light mode */
|
||||
box-shadow:
|
||||
0 4px 12px rgba(0, 0, 0, 0.05),
|
||||
0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
#login_card input {
|
||||
padding: 12px;
|
||||
background-color: var(--bg-input);
|
||||
border: 1px solid var(--border-subtle);
|
||||
color: var(--text-main);
|
||||
border-radius: 6px;
|
||||
width: 324px;
|
||||
}
|
||||
|
||||
#login_card input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
#login_card button {
|
||||
padding: 12px;
|
||||
background-color: var(--primary-accent); /* Our Teal/Blue */
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
#login_card div {
|
||||
width: 100%;
|
||||
}
|
||||
@@ -69,48 +35,8 @@
|
||||
flex: 2;
|
||||
}
|
||||
|
||||
#login_card button:hover {
|
||||
background-color: var(--primary-hover);
|
||||
}
|
||||
|
||||
.login_text {
|
||||
color: var(--text-muted);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
#welcome_text {
|
||||
font-weight: 700;
|
||||
font-size: 1.25rem;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
#incorrect_password_text {
|
||||
background-color: var(--error-red) !important;
|
||||
border-radius: 10px;
|
||||
padding: 20px;
|
||||
border-style: solid;
|
||||
border-color: var(--error-border-red);
|
||||
border-width: 1px;
|
||||
box-sizing: border-box;
|
||||
font-size: 12px;
|
||||
position: relative;
|
||||
color: white;
|
||||
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
#incorrect_password_close_button {
|
||||
position: absolute !important;
|
||||
background-color: rgba(0, 0, 0, 0) !important;
|
||||
padding: 0px !important;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
color: black !important;
|
||||
font-weight: normal !important;
|
||||
}
|
||||
|
||||
#incorrect_password_close_button:hover {
|
||||
cursor: default;
|
||||
font-weight: bold !important;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
max-width: 500px;
|
||||
text-align: center;
|
||||
|
||||
gap: 0px !important;
|
||||
|
||||
position: fixed;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
@@ -83,6 +85,8 @@
|
||||
border-radius: 50%;
|
||||
border: none;
|
||||
padding: 6px;
|
||||
|
||||
width: fit-content !important;
|
||||
}
|
||||
|
||||
#edit_picture_button:hover {
|
||||
@@ -90,8 +94,8 @@
|
||||
}
|
||||
|
||||
#edit_picture_image {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
width: 20px !important;
|
||||
height: 20px !important;
|
||||
}
|
||||
|
||||
#picture_holder {
|
||||
@@ -100,6 +104,31 @@
|
||||
line-height: 0;
|
||||
}
|
||||
|
||||
#signout_button:hover {
|
||||
.bottom_button:hover {
|
||||
text-decoration: underline !important;
|
||||
background: none !important;
|
||||
}
|
||||
|
||||
.bottom_button {
|
||||
background: none;
|
||||
border-style: none;
|
||||
color: var(--primary-accent);
|
||||
text-decoration: none;
|
||||
font-weight: bold;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
#change_password_dialogue {
|
||||
z-index: 10000;
|
||||
position: fixed;
|
||||
}
|
||||
|
||||
#change_password_dialogue input {
|
||||
width: 350px;
|
||||
}
|
||||
|
||||
#close_password_dialogue {
|
||||
width: fit-content;
|
||||
position: absolute;
|
||||
right: 2.5rem;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,52 @@ body {
|
||||
background-color: var(--bg-main);
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
button {
|
||||
padding: 12px;
|
||||
background-color: var(--primary-accent); /* Our Teal/Blue */
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
font-weight: bold;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background-color: var(--primary-hover);
|
||||
}
|
||||
|
||||
input {
|
||||
padding: 12px;
|
||||
background-color: var(--bg-input);
|
||||
border: 1px solid var(--border-subtle);
|
||||
color: var(--text-main);
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.input_label {
|
||||
color: var(--text-muted);
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.blocked {
|
||||
position: fixed; /* or absolute */
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 9999; /* higher = on top */
|
||||
|
||||
background-color: black;
|
||||
opacity: 10%;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user