aboutsummaryrefslogtreecommitdiff
path: root/server
diff options
context:
space:
mode:
authorGabriel Arakaki Giovanini <mail@gabrielgio.me>2022-12-10 23:36:39 +0100
committerGabriel Arakaki Giovanini <mail@gabrielgio.me>2022-12-11 00:58:31 +0100
commit6734c4408ffb67841115ca17d14d879043a3343e (patch)
treec1cdb11e698a71911dea63e9f01e34042662396d /server
downloads4o-6734c4408ffb67841115ca17d14d879043a3343e.tar.gz
s4o-6734c4408ffb67841115ca17d14d879043a3343e.tar.bz2
s4o-6734c4408ffb67841115ca17d14d879043a3343e.zip
feat: Initial set up for static single sign on
This is a simple project to have a static site behind single sign on.
Diffstat (limited to 'server')
-rw-r--r--server/server.go68
1 files changed, 68 insertions, 0 deletions
diff --git a/server/server.go b/server/server.go
new file mode 100644
index 0000000..dc71c95
--- /dev/null
+++ b/server/server.go
@@ -0,0 +1,68 @@
+package server
+
+import (
+ "fmt"
+
+ "github.com/fasthttp/router"
+ "github.com/valyala/fasthttp"
+ "github.com/zitadel/oidc/pkg/client/rp"
+)
+
+func IsAuthenticate(relayPartyProvider rp.RelyingParty, next fasthttp.RequestHandler) fasthttp.RequestHandler {
+ return func(ctx *fasthttp.RequestCtx) {
+ token := string(ctx.Request.Header.Cookie("token"))
+ tokenVerifier := relayPartyProvider.IDTokenVerifier()
+ _, err := rp.VerifyIDToken(ctx, token, tokenVerifier)
+ if err != nil {
+ ctx.Redirect("/login", 307)
+ return
+ }
+ next(ctx)
+ }
+}
+
+func NewS4OServer(clientID, clientSecret, issuer, callback, rootPath string, scopes []string) (*fasthttp.Server, error) {
+ r := router.New()
+
+ relayPartyProvider, err := rp.NewRelyingPartyOIDC(issuer, clientID, clientSecret, callback, scopes)
+ if err != nil {
+ return nil, err
+ }
+
+ fs := &fasthttp.FS{
+ Root: rootPath,
+ IndexNames: []string{"index.html"},
+ GenerateIndexPages: true,
+ AcceptByteRange: true,
+ Compress: true,
+ }
+
+ r.Handle("GET", "/login", func(ctx *fasthttp.RequestCtx) {
+ url := rp.AuthURL(" ", relayPartyProvider)
+ ctx.Redirect(url, 307)
+ })
+
+ r.Handle("GET", "/callback", func(ctx *fasthttp.RequestCtx) {
+ code := string(ctx.QueryArgs().Peek("code"))
+ token, err := rp.CodeExchange(ctx, code, relayPartyProvider)
+ if err != nil {
+ ctx.WriteString(fmt.Sprintf("Error: %+v", err))
+ return
+ }
+
+ cookie := &fasthttp.Cookie{}
+ cookie.SetKey("token")
+ cookie.SetValue(token.IDToken)
+ cookie.SetExpire(token.Expiry)
+ cookie.SetHTTPOnly(true)
+ cookie.SetSameSite(fasthttp.CookieSameSiteDefaultMode)
+ ctx.Response.Header.SetCookie(cookie)
+ ctx.Redirect("/", 307)
+ })
+
+ r.Handle("GET", "/{filepath:*}", IsAuthenticate(relayPartyProvider, fs.NewRequestHandler()))
+
+ return &fasthttp.Server{
+ Handler: r.Handler,
+ }, nil
+}