Initial commit

This commit is contained in:
2020-04-08 08:56:42 +02:00
commit 3a84d819ff
44 changed files with 1769 additions and 0 deletions

104
internal/config/config.go Normal file
View File

@ -0,0 +1,104 @@
package config
import (
"io"
"io/ioutil"
"time"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type Config struct {
HTTP HTTPConfig `yaml:"http"`
TestApp TestAppConfig `yaml:"testApp"`
SMTP SMTPConfig `yaml:"smtp"`
Hydra HydraConfig `yaml:"hydra"`
}
// NewFromFile retrieves the configuration from the given file
func NewFromFile(filepath string) (*Config, error) {
config := NewDefault()
data, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, errors.Wrapf(err, "could not read file '%s'", filepath)
}
if err := yaml.Unmarshal(data, config); err != nil {
return nil, errors.Wrapf(err, "could not unmarshal configuration")
}
return config, nil
}
type HTTPConfig struct {
Address string `yaml:"address"`
CookieAuthenticationKey string `yaml:"cookieAuthenticationKey"`
CookieEncryptionKey string `yaml:"cookieEncryptionKey"`
CookieMaxAge int `yaml:"cookieMaxAge"`
TemplateDir string `yaml:"templateDir"`
PublicDir string `yaml:"publicDir"`
}
type TestAppConfig struct {
Enabled bool `yaml:"enabled"`
ClientID string `yaml:"clientId"`
ClientSecret string `yaml:"clientSecret"`
IssuerURL string `ymal:"issuerUrl"`
RedirectURL string `yaml:"redirectUrl"`
}
type SMTPConfig struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
UseStartTLS bool `yaml:"useStartTLS"`
User string `yaml:"user"`
Password string `yaml:"password"`
InsecureSkipVerify bool `yaml:"insecureSkipVerify"`
}
type HydraConfig struct {
BaseURL string `yaml:"baseURL"`
}
func NewDumpDefault() *Config {
config := NewDefault()
return config
}
func NewDefault() *Config {
return &Config{
HTTP: HTTPConfig{
Address: ":3000",
CookieAuthenticationKey: "",
CookieEncryptionKey: "",
CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour
TemplateDir: "template",
PublicDir: "public",
},
TestApp: TestAppConfig{
Enabled: false,
IssuerURL: "http://localhost:4444/",
RedirectURL: "http://localhost:3000/test/oauth2/callback",
},
SMTP: SMTPConfig{},
Hydra: HydraConfig{
BaseURL: "http://localhost:4444/",
},
}
}
func Dump(config *Config, w io.Writer) error {
data, err := yaml.Marshal(config)
if err != nil {
return errors.Wrap(err, "could not dump config")
}
if _, err := w.Write(data); err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,9 @@
package config
import "gitlab.com/wpetit/goweb/service"
func ServiceProvider(config *Config) service.Provider {
return func(ctn *service.Container) (interface{}, error) {
return config, nil
}
}

View File

@ -0,0 +1,33 @@
package config
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "config"
// From retrieves the config service in the given container
func From(container *service.Container) (*Config, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Config)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the config service in the given container or panic otherwise
func Must(container *service.Container) *Config {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}

61
internal/hydra/client.go Normal file
View File

@ -0,0 +1,61 @@
package hydra
import (
"net/http"
"time"
)
type Client struct {
baseURL string
http *http.Client
}
func (c *Client) LoginRequest(challenge string) (*LoginResponse, error) {
return nil, nil
}
func (c *Client) Accept(challenge string) (*AcceptResponse, error) {
return nil, nil
}
func (c *Client) RejectRequest(challenge string) (*RejectResponse, error) {
return nil, nil
}
func (c *Client) LogoutRequest(challenge string) (*LogoutResponse, error) {
return nil, nil
}
func (c *Client) ConsentRequest(challenge string) (*ConsentResponse, error) {
return nil, nil
}
func (c *Client) LoginChallenge(r *http.Request) (string, error) {
return c.challenge(r, "login_challenge")
}
func (c *Client) ConsentChallenge(r *http.Request) (string, error) {
return c.challenge(r, "consent_challenge")
}
func (c *Client) LogoutChallenge(r *http.Request) (string, error) {
return c.challenge(r, "logout_challenge")
}
func (c *Client) challenge(r *http.Request, name string) (string, error) {
challenge := r.URL.Query().Get(name)
if challenge == "" {
return "", ErrChallengeNotFound
}
return challenge, nil
}
func NewClient(baseURL string, httpTimeout time.Duration) *Client {
return &Client{
baseURL: baseURL,
http: &http.Client{
Timeout: 30 * time.Second,
},
}
}

7
internal/hydra/error.go Normal file
View File

@ -0,0 +1,7 @@
package hydra
import "errors"
var (
ErrChallengeNotFound = errors.New("challenge not found")
)

View File

@ -0,0 +1,15 @@
package hydra
import (
"time"
"gitlab.com/wpetit/goweb/service"
)
func ServiceProvider(baseURL string, httpTimeout time.Duration) service.Provider {
client := NewClient(baseURL, httpTimeout)
return func(ctn *service.Container) (interface{}, error) {
return client, nil
}
}

View File

@ -0,0 +1,16 @@
package hydra
type LoginResponse struct {
}
type AcceptResponse struct {
}
type RejectResponse struct {
}
type LogoutResponse struct {
}
type ConsentResponse struct {
}

33
internal/hydra/service.go Normal file
View File

@ -0,0 +1,33 @@
package hydra
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "hydra"
// From retrieves the hydra service in the given container
func From(container *service.Container) (*Client, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Client)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the hydra service in the given container or panic otherwise
func Must(container *service.Container) *Client {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}

19
internal/mail/mailer.go Normal file
View File

@ -0,0 +1,19 @@
package mail
type Option struct {
Host string
Port int
User string
Password string
InsecureSkipVerify bool
}
type OptionFunc func(*Option)
type Mailer struct {
opt *Option
}
func NewMailer(funcs ...OptionFunc) *Mailer {
return &Mailer{}
}

11
internal/mail/provider.go Normal file
View File

@ -0,0 +1,11 @@
package mail
import "gitlab.com/wpetit/goweb/service"
func ServiceProvider(opts ...OptionFunc) service.Provider {
mailer := NewMailer(opts...)
return func(ctn *service.Container) (interface{}, error) {
return mailer, nil
}
}

138
internal/mail/send.go Normal file
View File

@ -0,0 +1,138 @@
package mail
import (
"crypto/tls"
"github.com/pkg/errors"
gomail "gopkg.in/mail.v2"
)
type SendFunc func(*SendOption)
type SendOption struct {
Charset string
AddressHeaders []AddressHeader
Headers []Header
Body Body
AlternativeBodies []Body
}
type AddressHeader struct {
Field string
Address string
Name string
}
type Header struct {
Field string
Values []string
}
type Body struct {
Type string
Content string
PartSetting gomail.PartSetting
}
func WithCharset(charset string) func(*SendOption) {
return func(opt *SendOption) {
opt.Charset = charset
}
}
func WithFrom(address string, name string) func(*SendOption) {
return WithAddressHeader("From", address, name)
}
func WithAddressHeader(field, address, name string) func(*SendOption) {
return func(opt *SendOption) {
opt.AddressHeaders = append(opt.AddressHeaders, AddressHeader{field, address, name})
}
}
func WithHeader(field string, values ...string) func(*SendOption) {
return func(opt *SendOption) {
opt.Headers = append(opt.Headers, Header{field, values})
}
}
func WithBody(contentType string, content string, setting gomail.PartSetting) func(*SendOption) {
return func(opt *SendOption) {
opt.Body = Body{contentType, content, setting}
}
}
func WithAlternativeBody(contentType string, content string, setting gomail.PartSetting) func(*SendOption) {
return func(opt *SendOption) {
opt.AlternativeBodies = append(opt.AlternativeBodies, Body{contentType, content, setting})
}
}
func (m *Mailer) Send(funcs ...SendFunc) error {
opt := &SendOption{
Charset: "UTF-8",
Body: Body{
Type: "text/plain",
Content: "",
PartSetting: gomail.SetPartEncoding(gomail.Unencoded),
},
AddressHeaders: make([]AddressHeader, 0),
Headers: make([]Header, 0),
AlternativeBodies: make([]Body, 0),
}
for _, f := range funcs {
f(opt)
}
conn, err := m.openConnection()
if err != nil {
return errors.Wrap(err, "could not open connection")
}
defer conn.Close()
message := gomail.NewMessage(gomail.SetCharset(opt.Charset))
for _, h := range opt.AddressHeaders {
message.SetAddressHeader(h.Field, h.Address, h.Name)
}
for _, h := range opt.Headers {
message.SetHeader(h.Field, h.Values...)
}
message.SetBody(opt.Body.Type, opt.Body.Content, opt.Body.PartSetting)
for _, b := range opt.AlternativeBodies {
message.AddAlternative(b.Type, b.Content, b.PartSetting)
}
if err := gomail.Send(conn, message); err != nil {
return errors.Wrap(err, "could not send message")
}
return nil
}
func (m *Mailer) openConnection() (gomail.SendCloser, error) {
dialer := gomail.NewDialer(
m.opt.Host,
m.opt.Port,
m.opt.User,
m.opt.Password,
)
if m.opt.InsecureSkipVerify {
dialer.TLSConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
conn, err := dialer.Dial()
if err != nil {
return nil, errors.Wrap(err, "could not dial smtp server")
}
return conn, nil
}

33
internal/mail/service.go Normal file
View File

@ -0,0 +1,33 @@
package mail
import (
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/service"
)
const ServiceName service.Name = "mail"
// From retrieves the mail service in the given container
func From(container *service.Container) (*Mailer, error) {
service, err := container.Service(ServiceName)
if err != nil {
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
}
srv, ok := service.(*Mailer)
if !ok {
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
}
return srv, nil
}
// Must retrieves the mail service in the given container or panic otherwise
func Must(container *service.Container) *Mailer {
srv, err := From(container)
if err != nil {
panic(err)
}
return srv
}

20
internal/route/consent.go Normal file
View File

@ -0,0 +1,20 @@
package route
import (
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveConsentPage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
data := extendTemplateData(w, r, template.Data{})
if err := tmpl.RenderPage(w, "consent.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}

24
internal/route/helper.go Normal file
View File

@ -0,0 +1,24 @@
package route
import (
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
"gitlab.com/wpetit/goweb/template/html"
)
func extendTemplateData(w http.ResponseWriter, r *http.Request, data template.Data) template.Data {
ctn := container.Must(r.Context())
data, err := template.Extend(data,
html.WithFlashes(w, r, ctn),
template.WithBuildInfo(w, r, ctn),
)
if err != nil {
panic(errors.Wrap(err, "could not extend template data"))
}
return data
}

20
internal/route/home.go Normal file
View File

@ -0,0 +1,20 @@
package route
import (
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveHomePage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
data := extendTemplateData(w, r, template.Data{})
if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}

57
internal/route/login.go Normal file
View File

@ -0,0 +1,57 @@
package route
import (
"net/http"
"github.com/davecgh/go-spew/spew"
"forge.cadoles.com/wpetit/hydra-passwordless/internal/hydra"
"github.com/gorilla/csrf"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveLoginPage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
hydr := hydra.Must(ctn)
challenge, err := hydr.LoginChallenge(r)
if err != nil {
if err == hydra.ErrChallengeNotFound {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
panic(errors.Wrap(err, "could not retrieve login challenge"))
}
res, err := hydr.LoginRequest(challenge)
if err != nil {
panic(errors.Wrap(err, "could not retrieve hydra login response"))
}
spew.Dump(res)
tmpl := template.Must(ctn)
data := extendTemplateData(w, r, template.Data{
csrf.TemplateTag: csrf.TemplateField(r),
})
if err := tmpl.RenderPage(w, "login.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}
func handleLoginForm(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
data := extendTemplateData(w, r, template.Data{})
if err := tmpl.RenderPage(w, "email_sent.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}

9
internal/route/logout.go Normal file
View File

@ -0,0 +1,9 @@
package route
import (
"net/http"
)
func serveLogoutPage(w http.ResponseWriter, r *http.Request) {
}

52
internal/route/mount.go Normal file
View File

@ -0,0 +1,52 @@
package route
import (
"log"
"forge.cadoles.com/wpetit/hydra-passwordless/internal/config"
"forge.cadoles.com/wpetit/hydra-passwordless/oidc"
"github.com/go-chi/chi"
"github.com/gorilla/csrf"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/session/gorilla"
"gitlab.com/wpetit/goweb/static"
)
func Mount(r *chi.Mux, config *config.Config) error {
csrfSecret, err := gorilla.GenerateRandomBytes(32)
if err != nil {
return errors.Wrap(err, "could not generate CSRF secret")
}
csrfMiddleware := csrf.Protect(
csrfSecret,
csrf.Secure(false),
)
r.Group(func(r chi.Router) {
r.Use(csrfMiddleware)
r.Get("/login", serveLoginPage)
r.Post("/login", handleLoginForm)
r.Get("/logout", serveLogoutPage)
r.Get("/consent", serveConsentPage)
})
if config.TestApp.Enabled {
log.Println("test app enabled")
r.Route("/test", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(oidc.Middleware)
r.Get("/", serveTestAppHomePage)
})
})
}
notFoundHandler := r.NotFoundHandler()
r.Get("/*", static.Dir(config.HTTP.PublicDir, "", notFoundHandler))
return nil
}

View File

@ -0,0 +1,23 @@
package route
import (
"log"
"net/http"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveTestAppHomePage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
data := extendTemplateData(w, r, template.Data{})
log.Println("rendering test app home")
if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}