79 lines
1.8 KiB
Go
79 lines
1.8 KiB
Go
|
package web
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"github.com/google/uuid"
|
||
|
"golang.org/x/crypto/bcrypt"
|
||
|
)
|
||
|
|
||
|
var sessions map[string]time.Time
|
||
|
|
||
|
func init() {
|
||
|
sessions = make(map[string]time.Time)
|
||
|
}
|
||
|
|
||
|
func auth(w http.ResponseWriter, r *http.Request) {
|
||
|
switch r.Method {
|
||
|
case "POST":
|
||
|
password := r.FormValue("password")
|
||
|
if bcrypt.CompareHashAndPassword([]byte("$2a$04$i4bdOiia2YFN7JXfXLgO4ONCffC67ECyzPEcTLzoP3Lzse/sZT5EC"), []byte(password)) != nil {
|
||
|
w.WriteHeader(401)
|
||
|
w.Write([]byte("Wrong Password"))
|
||
|
return
|
||
|
}
|
||
|
token := uuid.New().String()
|
||
|
sessions[token] = time.Now().Add(time.Hour * 24)
|
||
|
w.Header().Add("Set-Cookie", fmt.Sprintf("session=%s; Path=/; SameSite=Strict; HttpOnly; Secure", token))
|
||
|
http.Redirect(w, r, "/device", http.StatusTemporaryRedirect)
|
||
|
default:
|
||
|
w.WriteHeader(http.StatusMethodNotAllowed) // Method not Allowed
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func deauth(w http.ResponseWriter, r *http.Request) {
|
||
|
switch r.Method {
|
||
|
case "POST":
|
||
|
cookie, err := r.Cookie("session")
|
||
|
if err != nil {
|
||
|
w.WriteHeader(400)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
token := cookie.Value
|
||
|
if isAuthenticated(token) == nil {
|
||
|
delete(sessions, token)
|
||
|
}
|
||
|
default:
|
||
|
w.WriteHeader(405)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func checkAuthentication(w http.ResponseWriter, r *http.Request) error {
|
||
|
sCookie, err := r.Cookie("")
|
||
|
if err == nil && isAuthenticated(sCookie.Value) == nil {
|
||
|
return nil
|
||
|
}
|
||
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
||
|
return errors.New("authentication error")
|
||
|
}
|
||
|
|
||
|
func isAuthenticated(token string) error {
|
||
|
for sToken, expiree := range sessions {
|
||
|
// Expire old sessions
|
||
|
if time.Now().After(expiree) {
|
||
|
delete(sessions, sToken)
|
||
|
continue
|
||
|
}
|
||
|
// Check for valid session of token
|
||
|
if token == sToken {
|
||
|
return nil
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return errors.New("this token is not associated with a valid session")
|
||
|
}
|