Initial commit with user management
This commit is contained in:
commit
a1a928e7cb
98 changed files with 13042 additions and 0 deletions
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
notes2
|
192
authentication/pkg.go
Normal file
192
authentication/pkg.go
Normal file
|
@ -0,0 +1,192 @@
|
|||
package authentication
|
||||
|
||||
import (
|
||||
// External
|
||||
_ "git.gibonuddevalla.se/go/wrappederror"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/lib/pq"
|
||||
|
||||
// Standard
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Manager struct {
|
||||
db *sqlx.DB
|
||||
log *slog.Logger
|
||||
secret []byte
|
||||
ExpireDays int
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int
|
||||
Username string
|
||||
Name string
|
||||
}
|
||||
|
||||
func httpError(w http.ResponseWriter, err error) { // {{{
|
||||
j, _ := json.Marshal(struct {
|
||||
OK bool
|
||||
Error string
|
||||
}{
|
||||
false,
|
||||
err.Error(),
|
||||
})
|
||||
w.Write(j)
|
||||
} // }}}
|
||||
|
||||
func NewManager(db *sqlx.DB, log *slog.Logger, secret string, expireDays int) (mngr Manager, err error) { // {{{
|
||||
mngr.db = db
|
||||
mngr.log = log
|
||||
|
||||
mngr.secret, err = hex.DecodeString(secret)
|
||||
mngr.ExpireDays = expireDays
|
||||
return
|
||||
} // }}}
|
||||
func (mngr *Manager) GenerateToken(data map[string]any) (string, error) { // {{{
|
||||
// Create a new token object, specifying signing method and the claims
|
||||
// you would like it to contain.
|
||||
now := time.Now()
|
||||
data["iat"] = now.Unix()
|
||||
data["exp"] = now.Add(time.Hour * 24 * time.Duration(mngr.ExpireDays)).Unix()
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(data))
|
||||
|
||||
// Sign and get the complete encoded token as a string using the secret.
|
||||
return token.SignedString(mngr.secret)
|
||||
} // }}}
|
||||
func (mngr *Manager) AuthenticationHandler(w http.ResponseWriter, r *http.Request) { // {{{
|
||||
var request struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
err := json.Unmarshal(body, &request)
|
||||
if err != nil {
|
||||
httpError(w, err)
|
||||
}
|
||||
|
||||
// Verify username and password against the db user table.
|
||||
authenticated, user, err := mngr.Authenticate(request.Username, request.Password)
|
||||
if err != nil {
|
||||
httpError(w, err)
|
||||
}
|
||||
|
||||
if !authenticated {
|
||||
httpError(w, errors.New("Authentication failed"))
|
||||
}
|
||||
|
||||
j, _ := json.Marshal(struct {
|
||||
OK bool
|
||||
User User
|
||||
}{true, user})
|
||||
w.Write(j)
|
||||
} // }}}
|
||||
|
||||
func (mngr *Manager) Authenticate(username, password string) (authenticated bool, user User, err error) { // {{{
|
||||
var row *sql.Row
|
||||
row = mngr.db.QueryRow(`
|
||||
SELECT id, username, name
|
||||
FROM public.user
|
||||
WHERE
|
||||
LOWER(username) = LOWER($1) AND
|
||||
password = password_hash(SUBSTRING(password FROM 1 FOR 32), $2::bytea)
|
||||
`,
|
||||
username,
|
||||
password,
|
||||
)
|
||||
err = row.Scan(&user.ID, &user.Username, &user.Name)
|
||||
authenticated = user.ID > 0
|
||||
return
|
||||
} // }}}
|
||||
func (mngr *Manager) CreateUser(username, password, name string) (alreadyExists bool, err error) { // {{{
|
||||
_, err = mngr.db.Exec(`
|
||||
INSERT INTO public.user(username, password, name, totp)
|
||||
VALUES(
|
||||
$1,
|
||||
public.password_hash(
|
||||
/* salt in hex */
|
||||
ENCODE(public.gen_random_bytes(16), 'hex'),
|
||||
|
||||
/* password */
|
||||
$2::bytea
|
||||
),
|
||||
$3,
|
||||
''
|
||||
)
|
||||
`,
|
||||
username,
|
||||
password,
|
||||
name,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
if pqErr, ok := err.(*pq.Error); ok && pqErr.Code == "23505" {
|
||||
err = errors.New("User already exists")
|
||||
alreadyExists = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
} // }}}
|
||||
func (mngr *Manager) ChangePassword(username, currentPassword, newPassword string, forceChange bool) (changed bool, err error) { // {{{
|
||||
var res sql.Result
|
||||
|
||||
if forceChange {
|
||||
res, err = mngr.db.Exec(`
|
||||
UPDATE public.user
|
||||
SET
|
||||
"password" = public.password_hash(
|
||||
/* salt in hex */
|
||||
ENCODE(public.gen_random_bytes(16), 'hex'),
|
||||
|
||||
/* password */
|
||||
$2::bytea
|
||||
)
|
||||
WHERE
|
||||
username = $1
|
||||
|
||||
`,
|
||||
username,
|
||||
newPassword,
|
||||
)
|
||||
} else {
|
||||
res, err = mngr.db.Exec(`
|
||||
UPDATE public.user
|
||||
SET
|
||||
"password" = public.password_hash(
|
||||
/* salt in hex */
|
||||
ENCODE(public.gen_random_bytes(16), 'hex'),
|
||||
|
||||
/* password */
|
||||
$3::bytea
|
||||
)
|
||||
WHERE
|
||||
username = $1 AND
|
||||
"password" = public.password_hash(SUBSTRING(password FROM 1 FOR 32), $2::bytea)
|
||||
|
||||
`,
|
||||
username,
|
||||
currentPassword,
|
||||
newPassword,
|
||||
)
|
||||
}
|
||||
|
||||
var rowsAffected int64
|
||||
rowsAffected, err = res.RowsAffected()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
changed = (rowsAffected == 1)
|
||||
return
|
||||
} // }}}
|
40
config.go
Normal file
40
config.go
Normal file
|
@ -0,0 +1,40 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
// Standard
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Network struct {
|
||||
Address string
|
||||
Port int
|
||||
}
|
||||
|
||||
Database struct {
|
||||
Host string
|
||||
Port int
|
||||
Db string
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
JWT struct {
|
||||
Secret string
|
||||
ExpireDays int
|
||||
}
|
||||
}
|
||||
|
||||
func readConfig() (err error) {
|
||||
var configData []byte
|
||||
fname := fmt.Sprintf("%s/.config/notes2.json", os.Getenv("HOME"))
|
||||
configData, err = os.ReadFile(fname)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = json.Unmarshal(configData, &config)
|
||||
return
|
||||
}
|
63
db.go
Normal file
63
db.go
Normal file
|
@ -0,0 +1,63 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
// External
|
||||
"git.gibonuddevalla.se/go/dbschema"
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
// Standard
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
db *sqlx.DB
|
||||
)
|
||||
|
||||
func sqlCallback(db string, version int) (sql []byte, found bool) { // {{{
|
||||
var err error
|
||||
fname := fmt.Sprintf("sql/%05d.sql", version)
|
||||
sql, err = SqlFS.ReadFile(fname)
|
||||
found = (err == nil)
|
||||
return
|
||||
} // }}}
|
||||
func logCallback(section, message string) { // {{{
|
||||
Log.Info("database", section, message)
|
||||
} // }}}
|
||||
func initDB() (err error) { // {{{
|
||||
dbConn := fmt.Sprintf(
|
||||
"host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
|
||||
config.Database.Host,
|
||||
config.Database.Port,
|
||||
config.Database.Username,
|
||||
config.Database.Password,
|
||||
config.Database.Db,
|
||||
)
|
||||
|
||||
Log.Info(
|
||||
"database",
|
||||
"host", config.Database.Host,
|
||||
"port", config.Database.Port,
|
||||
)
|
||||
|
||||
if db, err = sqlx.Connect("postgres", dbConn); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
upgrader := dbschema.NewUpgrader()
|
||||
upgrader.SetSqlCallback(sqlCallback)
|
||||
upgrader.SetLogCallback(logCallback)
|
||||
_, err = upgrader.AddDatabase(
|
||||
config.Database.Host,
|
||||
config.Database.Port,
|
||||
config.Database.Db,
|
||||
config.Database.Username,
|
||||
config.Database.Password,
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = upgrader.Run()
|
||||
|
||||
return
|
||||
} // }}}
|
12
go.mod
Normal file
12
go.mod
Normal file
|
@ -0,0 +1,12 @@
|
|||
module notes2
|
||||
|
||||
go 1.23.0
|
||||
|
||||
require (
|
||||
git.gibonuddevalla.se/go/dbschema v1.3.1
|
||||
git.gibonuddevalla.se/go/wrappederror v0.3.5
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jmoiron/sqlx v1.4.0
|
||||
github.com/lib/pq v1.10.9
|
||||
)
|
18
go.sum
Normal file
18
go.sum
Normal file
|
@ -0,0 +1,18 @@
|
|||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
git.gibonuddevalla.se/go/dbschema v1.3.1 h1:TGPvbNO/u7IK5TU0HT92mVzqdF179lLCfdTxM1ftcAE=
|
||||
git.gibonuddevalla.se/go/dbschema v1.3.1/go.mod h1:BNw3q/574nXbGoeWyK+tLhRfggVkw2j2aXZzrBKC3ig=
|
||||
git.gibonuddevalla.se/go/wrappederror v0.3.5 h1:/EzrdXETlZfNpS6TcK1Ix6BaV+Fl7qcGoxUM0GkrIN8=
|
||||
git.gibonuddevalla.se/go/wrappederror v0.3.5/go.mod h1:j4w320Hk1wvhOPjUaK4GgLvmtnjUUM5yVu6JFO1OCSc=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
31
html_template/page.go
Normal file
31
html_template/page.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
package HTMLTemplate
|
||||
|
||||
type Page interface {
|
||||
GetVersion() string
|
||||
GetLayout() string
|
||||
GetPage() string
|
||||
GetData() any
|
||||
}
|
||||
|
||||
type SimplePage struct {
|
||||
Version string
|
||||
Layout string
|
||||
Page string
|
||||
Data any
|
||||
}
|
||||
|
||||
func (s SimplePage) GetVersion() string {
|
||||
return s.Version
|
||||
}
|
||||
|
||||
func (s SimplePage) GetLayout() string {
|
||||
return s.Layout
|
||||
}
|
||||
|
||||
func (s SimplePage) GetPage() string {
|
||||
return s.Page
|
||||
}
|
||||
|
||||
func (s SimplePage) GetData() any {
|
||||
return s.Data
|
||||
}
|
158
html_template/pkg.go
Normal file
158
html_template/pkg.go
Normal file
|
@ -0,0 +1,158 @@
|
|||
package HTMLTemplate
|
||||
|
||||
import (
|
||||
// External
|
||||
werr "git.gibonuddevalla.se/go/wrappederror"
|
||||
|
||||
// Standard
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type Engine struct {
|
||||
parsedTemplates map[string]*template.Template
|
||||
viewFS fs.FS
|
||||
staticEmbeddedFS http.Handler
|
||||
staticLocalFS http.Handler
|
||||
componentFilenames []string
|
||||
DevMode bool
|
||||
}
|
||||
|
||||
func NewEngine(viewFS, staticFS fs.FS, devmode bool) (e Engine, err error) { // {{{
|
||||
e.parsedTemplates = make(map[string]*template.Template)
|
||||
e.viewFS = viewFS
|
||||
e.DevMode = devmode
|
||||
|
||||
e.componentFilenames, err = e.getComponentFilenames()
|
||||
|
||||
// Set up fileservers for static resources.
|
||||
// The embedded FS is using the embedded files intented for production use.
|
||||
// The local FS is for development of Javascript to avoid server rebuild (devmode).
|
||||
var staticSubFS fs.FS
|
||||
staticSubFS, err = fs.Sub(staticFS, "static")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
e.staticEmbeddedFS = http.FileServer(http.FS(staticSubFS))
|
||||
e.staticLocalFS = http.FileServer(http.Dir("static"))
|
||||
|
||||
return
|
||||
} // }}}
|
||||
|
||||
func (e *Engine) getComponentFilenames() (files []string, err error) { // {{{
|
||||
files = []string{}
|
||||
if err := fs.WalkDir(e.viewFS, "views/components", func(path string, d fs.DirEntry, err error) error {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
if d.IsDir() {
|
||||
return nil
|
||||
}
|
||||
files = append(files, path)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return files, nil
|
||||
} // }}}
|
||||
|
||||
func (e *Engine) ReloadTemplates() { // {{{
|
||||
e.parsedTemplates = make(map[string]*template.Template)
|
||||
} // }}}
|
||||
|
||||
func (e *Engine) StaticResource(w http.ResponseWriter, r *http.Request) { // {{{
|
||||
var err error
|
||||
|
||||
// URLs with pattern /(css|images)/v1.0.0/foobar are stripped of the version.
|
||||
// To get rid of problems with cached content in browser on a new version release,
|
||||
// while also not disabling cache altogether.
|
||||
if r.URL.Path == "/favicon.ico" {
|
||||
e.staticEmbeddedFS.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
rxp := regexp.MustCompile("^/(css|images|js|fonts)/v[0-9]+/(.*)$")
|
||||
if comp := rxp.FindStringSubmatch(r.URL.Path); comp != nil {
|
||||
w.Header().Add("Pragma", "public")
|
||||
w.Header().Add("Cache-Control", "max-age=604800")
|
||||
|
||||
r.URL.Path = fmt.Sprintf("/%s/%s", comp[1], comp[2])
|
||||
if e.DevMode {
|
||||
p := fmt.Sprintf("static/%s/%s", comp[1], comp[2])
|
||||
_, err = os.Stat(p)
|
||||
if err == nil {
|
||||
e.staticLocalFS.ServeHTTP(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
e.staticEmbeddedFS.ServeHTTP(w, r)
|
||||
} // }}}
|
||||
func (e *Engine) getPage(layout, page string) (tmpl *template.Template, err error) { // {{{
|
||||
layoutFilename := fmt.Sprintf("views/layouts/%s.gotmpl", layout)
|
||||
pageFilename := fmt.Sprintf("views/pages/%s.gotmpl", page)
|
||||
|
||||
if tmpl, found := e.parsedTemplates[page]; found {
|
||||
return tmpl, nil
|
||||
}
|
||||
|
||||
funcMap := template.FuncMap{
|
||||
/*
|
||||
"format_time": func(t time.Time) template.HTML {
|
||||
return template.HTML(
|
||||
t.In(smonConfig.Timezone()).Format(`<span class="date">2006-01-02</span> <span class="time">15:04:05<span class="seconds">:05</span></span>`),
|
||||
)
|
||||
},
|
||||
*/
|
||||
}
|
||||
|
||||
filenames := []string{layoutFilename, pageFilename}
|
||||
filenames = append(filenames, e.componentFilenames...)
|
||||
|
||||
if e.DevMode {
|
||||
tmpl, err = template.New(layout+".gotmpl").Funcs(funcMap).ParseFS(os.DirFS("."), filenames...)
|
||||
} else {
|
||||
tmpl, err = template.New(layout+".gotmpl").Funcs(funcMap).ParseFS(e.viewFS, filenames...)
|
||||
}
|
||||
if err != nil {
|
||||
err = werr.Wrap(err).Log()
|
||||
return
|
||||
}
|
||||
|
||||
e.parsedTemplates[page] = tmpl
|
||||
return
|
||||
} // }}}
|
||||
func (e *Engine) Render(p Page, w http.ResponseWriter, r *http.Request) (err error) { // {{{
|
||||
if e.DevMode {
|
||||
e.ReloadTemplates()
|
||||
}
|
||||
|
||||
var tmpl *template.Template
|
||||
tmpl, err = e.getPage(p.GetLayout(), p.GetPage())
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]any{
|
||||
"VERSION": p.GetVersion(),
|
||||
"LAYOUT": p.GetLayout(),
|
||||
"PAGE": p.GetPage(),
|
||||
"ERROR": r.URL.Query().Get("_err"),
|
||||
"Data": p.GetData(),
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, data)
|
||||
if err != nil {
|
||||
err = werr.Wrap(err)
|
||||
}
|
||||
return
|
||||
} // }}}
|
||||
|
||||
// vim: foldmethod=marker
|
202
main.go
Normal file
202
main.go
Normal file
|
@ -0,0 +1,202 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
// External
|
||||
|
||||
// Internal
|
||||
"notes2/authentication"
|
||||
"notes2/html_template"
|
||||
"os"
|
||||
|
||||
// Standard
|
||||
"bufio"
|
||||
"embed"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
const VERSION = "v1"
|
||||
|
||||
var (
|
||||
FlagDev bool
|
||||
FlagConfig string
|
||||
FlagCreateUser string
|
||||
FlagChangePassword string
|
||||
Webengine HTMLTemplate.Engine
|
||||
config Config
|
||||
Log *slog.Logger
|
||||
AuthManager authentication.Manager
|
||||
|
||||
//go:embed views
|
||||
ViewFS embed.FS
|
||||
|
||||
//go:embed static
|
||||
StaticFS embed.FS
|
||||
|
||||
//go:embed sql
|
||||
SqlFS embed.FS
|
||||
)
|
||||
|
||||
func init() { // {{{
|
||||
// Configuration filename to use with a somewhat sane default.
|
||||
cfgDir, err := os.UserConfigDir()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
cfgFilename := path.Join(cfgDir, "notes2.json")
|
||||
|
||||
flag.StringVar(&FlagConfig, "config", cfgFilename, "Configuration file")
|
||||
flag.BoolVar(&FlagDev, "dev", false, "Use local files instead of embedded files")
|
||||
flag.StringVar(&FlagCreateUser, "create-user", "", "Username for creating a new user")
|
||||
flag.StringVar(&FlagChangePassword, "change-password", "", "Change the password for the given username")
|
||||
flag.Parse()
|
||||
} // }}}
|
||||
func initLog() { // {{{
|
||||
opts := slog.HandlerOptions{}
|
||||
opts.Level = slog.LevelDebug
|
||||
Log = slog.New(slog.NewJSONHandler(os.Stdout, &opts))
|
||||
} // }}}
|
||||
func main() { // {{{
|
||||
initLog()
|
||||
err := readConfig()
|
||||
if err != nil {
|
||||
Log.Error("config", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// dbschema uses the embedded SQL files to keep the database schema up to date.
|
||||
err = initDB()
|
||||
if err != nil {
|
||||
Log.Error("database", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// The session manager contains authentication, authorization and session settings.
|
||||
AuthManager, err = authentication.NewManager(db, Log, config.JWT.Secret, config.JWT.ExpireDays)
|
||||
|
||||
// A new user?
|
||||
if FlagCreateUser != "" {
|
||||
createNewUser(FlagCreateUser)
|
||||
return
|
||||
}
|
||||
|
||||
// Forgotten the password?
|
||||
if FlagChangePassword != "" {
|
||||
changePassword(FlagChangePassword)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// The webengine takes layouts, pages and components and renders them into HTML.
|
||||
Webengine, err = HTMLTemplate.NewEngine(ViewFS, StaticFS, FlagDev)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
http.HandleFunc("/", rootHandler)
|
||||
http.HandleFunc("/authenticate", AuthManager.AuthenticationHandler)
|
||||
http.HandleFunc("/service_worker.js", pageServiceWorker)
|
||||
listen := fmt.Sprintf("%s:%d", config.Network.Address, config.Network.Port)
|
||||
http.ListenAndServe(listen, nil)
|
||||
} // }}}
|
||||
|
||||
func rootHandler(w http.ResponseWriter, r *http.Request) { // {{{
|
||||
// All URLs not specifically handled are routed to this function.
|
||||
// Everything going here should be a static resource.
|
||||
if r.URL.Path != "/" {
|
||||
Webengine.StaticResource(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
pageIndex(w, r)
|
||||
} // }}}
|
||||
func pageServiceWorker(w http.ResponseWriter, r *http.Request) { // {{{
|
||||
w.Header().Add("Content-Type", "text/javascript; charset=utf-8")
|
||||
|
||||
var tmpl *template.Template
|
||||
var err error
|
||||
if FlagDev {
|
||||
tmpl, err = template.ParseFiles("static/service_worker.js")
|
||||
} else {
|
||||
tmpl, err = template.ParseFS(StaticFS, "static/service_worker.js")
|
||||
}
|
||||
if err != nil {
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
err = tmpl.Execute(w, struct{ VERSION string }{VERSION})
|
||||
if err != nil {
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
} // }}}
|
||||
func pageIndex(w http.ResponseWriter, r *http.Request) { // {{{
|
||||
// Index page is rendered since everything
|
||||
// else are specifically handled.
|
||||
page := HTMLTemplate.SimplePage{
|
||||
Layout: "main",
|
||||
Page: "index",
|
||||
Version: VERSION,
|
||||
}
|
||||
|
||||
err := Webengine.Render(page, w, r)
|
||||
if err != nil {
|
||||
w.Write([]byte(err.Error()))
|
||||
return
|
||||
}
|
||||
} // }}}
|
||||
func sessionFilter(fn func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { // {{{
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Printf("Filtered ")
|
||||
fn(w, r)
|
||||
}
|
||||
} // }}}
|
||||
|
||||
func createNewUser(username string) { // {{{
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
fmt.Print("\nPassword: ")
|
||||
pwd, _ := reader.ReadString('\n')
|
||||
pwd = strings.Trim(pwd, "\r\n")
|
||||
|
||||
fmt.Print("Name: ")
|
||||
name, _ := reader.ReadString('\n')
|
||||
name = strings.Trim(name, "\r\n")
|
||||
|
||||
alreadyExists, err := AuthManager.CreateUser(username, pwd, name)
|
||||
if alreadyExists {
|
||||
fmt.Printf("\nUser '%s' already exists\n", username)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
Log.Error("create_user", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("\nUser '%s' with username '%s' is created.\n", name, username)
|
||||
} // }}}
|
||||
func changePassword(username string) { // {{{
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
|
||||
fmt.Print("\nPassword: ")
|
||||
newPwd, _ := reader.ReadString('\n')
|
||||
newPwd = strings.Trim(newPwd, "\r\n")
|
||||
|
||||
hasChanged, err := AuthManager.ChangePassword(username, "", newPwd, true)
|
||||
if !hasChanged {
|
||||
fmt.Printf("Invalid user\n")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
Log.Error("change_password", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("\nPassword changed\n")
|
||||
} // }}}
|
43
sql/00001.sql
Normal file
43
sql/00001.sql
Normal file
|
@ -0,0 +1,43 @@
|
|||
CREATE TABLE public.user (
|
||||
id serial NOT NULL,
|
||||
"name" varchar NOT NULL,
|
||||
"username" varchar NOT NULL,
|
||||
"password" char(96) NOT NULL,
|
||||
totp varchar NOT NULL,
|
||||
last_login timestamp with time zone NOT NULL DEFAULT '1970-01-01 00:00:00',
|
||||
CONSTRAINT user_pk PRIMARY KEY (id),
|
||||
CONSTRAINT user_un UNIQUE (username)
|
||||
);
|
||||
|
||||
CREATE TABLE public.session (
|
||||
id serial NOT NULL,
|
||||
user_id int4 NULL,
|
||||
"uuid" char(36) NOT NULL,
|
||||
created timestamp with time zone NOT NULL DEFAULT NOW(),
|
||||
last_used timestamp with time zone NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT session_pk PRIMARY KEY (id),
|
||||
CONSTRAINT session_un UNIQUE ("uuid"),
|
||||
CONSTRAINT session_user_fk FOREIGN KEY (user_id) REFERENCES "user"(id) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto SCHEMA public;
|
||||
|
||||
CREATE FUNCTION password_hash(salt_hex char(32), pass bytea)
|
||||
RETURNS char(96)
|
||||
LANGUAGE plpgsql
|
||||
AS
|
||||
$$
|
||||
BEGIN
|
||||
RETURN (
|
||||
SELECT
|
||||
salt_hex ||
|
||||
encode(
|
||||
sha256(
|
||||
decode(salt_hex, 'hex') || /* salt in binary */
|
||||
pass /* password */
|
||||
),
|
||||
'hex'
|
||||
)
|
||||
);
|
||||
END;
|
||||
$$;
|
14
static/css/main.css
Normal file
14
static/css/main.css
Normal file
|
@ -0,0 +1,14 @@
|
|||
html {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
*,
|
||||
*:before,
|
||||
*:after {
|
||||
box-sizing: inherit;
|
||||
}
|
||||
*:focus {
|
||||
outline: none;
|
||||
}
|
||||
[onClick] {
|
||||
cursor: pointer;
|
||||
}
|
1
static/foo
Normal file
1
static/foo
Normal file
|
@ -0,0 +1 @@
|
|||
foo
|
1
static/js/app.mjs
Normal file
1
static/js/app.mjs
Normal file
|
@ -0,0 +1 @@
|
|||
console.log('app.mjs')
|
6
static/js/lib/fullcalendar.min.js
vendored
Normal file
6
static/js/lib/fullcalendar.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
6
static/js/lib/htm/htm.d.ts
vendored
Normal file
6
static/js/lib/htm/htm.d.ts
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
declare const htm: {
|
||||
bind<HResult>(
|
||||
h: (type: any, props: Record<string, any>, ...children: any[]) => HResult
|
||||
): (strings: TemplateStringsArray, ...values: any[]) => HResult | HResult[];
|
||||
};
|
||||
export default htm;
|
1
static/js/lib/htm/htm.js
Normal file
1
static/js/lib/htm/htm.js
Normal file
|
@ -0,0 +1 @@
|
|||
!function(){const t=(e,n,s,u)=>{let h;n[0]=0;for(let l=1;l<n.length;l++){const p=n[l++],o=n[l]?(n[0]|=p?1:2,s[n[l++]]):n[++l];3===p?u[0]=o:4===p?u[1]=Object.assign(u[1]||{},o):5===p?(u[1]=u[1]||{})[n[++l]]=o:6===p?u[1][n[++l]]+=o+"":p?(h=e.apply(o,t(e,o,s,["",null])),u.push(h),o[0]?n[0]|=2:(n[l-2]=0,n[l]=h)):u.push(o)}return u},e=function(t){let e,n,s=1,u="",h="",l=[0];const p=t=>{1===s&&(t||(u=u.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?l.push(0,t,u):3===s&&(t||u)?(l.push(3,t,u),s=2):2===s&&"..."===u&&t?l.push(4,t,0):2===s&&u&&!t?l.push(5,0,!0,u):s>=5&&((u||!t&&5===s)&&(l.push(s,0,u,n),s=6),t&&(l.push(s,t,0,n),s=6)),u=""};for(let o=0;o<t.length;o++){o&&(1===s&&p(),p(o));for(let r=0;r<t[o].length;r++)e=t[o][r],1===s?"<"===e?(p(),l=[l],s=3):u+=e:4===s?"--"===u&&">"===e?(s=1,u=""):u=e+u[0]:h?e===h?h="":u+=e:'"'===e||"'"===e?h=e:">"===e?(p(),s=1):s&&("="===e?(s=5,n=u,u=""):"/"===e&&(s<5||">"===t[o][r+1])?(p(),3===s&&(l=l[0]),s=l,(l=l[0]).push(2,0,s),s=0):" "===e||"\t"===e||"\n"===e||"\r"===e?(p(),s=2):u+=e),3===s&&"!--"===u&&(s=4,l=l[0])}return p(),l},n=new Map;var s=function(s){let u=n.get(this);return u||(u=new Map,n.set(this,u)),u=t(this,u.get(s)||(u.set(s,u=e(s)),u),arguments,[]),u.length>1?u:u[0]};"undefined"!=typeof module?module.exports=s:self.htm=s}();
|
1
static/js/lib/htm/htm.mjs
Normal file
1
static/js/lib/htm/htm.mjs
Normal file
|
@ -0,0 +1 @@
|
|||
const t=(e,s,n,h)=>{let u;s[0]=0;for(let l=1;l<s.length;l++){const p=s[l++],r=s[l]?(s[0]|=p?1:2,n[s[l++]]):s[++l];3===p?h[0]=r:4===p?h[1]=Object.assign(h[1]||{},r):5===p?(h[1]=h[1]||{})[s[++l]]=r:6===p?h[1][s[++l]]+=r+"":p?(u=e.apply(r,t(e,r,n,["",null])),h.push(u),r[0]?s[0]|=2:(s[l-2]=0,s[l]=u)):h.push(r)}return h},e=function(t){let e,s,n=1,h="",u="",l=[0];const p=t=>{1===n&&(t||(h=h.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?l.push(0,t,h):3===n&&(t||h)?(l.push(3,t,h),n=2):2===n&&"..."===h&&t?l.push(4,t,0):2===n&&h&&!t?l.push(5,0,!0,h):n>=5&&((h||!t&&5===n)&&(l.push(n,0,h,s),n=6),t&&(l.push(n,t,0,s),n=6)),h=""};for(let r=0;r<t.length;r++){r&&(1===n&&p(),p(r));for(let o=0;o<t[r].length;o++)e=t[r][o],1===n?"<"===e?(p(),l=[l],n=3):h+=e:4===n?"--"===h&&">"===e?(n=1,h=""):h=e+h[0]:u?e===u?u="":h+=e:'"'===e||"'"===e?u=e:">"===e?(p(),n=1):n&&("="===e?(n=5,s=h,h=""):"/"===e&&(n<5||">"===t[r][o+1])?(p(),3===n&&(l=l[0]),n=l,(l=l[0]).push(2,0,n),n=0):" "===e||"\t"===e||"\n"===e||"\r"===e?(p(),n=2):h+=e),3===n&&"!--"===h&&(n=4,l=l[0])}return p(),l},s=new Map;var n=function(n){let h=s.get(this);return h||(h=new Map,s.set(this,h)),h=t(this,h.get(n)||(h.set(n,h=e(n)),h),arguments,[]),h.length>1?h:h[0]};export{n as default};
|
1
static/js/lib/htm/htm.module.js
Normal file
1
static/js/lib/htm/htm.module.js
Normal file
|
@ -0,0 +1 @@
|
|||
const t=(e,s,n,h)=>{let u;s[0]=0;for(let l=1;l<s.length;l++){const p=s[l++],r=s[l]?(s[0]|=p?1:2,n[s[l++]]):s[++l];3===p?h[0]=r:4===p?h[1]=Object.assign(h[1]||{},r):5===p?(h[1]=h[1]||{})[s[++l]]=r:6===p?h[1][s[++l]]+=r+"":p?(u=e.apply(r,t(e,r,n,["",null])),h.push(u),r[0]?s[0]|=2:(s[l-2]=0,s[l]=u)):h.push(r)}return h},e=function(t){let e,s,n=1,h="",u="",l=[0];const p=t=>{1===n&&(t||(h=h.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?l.push(0,t,h):3===n&&(t||h)?(l.push(3,t,h),n=2):2===n&&"..."===h&&t?l.push(4,t,0):2===n&&h&&!t?l.push(5,0,!0,h):n>=5&&((h||!t&&5===n)&&(l.push(n,0,h,s),n=6),t&&(l.push(n,t,0,s),n=6)),h=""};for(let r=0;r<t.length;r++){r&&(1===n&&p(),p(r));for(let o=0;o<t[r].length;o++)e=t[r][o],1===n?"<"===e?(p(),l=[l],n=3):h+=e:4===n?"--"===h&&">"===e?(n=1,h=""):h=e+h[0]:u?e===u?u="":h+=e:'"'===e||"'"===e?u=e:">"===e?(p(),n=1):n&&("="===e?(n=5,s=h,h=""):"/"===e&&(n<5||">"===t[r][o+1])?(p(),3===n&&(l=l[0]),n=l,(l=l[0]).push(2,0,n),n=0):" "===e||"\t"===e||"\n"===e||"\r"===e?(p(),n=2):h+=e),3===n&&"!--"===h&&(n=4,l=l[0])}return p(),l},s=new Map;var n=function(n){let h=s.get(this);return h||(h=new Map,s.set(this,h)),h=t(this,h.get(n)||(h.set(n,h=e(n)),h),arguments,[]),h.length>1?h:h[0]};export{n as default};
|
1
static/js/lib/htm/htm.umd.js
Normal file
1
static/js/lib/htm/htm.umd.js
Normal file
|
@ -0,0 +1 @@
|
|||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e||self).htm=t()}(this,function(){const e=(t,n,s,u)=>{let o;n[0]=0;for(let l=1;l<n.length;l++){const h=n[l++],p=n[l]?(n[0]|=h?1:2,s[n[l++]]):n[++l];3===h?u[0]=p:4===h?u[1]=Object.assign(u[1]||{},p):5===h?(u[1]=u[1]||{})[n[++l]]=p:6===h?u[1][n[++l]]+=p+"":h?(o=t.apply(p,e(t,p,s,["",null])),u.push(o),p[0]?n[0]|=2:(n[l-2]=0,n[l]=o)):u.push(p)}return u},t=function(e){let t,n,s=1,u="",o="",l=[0];const h=e=>{1===s&&(e||(u=u.replace(/^\s*\n\s*|\s*\n\s*$/g,"")))?l.push(0,e,u):3===s&&(e||u)?(l.push(3,e,u),s=2):2===s&&"..."===u&&e?l.push(4,e,0):2===s&&u&&!e?l.push(5,0,!0,u):s>=5&&((u||!e&&5===s)&&(l.push(s,0,u,n),s=6),e&&(l.push(s,e,0,n),s=6)),u=""};for(let p=0;p<e.length;p++){p&&(1===s&&h(),h(p));for(let f=0;f<e[p].length;f++)t=e[p][f],1===s?"<"===t?(h(),l=[l],s=3):u+=t:4===s?"--"===u&&">"===t?(s=1,u=""):u=t+u[0]:o?t===o?o="":u+=t:'"'===t||"'"===t?o=t:">"===t?(h(),s=1):s&&("="===t?(s=5,n=u,u=""):"/"===t&&(s<5||">"===e[p][f+1])?(h(),3===s&&(l=l[0]),s=l,(l=l[0]).push(2,0,s),s=0):" "===t||"\t"===t||"\n"===t||"\r"===t?(h(),s=2):u+=t),3===s&&"!--"===u&&(s=4,l=l[0])}return h(),l},n=new Map;return function(s){let u=n.get(this);return u||(u=new Map,n.set(this,u)),u=e(this,u.get(s)||(u.set(s,u=t(s)),u),arguments,[]),u.length>1?u:u[0]}});
|
1
static/js/lib/node_modules/.bin/marked
generated
vendored
Symbolic link
1
static/js/lib/node_modules/.bin/marked
generated
vendored
Symbolic link
|
@ -0,0 +1 @@
|
|||
../marked/bin/marked.js
|
18
static/js/lib/node_modules/.package-lock.json
generated
vendored
Normal file
18
static/js/lib/node_modules/.package-lock.json
generated
vendored
Normal file
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"name": "lib",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/marked": {
|
||||
"version": "11.1.1",
|
||||
"resolved": "https://registry.npmjs.org/marked/-/marked-11.1.1.tgz",
|
||||
"integrity": "sha512-EgxRjgK9axsQuUa/oKMx5DEY8oXpKJfk61rT5iY3aRlgU6QJtUcxU5OAymdhCvWvhYcd9FKmO5eQoX8m9VGJXg==",
|
||||
"bin": {
|
||||
"marked": "bin/marked.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
44
static/js/lib/node_modules/marked/LICENSE.md
generated
vendored
Normal file
44
static/js/lib/node_modules/marked/LICENSE.md
generated
vendored
Normal file
|
@ -0,0 +1,44 @@
|
|||
# License information
|
||||
|
||||
## Contribution License Agreement
|
||||
|
||||
If you contribute code to this project, you are implicitly allowing your code
|
||||
to be distributed under the MIT license. You are also implicitly verifying that
|
||||
all code is your original work. `</legalese>`
|
||||
|
||||
## Marked
|
||||
|
||||
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
|
||||
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
## Markdown
|
||||
|
||||
Copyright © 2004, John Gruber
|
||||
http://daringfireball.net/
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
|
107
static/js/lib/node_modules/marked/README.md
generated
vendored
Normal file
107
static/js/lib/node_modules/marked/README.md
generated
vendored
Normal file
|
@ -0,0 +1,107 @@
|
|||
<a href="https://marked.js.org">
|
||||
<img width="60px" height="60px" src="https://marked.js.org/img/logo-black.svg" align="right" />
|
||||
</a>
|
||||
|
||||
# Marked
|
||||
|
||||
[](https://www.npmjs.com/package/marked)
|
||||
[](https://cdn.jsdelivr.net/npm/marked/marked.min.js)
|
||||
[](https://packagephobia.now.sh/result?p=marked)
|
||||
[](https://www.npmjs.com/package/marked)
|
||||
[](https://github.com/markedjs/marked/actions)
|
||||
[](https://snyk.io/test/npm/marked)
|
||||
|
||||
- ⚡ built for speed
|
||||
- ⬇️ low-level compiler for parsing markdown without caching or blocking for long periods of time
|
||||
- ⚖️ light-weight while implementing all markdown features from the supported flavors & specifications
|
||||
- 🌐 works in a browser, on a server, or from a command line interface (CLI)
|
||||
|
||||
## Demo
|
||||
|
||||
Checkout the [demo page](https://marked.js.org/demo/) to see marked in action ⛹️
|
||||
|
||||
## Docs
|
||||
|
||||
Our [documentation pages](https://marked.js.org) are also rendered using marked 💯
|
||||
|
||||
Also read about:
|
||||
|
||||
* [Options](https://marked.js.org/using_advanced)
|
||||
* [Extensibility](https://marked.js.org/using_pro)
|
||||
|
||||
## Compatibility
|
||||
|
||||
**Node.js:** Only [current and LTS](https://nodejs.org/en/about/releases/) Node.js versions are supported. End of life Node.js versions may become incompatible with Marked at any point in time.
|
||||
|
||||
**Browser:** Not IE11 :)
|
||||
|
||||
## Installation
|
||||
|
||||
**CLI:**
|
||||
|
||||
```sh
|
||||
npm install -g marked
|
||||
```
|
||||
|
||||
**In-browser:**
|
||||
|
||||
```sh
|
||||
npm install marked
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Warning: 🚨 Marked does not [sanitize](https://marked.js.org/using_advanced#options) the output HTML. Please use a sanitize library, like [DOMPurify](https://github.com/cure53/DOMPurify) (recommended), [sanitize-html](https://github.com/apostrophecms/sanitize-html) or [insane](https://github.com/bevacqua/insane) on the *output* HTML! 🚨
|
||||
|
||||
```
|
||||
DOMPurify.sanitize(marked.parse(`<img src="x" onerror="alert('not happening')">`));
|
||||
```
|
||||
|
||||
**CLI**
|
||||
|
||||
``` bash
|
||||
# Example with stdin input
|
||||
$ marked -o hello.html
|
||||
hello world
|
||||
^D
|
||||
$ cat hello.html
|
||||
<p>hello world</p>
|
||||
```
|
||||
|
||||
```bash
|
||||
# Print all options
|
||||
$ marked --help
|
||||
```
|
||||
|
||||
**Browser**
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8"/>
|
||||
<title>Marked in the browser</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="content"></div>
|
||||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||||
<script>
|
||||
document.getElementById('content').innerHTML =
|
||||
marked.parse('# Marked in the browser\n\nRendered by **marked**.');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
or import esm module
|
||||
|
||||
```html
|
||||
<script type="module">
|
||||
import { marked } from "https://cdn.jsdelivr.net/npm/marked/lib/marked.esm.js";
|
||||
document.getElementById('content').innerHTML =
|
||||
marked.parse('# Marked in the browser\n\nRendered by **marked**.');
|
||||
</script>
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2011-2022, Christopher Jeffrey. (MIT License)
|
279
static/js/lib/node_modules/marked/bin/main.js
generated
vendored
Normal file
279
static/js/lib/node_modules/marked/bin/main.js
generated
vendored
Normal file
|
@ -0,0 +1,279 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Marked CLI
|
||||
* Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
|
||||
*/
|
||||
|
||||
import { promises } from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { createRequire } from 'node:module';
|
||||
import { marked } from '../lib/marked.esm.js';
|
||||
|
||||
const { access, readFile, writeFile } = promises;
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
/**
|
||||
* @param {Process} nodeProcess inject process so it can be mocked in tests.
|
||||
*/
|
||||
export async function main(nodeProcess) {
|
||||
/**
|
||||
* Man Page
|
||||
*/
|
||||
async function help() {
|
||||
const { spawn } = await import('child_process');
|
||||
const { fileURLToPath } = await import('url');
|
||||
|
||||
const options = {
|
||||
cwd: nodeProcess.cwd(),
|
||||
env: nodeProcess.env,
|
||||
stdio: 'inherit'
|
||||
};
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const helpText = await readFile(resolve(__dirname, '../man/marked.1.md'), 'utf8');
|
||||
|
||||
// eslint-disable-next-line promise/param-names
|
||||
await new Promise(res => {
|
||||
spawn('man', [resolve(__dirname, '../man/marked.1')], options)
|
||||
.on('error', () => {
|
||||
console.log(helpText);
|
||||
})
|
||||
.on('close', res);
|
||||
});
|
||||
}
|
||||
|
||||
async function version() {
|
||||
const pkg = require('../package.json');
|
||||
console.log(pkg.version);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main
|
||||
*/
|
||||
async function start(argv) {
|
||||
const files = [];
|
||||
const options = {};
|
||||
let input;
|
||||
let output;
|
||||
let string;
|
||||
let arg;
|
||||
let tokens;
|
||||
let config;
|
||||
let opt;
|
||||
let noclobber;
|
||||
|
||||
function getArg() {
|
||||
let arg = argv.shift();
|
||||
|
||||
if (arg.indexOf('--') === 0) {
|
||||
// e.g. --opt
|
||||
arg = arg.split('=');
|
||||
if (arg.length > 1) {
|
||||
// e.g. --opt=val
|
||||
argv.unshift(arg.slice(1).join('='));
|
||||
}
|
||||
arg = arg[0];
|
||||
} else if (arg[0] === '-') {
|
||||
if (arg.length > 2) {
|
||||
// e.g. -abc
|
||||
argv = arg.substring(1).split('').map(function(ch) {
|
||||
return '-' + ch;
|
||||
}).concat(argv);
|
||||
arg = argv.shift();
|
||||
} else {
|
||||
// e.g. -a
|
||||
}
|
||||
} else {
|
||||
// e.g. foo
|
||||
}
|
||||
|
||||
return arg;
|
||||
}
|
||||
|
||||
while (argv.length) {
|
||||
arg = getArg();
|
||||
switch (arg) {
|
||||
case '-o':
|
||||
case '--output':
|
||||
output = argv.shift();
|
||||
break;
|
||||
case '-i':
|
||||
case '--input':
|
||||
input = argv.shift();
|
||||
break;
|
||||
case '-s':
|
||||
case '--string':
|
||||
string = argv.shift();
|
||||
break;
|
||||
case '-t':
|
||||
case '--tokens':
|
||||
tokens = true;
|
||||
break;
|
||||
case '-c':
|
||||
case '--config':
|
||||
config = argv.shift();
|
||||
break;
|
||||
case '-n':
|
||||
case '--no-clobber':
|
||||
noclobber = true;
|
||||
break;
|
||||
case '-h':
|
||||
case '--help':
|
||||
return await help();
|
||||
case '-v':
|
||||
case '--version':
|
||||
return await version();
|
||||
default:
|
||||
if (arg.indexOf('--') === 0) {
|
||||
opt = camelize(arg.replace(/^--(no-)?/, ''));
|
||||
if (!marked.defaults.hasOwnProperty(opt)) {
|
||||
continue;
|
||||
}
|
||||
if (arg.indexOf('--no-') === 0) {
|
||||
options[opt] = typeof marked.defaults[opt] !== 'boolean'
|
||||
? null
|
||||
: false;
|
||||
} else {
|
||||
options[opt] = typeof marked.defaults[opt] !== 'boolean'
|
||||
? argv.shift()
|
||||
: true;
|
||||
}
|
||||
} else {
|
||||
files.push(arg);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
async function getData() {
|
||||
if (!input) {
|
||||
if (files.length <= 2) {
|
||||
if (string) {
|
||||
return string;
|
||||
}
|
||||
return await getStdin();
|
||||
}
|
||||
input = files.pop();
|
||||
}
|
||||
return await readFile(input, 'utf8');
|
||||
}
|
||||
|
||||
function resolveFile(file) {
|
||||
return resolve(file.replace(/^~/, homedir));
|
||||
}
|
||||
|
||||
function fileExists(file) {
|
||||
return access(resolveFile(file)).then(() => true, () => false);
|
||||
}
|
||||
|
||||
async function runConfig(file) {
|
||||
const configFile = resolveFile(file);
|
||||
let markedConfig;
|
||||
try {
|
||||
// try require for json
|
||||
markedConfig = require(configFile);
|
||||
} catch (err) {
|
||||
if (err.code !== 'ERR_REQUIRE_ESM') {
|
||||
throw err;
|
||||
}
|
||||
// must import esm
|
||||
markedConfig = await import('file:///' + configFile);
|
||||
}
|
||||
|
||||
if (markedConfig.default) {
|
||||
markedConfig = markedConfig.default;
|
||||
}
|
||||
|
||||
if (typeof markedConfig === 'function') {
|
||||
markedConfig(marked);
|
||||
} else {
|
||||
marked.use(markedConfig);
|
||||
}
|
||||
}
|
||||
|
||||
const data = await getData();
|
||||
|
||||
if (config) {
|
||||
if (!await fileExists(config)) {
|
||||
throw Error(`Cannot load config file '${config}'`);
|
||||
}
|
||||
|
||||
await runConfig(config);
|
||||
} else {
|
||||
const defaultConfig = [
|
||||
'~/.marked.json',
|
||||
'~/.marked.js',
|
||||
'~/.marked/index.js'
|
||||
];
|
||||
|
||||
for (const configFile of defaultConfig) {
|
||||
if (await fileExists(configFile)) {
|
||||
await runConfig(configFile);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const html = tokens
|
||||
? JSON.stringify(marked.lexer(data, options), null, 2)
|
||||
: await marked.parse(data, options);
|
||||
|
||||
if (output) {
|
||||
if (noclobber && await fileExists(output)) {
|
||||
nodeProcess.stderr.write('marked: output file \'' + output + '\' already exists, disable the \'-n\' / \'--no-clobber\' flag to overwrite\n');
|
||||
nodeProcess.exit(1);
|
||||
}
|
||||
return await writeFile(output, html);
|
||||
}
|
||||
|
||||
nodeProcess.stdout.write(html + '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Helpers
|
||||
*/
|
||||
function getStdin() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const stdin = nodeProcess.stdin;
|
||||
let buff = '';
|
||||
|
||||
stdin.setEncoding('utf8');
|
||||
|
||||
stdin.on('data', function(data) {
|
||||
buff += data;
|
||||
});
|
||||
|
||||
stdin.on('error', function(err) {
|
||||
reject(err);
|
||||
});
|
||||
|
||||
stdin.on('end', function() {
|
||||
resolve(buff);
|
||||
});
|
||||
|
||||
stdin.resume();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} text
|
||||
*/
|
||||
function camelize(text) {
|
||||
return text.replace(/(\w)-(\w)/g, function(_, a, b) {
|
||||
return a + b.toUpperCase();
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await start(nodeProcess.argv.slice());
|
||||
nodeProcess.exit(0);
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
nodeProcess.stderr.write('marked: output to ' + err.path + ': No such directory');
|
||||
}
|
||||
nodeProcess.stderr.write(err);
|
||||
return nodeProcess.exit(1);
|
||||
}
|
||||
}
|
15
static/js/lib/node_modules/marked/bin/marked.js
generated
vendored
Executable file
15
static/js/lib/node_modules/marked/bin/marked.js
generated
vendored
Executable file
|
@ -0,0 +1,15 @@
|
|||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Marked CLI
|
||||
* Copyright (c) 2011-2013, Christopher Jeffrey (MIT License)
|
||||
*/
|
||||
|
||||
import { main } from './main.js';
|
||||
|
||||
/**
|
||||
* Expose / Entry Point
|
||||
*/
|
||||
|
||||
process.title = 'marked';
|
||||
main(process);
|
2442
static/js/lib/node_modules/marked/lib/marked.cjs
generated
vendored
Normal file
2442
static/js/lib/node_modules/marked/lib/marked.cjs
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
static/js/lib/node_modules/marked/lib/marked.cjs.map
generated
vendored
Normal file
1
static/js/lib/node_modules/marked/lib/marked.cjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
638
static/js/lib/node_modules/marked/lib/marked.d.cts
generated
vendored
Normal file
638
static/js/lib/node_modules/marked/lib/marked.d.cts
generated
vendored
Normal file
|
@ -0,0 +1,638 @@
|
|||
// Generated by dts-bundle-generator v9.0.0
|
||||
|
||||
export type Token = (Tokens.Space | Tokens.Code | Tokens.Heading | Tokens.Table | Tokens.Hr | Tokens.Blockquote | Tokens.List | Tokens.ListItem | Tokens.Paragraph | Tokens.HTML | Tokens.Text | Tokens.Def | Tokens.Escape | Tokens.Tag | Tokens.Image | Tokens.Link | Tokens.Strong | Tokens.Em | Tokens.Codespan | Tokens.Br | Tokens.Del | Tokens.Generic);
|
||||
export declare namespace Tokens {
|
||||
interface Space {
|
||||
type: "space";
|
||||
raw: string;
|
||||
}
|
||||
interface Code {
|
||||
type: "code";
|
||||
raw: string;
|
||||
codeBlockStyle?: "indented" | undefined;
|
||||
lang?: string | undefined;
|
||||
text: string;
|
||||
escaped?: boolean;
|
||||
}
|
||||
interface Heading {
|
||||
type: "heading";
|
||||
raw: string;
|
||||
depth: number;
|
||||
text: string;
|
||||
tokens: Token[];
|
||||
}
|
||||
interface Table {
|
||||
type: "table";
|
||||
raw: string;
|
||||
align: Array<"center" | "left" | "right" | null>;
|
||||
header: TableCell[];
|
||||
rows: TableCell[][];
|
||||