guichet/invite.go

360 lines
8.9 KiB
Go
Raw Permalink Normal View History

2020-02-14 17:57:25 +00:00
package main
import (
2020-02-14 20:58:34 +00:00
"bytes"
"crypto/rand"
"encoding/binary"
"encoding/hex"
2020-02-14 17:57:25 +00:00
"fmt"
"html/template"
2020-02-14 20:58:34 +00:00
"log"
2020-02-14 17:57:25 +00:00
"net/http"
"regexp"
"strings"
2020-02-14 20:58:34 +00:00
"github.com/emersion/go-sasl"
"github.com/emersion/go-smtp"
2020-02-14 17:57:25 +00:00
"github.com/go-ldap/ldap/v3"
2020-02-14 20:58:34 +00:00
"github.com/gorilla/mux"
2020-02-15 09:29:46 +00:00
"golang.org/x/crypto/argon2"
2020-02-14 17:57:25 +00:00
)
2020-02-14 20:58:34 +00:00
var EMAIL_REGEXP = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
2023-09-25 13:35:54 +00:00
func checkInviterLogin(w http.ResponseWriter, r *http.Request) *LoggedUser {
user := RequireUserHtml(w, r)
if user == nil {
2020-02-14 17:57:25 +00:00
return nil
}
2023-09-25 13:35:54 +00:00
if !user.Capabilities.CanInvite {
2020-02-14 17:57:25 +00:00
http.Error(w, "Not authorized to invite new users.", http.StatusUnauthorized)
return nil
}
2023-09-25 13:35:54 +00:00
return user
2020-02-14 17:57:25 +00:00
}
2020-02-14 20:58:34 +00:00
// New account creation directly from interface
func handleInviteNewAccount(w http.ResponseWriter, r *http.Request) {
2023-09-25 13:35:54 +00:00
user := checkInviterLogin(w, r)
if user == nil {
2020-02-14 20:58:34 +00:00
return
}
2023-09-25 13:35:54 +00:00
handleNewAccount(w, r, user.Login.conn, user.Login.Info.DN())
2020-02-14 20:58:34 +00:00
}
// New account creation using code
func handleInvitationCode(w http.ResponseWriter, r *http.Request) {
code := mux.Vars(r)["code"]
code_id, code_pw := readCode(code)
2023-09-25 13:35:54 +00:00
l, err := NewLdapCon()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
2020-02-14 20:58:34 +00:00
}
inviteDn := config.InvitationNameAttr + "=" + code_id + "," + config.InvitationBaseDN
2023-09-25 13:35:54 +00:00
err = l.Bind(inviteDn, code_pw)
2020-02-14 20:58:34 +00:00
if err != nil {
2023-09-26 06:40:30 +00:00
log.Println(err)
2022-12-01 22:05:59 +00:00
templateInviteInvalidCode := getTemplate("invite_invalid_code.html")
2020-02-14 20:58:34 +00:00
templateInviteInvalidCode.Execute(w, nil)
return
}
2020-02-14 21:51:12 +00:00
sReq := ldap.NewSearchRequest(
inviteDn,
ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,
fmt.Sprintf("(objectclass=*)"),
[]string{"dn", "creatorsname"},
nil)
sr, err := l.Search(sReq)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if len(sr.Entries) != 1 {
http.Error(w, fmt.Sprintf("Expected 1 entry, got %d", len(sr.Entries)), http.StatusInternalServerError)
return
}
invitedBy := sr.Entries[0].GetAttributeValue("creatorsname")
if handleNewAccount(w, r, l, invitedBy) {
2020-02-14 20:58:34 +00:00
del_req := ldap.NewDelRequest(inviteDn, nil)
err = l.Del(del_req)
if err != nil {
log.Printf("Could not delete invitation %s: %s", inviteDn, err)
}
}
}
// Common functions for new account
2020-02-14 17:57:25 +00:00
type NewAccountData struct {
Username string
DisplayName string
GivenName string
Surname string
ErrorUsernameTaken bool
ErrorInvalidUsername bool
ErrorPasswordTooShort bool
ErrorPasswordMismatch bool
ErrorMessage string
WarningMessage string
Success bool
}
2020-02-14 21:51:12 +00:00
func handleNewAccount(w http.ResponseWriter, r *http.Request, l *ldap.Conn, invitedBy string) bool {
2022-12-01 22:05:59 +00:00
templateInviteNewAccount := getTemplate("invite_new_account.html")
2020-02-14 17:57:25 +00:00
data := &NewAccountData{}
if r.Method == "POST" {
r.ParseForm()
data.Username = strings.TrimSpace(strings.Join(r.Form["username"], ""))
data.DisplayName = strings.TrimSpace(strings.Join(r.Form["displayname"], ""))
data.GivenName = strings.TrimSpace(strings.Join(r.Form["givenname"], ""))
data.Surname = strings.TrimSpace(strings.Join(r.Form["surname"], ""))
password1 := strings.Join(r.Form["password"], "")
password2 := strings.Join(r.Form["password2"], "")
2020-02-14 21:51:12 +00:00
tryCreateAccount(l, data, password1, password2, invitedBy)
2020-02-14 17:57:25 +00:00
}
templateInviteNewAccount.Execute(w, data)
2020-02-14 20:58:34 +00:00
return data.Success
2020-02-14 17:57:25 +00:00
}
2020-02-14 21:51:12 +00:00
func tryCreateAccount(l *ldap.Conn, data *NewAccountData, pass1 string, pass2 string, invitedBy string) {
2022-07-19 08:35:14 +00:00
checkFailed := false
2020-02-14 17:57:25 +00:00
// Check if username is correct
2022-07-19 08:35:14 +00:00
if match, err := regexp.MatchString("^[a-z0-9._-]+$", data.Username); !(err == nil && match) {
2020-02-14 17:57:25 +00:00
data.ErrorInvalidUsername = true
2022-07-19 08:35:14 +00:00
checkFailed = true
2020-02-14 17:57:25 +00:00
}
// Check if user exists
userDn := config.UserNameAttr + "=" + data.Username + "," + config.UserBaseDN
searchRq := ldap.NewSearchRequest(
userDn,
ldap.ScopeBaseObject, ldap.NeverDerefAliases, 0, 0, false,
"(objectclass=*)",
[]string{"dn"},
nil)
sr, err := l.Search(searchRq)
if err != nil {
data.ErrorMessage = err.Error()
2022-07-19 08:35:14 +00:00
checkFailed = true
2020-02-14 17:57:25 +00:00
}
if len(sr.Entries) > 0 {
data.ErrorUsernameTaken = true
2022-07-19 08:35:14 +00:00
checkFailed = true
2020-02-14 17:57:25 +00:00
}
// Check that password is long enough
if len(pass1) < 8 {
data.ErrorPasswordTooShort = true
2022-07-19 08:35:14 +00:00
checkFailed = true
2020-02-14 17:57:25 +00:00
}
if pass1 != pass2 {
data.ErrorPasswordMismatch = true
2022-07-19 08:35:14 +00:00
checkFailed = true
2020-02-14 17:57:25 +00:00
}
2022-07-19 08:35:14 +00:00
if checkFailed {
return
}
2022-07-19 08:35:14 +00:00
2020-02-14 17:57:25 +00:00
// Actually create user
req := ldap.NewAddRequest(userDn, nil)
req.Attribute("objectclass", []string{"inetOrgPerson", "organizationalPerson", "person", "top"})
req.Attribute("structuralobjectclass", []string{"inetOrgPerson"})
2022-07-19 08:35:14 +00:00
pw, err := SSHAEncode(pass1)
if err != nil {
data.ErrorMessage = err.Error()
return
}
req.Attribute("userpassword", []string{pw})
2020-02-14 21:51:12 +00:00
req.Attribute("invitedby", []string{invitedBy})
2020-02-14 17:57:25 +00:00
if len(data.DisplayName) > 0 {
req.Attribute("displayname", []string{data.DisplayName})
}
if len(data.GivenName) > 0 {
req.Attribute("givenname", []string{data.GivenName})
}
if len(data.Surname) > 0 {
req.Attribute("sn", []string{data.Surname})
}
if len(config.InvitedMailFormat) > 0 {
email := strings.ReplaceAll(config.InvitedMailFormat, "{}", data.Username)
req.Attribute("mail", []string{email})
}
err = l.Add(req)
if err != nil {
data.ErrorMessage = err.Error()
return
}
for _, group := range config.InvitedAutoGroups {
req := ldap.NewModifyRequest(group, nil)
req.Add("member", []string{userDn})
err = l.Modify(req)
if err != nil {
data.WarningMessage += fmt.Sprintf("Cannot add to %s: %s\n", group, err.Error())
}
}
data.Success = true
}
2020-02-14 20:58:34 +00:00
// ---- Code generation ----
type SendCodeData struct {
ErrorMessage string
ErrorInvalidEmail bool
Success bool
CodeDisplay string
CodeSentTo string
WebBaseAddress string
}
type CodeMailFields struct {
From string
To string
Code string
InviteFrom string
WebBaseAddress string
}
2020-02-14 17:57:25 +00:00
func handleInviteSendCode(w http.ResponseWriter, r *http.Request) {
2022-12-01 22:05:59 +00:00
templateInviteSendCode := getTemplate("invite_send_code.html")
2020-02-14 20:58:34 +00:00
2023-09-25 13:35:54 +00:00
user := checkInviterLogin(w, r)
if user == nil {
2020-02-14 20:58:34 +00:00
return
}
data := &SendCodeData{
WebBaseAddress: config.WebAddress,
}
if r.Method == "POST" {
r.ParseForm()
choice := strings.Join(r.Form["choice"], "")
sendto := strings.Join(r.Form["sendto"], "")
2020-02-14 21:40:44 +00:00
if choice == "display" || choice == "send" {
2023-09-25 13:35:54 +00:00
trySendCode(user, choice, sendto, data)
2020-02-14 21:40:44 +00:00
}
2020-02-14 20:58:34 +00:00
}
templateInviteSendCode.Execute(w, data)
}
2023-09-25 13:35:54 +00:00
func trySendCode(user *LoggedUser, choice string, sendto string, data *SendCodeData) {
2020-02-14 20:58:34 +00:00
// Generate code
code, code_id, code_pw := genCode()
// Create invitation object in database
inviteDn := config.InvitationNameAttr + "=" + code_id + "," + config.InvitationBaseDN
req := ldap.NewAddRequest(inviteDn, nil)
2022-07-19 08:35:14 +00:00
pw, err := SSHAEncode(code_pw)
if err != nil {
data.ErrorMessage = err.Error()
return
}
req.Attribute("userpassword", []string{pw})
2020-02-14 20:58:34 +00:00
req.Attribute("objectclass", []string{"top", "invitationCode"})
2023-09-25 13:35:54 +00:00
err = user.Login.conn.Add(req)
2020-02-14 20:58:34 +00:00
if err != nil {
data.ErrorMessage = err.Error()
return
}
// If we want to display it, do so
if choice == "display" {
data.Success = true
data.CodeDisplay = code
return
}
// Otherwise, we are sending a mail
if !EMAIL_REGEXP.MatchString(sendto) {
data.ErrorInvalidEmail = true
return
}
2022-12-01 22:05:59 +00:00
templateMail := template.Must(template.ParseFiles(templatePath + "/invite_mail.txt"))
2020-02-14 20:58:34 +00:00
buf := bytes.NewBuffer([]byte{})
templateMail.Execute(buf, &CodeMailFields{
To: sendto,
From: config.MailFrom,
2023-09-25 13:35:54 +00:00
InviteFrom: user.WelcomeName(),
2020-02-14 20:58:34 +00:00
Code: code,
WebBaseAddress: config.WebAddress,
})
log.Printf("Sending mail to: %s", sendto)
var auth sasl.Client = nil
if config.SMTPUsername != "" {
auth = sasl.NewPlainClient("", config.SMTPUsername, config.SMTPPassword)
}
err = smtp.SendMail(config.SMTPServer, auth, config.MailFrom, []string{sendto}, buf)
if err != nil {
data.ErrorMessage = err.Error()
return
}
log.Printf("Mail sent.")
data.Success = true
data.CodeSentTo = sendto
}
func genCode() (code string, code_id string, code_pw string) {
random := make([]byte, 32)
n, err := rand.Read(random)
if err != nil || n != 32 {
log.Fatalf("Could not generate random bytes: %s", err)
}
a := binary.BigEndian.Uint32(random[0:4])
b := binary.BigEndian.Uint32(random[4:8])
c := binary.BigEndian.Uint32(random[8:12])
code = fmt.Sprintf("%03d-%03d-%03d", a%1000, b%1000, c%1000)
code_id, code_pw = readCode(code)
return
}
func readCode(code string) (code_id string, code_pw string) {
// Strip everything that is not a digit
code_digits := ""
for _, c := range code {
if c >= '0' && c <= '9' {
code_digits = code_digits + string(c)
}
}
2020-02-15 09:29:46 +00:00
id_hash := argon2.IDKey([]byte(code_digits), []byte("Guichet ID"), 2, 64*1024, 4, 32)
pw_hash := argon2.IDKey([]byte(code_digits), []byte("Guichet PW"), 2, 64*1024, 4, 32)
2020-02-14 20:58:34 +00:00
code_id = hex.EncodeToString(id_hash[:8])
code_pw = hex.EncodeToString(pw_hash[:16])
return
2020-02-14 17:57:25 +00:00
}