peer management HTTP API (#81)

* feature: create account for a newly registered user

* feature: finalize user auth flow

* feature: create protected API with JWT

* chore: cleanup http server

* feature: add UI assets

* chore: update react UI

* refactor: move account not exists -> create to AccountManager

* chore: update UI

* chore: return only peers on peers endpoint

* chore: add UI path to the config

* chore: remove ui from management

* chore: remove unused Docker comamnds

* docs: update management config sample

* fix: store creation

* feature: introduce peer response to the HTTP api

* fix: lint errors

* feature: add setup-keys HTTP endpoint

* fix: return empty json arrays in HTTP API

* feature: add new peer response fields
This commit is contained in:
Mikhail Bragin
2021-08-12 12:49:10 +02:00
committed by GitHub
parent d5af5f1878
commit 3c47a3c408
22 changed files with 633 additions and 394 deletions

View File

@@ -1,96 +0,0 @@
package handler
import (
"context"
"github.com/coreos/go-oidc"
"github.com/gorilla/sessions"
middleware2 "github.com/wiretrustee/wiretrustee/management/server/http/middleware"
"log"
"net/http"
)
// Callback handler used to receive a callback from the identity provider
type Callback struct {
authenticator *middleware2.Authenticator
sessionStore sessions.Store
}
func NewCallback(authenticator *middleware2.Authenticator, sessionStore sessions.Store) *Callback {
return &Callback{
authenticator: authenticator,
sessionStore: sessionStore,
}
}
// ServeHTTP checks the user session, verifies the state, verifies the token, stores user profile in a session,
// and in case of the successful auth redirects user to the main page
func (h *Callback) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session, err := h.sessionStore.Get(r, "auth-session")
if err != nil {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
//http.Error(w, err.Error(), http.StatusInternalServerError)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if r.URL.Query().Get("state") != session.Values["state"] {
//todo redirect to the error page stating: "error authenticating plz try to login once again"
//http.Error(w, "invalid state parameter", http.StatusBadRequest)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
token, err := h.authenticator.Config.Exchange(context.TODO(), r.URL.Query().Get("code"))
if err != nil {
log.Printf("no token found: %v", err)
//todo redirect to the error page stating: "error authenticating plz try to login once again"
//w.WriteHeader(http.StatusUnauthorized)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
//http.Error(w, "no id_token field in oauth2 token.", http.StatusInternalServerError)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
oidcConfig := &oidc.Config{
ClientID: h.authenticator.Config.ClientID,
}
idToken, err := h.authenticator.Provider.Verifier(oidcConfig).Verify(context.TODO(), rawIDToken)
if err != nil {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
//http.Error(w, "failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// get the userInfo from the token
var profile map[string]interface{}
if err := idToken.Claims(&profile); err != nil {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
//http.Error(w, err.Error(), http.StatusInternalServerError)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
session.Values["id_token"] = rawIDToken
session.Values["access_token"] = token.AccessToken
session.Values["profile"] = profile
err = session.Save(r, w)
if err != nil {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
//http.Error(w, err.Error(), http.StatusInternalServerError)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
// redirect to logged in page
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}

View File

@@ -1,44 +0,0 @@
package handler
import (
"fmt"
"github.com/gorilla/sessions"
"io"
"net/http"
"strings"
)
// Dashboard is a handler of the main page of the app (dashboard)
type Dashboard struct {
sessionStore sessions.Store
}
func NewDashboard(sessionStore sessions.Store) *Dashboard {
return &Dashboard{
sessionStore: sessionStore,
}
}
// ServeHTTP verifies if user is authenticated and returns a user dashboard
func (h *Dashboard) ServeHTTP(w http.ResponseWriter, r *http.Request) {
session, err := h.sessionStore.Get(r, "auth-session")
if err != nil {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
//http.Error(w, err.Error(), http.StatusInternalServerError)
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
//todo get user account and relevant data to show
profile := session.Values["profile"].(map[string]interface{})
name := profile["name"]
w.WriteHeader(200)
_, err = io.Copy(w, strings.NewReader("hello "+fmt.Sprintf("%v", name)))
if err != nil {
return
}
//template.RenderTemplate(w, "dashboard", session.Values["profile"])
}

View File

@@ -1,58 +0,0 @@
package handler
import (
"crypto/rand"
"encoding/base64"
"github.com/gorilla/sessions"
middleware2 "github.com/wiretrustee/wiretrustee/management/server/http/middleware"
"io/fs"
"net/http"
)
// Login handler used to login a user
type Login struct {
authenticator *middleware2.Authenticator
sessionStore sessions.Store
}
func NewLogin(authenticator *middleware2.Authenticator, sessionStore sessions.Store) *Login {
return &Login{
authenticator: authenticator,
sessionStore: sessionStore,
}
}
// ServeHTTP generates a new session state for a user and redirects the user to the auth URL
func (h *Login) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Generate random state
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
//todo redirect to the error page stating: "error occurred plz try again later and a link to login"
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
state := base64.StdEncoding.EncodeToString(b)
session, err := h.sessionStore.Get(r, "auth-session")
if err != nil {
switch err.(type) {
case *fs.PathError:
// a case when session doesn't exist in the store but was sent by the client in the cookie -> create new session ID
// it appears that in this case session is always non empty object
session.ID = "" //nolint
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
session.Values["state"] = state //nolint
err = session.Save(r, w) //nolint
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
url := h.authenticator.Config.AuthCodeURL(state)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

View File

@@ -1,48 +0,0 @@
package handler
import (
"net/http"
"net/url"
)
// Logout logs out a user
type Logout struct {
authDomain string
authClientId string
}
func NewLogout(authDomain string, authClientId string) *Logout {
return &Logout{authDomain: authDomain, authClientId: authClientId}
}
// ServeHTTP redirects user to teh auth identity provider logout URL
func (h *Logout) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logoutUrl, err := url.Parse("https://" + h.authDomain)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
logoutUrl.Path += "/v2/logout"
parameters := url.Values{}
var scheme string
if r.TLS == nil {
scheme = "http"
} else {
scheme = "https"
}
returnTo, err := url.Parse(scheme + "://" + r.Host + "/login")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
parameters.Add("returnTo", returnTo.String())
parameters.Add("client_id", h.authClientId)
logoutUrl.RawQuery = parameters.Encode()
http.Redirect(w, r, logoutUrl.String(), http.StatusTemporaryRedirect)
}

View File

@@ -0,0 +1,67 @@
package handler
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"github.com/wiretrustee/wiretrustee/management/server"
"net/http"
"time"
)
// Peers is a handler that returns peers of the account
type Peers struct {
accountManager *server.AccountManager
}
// PeerResponse is a response sent to the client
type PeerResponse struct {
Name string
IP string
Connected bool
LastSeen time.Time
Os string
}
func NewPeers(accountManager *server.AccountManager) *Peers {
return &Peers{
accountManager: accountManager,
}
}
func (h *Peers) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
accountId := extractAccountIdFromRequestContext(r)
//new user -> create a new account
account, err := h.accountManager.GetOrCreateAccount(accountId)
if err != nil {
log.Errorf("failed getting user account %s: %v", accountId, err)
http.Redirect(w, r, "/", http.StatusInternalServerError)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
respBody := []*PeerResponse{}
for _, peer := range account.Peers {
respBody = append(respBody, &PeerResponse{
Name: peer.Key,
IP: peer.IP.String(),
LastSeen: time.Now(),
Connected: false,
Os: "Ubuntu 21.04 (Hirsute Hippo)",
})
}
err = json.NewEncoder(w).Encode(respBody)
if err != nil {
log.Errorf("failed encoding account peers %s: %v", accountId, err)
http.Redirect(w, r, "/", http.StatusInternalServerError)
return
}
case http.MethodOptions:
default:
http.Error(w, "", http.StatusNotFound)
}
}

View File

@@ -0,0 +1,58 @@
package handler
import (
"encoding/json"
log "github.com/sirupsen/logrus"
"github.com/wiretrustee/wiretrustee/management/server"
"net/http"
)
// SetupKeys is a handler that returns a list of setup keys of the account
type SetupKeys struct {
accountManager *server.AccountManager
}
// SetupKeyResponse is a response sent to the client
type SetupKeyResponse struct {
Key string
}
func NewSetupKeysHandler(accountManager *server.AccountManager) *SetupKeys {
return &SetupKeys{
accountManager: accountManager,
}
}
func (h *SetupKeys) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
accountId := extractAccountIdFromRequestContext(r)
//new user -> create a new account
account, err := h.accountManager.GetOrCreateAccount(accountId)
if err != nil {
log.Errorf("failed getting user account %s: %v", accountId, err)
http.Redirect(w, r, "/", http.StatusInternalServerError)
return
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
respBody := []*SetupKeyResponse{}
for _, key := range account.SetupKeys {
respBody = append(respBody, &SetupKeyResponse{
Key: key.Key,
})
}
err = json.NewEncoder(w).Encode(respBody)
if err != nil {
log.Errorf("failed encoding account peers %s: %v", accountId, err)
http.Redirect(w, r, "/", http.StatusInternalServerError)
return
}
case http.MethodOptions:
default:
http.Error(w, "", http.StatusNotFound)
}
}

View File

@@ -0,0 +1,15 @@
package handler
import (
"github.com/golang-jwt/jwt"
"net/http"
)
// extractAccountIdFromRequestContext extracts accountId from the request context previously filled by the JWT token (after auth)
func extractAccountIdFromRequestContext(r *http.Request) string {
token := r.Context().Value("user").(*jwt.Token)
claims := token.Claims.(jwt.MapClaims)
//actually a user id but for now we have a 1 to 1 mapping.
return claims["sub"].(string)
}