login-validator: talk to remote validator to register new users

This commit is contained in:
nemunaire 2018-02-22 00:17:07 +01:00 committed by Pierre-Olivier Mercier
parent 60a6b70ccf
commit 6bcc445691

View File

@ -1,9 +1,11 @@
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha512"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
@ -15,6 +17,7 @@ import (
"path"
"strings"
"text/template"
"time"
"gopkg.in/ldap.v2"
)
@ -152,6 +155,12 @@ func (l loginChecker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
if err := l.registerUser(lu.Username, r.RemoteAddr); err != nil {
log.Println("Error on remote registration:", err)
http.Error(w, "Internal server error. Please retry in a few minutes", http.StatusInternalServerError)
return
}
if err := l.lateLoginAction(lu.Username, r.RemoteAddr); err != nil {
log.Println("Error on late login action:", err)
http.Error(w, "Internal server error. Please retry in a few minutes", http.StatusInternalServerError)
@ -162,6 +171,32 @@ func (l loginChecker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Success", http.StatusOK)
}
func (l loginChecker) registerUser(username, remoteAddr string) error {
bts, err := json.Marshal(map[string]interface{}{"login": username})
if err != nil {
return nil
}
req, err := http.NewRequest("POST", "https://adlin.nemunai.re/api/students/", bytes.NewReader(bts))
if err != nil {
return err
}
req.Header.Add("X-ADLIN-Authentication", base64.StdEncoding.EncodeToString(hmac.New(sha512.New, []byte(loginSalt)).Sum([]byte(fmt.Sprintf("%d", time.Now().Unix()/10)))))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
} else {
return nil
}
}
func (l loginChecker) lateLoginAction(username, remoteAddr string) error {
// Find corresponding MAC
var fname string