parcoursmob/handlers/auth/groups.go

117 lines
2.7 KiB
Go
Raw Normal View History

package auth
import (
"context"
"fmt"
"net/http"
"git.coopgo.io/coopgo-apps/parcoursmob/renderer"
"git.coopgo.io/coopgo-apps/parcoursmob/services"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/cache"
"git.coopgo.io/coopgo-apps/parcoursmob/utils/identification"
groupsmanagement "git.coopgo.io/coopgo-platform/groups-management/grpcapi"
"github.com/spf13/viper"
)
type AuthHandler struct {
idp *identification.IdentificationProvider
config *viper.Viper
services *services.ServicesHandler
Renderer *renderer.Renderer
cache *cache.CacheHandler
}
func NewAuthHandler(cfg *viper.Viper, idp *identification.IdentificationProvider, svc *services.ServicesHandler, cache *cache.CacheHandler) (*AuthHandler, error) {
templates_root := cfg.GetString("templates.root")
renderer := renderer.NewRenderer(cfg, templates_root)
return &AuthHandler{
idp: idp,
config: cfg,
services: svc,
Renderer: renderer,
cache: cache,
}, nil
}
func (h *AuthHandler) Groups(w http.ResponseWriter, r *http.Request) {
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
if r.Method == "POST" {
r.ParseForm()
groupid := r.FormValue("group")
session.Values["organization"] = groupid
session.Save(r, w)
http.Redirect(w, r, "/app/", http.StatusFound)
return
}
tokenstring, ok := session.Values["idtoken"]
if !ok {
http.Redirect(w, r, "/app/", http.StatusFound)
return
}
idtoken, err := h.idp.TokenVerifier.Verify(context.Background(), tokenstring.(string))
if err != nil {
delete(session.Values, "idtoken")
http.Redirect(w, r, "/app/", http.StatusFound)
return
}
var claims map[string]any
err = idtoken.Claims(&claims)
if err != nil {
fmt.Println(err)
}
g := claims["groups"]
groups_interface, ok := g.([]any)
if !ok {
w.WriteHeader(http.StatusInternalServerError)
return
}
groups := []string{}
for _, v := range groups_interface {
groups = append(groups, v.(string))
}
request := &groupsmanagement.GetGroupsBatchRequest{
Groupids: groups,
}
resp, err := h.services.GRPC.GroupsManagement.GetGroupsBatch(context.TODO(), request)
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
var groupsresponse = []any{}
for _, group := range resp.Groups {
if group.Namespace != "parcoursmob_organizations" {
continue
}
g := group.ToStorageType()
groupsresponse = append(groupsresponse, g)
}
h.Renderer.AuthGroups(w, r, groupsresponse)
}
func (h *AuthHandler) GroupSwitch(w http.ResponseWriter, r *http.Request) {
session, _ := h.idp.SessionsStore.Get(r, "parcoursmob_session")
delete(session.Values, "organization")
session.Save(r, w)
http.Redirect(w, r, "/app/", http.StatusFound)
}