gvguichet/main.go

350 lines
7.9 KiB
Go
Raw Normal View History

2020-02-09 14:46:52 +01:00
package main
import (
2020-02-09 15:01:20 +01:00
"crypto/rand"
2020-02-09 15:44:18 +01:00
"crypto/tls"
2020-02-09 16:46:26 +01:00
"encoding/base64"
"encoding/json"
"flag"
"fmt"
2020-02-09 15:44:18 +01:00
"html/template"
2020-02-09 16:46:26 +01:00
"io/ioutil"
"log"
"net/http"
"os"
"strings"
2020-02-09 14:46:52 +01:00
2020-02-09 15:44:18 +01:00
"github.com/go-ldap/ldap/v3"
2020-02-09 22:06:33 +01:00
"github.com/gorilla/mux"
2020-02-09 23:04:37 +01:00
"github.com/gorilla/sessions"
2020-02-09 14:46:52 +01:00
)
2020-02-09 15:01:20 +01:00
type ConfigFile struct {
HttpBindAddr string `json:"http_bind_addr"`
SessionKey string `json:"session_key"`
LdapServerAddr string `json:"ldap_server_addr"`
2020-02-09 16:46:26 +01:00
LdapTLS bool `json:"ldap_tls"`
2020-02-09 23:04:37 +01:00
BaseDN string `json:"base_dn"`
UserBaseDN string `json:"user_base_dn"`
UserNameAttr string `json:"user_name_attr"`
GroupBaseDN string `json:"group_base_dn"`
GroupNameAttr string `json:"group_name_attr"`
GroupCanInvite string `json:"group_can_invite"`
GroupCanAdmin string `json:"group_can_admin"`
2020-02-09 15:01:20 +01:00
}
2020-02-09 14:46:52 +01:00
2020-02-09 15:01:20 +01:00
var configFlag = flag.String("config", "./config.json", "Configuration file path")
2020-02-09 15:44:18 +01:00
var config *ConfigFile
const SESSION_NAME = "guichet_session"
2020-02-09 16:46:26 +01:00
var store sessions.Store = nil
func readConfig() ConfigFile {
2020-02-09 15:01:20 +01:00
key_bytes := make([]byte, 32)
n, err := rand.Read(key_bytes)
2020-02-09 16:46:26 +01:00
if err != nil || n != 32 {
2020-02-09 15:01:20 +01:00
log.Fatal(err)
}
config_file := ConfigFile{
HttpBindAddr: ":9991",
SessionKey: base64.StdEncoding.EncodeToString(key_bytes),
2020-02-09 15:44:18 +01:00
LdapServerAddr: "ldap://127.0.0.1:389",
2020-02-09 16:46:26 +01:00
LdapTLS: false,
2020-02-09 23:04:37 +01:00
BaseDN: "dc=example,dc=com",
UserBaseDN: "ou=users,dc=example,dc=com",
UserNameAttr: "uid",
GroupBaseDN: "ou=groups,dc=example,dc=com",
GroupNameAttr: "gid",
GroupCanInvite: "",
GroupCanAdmin: "gid=admin,ou=groups,dc=example,dc=com",
2020-02-09 15:01:20 +01:00
}
_, err = os.Stat(*configFlag)
if os.IsNotExist(err) {
// Generate default config file
log.Printf("Generating default config file as %s", *configFlag)
bytes, err := json.MarshalIndent(&config_file, "", " ")
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile(*configFlag, bytes, 0644)
if err != nil {
log.Fatal(err)
}
return config_file
}
if err != nil {
log.Fatal(err)
}
bytes, err := ioutil.ReadFile(*configFlag)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(bytes, &config_file)
if err != nil {
log.Fatal(err)
}
return config_file
2020-02-09 14:46:52 +01:00
}
func main() {
2020-02-09 15:01:20 +01:00
flag.Parse()
2020-02-09 14:46:52 +01:00
2020-02-09 15:44:18 +01:00
config_file := readConfig()
config = &config_file
2020-02-09 16:46:26 +01:00
store = sessions.NewFilesystemStore("", []byte(config.SessionKey))
2020-02-09 15:01:20 +01:00
2020-02-09 22:06:33 +01:00
r := mux.NewRouter()
r.HandleFunc("/", handleHome)
r.HandleFunc("/logout", handleLogout)
r.HandleFunc("/profile", handleProfile)
r.HandleFunc("/passwd", handlePasswd)
2020-02-09 14:46:52 +01:00
2020-02-09 22:06:33 +01:00
r.HandleFunc("/admin/users", handleAdminUsers)
r.HandleFunc("/admin/groups", handleAdminGroups)
r.HandleFunc("/admin/ldap/{dn}", handleAdminLDAP)
2020-02-09 23:04:27 +01:00
r.HandleFunc("/admin/create/{template}/{super_dn}", handleAdminCreate)
2020-02-09 18:28:42 +01:00
2020-02-09 15:44:18 +01:00
staticfiles := http.FileServer(http.Dir("static"))
2020-02-09 22:06:33 +01:00
r.Handle("/static/{file:.*}", http.StripPrefix("/static/", staticfiles))
2020-02-09 15:44:18 +01:00
2020-02-09 22:06:33 +01:00
err := http.ListenAndServe(config.HttpBindAddr, logRequest(r))
2020-02-09 14:46:52 +01:00
if err != nil {
log.Fatal("Cannot start http server: ", err)
}
}
2020-02-09 15:01:20 +01:00
2020-02-09 15:44:18 +01:00
type LoginInfo struct {
Username string
2020-02-09 16:46:26 +01:00
DN string
2020-02-09 15:44:18 +01:00
Password string
2020-02-09 16:46:26 +01:00
}
2020-02-09 15:44:18 +01:00
2020-02-09 17:35:16 +01:00
type LoginStatus struct {
Info *LoginInfo
conn *ldap.Conn
2020-02-09 17:35:16 +01:00
UserEntry *ldap.Entry
}
2020-02-09 15:44:18 +01:00
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
2020-02-09 17:35:16 +01:00
func checkLogin(w http.ResponseWriter, r *http.Request) *LoginStatus {
2020-02-09 15:44:18 +01:00
session, err := store.Get(r, SESSION_NAME)
2020-02-09 16:46:26 +01:00
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
2020-02-09 15:44:18 +01:00
2020-02-09 16:46:26 +01:00
username, ok := session.Values["login_username"]
password, ok2 := session.Values["login_password"]
user_dn, ok3 := session.Values["login_dn"]
2020-02-09 17:35:16 +01:00
var login_info *LoginInfo
2020-02-09 16:46:26 +01:00
if !(ok && ok2 && ok3) {
2020-02-09 17:35:16 +01:00
login_info = handleLogin(w, r)
if login_info == nil {
return nil
}
} else {
login_info = &LoginInfo{
DN: user_dn.(string),
Username: username.(string),
Password: password.(string),
}
2020-02-09 15:44:18 +01:00
}
2020-02-09 17:35:16 +01:00
l := ldapOpen(w)
if l == nil {
return nil
}
err = l.Bind(login_info.DN, login_info.Password)
if err != nil {
delete(session.Values, "login_username")
delete(session.Values, "login_password")
delete(session.Values, "login_dn")
err = session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
return checkLogin(w, r)
}
searchRequest := ldap.NewSearchRequest(
login_info.DN,
ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(&(objectClass=organizationalPerson))"),
[]string{"dn", "displayname", "givenname", "sn", "mail", "memberof"},
2020-02-09 17:35:16 +01:00
nil)
sr, err := l.Search(searchRequest)
if err != nil {
2020-02-09 17:35:16 +01:00
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
if len(sr.Entries) != 1 {
http.Error(w, fmt.Sprintf("Multiple entries: %#v", sr.Entries), http.StatusInternalServerError)
return nil
}
return &LoginStatus{
Info: login_info,
conn: l,
2020-02-09 17:35:16 +01:00
UserEntry: sr.Entries[0],
2020-02-09 16:46:26 +01:00
}
2020-02-09 15:44:18 +01:00
}
func ldapOpen(w http.ResponseWriter) *ldap.Conn {
l, err := ldap.DialURL(config.LdapServerAddr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
if config.LdapTLS {
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
}
return l
}
2020-02-09 15:01:20 +01:00
// Page handlers ----
type HomePageData struct {
Login *LoginStatus
CanAdmin bool
CanInvite bool
2020-02-09 23:04:37 +01:00
BaseDN string
}
2020-02-09 15:01:20 +01:00
func handleHome(w http.ResponseWriter, r *http.Request) {
2020-02-09 16:46:26 +01:00
templateHome := template.Must(template.ParseFiles("templates/layout.html", "templates/home.html"))
2020-02-09 15:44:18 +01:00
login := checkLogin(w, r)
if login == nil {
return
}
can_admin := false
can_invite := false
for _, group := range login.UserEntry.GetAttributeValues("memberof") {
if config.GroupCanInvite != "" && group == config.GroupCanInvite {
can_invite = true
}
if config.GroupCanAdmin != "" && group == config.GroupCanAdmin {
can_admin = true
}
}
templateHome.Execute(w, &HomePageData{
Login: login,
CanAdmin: can_admin,
CanInvite: can_invite,
2020-02-09 23:04:37 +01:00
BaseDN: config.BaseDN,
})
2020-02-09 15:44:18 +01:00
}
2020-02-09 16:46:26 +01:00
func handleLogout(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, SESSION_NAME)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
delete(session.Values, "login_username")
delete(session.Values, "login_password")
delete(session.Values, "login_dn")
err = session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
type LoginFormData struct {
Username string
ErrorMessage string
}
2020-02-09 15:44:18 +01:00
func handleLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
2020-02-09 16:46:26 +01:00
templateLogin := template.Must(template.ParseFiles("templates/layout.html", "templates/login.html"))
2020-02-09 15:44:18 +01:00
if r.Method == "GET" {
templateLogin.Execute(w, LoginFormData{})
return nil
} else if r.Method == "POST" {
r.ParseForm()
username := strings.Join(r.Form["username"], "")
2020-02-09 16:46:26 +01:00
password := strings.Join(r.Form["password"], "")
user_dn := fmt.Sprintf("%s=%s,%s", config.UserNameAttr, username, config.UserBaseDN)
2020-02-09 15:44:18 +01:00
l := ldapOpen(w)
if l == nil {
return nil
}
2020-02-09 16:46:26 +01:00
err := l.Bind(user_dn, password)
2020-02-09 15:44:18 +01:00
if err != nil {
templateLogin.Execute(w, LoginFormData{
2020-02-09 16:46:26 +01:00
Username: username,
2020-02-09 15:44:18 +01:00
ErrorMessage: err.Error(),
})
return nil
}
// Successfully logged in, save it to session
session, err := store.Get(r, SESSION_NAME)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
2020-02-09 16:46:26 +01:00
session.Values["login_username"] = username
session.Values["login_password"] = password
session.Values["login_dn"] = user_dn
err = session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
return &LoginInfo{
DN: user_dn,
Username: username,
Password: password,
}
2020-02-09 15:44:18 +01:00
} else {
http.Error(w, "Unsupported method", http.StatusBadRequest)
return nil
}
2020-02-09 15:01:20 +01:00
}