diff --git a/assets/static/img/logo.png b/assets/static/img/logo.png deleted file mode 100644 index a016c2b..0000000 Binary files a/assets/static/img/logo.png and /dev/null differ diff --git a/assets/static/img/logo.svg b/assets/static/img/logo.svg new file mode 100644 index 0000000..cd6e87b --- /dev/null +++ b/assets/static/img/logo.svg @@ -0,0 +1,59 @@ + +image/svg+xmlONEOFFONEOFFCreated with Sketch. \ No newline at end of file diff --git a/assets/templates/errors/403.gohtml b/assets/templates/errors/403.gohtml new file mode 100644 index 0000000..10b4e81 --- /dev/null +++ b/assets/templates/errors/403.gohtml @@ -0,0 +1,21 @@ +{{ define "meta" }} + Forbidden +{{ end }} + +{{ define "content" }} +
+
+
+
+
+

Forbidden

+

+ The received the request was not processed. + For example, the CSRF validation may have failed. +

+
+
+
+
+
+{{ end }} \ No newline at end of file diff --git a/assets/templates/layouts/admin.gohtml b/assets/templates/layouts/admin.gohtml index 3e00c6e..a6d2c64 100644 --- a/assets/templates/layouts/admin.gohtml +++ b/assets/templates/layouts/admin.gohtml @@ -6,11 +6,11 @@ - + Admin - + diff --git a/assets/templates/layouts/application.gohtml b/assets/templates/layouts/application.gohtml index abf3795..7a231d9 100644 --- a/assets/templates/layouts/application.gohtml +++ b/assets/templates/layouts/application.gohtml @@ -6,24 +6,29 @@ - + - - + + {{ template "meta" . }} {{ if eq .Meta.Env "production" }} {{ end }} + - {{ template "header" . }} + {{ if .flashes}}
{{range .flashes}} -
{{ .Message }}
+ {{ .Render }} {{end}}
+ {{ end }} + {{ template "header" . }}
{{ template "content" . }} @@ -32,8 +37,8 @@ {{ template "footer" . }} {{ template "sink" .}} - - + + diff --git a/assets/templates/layouts/auth.gohtml b/assets/templates/layouts/auth.gohtml new file mode 100644 index 0000000..8f2b65a --- /dev/null +++ b/assets/templates/layouts/auth.gohtml @@ -0,0 +1,56 @@ +{{ define "base" }} + + + + + + + + + + + + + {{ template "meta" . }} + {{ if eq .Meta.Env "production" }} + + {{ end }} + + + + +
+ {{ if .flashes}} +
+ {{range .flashes}} + {{ .Render }} + {{end}} +
+ {{ end }} +
+
+
+
+
+
+ +
+
+ {{ template "content" . }} +
+
+
+
+
+ + + + + + + +{{ end }} + +{{ define "meta"}}{{end}} \ No newline at end of file diff --git a/assets/templates/shared/header.gohtml b/assets/templates/shared/header.gohtml index d3cfbd9..5d3cbe7 100644 --- a/assets/templates/shared/header.gohtml +++ b/assets/templates/shared/header.gohtml @@ -1,25 +1,37 @@ {{ define "header" }} - +
+
+
+
+ + {{ end }} \ No newline at end of file diff --git a/assets/templates/views/cert_list.gohtml b/assets/templates/views/cert_list.gohtml index 3cd0983..f667653 100644 --- a/assets/templates/views/cert_list.gohtml +++ b/assets/templates/views/cert_list.gohtml @@ -1,6 +1,5 @@ {{ define "meta" }} Log in - {{ end}} {{ define "content" }} diff --git a/assets/templates/views/forgot-password.gohtml b/assets/templates/views/forgot-password.gohtml new file mode 100644 index 0000000..2996737 --- /dev/null +++ b/assets/templates/views/forgot-password.gohtml @@ -0,0 +1,24 @@ +{{ define "meta" }}Forgot Password{{ end }} + +{{ define "content" }} +
+
+

Reset Password

+
+
+ +
+ + + + +
+
+ {{ .csrfField }} +
+ +
+
+
+
+{{ end }} \ No newline at end of file diff --git a/assets/templates/views/login.gohtml b/assets/templates/views/login.gohtml index 5218dec..7dcd655 100644 --- a/assets/templates/views/login.gohtml +++ b/assets/templates/views/login.gohtml @@ -1,24 +1,41 @@ -{{ define "meta" }} - Log in - -{{ end}} +{{ define "meta" }}Log In{{ end }} {{ define "content" }} -
-
-
-
-
-

Hello, World!

-
- - - {{ .csrfField }} - -
+
+
+

Log In

+
+
+ +
+ + + +
-
+
+ +
+ + + + +
+
+ {{ .csrfField }} +
+ +
+ +
-
-{{ end}} +
+
+

+ Don't have an account? Sign Up +

+
+{{ end }} \ No newline at end of file diff --git a/assets/templates/views/register.gohtml b/assets/templates/views/register.gohtml new file mode 100644 index 0000000..44ee692 --- /dev/null +++ b/assets/templates/views/register.gohtml @@ -0,0 +1,41 @@ +{{ define "meta" }}Log In{{ end }} + +{{ define "content" }} +
+
+

Sign Up

+
+
+ +
+ + + + +
+
+
+ +
+ + + + +
+
+ {{ .csrfField }} +
+ +
+
+

By signing up you agree to the Terms of Service

+
+
+
+
+
+

+ Already have an account? Log In +

+
+{{ end }} \ No newline at end of file diff --git a/handlers/auth.go b/handlers/auth.go new file mode 100644 index 0000000..5968650 --- /dev/null +++ b/handlers/auth.go @@ -0,0 +1,80 @@ +package handlers + +import ( + "net/http" + + "git.klink.asia/paul/certman/services" + + "git.klink.asia/paul/certman/models" +) + +func RegisterHandler(w http.ResponseWriter, req *http.Request) { + // Get parameters + email := req.Form.Get("email") + password := req.Form.Get("password") + + user := models.User{} + user.Email = email + user.SetPassword(password) + + err := services.Database.Create(&user).Error + if err != nil { + panic(err.Error) + } + + services.SessionStore.Flash(w, req, + services.Flash{ + Type: "success", + Message: "The user was created. Check your inbox for the confirmation email.", + }, + ) + + http.Redirect(w, req, "/login", http.StatusFound) + return +} + +func LoginHandler(w http.ResponseWriter, req *http.Request) { + // Get parameters + email := req.Form.Get("email") + password := req.Form.Get("password") + + user := models.User{} + + err := services.Database.Where(&models.User{Email: email}).Find(&user).Error + if err != nil { + // could not find user + services.SessionStore.Flash( + w, req, services.Flash{ + Type: "warning", Message: "Invalid Email or Password.", + }, + ) + http.Redirect(w, req, "/login", http.StatusFound) + return + } + + if !user.EmailValid { + services.SessionStore.Flash( + w, req, services.Flash{ + Type: "warning", Message: "You need to confirm your email before logging in.", + }, + ) + http.Redirect(w, req, "/login", http.StatusFound) + return + } + + if err := user.CheckPassword(password); err != nil { + // wrong password + services.SessionStore.Flash( + w, req, services.Flash{ + Type: "warning", Message: "Invalid Email or Password.", + }, + ) + http.Redirect(w, req, "/login", http.StatusFound) + return + } + + // user is logged in, set cookie + services.SessionStore.SetUserEmail(w, req, email) + + http.Redirect(w, req, "/certs", http.StatusSeeOther) +} diff --git a/handlers/gencert.go b/handlers/cert.go similarity index 52% rename from handlers/gencert.go rename to handlers/cert.go index ac033a0..5f59ab6 100644 --- a/handlers/gencert.go +++ b/handlers/cert.go @@ -13,40 +13,75 @@ import ( "net/http" "time" - "git.klink.asia/paul/certman/views" + "git.klink.asia/paul/certman/models" + "git.klink.asia/paul/certman/services" - "github.com/jinzhu/gorm" + "git.klink.asia/paul/certman/views" ) -func ListCertHandler(db *gorm.DB) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - v := views.New(req) - v.Render(w, "cert_list") - } +func ListCertHandler(w http.ResponseWriter, req *http.Request) { + v := views.New(req) + v.Render(w, "cert_list") } -func GenCertHandler(db *gorm.DB) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - v := views.New(req) +func CreateCertHandler(w http.ResponseWriter, req *http.Request) { + email := services.SessionStore.GetUserEmail(req) + certname := req.FormValue("certname") - key, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - log.Fatalf("Could not generate keypair: %s", err) - } - - caCert, caKey, err := loadX509KeyPair("ca.crt", "ca.key") - if err != nil { - v.Render(w, "500") - log.Fatalf("error loading ca keyfiles: %s", err) - } - - derBytes, err := CreateCertificate(key, caCert, caKey) - pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - - pkBytes := x509.MarshalPKCS1PrivateKey(key) - pem.Encode(w, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: pkBytes}) - return + user := models.User{} + err := services.Database.Where(&models.User{Email: email}).Find(&user).Error + if err != nil { + fmt.Printf("Could not fetch user for mail %s\n", email) } + + // Load CA master certificate + caCert, caKey, err := loadX509KeyPair("ca.crt", "ca.key") + if err != nil { + log.Fatalf("error loading ca keyfiles: %s", err) + panic(err.Error()) + } + + // Generate Keypair + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + log.Fatalf("Could not generate keypair: %s", err) + } + + // Generate Certificate + derBytes, err := CreateCertificate(key, caCert, caKey) + + // Initialize new client config + client := models.Client{ + Name: certname, + PrivateKey: x509.MarshalPKCS1PrivateKey(key), + Cert: derBytes, + UserID: user.ID, + } + + // Insert client into database + if err := services.Database.Create(&client).Error; err != nil { + panic(err.Error()) + } + + services.SessionStore.Flash(w, req, + services.Flash{ + Type: "success", + Message: "The certificate was created successfully.", + }, + ) + + http.Redirect(w, req, "/certs", http.StatusFound) +} + +func DownloadCertHandler(w http.ResponseWriter, req *http.Request) { + //v := views.New(req) + // + //derBytes, err := CreateCertificate(key, caCert, caKey) + //pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) + // + //pkBytes := x509.MarshalPKCS1PrivateKey(key) + //pem.Encode(w, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: pkBytes}) + return } func loadX509KeyPair(certFile, keyFile string) (*x509.Certificate, *rsa.PrivateKey, error) { diff --git a/handlers/handlers.go b/handlers/handlers.go index f02ea5a..d131713 100644 --- a/handlers/handlers.go +++ b/handlers/handlers.go @@ -15,3 +15,8 @@ func ErrorHandler(w http.ResponseWriter, req *http.Request) { view := views.New(req) view.RenderError(w, http.StatusInternalServerError) } + +func CSRFErrorHandler(w http.ResponseWriter, req *http.Request) { + view := views.New(req) + view.RenderError(w, http.StatusForbidden) +} diff --git a/handlers/login.go b/handlers/login.go deleted file mode 100644 index 25ebc88..0000000 --- a/handlers/login.go +++ /dev/null @@ -1,33 +0,0 @@ -package handlers - -import ( - "net/http" - - "git.klink.asia/paul/certman/models" - "github.com/jinzhu/gorm" -) - -func LoginHandler(db *gorm.DB) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - // Get parameters - username := req.Form.Get("username") - password := req.Form.Get("password") - - user := models.User{} - - err := db.Where(&models.User{Username: username}).Find(&user).Error - if err != nil { - // could not find user - http.Redirect(w, req, "/login", http.StatusFound) - } - - if err := user.CheckPassword(password); err != nil { - // wrong password - http.Redirect(w, req, "/login", http.StatusFound) - } - - // user is logged in - // set cookie - http.Redirect(w, req, "/certs", http.StatusFound) - } -} diff --git a/main.go b/main.go index 63f8475..15f0c37 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,14 @@ func main() { // Connect to the database db := services.InitDB() + services.InitSession() + + //user := models.User{} + //user.Username = "test" + //user.SetPassword("test") + //fmt.Println(user.HashedPassword) + //fmt.Println(db.Create(&user).Error) + // load and parse template files views.LoadTemplates() diff --git a/middleware/requirelogin.go b/middleware/requirelogin.go index d8178c2..a1917a2 100644 --- a/middleware/requirelogin.go +++ b/middleware/requirelogin.go @@ -1,25 +1,20 @@ package middleware import ( - "log" "net/http" - "runtime/debug" - "git.klink.asia/paul/certman/handlers" + "git.klink.asia/paul/certman/services" ) +// RequireLogin is a middleware that checks for a username in the active +// session, and redirects to `/login` if no username was found. func RequireLogin(next http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - defer func() { - if rvr := recover(); rvr != nil { - log.Println(rvr) - log.Println(string(debug.Stack())) - handlers.ErrorHandler(w, r) - } - }() + fn := func(w http.ResponseWriter, req *http.Request) { + if username := services.SessionStore.GetUserEmail(req); username == "" { + http.Redirect(w, req, "/login", http.StatusFound) + } - next.ServeHTTP(w, r) + next.ServeHTTP(w, req) } - return http.HandlerFunc(fn) } diff --git a/models/models.go b/models/models.go index 49a93cc..00764fe 100644 --- a/models/models.go +++ b/models/models.go @@ -2,8 +2,9 @@ package models import ( "errors" + "time" - "github.com/jinzhu/gorm" + "golang.org/x/crypto/bcrypt" ) var ( @@ -12,31 +13,64 @@ var ( ErrNotImplemented = errors.New("Not implemented") ) +// Model is a base model definition, including helpful fields for dealing with +// models in a database +type Model struct { + ID uint `gorm:"primary_key"` + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt *time.Time `sql:"index"` +} + // User represents a User of the system which is able to log in type User struct { - gorm.Model - Username string + Model + Email string + EmailValid bool + DisplayName string HashedPassword []byte IsAdmin bool } // SetPassword sets the password of an user struct, but does not save it yet func (u *User) SetPassword(password string) error { - return ErrNotImplemented + bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return err + } + u.HashedPassword = bytes + return nil } // CheckPassword compares a supplied plain text password with the internally // stored password hash, returns error=nil on success. func (u *User) CheckPassword(password string) error { - return ErrNotImplemented + return bcrypt.CompareHashAndPassword(u.HashedPassword, []byte(password)) } -// ClientConf represent the OpenVPN client configuration -type ClientConf struct { - gorm.Model +type UserProvider interface { + CountUsers() (uint, error) + CreateUser(*User) (*User, error) + ListUsers(count, offset int) ([]*User, error) + GetUserByID(id uint) (*User, error) + GetUserByEmail(email string) (*User, error) + DeleteUser(id uint) error +} + +// Client represent the OpenVPN client configuration +type Client struct { + Model Name string User User + UserID uint Cert []byte - PublicKey []byte PrivateKey []byte } + +type ClientProvider interface { + CountClients() (uint, error) + CreateClient(*User) (*User, error) + ListClients(count, offset int) ([]*User, error) + GetClientByID(id uint) (*User, error) + DeleteClient(id uint) error +} diff --git a/router/router.go b/router/router.go index 00a4c78..5883cbe 100644 --- a/router/router.go +++ b/router/router.go @@ -5,6 +5,8 @@ import ( "os" "strings" + "git.klink.asia/paul/certman/services" + "git.klink.asia/paul/certman/assets" "git.klink.asia/paul/certman/handlers" "git.klink.asia/paul/certman/views" @@ -27,13 +29,16 @@ var ( func HandleRoutes(db *gorm.DB) http.Handler { mux := chi.NewMux() - // mux.Use(middleware.RequestID) - mux.Use(middleware.Logger) - mux.Use(middleware.RealIP) - mux.Use(middleware.RedirectSlashes) - mux.Use(mw.Recoverer) + //mux.Use(middleware.RequestID) + mux.Use(middleware.Logger) // log requests + mux.Use(middleware.RealIP) // use proxy headers + mux.Use(middleware.RedirectSlashes) // redirect trailing slashes + mux.Use(mw.Recoverer) // recover on panic + mux.Use(services.SessionStore.Use) // use session storage // we are serving the static files directly from the assets package + // this either means we use the embedded files, or live-load + // from the file system (if `--tags="dev"` is used). fileServer(mux, "/static", assets.Assets) mux.Route("/", func(r chi.Router) { @@ -43,21 +48,35 @@ func HandleRoutes(db *gorm.DB) http.Handler { csrf.Secure(false), csrf.CookieName(csrfCookieName), csrf.FieldName(csrfFieldName), + csrf.ErrorHandler(http.HandlerFunc(handlers.CSRFErrorHandler)), )) } - r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { - view := views.New(req) - view.Render(w, "debug") + r.HandleFunc("/", v("debug")) + + r.Route("/register", func(r chi.Router) { + r.Get("/", v("register")) + r.Post("/", handlers.RegisterHandler) }) - r.Get("/login", func(w http.ResponseWriter, req *http.Request) { - view := views.New(req) - view.Render(w, "login") + r.Route("/login", func(r chi.Router) { + r.Get("/", v("login")) + r.Post("/", handlers.LoginHandler) }) - r.Get("/certs", handlers.ListCertHandler(db)) - r.HandleFunc("/certs/new", handlers.GenCertHandler(db)) + //r.Post("/confirm-email/{token}", handlers.ConfirmEmailHandler(db)) + + r.Route("/forgot-password", func(r chi.Router) { + r.Get("/", v("forgot-password")) + r.Post("/", handlers.LoginHandler) + }) + + r.Route("/certs", func(r chi.Router) { + r.Use(mw.RequireLogin) + r.Get("/", handlers.ListCertHandler) + r.Post("/new", handlers.CreateCertHandler) + r.HandleFunc("/download/{ID}", handlers.DownloadCertHandler) + }) r.HandleFunc("/500", func(w http.ResponseWriter, req *http.Request) { panic("500") @@ -70,6 +89,14 @@ func HandleRoutes(db *gorm.DB) http.Handler { return mux } +// v is a helper function for quickly displaying a view +func v(template string) http.HandlerFunc { + return func(w http.ResponseWriter, req *http.Request) { + view := views.New(req) + view.Render(w, template) + } +} + // fileServer sets up a http.FileServer handler to serve // static files from a http.FileSystem. func fileServer(r chi.Router, path string, root http.FileSystem) { diff --git a/services/db.go b/services/db.go index f88e28d..f86af66 100644 --- a/services/db.go +++ b/services/db.go @@ -1,6 +1,7 @@ package services import ( + "errors" "log" "git.klink.asia/paul/certman/models" @@ -8,7 +9,17 @@ import ( "github.com/jinzhu/gorm" ) -var DB *gorm.DB +// Error Definitions +var ( + ErrNotImplemented = errors.New("Not implemented") +) + +var Database *gorm.DB + +// DB is a wrapper around gorm.DB to provide custom methods +type DB struct { + *gorm.DB +} func InitDB() *gorm.DB { dsn := settings.Get("DATABASE_URL", "db.sqlite3") @@ -20,7 +31,41 @@ func InitDB() *gorm.DB { } // Migrate models - db.AutoMigrate(models.User{}, models.ClientConf{}) + db.AutoMigrate(models.User{}, models.Client{}) + db.LogMode(true) + Database = db return db } + +// CountUsers returns the number of Users in the datastore +func (db *DB) CountUsers() (uint, error) { + return 0, ErrNotImplemented +} + +// CreateUser inserts a user into the datastore +func (db *DB) CreateUser(*models.User) (*models.User, error) { + return nil, ErrNotImplemented +} + +// ListUsers returns a slice of 'count' users, starting at 'offset' +func (db *DB) ListUsers(count, offset int) ([]*models.User, error) { + var users = make([]*models.User, 0) + + return users, ErrNotImplemented +} + +// GetUserByID returns a single user by ID +func (db *DB) GetUserByID(id uint) (*models.User, error) { + return nil, ErrNotImplemented +} + +// GetUserByEmail returns a single user by email +func (db *DB) GetUserByEmail(email string) (*models.User, error) { + return nil, ErrNotImplemented +} + +// DeleteUser removes a user from the datastore +func (db *DB) DeleteUser(id uint) error { + return ErrNotImplemented +} diff --git a/services/sessions.go b/services/sessions.go index 2afbe0b..9efe6a5 100644 --- a/services/sessions.go +++ b/services/sessions.go @@ -1,21 +1,126 @@ package services import ( + "encoding/gob" + "fmt" + "html/template" + "log" + "net/http" + "time" + "git.klink.asia/paul/certman/settings" + "github.com/alexedwards/scs" "github.com/gorilla/securecookie" - "github.com/gorilla/sessions" ) -var Sessions sessions.Store +var ( + // SessionName is the name of the session cookie + SessionName = "session" + // CookieKey is the key the cookies are encrypted and signed with + CookieKey = string(securecookie.GenerateRandomKey(32)) + // FlashesKey is the key used for the flashes in the cookie + FlashesKey = "_flashes" + // UserEmailKey is the key used to reference usernames + UserEmailKey = "_user_email" +) -func InitSession() { - store := sessions.NewCookieStore( - securecookie.GenerateRandomKey(32), // signing key - securecookie.GenerateRandomKey(32), // encryption key - ) - store.Options.HttpOnly = true - store.Options.MaxAge = 7 * 24 * 60 * 60 // 1 Week - store.Options.Secure = settings.Get("ENVIRONMENT", "") == "production" - - Sessions = store +func init() { + // Register the Flash message type, so gob can serialize it + gob.Register(Flash{}) +} + +// SessionStore is a globally accessible sessions store for the application +var SessionStore *Store + +// Store is a wrapped scs.Store in order to implement custom +// logic +type Store struct { + *scs.Manager +} + +// InitSession populates the default sessions Store +func InitSession() { + store := scs.NewCookieManager( + CookieKey, + ) + store.HttpOnly(true) + store.Lifetime(24 * time.Hour) + + // Use secure cookies (HTTPS only) in production + store.Secure(settings.Get("ENVIRONMENT", "") == "production") + + SessionStore = &Store{store} +} + +func (store *Store) GetUserEmail(req *http.Request) string { + if store == nil { + // if store was not initialized, all requests fail + log.Println("Zero pointer when checking session for username") + return "" + } + + sess := store.Load(req) + + email, err := sess.GetString(UserEmailKey) + if err != nil { + // Username found + return "" + + } + + // User is logged in + return email +} + +func (store *Store) SetUserEmail(w http.ResponseWriter, req *http.Request, email string) { + if store == nil { + // if store was not initialized, do nothing + return + } + + sess := store.Load(req) + + // renew token to avoid session pinning/fixation attack + sess.RenewToken(w) + + sess.PutString(w, UserEmailKey, email) + +} + +type Flash struct { + Message template.HTML + Type string +} + +// Render renders the flash message as a notification box +func (flash Flash) Render() template.HTML { + return template.HTML( + fmt.Sprintf( + "
%s
", + flash.Type, flash.Message, + ), + ) +} + +// Flash add flash message to session data +func (store *Store) Flash(w http.ResponseWriter, req *http.Request, flash Flash) error { + var flashes []Flash + + sess := store.Load(req) + + if err := sess.GetObject(FlashesKey, &flashes); err != nil { + return err + } + + flashes = append(flashes, flash) + + return sess.PutObject(w, FlashesKey, flashes) +} + +// Flashes returns a slice of flash messages from session data +func (store *Store) Flashes(w http.ResponseWriter, req *http.Request) []Flash { + var flashes []Flash + sess := store.Load(req) + sess.PopObject(w, FlashesKey, &flashes) + return flashes } diff --git a/views/funcs.go b/views/funcs.go index 099785f..2023d79 100644 --- a/views/funcs.go +++ b/views/funcs.go @@ -8,11 +8,13 @@ import ( ) var funcs = template.FuncMap{ - "assetURL": assetURLFn, + "asset": assetURLFn, + "url": relURLFn, "lower": lower, "upper": upper, "date": dateFn, "humanDate": readableDateFn, + "t": translateFn, } func lower(input string) string { @@ -28,6 +30,11 @@ func assetURLFn(input string) string { return fmt.Sprintf("%s%s", url, input) } +func relURLFn(input string) string { + url := "/" //os.Getenv("ASSET_URL") + return fmt.Sprintf("%s%s", url, input) +} + func dateFn(format string, input interface{}) string { var t time.Time switch date := input.(type) { @@ -40,6 +47,10 @@ func dateFn(format string, input interface{}) string { return t.Format(format) } +func translateFn(language string, text string) string { + return text +} + func readableDateFn(t time.Time) string { if time.Now().Before(t) { return "in the future" diff --git a/views/templates.go b/views/templates.go index a8c444e..9d000ff 100644 --- a/views/templates.go +++ b/views/templates.go @@ -18,11 +18,15 @@ var templates map[string]*template.Template func LoadTemplates() { templates = map[string]*template.Template{ "401": newTemplate("layouts/application.gohtml", "errors/401.gohtml"), + "403": newTemplate("layouts/application.gohtml", "errors/403.gohtml"), "404": newTemplate("layouts/application.gohtml", "errors/404.gohtml"), "500": newTemplate("layouts/application.gohtml", "errors/500.gohtml"), + "login": newTemplate("layouts/auth.gohtml", "views/login.gohtml"), + "register": newTemplate("layouts/auth.gohtml", "views/register.gohtml"), + "forgot-password": newTemplate("layouts/auth.gohtml", "views/forgot-password.gohtml"), + "debug": newTemplate("layouts/application.gohtml", "shared/header.gohtml", "shared/footer.gohtml", "views/debug.gohtml"), - "login": newTemplate("layouts/application.gohtml", "shared/header.gohtml", "shared/footer.gohtml", "views/login.gohtml"), "cert_list": newTemplate("layouts/application.gohtml", "shared/header.gohtml", "shared/footer.gohtml", "views/cert_list.gohtml"), } return diff --git a/views/views.go b/views/views.go index 69c0bb2..563d31c 100644 --- a/views/views.go +++ b/views/views.go @@ -7,6 +7,8 @@ import ( "log" "net/http" + "git.klink.asia/paul/certman/services" + "github.com/gorilla/csrf" ) @@ -21,10 +23,12 @@ func New(req *http.Request) *View { Vars: map[string]interface{}{ "CSRF_TOKEN": csrf.Token(req), "csrfField": csrf.TemplateField(req), + "username": services.SessionStore.GetUserEmail(req), "Meta": map[string]interface{}{ "Path": req.URL.Path, "Env": "develop", }, + "flashes": []services.Flash{}, }, } } @@ -39,6 +43,9 @@ func (view View) Render(w http.ResponseWriter, name string) { return } + // add flashes to template + view.Vars["flashes"] = services.SessionStore.Flashes(w, view.Request) + w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusOK) t.Execute(w, view.Vars) @@ -49,12 +56,12 @@ func (view View) RenderError(w http.ResponseWriter, status int) { var name string switch status { - case http.StatusNotFound: - name = "404" case http.StatusUnauthorized: name = "401" case http.StatusForbidden: name = "403" + case http.StatusNotFound: + name = "404" default: name = "500" }