Implement logout

This commit is contained in:
Alex Auvolat 2020-02-09 16:46:26 +01:00
parent 3fe43f85ae
commit ebb7553cc8
5 changed files with 112 additions and 59 deletions

91
main.go
View File

@ -1,20 +1,20 @@
package main package main
import ( import (
"os"
"strings"
"flag"
"log"
"net/http"
"io/ioutil"
"encoding/json"
"encoding/base64"
"crypto/rand" "crypto/rand"
"crypto/tls" "crypto/tls"
"encoding/base64"
"encoding/json"
"flag"
"html/template" "html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/gorilla/sessions"
"github.com/go-ldap/ldap/v3" "github.com/go-ldap/ldap/v3"
"github.com/gorilla/sessions"
) )
type ConfigFile struct { type ConfigFile struct {
@ -30,7 +30,8 @@ var configFlag = flag.String("config", "./config.json", "Configuration file path
var config *ConfigFile var config *ConfigFile
const SESSION_NAME = "guichet_session" const SESSION_NAME = "guichet_session"
var store *sessions.CookieStore = nil
var store sessions.Store = nil
func readConfig() ConfigFile { func readConfig() ConfigFile {
key_bytes := make([]byte, 32) key_bytes := make([]byte, 32)
@ -87,9 +88,10 @@ func main() {
config_file := readConfig() config_file := readConfig()
config = &config_file config = &config_file
store = sessions.NewCookieStore([]byte(config.SessionKey)) store = sessions.NewFilesystemStore("", []byte(config.SessionKey))
http.HandleFunc("/", handleHome) http.HandleFunc("/", handleHome)
http.HandleFunc("/logout", handleLogout)
staticfiles := http.FileServer(http.Dir("static")) staticfiles := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", staticfiles)) http.Handle("/static/", http.StripPrefix("/static/", staticfiles))
@ -120,12 +122,18 @@ func checkLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
return nil return nil
} }
login_info, has_login_info := session.Values["login_info"] username, ok := session.Values["login_username"]
if !has_login_info { password, ok2 := session.Values["login_password"]
user_dn, ok3 := session.Values["login_dn"]
if !(ok && ok2 && ok3) {
return handleLogin(w, r) return handleLogin(w, r)
} }
return login_info.(*LoginInfo) return &LoginInfo{
DN: user_dn.(string),
Username: username.(string),
Password: password.(string),
}
} }
func ldapOpen(w http.ResponseWriter) *ldap.Conn { func ldapOpen(w http.ResponseWriter) *ldap.Conn {
@ -153,14 +161,11 @@ type LoginFormData struct {
ErrorMessage string ErrorMessage string
} }
var (
templateLogin = template.Must(template.ParseFiles("templates/layout.html", "templates/login.html"))
templateHome = template.Must(template.ParseFiles("templates/layout.html", "templates/home.html"))
)
// Page handlers ---- // Page handlers ----
func handleHome(w http.ResponseWriter, r *http.Request) { func handleHome(w http.ResponseWriter, r *http.Request) {
templateHome := template.Must(template.ParseFiles("templates/layout.html", "templates/home.html"))
login := checkLogin(w, r) login := checkLogin(w, r)
if login == nil { if login == nil {
return return
@ -169,7 +174,29 @@ func handleHome(w http.ResponseWriter, r *http.Request) {
templateHome.Execute(w, login) templateHome.Execute(w, login)
} }
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)
}
func handleLogin(w http.ResponseWriter, r *http.Request) *LoginInfo { func handleLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
templateLogin := template.Must(template.ParseFiles("templates/layout.html", "templates/login.html"))
if r.Method == "GET" { if r.Method == "GET" {
templateLogin.Execute(w, LoginFormData{}) templateLogin.Execute(w, LoginFormData{})
return nil return nil
@ -177,20 +204,15 @@ func handleLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
r.ParseForm() r.ParseForm()
username := strings.Join(r.Form["username"], "") username := strings.Join(r.Form["username"], "")
password := strings.Join(r.Form["password"], "")
user_dn := strings.ReplaceAll(config.UserFormat, "%s", username) user_dn := strings.ReplaceAll(config.UserFormat, "%s", username)
login_info := &LoginInfo{
DN: user_dn,
Username: username,
Password: strings.Join(r.Form["password"], ""),
}
l := ldapOpen(w) l := ldapOpen(w)
if l == nil { if l == nil {
return nil return nil
} }
err := l.Bind(user_dn, login_info.Password) err := l.Bind(user_dn, password)
if err != nil { if err != nil {
templateLogin.Execute(w, LoginFormData{ templateLogin.Execute(w, LoginFormData{
Username: username, Username: username,
@ -206,8 +228,21 @@ func handleLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
return nil return nil
} }
session.Values["login_info"] = login_info session.Values["login_username"] = username
return login_info 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,
}
} else { } else {
http.Error(w, "Unsupported method", http.StatusBadRequest) http.Error(w, "Unsupported method", http.StatusBadRequest)
return nil return nil

View File

@ -1,6 +0,0 @@
#contents {
width: 800px;
margin: auto;
margin-top: 16px;
}

View File

@ -1,7 +1,18 @@
{{define "title"}}Guichet{{end}} {{define "title"}}Guichet{{end}}
{{define "body"}} {{define "body"}}
<h1>Guichet</h1> <div class="alert alert-success">
Bienvenue, <strong>{{ .Username }}</strong> !
</div>
<div class="card">
<div class="card-header">
Gérer mon compte
</div>
<div class="list-group list-group-flush">
<a class="list-group-item list-group-item-action" href="/">Test</a>
<a class="list-group-item list-group-item-action" href="/logout">Se déconnecter</a>
</div>
</div>
Welcome, {{ .Username }}!
{{end}} {{end}}

View File

@ -2,12 +2,16 @@
<html> <html>
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>{{template "title"}}</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="/static/css/bootstrap.min.css"> <link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/main.css">
<title>{{template "title"}} Guichet</title>
</head> </head>
<body> <body>
<div id="contents"> <div class="container">
<h1>Guichet Deuxfleurs💮💮</h1>
<hr />
{{template "body" .}} {{template "body" .}}
</div> </div>
</body> </body>

View File

@ -1,12 +1,21 @@
{{define "title"}}Log in{{end}} {{define "title"}}{{end}}
{{define "body"}} {{define "body"}}
<h1>Log in</h1>
<form method="POST"> <form method="POST">
<div>{{ .ErrorMessage }}</div> {{if .ErrorMessage}}
Username: <input type="text" name="username" value="{{ .Username }}" /><br /> <div class="alert alert-danger">Impossible de se connecter.
Password: <input type="password" name="password" /><br /> <div style="font-size: 0.8em">{{ .ErrorMessage }}</div>
<input type="submit" value="log in"> </div>
{{end}}
<div class="form-group">
<label for="username">Nom d'utilisateur:</label>
<input type="text" name="username" id="username" class="form-control" value="{{ .Username }}" />
</div>
<div class="form-group">
<label for="password">Mot de passe:</label>
<input type="password" name="password" id="password" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Se connecter</button>
</form> </form>
{{end}} {{end}}