Compare commits
11 Commits
33ea56fb0c
...
v0.0.4
| Author | SHA1 | Date | |
|---|---|---|---|
| a315161ed3 | |||
| e2531e3021 | |||
| a2602f74f0 | |||
| 1c1ba99080 | |||
| ad21d50ce5 | |||
| 3a3fab08f6 | |||
| bb649aef48 | |||
| f204069392 | |||
| ac663f21e1 | |||
| d1992ec466 | |||
| 46db63e62a |
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 (
|
import (
|
||||||
"net/smtp"
|
"net/smtp"
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package main
|
package helpers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"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
|
||||||
|
}
|
||||||
181
src/main/ldap.go
181
src/main/ldap.go
@@ -1,181 +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 changeLDAPPassword(server *LDAPServer, userDN, oldPassword, newPassword string) error {
|
|
||||||
logging.Infof("Changing LDAP password for %s", userDN)
|
|
||||||
|
|
||||||
if server == nil || server.Connection == nil {
|
|
||||||
return fmt.Errorf("LDAP connection not initialized")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure connection is alive
|
|
||||||
if server.Connection.IsClosing() {
|
|
||||||
if err := reconnectToLDAPServer(server); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bind as the user (required for FreeIPA self-password change)
|
|
||||||
err := server.Connection.Bind(userDN, oldPassword)
|
|
||||||
if err != nil {
|
|
||||||
logging.Errorf("Failed to bind as user: %s", err.Error())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Perform password modify extended operation
|
|
||||||
_, err = server.Connection.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 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) }
|
|
||||||
228
src/main/main.go
228
src/main/main.go
@@ -3,24 +3,22 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"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/logging"
|
||||||
"astraltech.xyz/accountmanager/src/session"
|
"astraltech.xyz/accountmanager/src/session"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ldapServer *LDAPServer
|
ldapServer ldap.LDAPServer
|
||||||
ldapServerMutex sync.Mutex
|
serverConfig *ServerConfig
|
||||||
serverConfig *ServerConfig
|
sessionManager *session.SessionManager
|
||||||
sessionManager *session.SessionManager
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type UserData struct {
|
type UserData struct {
|
||||||
@@ -30,62 +28,35 @@ type UserData struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
userData = make(map[string]UserData)
|
userData = make(map[string]*UserData)
|
||||||
userDataMutex sync.RWMutex
|
userDataMutex sync.RWMutex
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
func authenticateUser(username, password string) (*UserData, error) {
|
||||||
photoCreatedTimestamp = make(map[string]time.Time)
|
|
||||||
photoCreatedMutex sync.Mutex
|
|
||||||
blankPhotoData []byte
|
|
||||||
)
|
|
||||||
|
|
||||||
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) {
|
|
||||||
logging.Event(logging.AuthenticateUser, username)
|
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)
|
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(
|
connected, err := ldapServer.AuthenticateUser(userDN, password)
|
||||||
ldapServer,
|
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,
|
serverConfig.LDAPConfig.BaseDN,
|
||||||
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldapEscapeFilter(username)),
|
fmt.Sprintf("(&(objectClass=inetOrgPerson)(uid=%s))", ldap.LDAPEscapeFilter(username)),
|
||||||
[]string{"displayName", "mail", "jpegphoto"},
|
[]string{"displayName", "mail", "jpegphoto"},
|
||||||
)
|
)
|
||||||
if !userSearch.Succeeded {
|
if err != nil {
|
||||||
return UserData{isAuth: false}, fmt.Errorf("user metadata not found")
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
entry := userSearch.LDAPSearch.Entries[0]
|
entry := userSearch.GetEntry(0)
|
||||||
user := UserData{
|
user := UserData{
|
||||||
isAuth: true,
|
isAuth: true,
|
||||||
DisplayName: entry.GetAttributeValue("displayName"),
|
DisplayName: entry.GetAttributeValue("displayName"),
|
||||||
@@ -94,9 +65,9 @@ func authenticateUser(username, password string) (UserData, error) {
|
|||||||
|
|
||||||
photoData := entry.GetRawAttributeValue("jpegphoto")
|
photoData := entry.GetRawAttributeValue("jpegphoto")
|
||||||
if len(photoData) > 0 {
|
if len(photoData) > 0 {
|
||||||
createUserPhoto(username, photoData)
|
components.CreateUserPhoto(username, photoData)
|
||||||
}
|
}
|
||||||
return user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type LoginPageData struct {
|
type LoginPageData struct {
|
||||||
@@ -128,7 +99,7 @@ func loginHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
userData[username] = newUserData
|
userData[username] = newUserData
|
||||||
userDataMutex.Unlock()
|
userDataMutex.Unlock()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print(err)
|
logging.Error(err.Error())
|
||||||
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
|
tmpl.Execute(w, LoginPageData{IsHiddenClassList: ""})
|
||||||
} else {
|
} else {
|
||||||
if newUserData.isAuth == true {
|
if newUserData.isAuth == true {
|
||||||
@@ -177,57 +148,6 @@ func profileHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
func logoutHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
cookie, err := r.Cookie("session_token")
|
cookie, err := r.Cookie("session_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -251,48 +171,6 @@ func logoutHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||||
}
|
}
|
||||||
|
|
||||||
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, serverConfig.LDAPConfig.BaseDN)
|
|
||||||
ldapServerMutex.Lock()
|
|
||||||
defer ldapServerMutex.Unlock()
|
|
||||||
modifyLDAPAttribute(ldapServer, userDN, "jpegphoto", []string{string(data)})
|
|
||||||
createUserPhoto(sessionData.UserID, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func faviconHandler(w http.ResponseWriter, r *http.Request) {
|
func faviconHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
logging.Info("Requesting Favicon")
|
logging.Info("Requesting Favicon")
|
||||||
http.ServeFile(w, r, serverConfig.StyleConfig.FaviconPath)
|
http.ServeFile(w, r, serverConfig.StyleConfig.FaviconPath)
|
||||||
@@ -343,7 +221,7 @@ func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
serverConfig.LDAPConfig.BaseDN,
|
serverConfig.LDAPConfig.BaseDN,
|
||||||
)
|
)
|
||||||
|
|
||||||
err = changeLDAPPassword(ldapServer, userDN, oldPassword, newPassword)
|
err = ldapServer.ChangePassword(userDN, oldPassword, newPassword)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
|
||||||
@@ -363,37 +241,47 @@ func changePasswordHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
logging.Info("Starting the server")
|
logging.Info("Starting the server")
|
||||||
sessionManager = session.CreateSessionManager(session.InMemory)
|
sessionManager = session.GetSessionManager()
|
||||||
|
sessionManager.SetStoreType(session.InMemory)
|
||||||
|
|
||||||
var err error = nil
|
var err error
|
||||||
blankPhotoData, err = ReadFile("static/blank_profile.jpg")
|
|
||||||
if err != nil {
|
|
||||||
logging.Fatal("Could not load blank profile image")
|
|
||||||
}
|
|
||||||
serverConfig, err = loadServerConfig("./data/config.json")
|
serverConfig, err = loadServerConfig("./data/config.json")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Could not load server config")
|
log.Fatal("Could not load server config")
|
||||||
}
|
}
|
||||||
|
|
||||||
ldapServerMutex.Lock()
|
ldapServer = ldap.LDAPServer{
|
||||||
server := connectToLDAPServer(serverConfig.LDAPConfig.LDAPURL, serverConfig.LDAPConfig.Security == "tls", serverConfig.LDAPConfig.IgnoreInvalidCert)
|
URL: serverConfig.LDAPConfig.LDAPURL,
|
||||||
ldapServer = server
|
StartTLS: serverConfig.LDAPConfig.Security == "tls",
|
||||||
ldapServerMutex.Unlock()
|
IgnoreInsecureCert: serverConfig.LDAPConfig.IgnoreInvalidCert,
|
||||||
defer closeLDAPServer(ldapServer)
|
}
|
||||||
|
|
||||||
HandleFunc("/favicon.ico", faviconHandler)
|
components.LDAPServer = &ldapServer
|
||||||
HandleFunc("/logo", logoHandler)
|
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"))))
|
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
|
||||||
HandleFunc("/login", loginHandler)
|
helpers.HandleFunc("/login", loginHandler)
|
||||||
HandleFunc("/profile", profileHandler)
|
helpers.HandleFunc("/profile", profileHandler)
|
||||||
HandleFunc("/logout", logoutHandler)
|
helpers.HandleFunc("/logout", logoutHandler)
|
||||||
|
|
||||||
HandleFunc("/avatar", avatarHandler)
|
helpers.HandleFunc("/avatar", components.AvatarHandler)
|
||||||
HandleFunc("/change-photo", uploadPhotoHandler)
|
helpers.HandleFunc("/change-photo", components.UploadPhotoHandler)
|
||||||
HandleFunc("/change-password", changePasswordHandler)
|
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
|
http.Redirect(w, r, "/profile", http.StatusFound) // 302 redirect
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package session
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"astraltech.xyz/accountmanager/src/logging"
|
"astraltech.xyz/accountmanager/src/logging"
|
||||||
@@ -13,22 +14,31 @@ type SessionManager struct {
|
|||||||
store SessionStore
|
store SessionStore
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var instance *SessionManager
|
||||||
|
var once sync.Once
|
||||||
|
|
||||||
type StoreType int
|
type StoreType int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
InMemory StoreType = iota
|
InMemory StoreType = iota
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateSessionManager(storeType StoreType) *SessionManager {
|
func GetSessionManager() *SessionManager {
|
||||||
sessionManager := SessionManager{}
|
once.Do(func() {
|
||||||
|
instance = &SessionManager{}
|
||||||
|
})
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
|
||||||
|
func (manager *SessionManager) SetStoreType(storeType StoreType) {
|
||||||
|
logging.Infof("Changing session manager store type")
|
||||||
switch storeType {
|
switch storeType {
|
||||||
case InMemory:
|
case InMemory:
|
||||||
{
|
{
|
||||||
sessionManager.store = NewMemoryStore()
|
manager.store = NewMemoryStore()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return &sessionManager
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie, err error) {
|
func (manager *SessionManager) CreateSession(userID string) (cookie *http.Cookie, err error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user