├── render
├── testdata
│ └── views
│ │ ├── home.jet
│ │ └── home.page.tmpl
├── setup_test.go
├── render_test.go
└── render.go
├── .gitignore
├── cmd
└── cli
│ ├── templates
│ ├── migrations
│ │ ├── migration.postgres.down.sql
│ │ ├── mysql_session.sql
│ │ ├── postgres_session.sql
│ │ ├── migration.postgres.up.sql
│ │ ├── auth_tables.postgres.sql
│ │ └── auth_tables.mysql.sql
│ ├── mailer
│ │ ├── mail.plain.tmpl
│ │ ├── password-reset.plain.tmpl
│ │ ├── mail.html.tmpl
│ │ └── password-reset.html.tmpl
│ ├── handlers
│ │ ├── handler.go.txt
│ │ └── auth-handlers.go.txt
│ ├── middleware
│ │ ├── auth.go.txt
│ │ ├── auth-token.go.txt
│ │ └── remember.go.txt
│ ├── data
│ │ ├── remember_token.go.txt
│ │ ├── model.go.txt
│ │ ├── token.go.txt
│ │ └── user.go.txt
│ ├── env.txt
│ ├── views
│ │ ├── forgot.jet
│ │ ├── login.jet
│ │ └── reset-password.jet
│ └── go.mod.txt
│ ├── migrate.go
│ ├── copy-files.go
│ ├── session.go
│ ├── main.go
│ ├── auth.go
│ ├── helpers.go
│ ├── new.go
│ └── make.go
├── public
└── ghostly.jpg
├── mailer
├── testdata
│ └── mail
│ │ ├── test.plain.tmpl
│ │ └── test.html.tmpl
├── setup_test.go
├── mail_test.go
└── mail.go
├── session
├── setup_test.go
├── session_test.go
└── session.go
├── testfolder
└── test.go
├── Makefile
├── filesystems
├── filesystems.go
├── webdevfilesystem
│ └── webdev.go
├── sftpfilesystem
│ └── sftp.go
├── s3filesystem
│ └── s3.go
└── miniofilesystem
│ └── minio.go
├── utils.go
├── driver.go
├── middleware.go
├── routes.go
├── types.go
├── urlsigner
└── signer.go
├── cache
├── setup_test.go
├── badger-cache_test.go
├── cache_test.go
├── badger_cache.go
└── cache.go
├── migrations.go
├── validator.go
├── helpers.go
├── response-utils.go
├── README.md
├── go.mod
├── ghostly.go
└── LICENSE.md
/render/testdata/views/home.jet:
--------------------------------------------------------------------------------
1 | Hello, jet.
--------------------------------------------------------------------------------
/render/testdata/views/home.page.tmpl:
--------------------------------------------------------------------------------
1 | Hello world.
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | coverage.out
3 | dist/*
4 | .DS_Store
5 | .vscode
--------------------------------------------------------------------------------
/cmd/cli/templates/migrations/migration.postgres.down.sql:
--------------------------------------------------------------------------------
1 | -- drop table some_table;
--------------------------------------------------------------------------------
/public/ghostly.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Dominic-Wassef/ghostly/HEAD/public/ghostly.jpg
--------------------------------------------------------------------------------
/cmd/cli/templates/mailer/mail.plain.tmpl:
--------------------------------------------------------------------------------
1 | {{define "body"}}
2 | Enter your message content here...
3 | {{end}}
--------------------------------------------------------------------------------
/mailer/testdata/mail/test.plain.tmpl:
--------------------------------------------------------------------------------
1 | {{define "body"}}
2 | Enter your message content here...
3 | {{end}}
--------------------------------------------------------------------------------
/session/setup_test.go:
--------------------------------------------------------------------------------
1 | package session
2 |
3 | import (
4 | "os"
5 | "testing"
6 | )
7 |
8 | func TestMain(m *testing.M) {
9 |
10 | os.Exit(m.Run())
11 | }
--------------------------------------------------------------------------------
/testfolder/test.go:
--------------------------------------------------------------------------------
1 | package testfolder
2 |
3 | import "net/http"
4 |
5 | func TestHandler(w http.ResponseWriter, r *http.Request) {
6 | w.Write([]byte("it works"))
7 | }
8 |
--------------------------------------------------------------------------------
/cmd/cli/templates/migrations/mysql_session.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE sessions (
2 | token CHAR(43) PRIMARY KEY,
3 | data BLOB NOT NULL,
4 | expiry TIMESTAMP(6) NOT NULL
5 | );
6 |
7 | CREATE INDEX sessions_expiry_idx ON sessions (expiry);
--------------------------------------------------------------------------------
/cmd/cli/templates/migrations/postgres_session.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE sessions (
2 | token TEXT PRIMARY KEY,
3 | data BYTEA NOT NULL,
4 | expiry TIMESTAMPTZ NOT NULL
5 | );
6 |
7 | CREATE INDEX sessions_expiry_idx ON sessions (expiry);
--------------------------------------------------------------------------------
/cmd/cli/templates/handlers/handler.go.txt:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import (
4 | "net/http"
5 | )
6 |
7 | // $HANDLERNAME$ comment goes here
8 | func (h *Handlers) $HANDLERNAME$(w http.ResponseWriter, r *http.Request) {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/cmd/cli/templates/mailer/password-reset.plain.tmpl:
--------------------------------------------------------------------------------
1 | {{define "body"}}
2 | Hello:
3 |
4 | You recently requested a link to reset your password.
5 |
6 | Visit the link below to get started. Note that the link expires in 60 minutes.
7 |
8 | {{.Link}}
9 |
10 | {{end}}
--------------------------------------------------------------------------------
/cmd/cli/templates/middleware/auth.go.txt:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import "net/http"
4 |
5 | func (m *Middleware) Auth(next http.Handler) http.Handler {
6 | return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request){
7 | if !m.App.Session.Exists(r.Context(), "userID") {
8 | http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
9 | }
10 | })
11 | }
--------------------------------------------------------------------------------
/cmd/cli/templates/mailer/mail.html.tmpl:
--------------------------------------------------------------------------------
1 | {{define "body"}}
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Enter your message content here...
12 |
13 |
14 |
15 | {{end}}
--------------------------------------------------------------------------------
/mailer/testdata/mail/test.html.tmpl:
--------------------------------------------------------------------------------
1 | {{define "body"}}
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Enter your message content here...
12 |
13 |
14 |
15 | {{end}}
--------------------------------------------------------------------------------
/render/setup_test.go:
--------------------------------------------------------------------------------
1 | package render
2 |
3 | import (
4 | "os"
5 | "testing"
6 |
7 | "github.com/CloudyKit/jet/v6"
8 | )
9 |
10 | var views = jet.NewSet(
11 | jet.NewOSFileSystemLoader("./testdata/views"),
12 | jet.InDevelopmentMode(),
13 | )
14 |
15 | var testRenderer = Render{
16 | Renderer: "",
17 | RootPath: "",
18 | JetViews: views,
19 | }
20 |
21 | func TestMain(m *testing.M) {
22 | os.Exit(m.Run())
23 | }
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | ## test: runs all tests
2 | test:
3 | @go test -v ./...
4 |
5 | ## cover: opens coverage in browser
6 | cover:
7 | @go test -coverprofile=coverage.out ./... && go tool cover -html=coverage.out
8 |
9 | ## coverage: displays test coverage
10 | coverage:
11 | @go test -cover ./...
12 |
13 | ## build_cli: builds the command line tool ghostly and copies it to myapp
14 | build_cli:
15 | @go build -o ../myapp/ghostly ./cmd/cli
16 |
17 | ## build: builds the command line tool to dist directory
18 | build:
19 | @go build -o ./dist/ghostly ./cmd/cli
--------------------------------------------------------------------------------
/filesystems/filesystems.go:
--------------------------------------------------------------------------------
1 | package filesystems
2 |
3 | import "time"
4 |
5 | // FS is the interface for file systems
6 | type FS interface {
7 | Put(fileName, folder string) error
8 | Get(destination string, items ...string) error
9 | List(prefix string) ([]Listing, error)
10 | Delete(itemsToDelete []string) bool
11 | }
12 |
13 | // Listing describes one file on a remote file system
14 | type Listing struct {
15 | Etag string
16 | LastModified time.Time
17 | Key string
18 | Size float64
19 | IsDir bool
20 | }
21 |
--------------------------------------------------------------------------------
/utils.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "fmt"
5 | "regexp"
6 | "runtime"
7 | "time"
8 | )
9 |
10 | // LoadTime calculates function execution time. To use, add
11 | // defer g.LoadTime(time.Now()) to the function body
12 | func (g *Ghostly) LoadTime(start time.Time) {
13 | elapsed := time.Since(start)
14 | pc, _, _, _ := runtime.Caller(1)
15 | funcObj := runtime.FuncForPC(pc)
16 | runtimeFunc := regexp.MustCompile(`^.*\.(.*)$`)
17 | name := runtimeFunc.ReplaceAllString(funcObj.Name(), "$1")
18 |
19 | g.InfoLog.Println(fmt.Sprintf("Load Time: %s took %s", name, elapsed))
20 | }
21 |
--------------------------------------------------------------------------------
/cmd/cli/templates/mailer/password-reset.html.tmpl:
--------------------------------------------------------------------------------
1 | {{define "body"}}
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Hello:
12 | You recently requested a link to reset your password.
13 | Visit the link below to get started. Note that the link expires in 60 minutes.
14 | Click here to reset your password
15 |
16 |
17 |
18 | {{end}}
--------------------------------------------------------------------------------
/cmd/cli/templates/middleware/auth-token.go.txt:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import "net/http"
4 |
5 | func (m *Middleware) AuthToken(next http.Handler) http.Handler {
6 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request){
7 | _, err := m.Models.Tokens.AuthenticateToken(r)
8 | if err != nil {
9 | var payload struct {
10 | Error bool `json:"error"`
11 | Message string `json:"message"`
12 | }
13 |
14 | payload.Error = true
15 | payload.Message = "invalid authentication credentials"
16 |
17 | _ = m.App.WriteJSON(w, http.StatusUnauthorized, payload)
18 | }
19 | })
20 | }
--------------------------------------------------------------------------------
/filesystems/webdevfilesystem/webdev.go:
--------------------------------------------------------------------------------
1 | package webdevfilesystem
2 |
3 | import "github.com/dominic-wassef/ghostly/filesystems"
4 |
5 | type WebDAV struct {
6 | Host string
7 | User string
8 | Pass string
9 | }
10 |
11 | func (s *WebDAV) Put(fileName, folder string) error {
12 | return nil
13 | }
14 |
15 | func (s *WebDAV) List(prefix string) ([]filesystems.Listing, error) {
16 | var listing []filesystems.Listing
17 | return listing, nil
18 | }
19 |
20 | func (s *WebDAV) Delete(itemsToDelete []string) bool {
21 | return true
22 | }
23 |
24 | func (s *WebDAV) Get(destination string, items ...string) error {
25 | return nil
26 | }
27 |
--------------------------------------------------------------------------------
/filesystems/sftpfilesystem/sftp.go:
--------------------------------------------------------------------------------
1 | package sftpfilesystem
2 |
3 | import "github.com/dominic-wassef/ghostly/filesystems"
4 |
5 | type SFTP struct {
6 | Host string
7 | User string
8 | Pass string
9 | Port string
10 | }
11 |
12 | func (s *SFTP) Put(fileName, folder string) error {
13 | return nil
14 | }
15 |
16 | func (s *SFTP) List(prefix string) ([]filesystems.Listing, error) {
17 | var listing []filesystems.Listing
18 | return listing, nil
19 | }
20 |
21 | func (s *SFTP) Delete(itemsToDelete []string) bool {
22 | return true
23 | }
24 |
25 | func (s *SFTP) Get(destination string, items ...string) error {
26 | return nil
27 | }
28 |
--------------------------------------------------------------------------------
/filesystems/s3filesystem/s3.go:
--------------------------------------------------------------------------------
1 | package s3filesystem
2 |
3 | import "github.com/dominic-wassef/ghostly/filesystems"
4 |
5 | type S3 struct {
6 | Key string
7 | Secret string
8 | Region string
9 | Endpoint string
10 | Bucket string
11 | }
12 |
13 | func (s *S3) Put(fileName, folder string) error {
14 | return nil
15 | }
16 |
17 | func (s *S3) List(prefix string) ([]filesystems.Listing, error) {
18 | var listing []filesystems.Listing
19 | return listing, nil
20 | }
21 |
22 | func (s *S3) Delete(itemsToDelete []string) bool {
23 | return true
24 | }
25 |
26 | func (s *S3) Get(destination string, items ...string) error {
27 | return nil
28 | }
--------------------------------------------------------------------------------
/driver.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "database/sql"
5 |
6 | _ "github.com/jackc/pgconn"
7 | _ "github.com/jackc/pgx/v4"
8 | _ "github.com/jackc/pgx/v4/stdlib"
9 | )
10 |
11 | // OpenDB opens a connection to a sql database. dbType must be one of postgres (or pgx).
12 | // TODO: add support for mysql/mariadb
13 | func (g *Ghostly) OpenDB(dbType, dsn string) (*sql.DB, error) {
14 | if dbType == "postgres" || dbType == "postgresql" {
15 | dbType = "pgx"
16 | }
17 |
18 | db, err := sql.Open(dbType, dsn)
19 | if err != nil {
20 | return nil, err
21 | }
22 |
23 | err = db.Ping()
24 | if err != nil {
25 | return nil, err
26 | }
27 |
28 | return db, nil
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/cmd/cli/templates/migrations/migration.postgres.up.sql:
--------------------------------------------------------------------------------
1 | -- CREATE TABLE some_table (
2 | -- id serial PRIMARY KEY,
3 | -- some_field VARCHAR ( 255 ) NOT NULL,
4 | -- created_at TIMESTAMP,
5 | -- updated_at TIMESTAMP
6 | -- );
7 |
8 | -- add auto update of updated_at. If you already have this trigger
9 | -- you can delete the next 7 lines
10 | -- CREATE OR REPLACE FUNCTION trigger_set_timestamp()
11 | -- RETURNS TRIGGER AS $$
12 | -- BEGIN
13 | -- NEW.updated_at = NOW();
14 | -- RETURN NEW;
15 | -- END;
16 | -- $$ LANGUAGE plpgsql;
17 |
18 | -- CREATE TRIGGER set_timestamp
19 | -- BEFORE UPDATE ON some_table
20 | -- FOR EACH ROW
21 | -- EXECUTE PROCEDURE trigger_set_timestamp();
--------------------------------------------------------------------------------
/middleware.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "net/http"
5 | "strconv"
6 |
7 | "github.com/justinas/nosurf"
8 | )
9 |
10 | func (g *Ghostly) SessionLoad(next http.Handler) http.Handler {
11 | return g.Session.LoadAndSave(next)
12 | }
13 |
14 | func (g *Ghostly) NoSurf(next http.Handler) http.Handler {
15 | csrfHandler := nosurf.New(next)
16 | secure, _ := strconv.ParseBool(g.config.cookie.secure)
17 |
18 | csrfHandler.ExemptGlob("/api/*")
19 |
20 | csrfHandler.SetBaseCookie(http.Cookie{
21 | HttpOnly: true,
22 | Path: "/",
23 | Secure: secure,
24 | SameSite: http.SameSiteStrictMode,
25 | Domain: g.config.cookie.domain,
26 | })
27 |
28 | return csrfHandler
29 | }
30 |
--------------------------------------------------------------------------------
/cmd/cli/migrate.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | func doMigrate(arg2, arg3 string) error {
4 | dsn := getDSN()
5 |
6 | // run the migration command
7 | switch arg2 {
8 | case "up":
9 | err := gho.MigrateUp(dsn)
10 | if err != nil {
11 | return err
12 | }
13 |
14 | case "down":
15 | if arg3 == "all" {
16 | err := gho.MigrateDownAll(dsn)
17 | if err != nil {
18 | return err
19 | }
20 | } else {
21 | err := gho.Steps(-1, dsn)
22 | if err != nil {
23 | return err
24 | }
25 | }
26 | case "reset":
27 | err := gho.MigrateDownAll(dsn)
28 | if err != nil {
29 | return err
30 | }
31 | err = gho.MigrateUp(dsn)
32 | if err != nil {
33 | return err
34 | }
35 | default:
36 | showHelp()
37 | }
38 |
39 | return nil
40 | }
41 |
--------------------------------------------------------------------------------
/routes.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "net/http"
5 |
6 | "github.com/go-chi/chi/v5"
7 | "github.com/go-chi/chi/v5/middleware"
8 | )
9 |
10 | func (g *Ghostly) routes() http.Handler {
11 | mux := chi.NewRouter()
12 | mux.Use(middleware.RequestID)
13 | mux.Use(middleware.RealIP)
14 | if g.Debug {
15 | mux.Use(middleware.Logger)
16 | }
17 | mux.Use(middleware.Recoverer)
18 | mux.Use(g.SessionLoad)
19 | mux.Use(g.NoSurf)
20 |
21 | return mux
22 | }
23 |
24 | // Routes are ghostly specific routes, which are mounted in the routes file
25 | // in Ghostly applications
26 | func Routes() http.Handler {
27 | r := chi.NewRouter()
28 | r.Get("/test-c", func(w http.ResponseWriter, r *http.Request) {
29 | w.Write([]byte("it works!"))
30 | })
31 | return r
32 | }
33 |
--------------------------------------------------------------------------------
/types.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import "database/sql"
4 |
5 | // initPaths is used when initializing the application. It holds the root
6 | // path for the application, and a slice of strings with the names of
7 | // folders that the application expects to find.
8 | type initPaths struct {
9 | rootPath string
10 | folderNames []string
11 | }
12 |
13 | // cookieConfig holds cookie config values
14 | type cookieConfig struct {
15 | name string
16 | lifetime string
17 | persist string
18 | secure string
19 | domain string
20 | }
21 |
22 | type databaseConfig struct {
23 | dsn string
24 | database string
25 | }
26 |
27 | type Database struct {
28 | DataType string
29 | Pool *sql.DB
30 | }
31 |
32 | type redisConfig struct {
33 | host string
34 | password string
35 | prefix string
36 | }
37 |
--------------------------------------------------------------------------------
/cmd/cli/copy-files.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "embed"
5 | "errors"
6 | "io/ioutil"
7 | "os"
8 | )
9 |
10 | //go:embed templates
11 | var templateFS embed.FS
12 |
13 | func copyFilefromTemplate(templatePath, targetFile string) error {
14 | if fileExists(targetFile) {
15 | return errors.New(targetFile + " already exists!")
16 | }
17 |
18 | data, err := templateFS.ReadFile(templatePath)
19 | if err != nil {
20 | exitGracefully(err)
21 | }
22 |
23 | err = copyDataToFile(data, targetFile)
24 | if err != nil {
25 | exitGracefully(err)
26 | }
27 |
28 | return nil
29 | }
30 |
31 | func copyDataToFile(data []byte, to string) error {
32 | err := ioutil.WriteFile(to, data, 0644)
33 | if err != nil {
34 | return err
35 | }
36 | return nil
37 | }
38 |
39 | func fileExists(fileToCheck string) bool {
40 | if _, err := os.Stat(fileToCheck); os.IsNotExist(err) {
41 | return false
42 | }
43 | return true
44 | }
45 |
--------------------------------------------------------------------------------
/cmd/cli/session.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 | )
7 |
8 | func doSessionTable() error {
9 | dbType := gho.DB.DataType
10 |
11 | if dbType == "mariadb" {
12 | dbType = "mysql"
13 | }
14 |
15 | if dbType == "postgresql" {
16 | dbType = "postgres"
17 | }
18 |
19 | fileName := fmt.Sprintf("%d_create_sessions_table", time.Now().UnixMicro())
20 |
21 | upFile := gho.RootPath + "/migrations/" + fileName + "." + dbType + ".up.sql"
22 | downFile := gho.RootPath + "/migrations/" + fileName + "." + dbType + ".down.sql"
23 |
24 | err := copyFilefromTemplate("templates/migrations/"+dbType+"_session.sql", upFile)
25 | if err != nil {
26 | exitGracefully(err)
27 | }
28 |
29 | err = copyDataToFile([]byte("drop table sessions"), downFile)
30 | if err != nil {
31 | exitGracefully(err)
32 | }
33 |
34 | err = doMigrate("up", "")
35 | if err != nil {
36 | exitGracefully(err)
37 | }
38 |
39 | return nil
40 | }
41 |
--------------------------------------------------------------------------------
/urlsigner/signer.go:
--------------------------------------------------------------------------------
1 | package urlsigner
2 |
3 | import (
4 | "fmt"
5 | "strings"
6 | "time"
7 |
8 | "github.com/bwmarrin/go-alone"
9 | )
10 |
11 | type Signer struct {
12 | Secret []byte
13 | }
14 |
15 | func (s *Signer) GenerateTokenFromString(data string) string {
16 | var urlToSign string
17 |
18 | crypt := goalone.New(s.Secret, goalone.Timestamp)
19 | if strings.Contains(data, "?") {
20 | urlToSign = fmt.Sprintf("%s&hash=", data)
21 | } else {
22 | urlToSign = fmt.Sprintf("%s?hash=", data)
23 | }
24 |
25 | tokenBytes := crypt.Sign([]byte(urlToSign))
26 | token := string(tokenBytes)
27 |
28 | return token
29 | }
30 |
31 | func (s *Signer) VerifyToken(token string) bool {
32 | crypt := goalone.New(s.Secret, goalone.Timestamp)
33 | _, err := crypt.Unsign([]byte(token))
34 | if err != nil {
35 | return false
36 | }
37 |
38 | return true
39 | }
40 |
41 | func (s *Signer) Expired(token string, minutesUntilExpire int) bool {
42 | crypt := goalone.New(s.Secret, goalone.Timestamp)
43 | ts := crypt.Parse([]byte(token))
44 |
45 | return time.Since(ts.Timestamp) > time.Duration(minutesUntilExpire)*time.Minute
46 | }
--------------------------------------------------------------------------------
/cmd/cli/templates/data/remember_token.go.txt:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "time"
5 |
6 | up "github.com/upper/db/v4"
7 | )
8 |
9 | type RememberToken struct {
10 | ID int `db:"id,omitempty"`
11 | UserID int `db:"user_id"`
12 | RememberToken string `db:"remember_token"`
13 | CreatedAt time.Time `db:"created_at"`
14 | UpdatedAt time.Time `db:"updated_at"`
15 | }
16 |
17 |
18 | func (t *RememberToken) Table() string {
19 | return "remember_tokens"
20 | }
21 |
22 | func (t *RememberToken) InsertToken(userID int, token string) error {
23 | collection := upper.Collection(t.Table())
24 | rememberToken := RememberToken{
25 | UserID: userID,
26 | RememberToken: token,
27 | CreatedAt: time.Now(),
28 | UpdatedAt: time.Now(),
29 | }
30 | _, err := collection.Insert(rememberToken)
31 | if err != nil {
32 | return err
33 | }
34 | return nil
35 | }
36 |
37 | func (t *RememberToken) Delete(rememberToken string) error {
38 | collection := upper.Collection(t.Table())
39 | res := collection.Find(up.Cond{"remember_token": rememberToken})
40 | err := res.Delete()
41 | if err != nil {
42 | return err
43 | }
44 | return nil
45 | }
46 |
--------------------------------------------------------------------------------
/session/session_test.go:
--------------------------------------------------------------------------------
1 | package session
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | "testing"
7 |
8 | "github.com/alexedwards/scs/v2"
9 | )
10 |
11 | func TestSession_InitSession(t *testing.T) {
12 |
13 | c := &Session{
14 | CookieLifetime: "100",
15 | CookiePersist: "true",
16 | CookieName: "ghostly",
17 | CookieDomain: "localhost",
18 | SessionType: "cookie",
19 | }
20 |
21 | var sm *scs.SessionManager
22 |
23 | ses := c.InitSession()
24 |
25 | var sessKind reflect.Kind
26 | var sessType reflect.Type
27 |
28 | rv := reflect.ValueOf(ses)
29 |
30 | for rv.Kind() == reflect.Ptr || rv.Kind() == reflect.Interface {
31 | fmt.Println("For loop:", rv.Kind(), rv.Type(), rv)
32 | sessKind = rv.Kind()
33 | sessType = rv.Type()
34 |
35 | rv = rv.Elem()
36 | }
37 |
38 | if !rv.IsValid() {
39 | t.Error("invalid type or kind; kind:", rv.Kind(), "type:", rv.Type())
40 | }
41 |
42 | if sessKind != reflect.ValueOf(sm).Kind() {
43 | t.Error("wrong kind returned testing cookie session. Expected", reflect.ValueOf(sm).Kind(), "and got", sessKind)
44 | }
45 |
46 | if sessType != reflect.ValueOf(sm).Type() {
47 | t.Error("wrong type returned testing cookie session. Expected", reflect.ValueOf(sm).Type(), "and got", sessType)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/cache/setup_test.go:
--------------------------------------------------------------------------------
1 | package cache
2 |
3 | import (
4 | "log"
5 | "os"
6 | "testing"
7 | "time"
8 |
9 | "github.com/alicebob/miniredis/v2"
10 | "github.com/dgraph-io/badger/v3"
11 | "github.com/gomodule/redigo/redis"
12 | )
13 |
14 | var testRedisCache RedisCache
15 | var testBadgerCache BadgerCache
16 |
17 | func TestMain(m *testing.M) {
18 | s, err := miniredis.Run()
19 | if err != nil {
20 | panic(err)
21 | }
22 | defer s.Close()
23 |
24 | pool := redis.Pool{
25 | MaxIdle: 50,
26 | MaxActive: 1000,
27 | IdleTimeout: 240 * time.Second,
28 | Dial: func() (redis.Conn, error) {
29 | return redis.Dial("tcp", s.Addr())
30 | },
31 | }
32 |
33 | testRedisCache.Conn = &pool
34 | testRedisCache.Prefix = "test-ghostly"
35 |
36 | defer testRedisCache.Conn.Close()
37 |
38 | _ = os.RemoveAll("./testdata/tmp/badger")
39 |
40 | // create a badger database
41 | if _, err := os.Stat("./testdata/tmp"); os.IsNotExist(err) {
42 | err := os.Mkdir("./testdata/tmp", 0755)
43 | if err != nil {
44 | log.Fatal(err)
45 | }
46 | }
47 | err = os.Mkdir("./testdata/tmp/badger", 0755)
48 | if err != nil {
49 | log.Fatal(err)
50 | }
51 |
52 | db, _ := badger.Open(badger.DefaultOptions("./testdata/tmp/badger"))
53 | testBadgerCache.Conn = db
54 |
55 | os.Exit(m.Run())
56 | }
57 |
--------------------------------------------------------------------------------
/cmd/cli/templates/env.txt:
--------------------------------------------------------------------------------
1 | # Give your application a unique name (no spaces)
2 | APP_NAME=${APP_NAME}
3 | APP_URL=http://localhost:4000
4 |
5 | # false for production, true for development
6 | DEBUG=true
7 |
8 | # the port should we listen on
9 | PORT=4000
10 |
11 | # the server name, e.g, www.mysite.com
12 | SERVER_NAME=localhost
13 |
14 | # should we use https?
15 | SECURE=false
16 |
17 | # database config - postgres or mysql
18 | DATABASE_TYPE=
19 | DATABASE_HOST=
20 | DATABASE_PORT=
21 | DATABASE_USER=
22 | DATABASE_PASS=
23 | DATABASE_NAME=
24 | DATABASE_SSL_MODE=
25 |
26 | # redis config
27 | REDIS_HOST=
28 | REDIS_PASSWORD=
29 | REDIS_PREFIX=${APP_NAME}
30 |
31 | # cache (currently only redis or badger)
32 | CACHE=
33 |
34 | # cookie seetings
35 | COOKIE_NAME=${APP_NAME}
36 | COOKIE_LIFETIME=1440
37 | COOKIE_PERSIST=true
38 | COOKIE_SECURE=false
39 | COOKIE_DOMAIN=localhost
40 |
41 | # session store: cookie, redis, mysql, or postgres
42 | SESSION_TYPE=cookie
43 |
44 | # mail settings
45 | SMTP_HOST=
46 | SMTP_USERNAME=
47 | SMTP_PASSWORD=
48 | SMTP_PORT=1025
49 | SMTP_ENCRYPTION=
50 | MAIL_DOMAIN=
51 | FROM_NAME=
52 | FROM_ADDRESS=
53 |
54 | # mail settings for api services
55 | MAILER_API=
56 | MAILER_KEY=
57 | MAILER_URL=
58 |
59 | # template engine: go or jet
60 | RENDERER=jet
61 |
62 | # the encryption key; must be exactly 32 characters long
63 | KEY=${KEY}
--------------------------------------------------------------------------------
/mailer/setup_test.go:
--------------------------------------------------------------------------------
1 | package mailer
2 |
3 | import (
4 | "log"
5 | "os"
6 | "testing"
7 | "time"
8 |
9 | "github.com/ory/dockertest/v3"
10 | "github.com/ory/dockertest/v3/docker"
11 | )
12 |
13 |
14 | var pool *dockertest.Pool
15 | var resource *dockertest.Resource
16 |
17 | var mailer = Mail{
18 | Domain: "localhost",
19 | Templates: "./testdata/mail",
20 | Host: "localhost",
21 | Port: 1026,
22 | Encryption: "none",
23 | FromAddress: "me@here.com",
24 | FromName: "Joe",
25 | Jobs: make(chan Message, 1),
26 | Results: make(chan Result, 1),
27 | }
28 |
29 | func TestMain(m *testing.M) {
30 | p, err := dockertest.NewPool("")
31 | if err != nil {
32 | log.Fatal("could not connect to docker", err)
33 | }
34 | pool = p
35 |
36 | opts := dockertest.RunOptions{
37 | Repository: "mailhog/mailhog",
38 | Tag: "latest",
39 | Env: []string{},
40 | ExposedPorts: []string{"1025", "8025"},
41 | PortBindings: map[docker.Port][]docker.PortBinding{
42 | "1025": {
43 | {HostIP: "0.0.0.0", HostPort: "1026"},
44 | },
45 | "8025": {
46 | {HostIP: "0.0.0.0", HostPort: "8026"},
47 | },
48 | },
49 | }
50 |
51 | resource, err := pool.RunWithOptions(&opts)
52 | if err != nil {
53 | log.Println(err)
54 | _ = pool.Purge(resource)
55 | log.Fatal("Could not start resource")
56 | }
57 |
58 | time.Sleep(2 * time.Second)
59 |
60 | go mailer.ListenForMail()
61 |
62 | code := m.Run()
63 |
64 | if err := pool.Purge(resource); err != nil {
65 | log.Fatalf("could not purge resource: %s", err)
66 | }
67 |
68 | os.Exit(code)
69 | }
--------------------------------------------------------------------------------
/migrations.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "log"
5 |
6 | "github.com/golang-migrate/migrate/v4"
7 |
8 | _ "github.com/go-sql-driver/mysql"
9 | _ "github.com/golang-migrate/migrate/v4/database/mysql"
10 | _ "github.com/golang-migrate/migrate/v4/database/postgres"
11 | _ "github.com/golang-migrate/migrate/v4/source/file"
12 | )
13 |
14 | func (g *Ghostly) MigrateUp(dsn string) error {
15 | m, err := migrate.New("file://"+g.RootPath+"/migrations", dsn)
16 | if err != nil {
17 | return err
18 | }
19 | defer m.Close()
20 |
21 | if err := m.Up(); err != nil {
22 | log.Println("Error running migration:", err)
23 | return err
24 | }
25 | return nil
26 | }
27 |
28 | func (g *Ghostly) MigrateDownAll(dsn string) error {
29 | m, err := migrate.New("file://"+g.RootPath+"/migrations", dsn)
30 | if err != nil {
31 | return err
32 | }
33 | defer m.Close()
34 |
35 | if err := m.Down(); err != nil {
36 | return err
37 | }
38 |
39 | return nil
40 | }
41 |
42 | func (g *Ghostly) Steps(n int, dsn string) error {
43 | m, err := migrate.New("file://"+g.RootPath+"/migrations", dsn)
44 | if err != nil {
45 | return err
46 | }
47 | defer m.Close()
48 |
49 | if err := m.Steps(n); err != nil {
50 | return err
51 | }
52 |
53 | return nil
54 | }
55 |
56 | func (g *Ghostly) MigrateForce(dsn string) error {
57 | m, err := migrate.New("file://"+g.RootPath+"/migrations", dsn)
58 | if err != nil {
59 | return err
60 | }
61 | defer m.Close()
62 |
63 | if err := m.Force(-1); err != nil {
64 | return err
65 | }
66 |
67 | return nil
68 | }
69 |
--------------------------------------------------------------------------------
/session/session.go:
--------------------------------------------------------------------------------
1 | package session
2 |
3 | import (
4 | "database/sql"
5 | "net/http"
6 | "strconv"
7 | "strings"
8 | "time"
9 |
10 | "github.com/alexedwards/scs/mysqlstore"
11 | "github.com/alexedwards/scs/postgresstore"
12 | "github.com/alexedwards/scs/redisstore"
13 | "github.com/alexedwards/scs/v2"
14 | "github.com/gomodule/redigo/redis"
15 | )
16 |
17 | type Session struct {
18 | CookieLifetime string
19 | CookiePersist string
20 | CookieName string
21 | CookieDomain string
22 | SessionType string
23 | CookieSecure string
24 | DBPool *sql.DB
25 | RedisPool *redis.Pool
26 | }
27 |
28 | func (c *Session) InitSession() *scs.SessionManager {
29 | var persist, secure bool
30 |
31 | // how long should sessions last?
32 | minutes, err := strconv.Atoi(c.CookieLifetime)
33 | if err != nil {
34 | minutes = 60
35 | }
36 |
37 | // should cookies persist?
38 | if strings.ToLower(c.CookiePersist) == "true" {
39 | persist = true
40 | }
41 |
42 | // must cookies be secure?
43 | if strings.ToLower(c.CookieSecure) == "true" {
44 | secure = true
45 | }
46 |
47 | // create session
48 | session := scs.New()
49 | session.Lifetime = time.Duration(minutes) * time.Minute
50 | session.Cookie.Persist = persist
51 | session.Cookie.Name = c.CookieName
52 | session.Cookie.Secure = secure
53 | session.Cookie.Domain = c.CookieDomain
54 | session.Cookie.SameSite = http.SameSiteLaxMode
55 |
56 | // which session store?
57 | switch strings.ToLower(c.SessionType) {
58 | case "redis":
59 | session.Store = redisstore.New(c.RedisPool)
60 | case "mysql", "mariadb":
61 | session.Store = mysqlstore.New(c.DBPool)
62 | case "postgres", "postgresql":
63 | session.Store = postgresstore.New(c.DBPool)
64 | default:
65 | // cookie
66 | }
67 |
68 | return session
69 | }
70 |
--------------------------------------------------------------------------------
/cmd/cli/templates/views/forgot.jet:
--------------------------------------------------------------------------------
1 | {{extends "./layouts/base.jet"}}
2 |
3 | {{block browserTitle()}}
4 | Forgot Password
5 | {{end}}
6 |
7 | {{block css()}} {{end}}
8 |
9 | {{block pageContent()}}
10 |
Forgot Password
11 |
12 |
13 |
14 | {{if .Error != ""}}
15 |
16 | {{.Error}}
17 |
18 | {{end}}
19 |
20 | {{if .Flash != ""}}
21 |
22 | {{.Flash}}
23 |
24 | {{end}}
25 |
26 |
27 |
28 | Enter your email address in the form below, and we'll
29 | email you a link to reset your password.
30 |
31 |
32 |
52 |
53 |
56 |
57 |
58 |
59 | {{end}}
60 |
61 | {{ block js()}}
62 |
75 | {{end}}
76 |
--------------------------------------------------------------------------------
/cmd/cli/templates/migrations/auth_tables.postgres.sql:
--------------------------------------------------------------------------------
1 | CREATE OR REPLACE FUNCTION trigger_set_timestamp()
2 | RETURNS TRIGGER AS $$
3 | BEGIN
4 | NEW.updated_at = NOW();
5 | RETURN NEW;
6 | END;
7 | $$ LANGUAGE plpgsql;
8 |
9 | drop table if exists users cascade;
10 |
11 | CREATE TABLE users (
12 | id SERIAL PRIMARY KEY,
13 | first_name character varying(255) NOT NULL,
14 | last_name character varying(255) NOT NULL,
15 | user_active integer NOT NULL DEFAULT 0,
16 | email character varying(255) NOT NULL UNIQUE,
17 | password character varying(60) NOT NULL,
18 | created_at timestamp without time zone NOT NULL DEFAULT now(),
19 | updated_at timestamp without time zone NOT NULL DEFAULT now()
20 | );
21 |
22 | CREATE TRIGGER set_timestamp
23 | BEFORE UPDATE ON users
24 | FOR EACH ROW
25 | EXECUTE PROCEDURE trigger_set_timestamp();
26 |
27 | drop table if exists remember_tokens;
28 |
29 | CREATE TABLE remember_tokens (
30 | id SERIAL PRIMARY KEY,
31 | user_id integer NOT NULL REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE,
32 | remember_token character varying(100) NOT NULL,
33 | created_at timestamp without time zone NOT NULL DEFAULT now(),
34 | updated_at timestamp without time zone NOT NULL DEFAULT now()
35 | );
36 |
37 | CREATE TRIGGER set_timestamp
38 | BEFORE UPDATE ON remember_tokens
39 | FOR EACH ROW
40 | EXECUTE PROCEDURE trigger_set_timestamp();
41 |
42 | drop table if exists tokens;
43 |
44 | CREATE TABLE tokens (
45 | id SERIAL PRIMARY KEY,
46 | user_id integer NOT NULL REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE,
47 | first_name character varying(255) NOT NULL,
48 | email character varying(255) NOT NULL,
49 | token character varying(255) NOT NULL,
50 | token_hash bytea NOT NULL,
51 | created_at timestamp without time zone NOT NULL DEFAULT now(),
52 | updated_at timestamp without time zone NOT NULL DEFAULT now(),
53 | expiry timestamp without time zone NOT NULL
54 | );
55 |
56 | CREATE TRIGGER set_timestamp
57 | BEFORE UPDATE ON tokens
58 | FOR EACH ROW
59 | EXECUTE PROCEDURE trigger_set_timestamp();
--------------------------------------------------------------------------------
/cmd/cli/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "errors"
5 | "os"
6 |
7 | "github.com/dominic-wassef/ghostly"
8 | "github.com/fatih/color"
9 | )
10 |
11 | const version = "1.0.0"
12 |
13 | var gho ghostly.Ghostly
14 |
15 | func main() {
16 | var message string
17 | arg1, arg2, arg3, err := validateInput()
18 | if err != nil {
19 | exitGracefully(err)
20 | }
21 |
22 | setup(arg1, arg2)
23 |
24 | switch arg1 {
25 | case "help":
26 | showHelp()
27 |
28 | case "new":
29 | if arg2 == "" {
30 | exitGracefully(errors.New("new requires an application name"))
31 | }
32 | doNew(arg2)
33 |
34 | case "version":
35 | color.Yellow("Application version: " + version)
36 |
37 | case "migrate":
38 | if arg2 == "" {
39 | arg2 = "up"
40 | }
41 | err = doMigrate(arg2, arg3)
42 | if err != nil {
43 | exitGracefully(err)
44 | }
45 | message = "Migrations complete!"
46 |
47 | case "make":
48 | if arg2 == "" {
49 | exitGracefully(errors.New("make requires a subcommand: (migration|model|handler)"))
50 | }
51 | err = doMake(arg2, arg3)
52 | if err != nil {
53 | exitGracefully(err)
54 | }
55 |
56 | default:
57 | showHelp()
58 | }
59 |
60 | exitGracefully(nil, message)
61 | }
62 |
63 | func validateInput() (string, string, string, error) {
64 | var arg1, arg2, arg3 string
65 |
66 | if len(os.Args) > 1 {
67 | arg1 = os.Args[1]
68 |
69 | if len(os.Args) >= 3 {
70 | arg2 = os.Args[2]
71 | }
72 |
73 | if len(os.Args) >= 4 {
74 | arg3 = os.Args[3]
75 | }
76 | } else {
77 | color.Red("Error: command required")
78 | showHelp()
79 | return "", "", "", errors.New("command required")
80 | }
81 |
82 | return arg1, arg2, arg3, nil
83 | }
84 |
85 | func exitGracefully(err error, msg ...string) {
86 | message := ""
87 | if len(msg) > 0 {
88 | message = msg[0]
89 | }
90 |
91 | if err != nil {
92 | color.Red("Error: %v\n", err)
93 | }
94 |
95 | if len(message) > 0 {
96 | color.Yellow(message)
97 | } else {
98 | color.Green("Finished!")
99 | }
100 |
101 | os.Exit(0)
102 | }
103 |
--------------------------------------------------------------------------------
/render/render_test.go:
--------------------------------------------------------------------------------
1 | package render
2 |
3 | import (
4 | "net/http"
5 | "net/http/httptest"
6 | "testing"
7 | )
8 |
9 | var pageData = []struct {
10 | name string
11 | renderer string
12 | template string
13 | errorExpected bool
14 | errorMessage string
15 | }{
16 | {"go_page", "go", "home", false, "error rendering go template"},
17 | {"go_page_no_template", "go", "no-file", true, "no error rendering non-existent go template, when one is expected"},
18 | {"jet_page", "jet", "home", false, "error rendering jet template"},
19 | {"jet_page_no_template", "jet", "no-file", true, "no error rendering non-existent jet template, when one is expected"},
20 | {"invalid_render_engine", "foo", "home", true, "no error rendering with non-existent template engine"},
21 | }
22 |
23 | func TestRender_Page(t *testing.T) {
24 | for _, e := range pageData{
25 | r, err := http.NewRequest("GET", "/some-url", nil)
26 | if err != nil {
27 | t.Error(err)
28 | }
29 |
30 | w := httptest.NewRecorder()
31 |
32 | testRenderer.Renderer = e.renderer
33 | testRenderer.RootPath = "./testdata"
34 |
35 | err = testRenderer.Page(w, r, e.template, nil, nil)
36 | if e.errorExpected {
37 | if err == nil {
38 | t.Errorf("%s: %s", e.name, e.errorMessage)
39 | }
40 | } else {
41 | if err != nil {
42 | t.Errorf("%s: %s: %s", e.name, e.errorMessage, err.Error())
43 | }
44 | }
45 | }
46 | }
47 |
48 | func TestRender_GoPage(t *testing.T) {
49 | w := httptest.NewRecorder()
50 | r, err := http.NewRequest("GET", "/url", nil)
51 | if err != nil {
52 | t.Error(err)
53 | }
54 |
55 | testRenderer.Renderer = "go"
56 | testRenderer.RootPath = "./testdata"
57 |
58 | err = testRenderer.Page(w, r, "home", nil, nil)
59 | if err != nil {
60 | t.Error("Error rendering page", err)
61 | }
62 |
63 | }
64 |
65 | func TestRender_JetPage(t *testing.T) {
66 | w := httptest.NewRecorder()
67 | r, err := http.NewRequest("GET", "/url", nil)
68 | if err != nil {
69 | t.Error(err)
70 | }
71 |
72 | testRenderer.Renderer = "jet"
73 |
74 | err = testRenderer.Page(w, r, "home", nil, nil)
75 | if err != nil {
76 | t.Error("Error rendering page", err)
77 | }
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/validator.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "net/http"
5 | "net/url"
6 | "strconv"
7 | "strings"
8 | "time"
9 |
10 | "github.com/asaskevich/govalidator"
11 | )
12 |
13 | type Validation struct {
14 | Data url.Values
15 | Errors map[string]string
16 | }
17 |
18 | func (g *Ghostly) Validator(data url.Values) *Validation {
19 | return &Validation{
20 | Errors: make(map[string]string),
21 | Data: data,
22 | }
23 | }
24 |
25 | func (v *Validation) Valid() bool {
26 | return len(v.Errors) == 0
27 | }
28 |
29 | func (v *Validation) AddError(key, message string) {
30 | if _, exists := v.Errors[key]; !exists {
31 | v.Errors[key] = message
32 | }
33 | }
34 |
35 | func (v *Validation) Has(field string, r *http.Request) bool {
36 | x := r.Form.Get(field)
37 | if x == "" {
38 | return false
39 | }
40 | return true
41 | }
42 |
43 | func (v *Validation) Required(r *http.Request, fields ...string) {
44 | for _, field := range fields {
45 | value := r.Form.Get(field)
46 | if strings.TrimSpace(value) == "" {
47 | v.AddError(field, "This field cannot be blank")
48 | }
49 | }
50 | }
51 |
52 | func (v *Validation) Check(ok bool, key, message string) {
53 | if !ok {
54 | v.AddError(key, message)
55 | }
56 | }
57 |
58 | func (v *Validation) IsEmail(field, value string) {
59 | if !govalidator.IsEmail(value) {
60 | v.AddError(field, "Invalid email address")
61 | }
62 | }
63 |
64 | func (v *Validation) IsInt(field, value string) {
65 | _, err := strconv.Atoi(value)
66 | if err != nil {
67 | v.AddError(field, "This field must be an integer")
68 | }
69 | }
70 |
71 | func (v *Validation) IsFloat(field, value string) {
72 | _, err := strconv.ParseFloat(value, 64)
73 | if err != nil {
74 | v.AddError(field, "This field must be a floating point number")
75 | }
76 | }
77 |
78 | func (v *Validation) IsDateISO(field, value string) {
79 | _, err := time.Parse("2006-01-02", value)
80 | if err != nil {
81 | v.AddError(field, "This field must be a date in the form of YYYY-MM-DD")
82 | }
83 | }
84 |
85 | func (v *Validation) NoSpaces(field, value string) {
86 | if govalidator.HasWhitespace(value) {
87 | v.AddError(field, "Spaces are not permitted")
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/cmd/cli/templates/views/login.jet:
--------------------------------------------------------------------------------
1 | {{extends "./layouts/base.jet"}}
2 |
3 | {{block browserTitle()}}
4 | Login
5 | {{end}}
6 |
7 | {{block css()}} {{end}}
8 |
9 | {{block pageContent()}}
10 | Login
11 |
12 |
13 |
14 |
15 | {{if .Flash != ""}}
16 |
17 | {{.Flash}}
18 |
19 | {{end}}
20 |
21 |
53 |
54 |
57 |
58 |
59 |
60 | {{end}}
61 |
62 | {{block js()}}
63 |
77 | {{end}}
--------------------------------------------------------------------------------
/cmd/cli/templates/migrations/auth_tables.mysql.sql:
--------------------------------------------------------------------------------
1 | drop table if exists users cascade;
2 |
3 | CREATE TABLE `users` (
4 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
5 | `first_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
6 | `last_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
7 | `user_active` int(11) NOT NULL,
8 | `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
9 | `password` char(60) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
10 | `created_at` timestamp NULL DEFAULT NULL,
11 | `updated_at` timestamp NULL DEFAULT NULL,
12 | PRIMARY KEY (`id`),
13 | UNIQUE KEY `users_email_unique` (`email`),
14 | KEY `users_email_index` (`email`)
15 | ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4;
16 |
17 | drop table if exists remember_tokens cascade;
18 |
19 | CREATE TABLE `remember_tokens` (
20 | `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
21 | `user_id` int(10) unsigned NOT NULL,
22 | `remember_token` varchar(100) NOT NULL DEFAULT '',
23 | `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
24 | `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
25 | PRIMARY KEY (`id`),
26 | KEY `remember_token` (`remember_token`),
27 | KEY `remember_tokens_user_id_foreign` (`user_id`),
28 | CONSTRAINT `remember_tokens_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
29 | ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
30 |
31 | drop table if exists tokens cascade;
32 |
33 | CREATE TABLE `tokens` (
34 | `id` int(11) NOT NULL AUTO_INCREMENT,
35 | `user_id` int(11) unsigned NOT NULL,
36 | `name` varchar(255) NOT NULL,
37 | `email` varchar(255) NOT NULL,
38 | `token` varchar(255) NOT NULL,
39 | `token_hash` varbinary(255) DEFAULT NULL,
40 | `created_at` datetime NOT NULL DEFAULT current_timestamp(),
41 | `updated_at` datetime NOT NULL DEFAULT current_timestamp(),
42 | `expiry` datetime NOT NULL,
43 | PRIMARY KEY (`id`),
44 | FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE cascade ON DELETE cascade
45 | ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8mb4;
--------------------------------------------------------------------------------
/cmd/cli/templates/middleware/remember.go.txt:
--------------------------------------------------------------------------------
1 | package middleware
2 |
3 | import (
4 | "fmt"
5 | "myapp/data"
6 | "net/http"
7 | "strconv"
8 | "strings"
9 | "time"
10 | )
11 |
12 | func (m *Middleware) CheckRemember(next http.Handler) http.Handler {
13 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14 | if !m.App.Session.Exists(r.Context(), "userID") {
15 | // user is not logged in
16 | cookie, err := r.Cookie(fmt.Sprintf("_%s_remember", m.App.AppName))
17 | if err != nil {
18 | // no cookie, so on to the next middleware
19 | next.ServeHTTP(w, r)
20 | } else {
21 | // we found a cookie, so check it
22 | key := cookie.Value
23 | var u data.User
24 | if len(key) > 0 {
25 | // cookie has some data, so validate it
26 | split := strings.Split(key, "|")
27 | uid, hash := split[0], split[1]
28 | id, _ := strconv.Atoi(uid)
29 | validHash := u.CheckForRememberToken(id, hash)
30 | if !validHash {
31 | m.deleteRememberCookie(w, r)
32 | m.App.Session.Put(r.Context(), "error", "You've been logged out from another device")
33 | next.ServeHTTP(w, r)
34 | } else {
35 | // valid hash, so log the user in
36 | user, _ := u.Get(id)
37 | m.App.Session.Put(r.Context(), "userID", user.ID)
38 | m.App.Session.Put(r.Context(), "remember_token", hash)
39 | next.ServeHTTP(w, r)
40 | }
41 | } else {
42 | // key length is zero, so it's probably a leftover cookie (user has not closed browser)
43 | m.deleteRememberCookie(w, r)
44 | next.ServeHTTP(w, r)
45 | }
46 | }
47 | } else {
48 | // user is logged in
49 | next.ServeHTTP(w, r)
50 | }
51 | })
52 | }
53 |
54 | func (m *Middleware) deleteRememberCookie(w http.ResponseWriter, r *http.Request) {
55 | _ = m.App.Session.RenewToken(r.Context())
56 | // delete the cookie
57 | newCookie := http.Cookie{
58 | Name: fmt.Sprintf("_%s_remember", m.App.AppName),
59 | Value: "",
60 | Path: "/",
61 | Expires: time.Now().Add(-100 * time.Hour),
62 | HttpOnly: true,
63 | Domain: m.App.Session.Cookie.Domain,
64 | MaxAge: -1,
65 | Secure: m.App.Session.Cookie.Secure,
66 | SameSite: http.SameSiteStrictMode,
67 | }
68 | http.SetCookie(w, &newCookie)
69 |
70 | // log the user out
71 | m.App.Session.Remove(r.Context(), "userID")
72 | m.App.Session.Destroy(r.Context())
73 | _ = m.App.Session.RenewToken(r.Context())
74 | }
--------------------------------------------------------------------------------
/cmd/cli/templates/views/reset-password.jet:
--------------------------------------------------------------------------------
1 | {{extends "./layouts/base.jet"}}
2 |
3 | {{block browserTitle()}}
4 | Form
5 | {{end}}
6 |
7 | {{block css()}} {{end}}
8 |
9 | {{block pageContent()}}
10 | Reset Password
11 |
12 | {{if .Error != ""}}
13 |
14 | {{.Error}}
15 |
16 | {{end}}
17 |
18 | {{if .Flash != ""}}
19 |
20 | {{.Flash}}
21 |
22 | {{end}}
23 |
24 |
52 |
53 |
54 |
55 |
56 |
57 |
60 |
61 |
62 |
63 | {{end}}
64 |
65 | {{ block js()}}
66 |
84 | {{end}}
85 |
--------------------------------------------------------------------------------
/helpers.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "crypto/aes"
5 | "crypto/cipher"
6 | "crypto/rand"
7 | "encoding/base64"
8 | "io"
9 | "os"
10 | )
11 |
12 | const (
13 | randomString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0987654321_+"
14 | )
15 |
16 | // RandomString generates a random string length n from values in the const randomString
17 | func (g *Ghostly) RandomString(n int) string {
18 | s, r := make([]rune, n), []rune(randomString)
19 |
20 | for i := range s {
21 | p, _ := rand.Prime(rand.Reader, len(r))
22 | x, y := p.Uint64(), uint64(len(r))
23 | s[i] = r[x%y]
24 | }
25 | return string(s)
26 | }
27 |
28 | // CreateDirIfNotExist creates a new directory if it does not exist
29 | func (g *Ghostly) CreateDirIfNotExist(path string) error {
30 | const mode = 0755
31 | if _, err := os.Stat(path); os.IsNotExist(err) {
32 | err := os.Mkdir(path, mode)
33 | if err != nil {
34 | return err
35 | }
36 | }
37 |
38 | return nil
39 | }
40 |
41 | // CreateFileIfNotExists creates a new file at path if it does not exist
42 | func (g *Ghostly) CreateFileIfNotExists(path string) error {
43 | var _, err = os.Stat(path)
44 | if os.IsNotExist(err) {
45 | var file, err = os.Create(path)
46 | if err != nil {
47 | return err
48 | }
49 |
50 | defer func(file *os.File) {
51 | _ = file.Close()
52 | }(file)
53 | }
54 | return nil
55 | }
56 |
57 | type Encryption struct {
58 | Key []byte
59 | }
60 |
61 | func (e *Encryption) Encrypt(text string) (string, error) {
62 | plaintext := []byte(text)
63 |
64 | block, err := aes.NewCipher(e.Key)
65 | if err != nil {
66 | return "", err
67 | }
68 |
69 | ciphertext := make([]byte, aes.BlockSize+len(plaintext))
70 | iv := ciphertext[:aes.BlockSize]
71 | if _, err := io.ReadFull(rand.Reader, iv); err != nil {
72 | return "", err
73 | }
74 |
75 | stream := cipher.NewCFBEncrypter(block, iv)
76 | stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
77 |
78 | return base64.URLEncoding.EncodeToString(ciphertext), nil
79 | }
80 |
81 | func (e *Encryption) Decrypt(cryptoText string) (string, error) {
82 | ciphertext, _ := base64.URLEncoding.DecodeString(cryptoText)
83 |
84 | block, err := aes.NewCipher(e.Key)
85 | if err != nil {
86 | return "", err
87 | }
88 |
89 | if len(ciphertext) < aes.BlockSize {
90 | return "", err
91 | }
92 |
93 | iv := ciphertext[:aes.BlockSize]
94 | ciphertext = ciphertext[aes.BlockSize:]
95 |
96 | stream := cipher.NewCFBDecrypter(block, iv)
97 | stream.XORKeyStream(ciphertext, ciphertext)
98 |
99 | return string(ciphertext), nil
100 | }
101 |
--------------------------------------------------------------------------------
/cmd/cli/templates/data/model.go.txt:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | up "github.com/upper/db/v4"
5 | "time"
6 | )
7 | // $MODELNAME$ struct
8 | type $MODELNAME$ struct {
9 | ID int `db:"id,omitempty"`
10 | CreatedAt time.Time `db:"created_at"`
11 | UpdatedAt time.Time `db:"updated_at"`
12 | }
13 |
14 | // Table returns the table name
15 | func (t *$MODELNAME$) Table() string {
16 | return "$TABLENAME$"
17 | }
18 |
19 | // GetAll gets all records from the database, using upper
20 | func (t *$MODELNAME$) GetAll(condition up.Cond) ([]*$MODELNAME$, error) {
21 | collection := upper.Collection(t.Table())
22 | var all []*$MODELNAME$
23 |
24 | res := collection.Find(condition)
25 | err := res.All(&all)
26 | if err != nil {
27 | return nil, err
28 | }
29 |
30 | return all, err
31 | }
32 |
33 | // Get gets one record from the database, by id, using upper
34 | func (t *$MODELNAME$) Get(id int) (*$MODELNAME$, error) {
35 | var one $MODELNAME$
36 | collection := upper.Collection(t.Table())
37 |
38 | res := collection.Find(up.Cond{"id": id})
39 | err := res.One(&one)
40 | if err != nil {
41 | return nil, err
42 | }
43 | return &one, nil
44 | }
45 |
46 | // Update updates a record in the database, using upper
47 | func (t *$MODELNAME$) Update(m $MODELNAME$) error {
48 | m.UpdatedAt = time.Now()
49 | collection := upper.Collection(t.Table())
50 | res := collection.Find(m.ID)
51 | err := res.Update(&m)
52 | if err != nil {
53 | return err
54 | }
55 | return nil
56 | }
57 |
58 | // Delete deletes a record from the database by id, using upper
59 | func (t *$MODELNAME$) Delete(id int) error {
60 | collection := upper.Collection(t.Table())
61 | res := collection.Find(id)
62 | err := res.Delete()
63 | if err != nil {
64 | return err
65 | }
66 | return nil
67 | }
68 |
69 | // Insert inserts a model into the database, using upper
70 | func (t *$MODELNAME$) Insert(m $MODELNAME$) (int, error) {
71 | m.CreatedAt = time.Now()
72 | m.UpdatedAt = time.Now()
73 | collection := upper.Collection(t.Table())
74 | res, err := collection.Insert(m)
75 | if err != nil {
76 | return 0, err
77 | }
78 |
79 | id := getInsertID(res.ID())
80 |
81 | return id, nil
82 | }
83 |
84 | // Builder is an example of using upper's sql builder
85 | func (t *$MODELNAME$) Builder(id int) ([]*$MODELNAME$, error) {
86 | collection := upper.Collection(t.Table())
87 |
88 | var result []*$MODELNAME$
89 |
90 | err := collection.Session().
91 | SQL().
92 | SelectFrom(t.Table()).
93 | Where("id > ?", id).
94 | OrderBy("id").
95 | All(&result)
96 | if err != nil {
97 | return nil, err
98 | }
99 | return result, nil
100 | }
101 |
102 |
--------------------------------------------------------------------------------
/render/render.go:
--------------------------------------------------------------------------------
1 | package render
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "html/template"
7 | "log"
8 | "net/http"
9 | "strings"
10 |
11 | "github.com/CloudyKit/jet/v6"
12 | "github.com/alexedwards/scs/v2"
13 | "github.com/justinas/nosurf"
14 | )
15 |
16 | type Render struct {
17 | Renderer string
18 | RootPath string
19 | Secure bool
20 | Port string
21 | ServerName string
22 | JetViews *jet.Set
23 | Session *scs.SessionManager
24 | }
25 |
26 | type TemplateData struct {
27 | IsAuthenticated bool
28 | IntMap map[string]int
29 | StringMap map[string]string
30 | FloatMap map[string]float32
31 | Data map[string]interface{}
32 | CSRFToken string
33 | Port string
34 | ServerName string
35 | Secure bool
36 | Error string
37 | Flash string
38 | }
39 |
40 | func (c *Render) defaultData(td *TemplateData, r *http.Request) *TemplateData {
41 | td.Secure = c.Secure
42 | td.ServerName = c.ServerName
43 | td.CSRFToken = nosurf.Token(r)
44 | td.Port = c.Port
45 | if c.Session.Exists(r.Context(), "userID") {
46 | td.IsAuthenticated = true
47 | }
48 | td.Error = c.Session.PopString(r.Context(), "error")
49 | td.Flash = c.Session.PopString(r.Context(), "flash")
50 | return td
51 | }
52 |
53 | func (c *Render) Page(w http.ResponseWriter, r *http.Request, view string, variables, data interface{}) error {
54 | switch strings.ToLower(c.Renderer) {
55 | case "go":
56 | return c.GoPage(w, r, view, data)
57 | case "jet":
58 | return c.JetPage(w, r, view, variables, data)
59 | default:
60 |
61 | }
62 | return errors.New("no rendering engine specified")
63 | }
64 |
65 | // GoPage renders a standard Go template
66 | func (c *Render) GoPage(w http.ResponseWriter, r *http.Request, view string, data interface{}) error {
67 | tmpl, err := template.ParseFiles(fmt.Sprintf("%s/views/%s.page.tmpl", c.RootPath, view))
68 | if err != nil {
69 | return err
70 | }
71 |
72 | td := &TemplateData{}
73 | if data != nil {
74 | td = data.(*TemplateData)
75 | }
76 |
77 | err = tmpl.Execute(w, &td)
78 | if err != nil {
79 | return err
80 | }
81 |
82 | return nil
83 | }
84 |
85 | // JetPage renders a template using the Jet templating engine
86 | func (c *Render) JetPage(w http.ResponseWriter, r *http.Request, templateName string, variables, data interface{}) error {
87 | var vars jet.VarMap
88 |
89 | if variables == nil {
90 | vars = make(jet.VarMap)
91 | } else {
92 | vars = variables.(jet.VarMap)
93 | }
94 |
95 | td := &TemplateData{}
96 | if data != nil {
97 | td = data.(*TemplateData)
98 | }
99 |
100 | td = c.defaultData(td, r)
101 |
102 | t, err := c.JetViews.GetTemplate(fmt.Sprintf("%s.jet", templateName))
103 | if err != nil {
104 | log.Println(err)
105 | return err
106 | }
107 |
108 | if err = t.Execute(w, vars, td); err != nil {
109 | log.Println(err)
110 | return err
111 | }
112 | return nil
113 | }
114 |
--------------------------------------------------------------------------------
/cache/badger-cache_test.go:
--------------------------------------------------------------------------------
1 | package cache
2 |
3 | import "testing"
4 |
5 | func TestBadgerCache_Has(t *testing.T) {
6 | err := testBadgerCache.Forget("foo")
7 | if err != nil {
8 | t.Error(err)
9 | }
10 |
11 | inCache, err := testBadgerCache.Has("foo")
12 | if err != nil {
13 | t.Error(err)
14 | }
15 |
16 | if inCache {
17 | t.Error("foo found in cache, and it shouldn't be there")
18 | }
19 |
20 | _ = testBadgerCache.Set("foo", "bar")
21 | inCache, err = testBadgerCache.Has("foo")
22 | if err != nil {
23 | t.Error(err)
24 | }
25 |
26 | if !inCache {
27 | t.Error("foo not found in cache")
28 | }
29 |
30 | err = testBadgerCache.Forget("foo")
31 | if err != nil {
32 | t.Error(err)
33 | }
34 | }
35 |
36 | func TestBadgerCache_Get(t *testing.T) {
37 | err := testBadgerCache.Set("foo", "bar")
38 | if err != nil {
39 | t.Error(err)
40 | }
41 |
42 | x, err := testBadgerCache.Get("foo")
43 | if err != nil {
44 | t.Error(err)
45 | }
46 |
47 | if x != "bar" {
48 | t.Error("did not get correct value from cache")
49 | }
50 | }
51 |
52 | func TestBadgerCache_Forget(t *testing.T) {
53 | err := testBadgerCache.Set("foo", "foo")
54 | if err != nil {
55 | t.Error(err)
56 | }
57 |
58 | err = testBadgerCache.Forget("foo")
59 | if err != nil {
60 | t.Error(err)
61 | }
62 |
63 | inCache, err := testBadgerCache.Has("foo")
64 | if err != nil {
65 | t.Error(err)
66 | }
67 |
68 | if inCache {
69 | t.Error("foo found in cache, and it shouldn't be there")
70 | }
71 |
72 | }
73 |
74 | func TestBadgerCache_Empty(t *testing.T) {
75 | err := testBadgerCache.Set("alpha", "beta")
76 | if err != nil {
77 | t.Error(err)
78 | }
79 |
80 | err = testBadgerCache.Empty()
81 | if err != nil {
82 | t.Error(err)
83 | }
84 |
85 | inCache, err := testBadgerCache.Has("alpha")
86 | if err != nil {
87 | t.Error(err)
88 | }
89 |
90 | if inCache {
91 | t.Error("alpha found in cache, and it shouldn't be there")
92 | }
93 | }
94 |
95 | func TestBadgerCache_EmptyByMatch(t *testing.T) {
96 | err := testBadgerCache.Set("alpha", "beta")
97 | if err != nil {
98 | t.Error(err)
99 | }
100 |
101 | err = testBadgerCache.Set("alpha2", "beta2")
102 | if err != nil {
103 | t.Error(err)
104 | }
105 |
106 | err = testBadgerCache.Set("beta", "beta")
107 | if err != nil {
108 | t.Error(err)
109 | }
110 |
111 | err = testBadgerCache.EmptyByMatch("a")
112 | if err != nil {
113 | t.Error(err)
114 | }
115 |
116 | inCache, err := testBadgerCache.Has("alpha")
117 | if err != nil {
118 | t.Error(err)
119 | }
120 |
121 | if inCache {
122 | t.Error("alpha found in cache, and it shouldn't be there")
123 | }
124 |
125 | inCache, err = testBadgerCache.Has("alpha2")
126 | if err != nil {
127 | t.Error(err)
128 | }
129 |
130 | if inCache {
131 | t.Error("alpha2 found in cache, and it shouldn't be there")
132 | }
133 |
134 | inCache, err = testBadgerCache.Has("beta")
135 | if err != nil {
136 | t.Error(err)
137 | }
138 |
139 | if !inCache {
140 | t.Error("beta not found in cache, and it should be there")
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/response-utils.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "encoding/json"
5 | "encoding/xml"
6 | "errors"
7 | "fmt"
8 | "io"
9 | "net/http"
10 | "path"
11 | "path/filepath"
12 | )
13 |
14 | func (g *Ghostly) ReadJSON(w http.ResponseWriter, r *http.Request, data interface{}) error {
15 | maxBytes := 1048576 // one megabyte
16 | r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytes))
17 |
18 | dec := json.NewDecoder(r.Body)
19 | err := dec.Decode(data)
20 | if err != nil {
21 | return err
22 | }
23 |
24 | err = dec.Decode(&struct{}{})
25 | if err != io.EOF {
26 | return errors.New("body must only have a single json value")
27 | }
28 |
29 | return nil
30 | }
31 |
32 | // WriteJSON writes json from arbitrary data
33 | func (g *Ghostly) WriteJSON(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error {
34 | out, err := json.MarshalIndent(data, "", "\t")
35 | if err != nil {
36 | return err
37 | }
38 |
39 | if len(headers) > 0 {
40 | for key, value := range headers[0] {
41 | w.Header()[key] = value
42 | }
43 | }
44 |
45 | w.Header().Set("Content-Type", "application/json")
46 | w.WriteHeader(status)
47 | _, err = w.Write(out)
48 | if err != nil {
49 | return err
50 | }
51 | return nil
52 | }
53 |
54 | // WriteXML writes xml from arbitrary data
55 | func (g *Ghostly) WriteXML(w http.ResponseWriter, status int, data interface{}, headers ...http.Header) error {
56 | out, err := xml.MarshalIndent(data, "", " ")
57 | if err != nil {
58 | return err
59 | }
60 |
61 | if len(headers) > 0 {
62 | for key, value := range headers[0] {
63 | w.Header()[key] = value
64 | }
65 | }
66 |
67 | w.Header().Set("Content-Type", "application/xml")
68 | w.WriteHeader(status)
69 | _, err = w.Write(out)
70 | if err != nil {
71 | return err
72 | }
73 | return nil
74 | }
75 |
76 | // DownloadFile downloads a file
77 | func (g *Ghostly) DownloadFile(w http.ResponseWriter, r *http.Request, pathToFile, fileName string) error {
78 | fp := path.Join(pathToFile, fileName)
79 | fileToServe := filepath.Clean(fp)
80 | w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; file=\"%s\"", fileName))
81 | http.ServeFile(w, r, fileToServe)
82 | return nil
83 | }
84 |
85 | // Error404 returns page not found response
86 | func (g *Ghostly) Error404(w http.ResponseWriter, r *http.Request) {
87 | g.ErrorStatus(w, http.StatusNotFound)
88 | }
89 |
90 | // Error500 returns internal server error response
91 | func (g *Ghostly) Error500(w http.ResponseWriter, r *http.Request) {
92 | g.ErrorStatus(w, http.StatusInternalServerError)
93 | }
94 |
95 | // ErrorUnauthorized sends an unauthorized status (client is not known)
96 | func (g *Ghostly) ErrorUnauthorized(w http.ResponseWriter, r *http.Request) {
97 | g.ErrorStatus(w, http.StatusUnauthorized)
98 | }
99 |
100 | // ErrorForbidden returns a forbidden status message (client is known)
101 | func (g *Ghostly) ErrorForbidden(w http.ResponseWriter, r *http.Request) {
102 | g.ErrorStatus(w, http.StatusForbidden)
103 | }
104 |
105 | // ErrorStatus returns a response with the supplied http status
106 | func (g *Ghostly) ErrorStatus(w http.ResponseWriter, status int) {
107 | http.Error(w, http.StatusText(status), status)
108 | }
109 |
--------------------------------------------------------------------------------
/cmd/cli/auth.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "time"
6 |
7 | "github.com/fatih/color"
8 | )
9 |
10 | func doAuth() error {
11 | // migrations
12 | dbType := gho.DB.DataType
13 | fileName := fmt.Sprintf("%d_create_auth_tables", time.Now().UnixMicro())
14 | upFile := gho.RootPath + "/migrations/" + fileName + ".up.sql"
15 | downFile := gho.RootPath + "/migrations/" + fileName + ".down.sql"
16 |
17 | err := copyFilefromTemplate("templates/migrations/auth_tables."+dbType+".sql", upFile)
18 | if err != nil {
19 | exitGracefully(err)
20 | }
21 |
22 | err = copyDataToFile([]byte("drop table if exists users cascade; drop table if exists tokens cascade; drop table if exists remember_tokens;"), downFile)
23 | if err != nil {
24 | exitGracefully(err)
25 | }
26 |
27 | // run migrations
28 | err = doMigrate("up", "")
29 | if err != nil {
30 | exitGracefully(err)
31 | }
32 |
33 | err = copyFilefromTemplate("templates/data/user.go.txt", gho.RootPath+"/data/user.go")
34 | if err != nil {
35 | exitGracefully(err)
36 | }
37 |
38 | err = copyFilefromTemplate("templates/data/token.go.txt", gho.RootPath+"/data/token.go")
39 | if err != nil {
40 | exitGracefully(err)
41 | }
42 |
43 | err = copyFilefromTemplate("templates/data/remember_token.go.txt", gho.RootPath+"/data/remember_token.go")
44 | if err != nil {
45 | exitGracefully(err)
46 | }
47 |
48 | // copy over middleware
49 | err = copyFilefromTemplate("templates/middleware/auth.go.txt", gho.RootPath+"/middleware/auth.go")
50 | if err != nil {
51 | exitGracefully(err)
52 | }
53 |
54 | err = copyFilefromTemplate("templates/middleware/auth-token.go.txt", gho.RootPath+"/middleware/auth-token.go")
55 | if err != nil {
56 | exitGracefully(err)
57 | }
58 |
59 | err = copyFilefromTemplate("templates/middleware/remember.go.txt", gho.RootPath+"/middleware/remember.go")
60 | if err != nil {
61 | exitGracefully(err)
62 | }
63 |
64 | err = copyFilefromTemplate("templates/handlers/auth-handlers.go.txt", gho.RootPath+"/handlers/auth-handlers.go")
65 | if err != nil {
66 | exitGracefully(err)
67 | }
68 |
69 | err = copyFilefromTemplate("templates/mailer/password-reset.html.tmpl", gho.RootPath+"/mail/password-reset.html.tmpl")
70 | if err != nil {
71 | exitGracefully(err)
72 | }
73 |
74 | err = copyFilefromTemplate("templates/mailer/password-reset.plain.tmpl", gho.RootPath+"/mail/password-reset.plain.tmpl")
75 | if err != nil {
76 | exitGracefully(err)
77 | }
78 |
79 | err = copyFilefromTemplate("templates/views/login.jet", gho.RootPath+"/views/login.jet")
80 | if err != nil {
81 | exitGracefully(err)
82 | }
83 |
84 | err = copyFilefromTemplate("templates/views/forgot.jet", gho.RootPath+"/views/forgot.jet")
85 | if err != nil {
86 | exitGracefully(err)
87 | }
88 |
89 | err = copyFilefromTemplate("templates/views/reset-password.jet", gho.RootPath+"/views/reset-password.jet")
90 | if err != nil {
91 | exitGracefully(err)
92 | }
93 |
94 | color.Yellow(" - users, tokens, and remember_tokens migrations created and executed")
95 | color.Yellow(" - user and token models created")
96 | color.Yellow(" - auth middleware created")
97 | color.Yellow("")
98 | color.Yellow("Don't forget to add user and token models in data/models.go, and to add appropriate middleware to your routes!")
99 |
100 | return nil
101 | }
102 |
--------------------------------------------------------------------------------
/cache/cache_test.go:
--------------------------------------------------------------------------------
1 | package cache
2 |
3 | import "testing"
4 |
5 | func TestRedisCache_Has( t *testing.T) {
6 | err := testRedisCache.Forget("foo")
7 | if err != nil {
8 | t.Error(err)
9 | }
10 |
11 | inCache, err := testRedisCache.Has("foo")
12 | if err != nil {
13 | t.Error(err)
14 | }
15 |
16 | if inCache {
17 | t.Error("foo found in cache, and it shouldn't be there")
18 | }
19 |
20 | err = testRedisCache.Set("foo", "bar")
21 | if err != nil {
22 | t.Error(err)
23 | }
24 |
25 | inCache, err = testRedisCache.Has("foo")
26 | if err != nil {
27 | t.Error(err)
28 | }
29 |
30 | if !inCache {
31 | t.Error("foo not found in cache, but it should be there")
32 | }
33 | }
34 |
35 | func TestRedisCache_Get(t *testing.T) {
36 | err := testRedisCache.Set("foo", "bar")
37 | if err != nil {
38 | t.Error(err)
39 | }
40 |
41 | x, err := testRedisCache.Get("foo")
42 | if err != nil {
43 | t.Error(err)
44 | }
45 |
46 | if x != "bar" {
47 | t.Error("did not get correct value from cache")
48 | }
49 | }
50 |
51 | func TestRedisCache_Forget(t *testing.T) {
52 | err := testRedisCache.Set("alpha", "beta")
53 | if err != nil {
54 | t.Error(err)
55 | }
56 |
57 | err = testRedisCache.Forget("alpha")
58 | if err != nil {
59 | t.Error(err)
60 | }
61 |
62 | inCache, err := testRedisCache.Has("alpha")
63 | if err != nil {
64 | t.Error(err)
65 | }
66 |
67 | if inCache {
68 | t.Error("alpha found in cache, and it should not be there")
69 | }
70 | }
71 |
72 | func TestRedisCache_Empty(t *testing.T) {
73 | err := testRedisCache.Set("alpha", "beta")
74 | if err != nil {
75 | t.Error(err)
76 | }
77 |
78 | err = testRedisCache.Empty()
79 | if err != nil {
80 | t.Error(err)
81 | }
82 |
83 | inCache, err := testRedisCache.Has("alpha")
84 | if err != nil {
85 | t.Error(err)
86 | }
87 |
88 | if inCache {
89 | t.Error("alpha found in cache, and it should not be there")
90 | }
91 |
92 | }
93 |
94 | func TestRedisCache_EmptyByMatch(t *testing.T) {
95 | err := testRedisCache.Set("alpha", "foo")
96 | if err != nil {
97 | t.Error(err)
98 | }
99 |
100 | err = testRedisCache.Set("alpha2", "foo")
101 | if err != nil {
102 | t.Error(err)
103 | }
104 |
105 | err = testRedisCache.Set("beta", "foo")
106 | if err != nil {
107 | t.Error(err)
108 | }
109 |
110 | err = testRedisCache.EmptyByMatch("alpha")
111 | if err != nil {
112 | t.Error(err)
113 | }
114 |
115 | inCache, err := testRedisCache.Has("alpha")
116 | if err != nil {
117 | t.Error(err)
118 | }
119 |
120 | if inCache {
121 | t.Error("alpha found in cache, and it should not be there")
122 | }
123 |
124 | inCache, err = testRedisCache.Has("alpha2")
125 | if err != nil {
126 | t.Error(err)
127 | }
128 |
129 | if inCache {
130 | t.Error("alpha2 found in cache, and it should not be there")
131 | }
132 |
133 | inCache, err = testRedisCache.Has("beta")
134 | if err != nil {
135 | t.Error(err)
136 | }
137 |
138 | if !inCache {
139 | t.Error("beta not found in cache, and it should be there")
140 | }
141 | }
142 |
143 | func TestEncodeDecode(t *testing.T) {
144 | entry := Entry{}
145 | entry["foo"] = "bar"
146 | bytes, err := encode(entry)
147 | if err != nil {
148 | t.Error(err)
149 | }
150 |
151 | _, err = decode(string(bytes))
152 | if err != nil {
153 | t.Error(err)
154 | }
155 |
156 | }
--------------------------------------------------------------------------------
/cmd/cli/helpers.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "path/filepath"
7 | "strings"
8 |
9 | "github.com/fatih/color"
10 | "github.com/joho/godotenv"
11 | )
12 |
13 | func setup(arg1, arg2 string) {
14 | if arg1 != "new" && arg1 != "version" && arg1 != "help" {
15 | err := godotenv.Load()
16 | if err != nil {
17 | exitGracefully(err)
18 | }
19 |
20 | path, err := os.Getwd()
21 | if err != nil {
22 | exitGracefully(err)
23 | }
24 |
25 | gho.RootPath = path
26 | gho.DB.DataType = os.Getenv("DATABASE_TYPE")
27 | }
28 | }
29 |
30 | func getDSN() string {
31 | dbType := gho.DB.DataType
32 |
33 | if dbType == "pgx" {
34 | dbType = "postgres"
35 | }
36 |
37 | if dbType == "postgres" {
38 | var dsn string
39 | if os.Getenv("DATABASE_PASS") != "" {
40 | dsn = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
41 | os.Getenv("DATABASE_USER"),
42 | os.Getenv("DATABASE_PASS"),
43 | os.Getenv("DATABASE_HOST"),
44 | os.Getenv("DATABASE_PORT"),
45 | os.Getenv("DATABASE_NAME"),
46 | os.Getenv("DATABASE_SSL_MODE"))
47 | } else {
48 | dsn = fmt.Sprintf("postgres://%s@%s:%s/%s?sslmode=%s",
49 | os.Getenv("DATABASE_USER"),
50 | os.Getenv("DATABASE_HOST"),
51 | os.Getenv("DATABASE_PORT"),
52 | os.Getenv("DATABASE_NAME"),
53 | os.Getenv("DATABASE_SSL_MODE"))
54 | }
55 | return dsn
56 | }
57 | return "mysql://" + gho.BuildDSN()
58 | }
59 |
60 | func showHelp() {
61 | color.Green(`Available commands:
62 |
63 | help - show the help commands
64 | version - print application version
65 | migrate - runs all up migrations
66 | migrate down - reverses most recent migration
67 | migrate reset - runs all down / up migrations
68 | make migration - two new up and down migrations
69 | make auth - new auth tables, models, middleware
70 | make handler - stub handler in the handlers folder
71 | make model - new model in the data directory
72 | make session - database table as a session store
73 | make mail - two starter mail templates
74 |
75 | `)
76 | }
77 |
78 | func updateSourceFiles(path string, fi os.FileInfo, err error) error {
79 | // check for an error before doing anything else
80 | if err != nil {
81 | return err
82 | }
83 |
84 | // check if current file is directory
85 | if fi.IsDir() {
86 | return nil
87 | }
88 |
89 | // only check go files
90 | matched, err := filepath.Match("*.go", fi.Name())
91 | if err != nil {
92 | return err
93 | }
94 |
95 | // we have a matching file
96 | if matched {
97 | // read file contents
98 | read, err := os.ReadFile(path)
99 | if err != nil {
100 | exitGracefully(err)
101 | }
102 |
103 | newContents := strings.Replace(string(read), "myapp", appURL, -1)
104 |
105 | // write the changed file
106 | err = os.WriteFile(path, []byte(newContents), 0)
107 | if err != nil {
108 | exitGracefully(err)
109 | }
110 | }
111 |
112 | return nil
113 | }
114 |
115 | func updateSource() {
116 | // walk entire project folder, including subfolders
117 | err := filepath.Walk(".", updateSourceFiles)
118 | if err != nil {
119 | exitGracefully(err)
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/cache/badger_cache.go:
--------------------------------------------------------------------------------
1 | package cache
2 |
3 | import (
4 | "time"
5 |
6 | "github.com/dgraph-io/badger/v3"
7 | )
8 |
9 | type BadgerCache struct {
10 | Conn *badger.DB
11 | Prefix string
12 | }
13 |
14 | func (b *BadgerCache) Has(str string) (bool, error) {
15 | _, err := b.Get(str)
16 | if err != nil {
17 | return false, nil
18 | }
19 | return true, nil
20 | }
21 |
22 | func (b *BadgerCache) Get(str string) (interface{}, error) {
23 | var fromCache []byte
24 |
25 | err := b.Conn.View(func(txn *badger.Txn) error {
26 | item, err := txn.Get([]byte(str))
27 | if err != nil {
28 | return err
29 | }
30 |
31 | err = item.Value(func(val []byte) error {
32 | fromCache = append([]byte{}, val...)
33 | return nil
34 | })
35 | if err != nil {
36 | return err
37 | }
38 | return nil
39 | })
40 | if err != nil {
41 | return nil, err
42 | }
43 |
44 | decoded, err := decode(string(fromCache))
45 | if err != nil {
46 | return nil, err
47 | }
48 |
49 | item := decoded[str]
50 |
51 | return item, nil
52 | }
53 |
54 | func (b *BadgerCache) Set(str string, value interface{}, expires ...int) error {
55 | entry := Entry{}
56 |
57 | entry[str] = value
58 | encoded, err := encode(entry)
59 | if err != nil {
60 | return err
61 | }
62 |
63 | if len(expires) > 0 {
64 | err = b.Conn.Update(func(txn *badger.Txn) error {
65 | e := badger.NewEntry([]byte(str), encoded).WithTTL(time.Second * time.Duration(expires[0]))
66 | err = txn.SetEntry(e)
67 | return err
68 | })
69 | } else {
70 | err = b.Conn.Update(func(txn *badger.Txn) error {
71 | e := badger.NewEntry([]byte(str), encoded)
72 | err = txn.SetEntry(e)
73 | return err
74 | })
75 | }
76 |
77 | return nil
78 | }
79 |
80 | func (b *BadgerCache) Forget(str string) error {
81 | err := b.Conn.Update(func(txn *badger.Txn) error {
82 | err := txn.Delete([]byte(str))
83 | return err
84 | })
85 |
86 | return err
87 | }
88 |
89 | func (b *BadgerCache) EmptyByMatch(str string) error {
90 | return b.emptyByMatch(str)
91 | }
92 |
93 | func (b *BadgerCache) Empty() error {
94 | return b.emptyByMatch("")
95 | }
96 |
97 | func (b *BadgerCache) emptyByMatch(str string) error {
98 | deleteKeys := func(keysForDelete [][]byte) error {
99 | if err := b.Conn.Update(func(txn *badger.Txn) error {
100 | for _, key := range keysForDelete {
101 | if err := txn.Delete(key); err != nil {
102 | return err
103 | }
104 | }
105 | return nil
106 | }); err != nil {
107 | return err
108 | }
109 | return nil
110 | }
111 |
112 | collectSize := 100000
113 |
114 | err := b.Conn.View(func(txn *badger.Txn) error{
115 | opts := badger.DefaultIteratorOptions
116 | opts.AllVersions = false
117 | opts.PrefetchValues = false
118 | it := txn.NewIterator(opts)
119 | defer it.Close()
120 |
121 | keysForDelete := make([][]byte, 0, collectSize)
122 | keysCollected := 0
123 |
124 | for it.Seek([]byte(str)); it.ValidForPrefix([]byte(str)); it.Next() {
125 | key := it.Item().KeyCopy(nil)
126 | keysForDelete = append(keysForDelete, key)
127 | keysCollected++
128 | if keysCollected == collectSize {
129 | if err := deleteKeys(keysForDelete); err != nil {
130 | return err
131 | }
132 | }
133 | }
134 |
135 | if keysCollected > 0 {
136 | if err := deleteKeys(keysForDelete); err != nil {
137 | return err
138 | }
139 | }
140 |
141 | return nil
142 | })
143 |
144 | return err
145 | }
--------------------------------------------------------------------------------
/mailer/mail_test.go:
--------------------------------------------------------------------------------
1 | package mailer
2 |
3 | import (
4 | "errors"
5 | "testing"
6 | )
7 |
8 |
9 | func TestMail_SendSMTPMessage(t *testing.T) {
10 | msg := Message{
11 | From: "me@here.com",
12 | FromName: "Joe",
13 | To: "you@there.com",
14 | Subject: "test",
15 | Template: "test",
16 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
17 | }
18 |
19 | err := mailer.SendSMTPMessage(msg)
20 | if err != nil {
21 | t.Error(err)
22 | }
23 | }
24 |
25 | func TestMail_SendUsingChan(t *testing.T) {
26 | msg := Message{
27 | From: "me@here.com",
28 | FromName: "Joe",
29 | To: "you@there.com",
30 | Subject: "test",
31 | Template: "test",
32 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
33 | }
34 |
35 | mailer.Jobs <-msg
36 | res := <-mailer.Results
37 | if res.Error != nil {
38 | t.Error(errors.New("failed to send over channel"))
39 | }
40 |
41 | msg.To = "not_an_email_address"
42 | mailer.Jobs <- msg
43 | res = <-mailer.Results
44 | if res.Error == nil {
45 | t.Error(errors.New("no error received with invalid to address"))
46 | }
47 | }
48 |
49 | func TestMail_SendUsingAPI(t *testing.T) {
50 | msg := Message{
51 | To: "you@there.com",
52 | Subject: "test",
53 | Template: "test",
54 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
55 | }
56 |
57 | mailer.API = "unknown"
58 | mailer.APIKey = "abc123"
59 | mailer.APIUrl = "https://www.fake.com"
60 |
61 | err := mailer.SendUsingAPI(msg, "unknown")
62 | if err == nil {
63 | t.Error(err)
64 | }
65 | mailer.API = ""
66 | mailer.APIKey = ""
67 | mailer.APIUrl = ""
68 | }
69 |
70 | func TestMail_buildHTMLMessage(t *testing.T) {
71 | msg := Message{
72 | From: "me@here.com",
73 | FromName: "Joe",
74 | To: "you@there.com",
75 | Subject: "test",
76 | Template: "test",
77 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
78 | }
79 |
80 | _, err := mailer.buildHTMLMessage(msg)
81 | if err != nil {
82 | t.Error(err)
83 | }
84 | }
85 |
86 | func TestMail_buildPlainMessage(t *testing.T) {
87 | msg := Message{
88 | From: "me@here.com",
89 | FromName: "Joe",
90 | To: "you@there.com",
91 | Subject: "test",
92 | Template: "test",
93 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
94 | }
95 |
96 | _, err := mailer.buildPlainTextMessage(msg)
97 | if err != nil {
98 | t.Error(err)
99 | }
100 | }
101 |
102 | func TestMail_send(t *testing.T) {
103 | msg := Message{
104 | From: "me@here.com",
105 | FromName: "Joe",
106 | To: "you@there.com",
107 | Subject: "test",
108 | Template: "test",
109 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
110 | }
111 |
112 | err := mailer.Send(msg)
113 | if err != nil {
114 | t.Error(err)
115 | }
116 |
117 | mailer.API = "unknown"
118 | mailer.APIKey = "abc123"
119 | mailer.APIUrl = "https://www.fake.com"
120 |
121 | err = mailer.Send(msg)
122 | if err == nil {
123 | t.Error("did not not get an error when we should have")
124 | }
125 |
126 | mailer.API = ""
127 | mailer.APIKey = ""
128 | mailer.APIUrl = ""
129 | }
130 |
131 | func TestMail_ChooseAPI(t *testing.T) {
132 | msg := Message{
133 | From: "me@here.com",
134 | FromName: "Joe",
135 | To: "you@there.com",
136 | Subject: "test",
137 | Template: "test",
138 | Attachments: []string{"./testdata/mail/test.html.tmpl"},
139 | }
140 | mailer.API = "unknown"
141 | err := mailer.ChooseAPI(msg)
142 | if err == nil {
143 | t.Error(err)
144 | }
145 | }
--------------------------------------------------------------------------------
/cmd/cli/new.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "log"
7 | "os"
8 | "os/exec"
9 | "runtime"
10 | "strings"
11 |
12 | "github.com/fatih/color"
13 | "github.com/go-git/go-git/v5"
14 | )
15 |
16 | var appURL string
17 |
18 | func doNew(appName string) {
19 | appName = strings.ToLower(appName)
20 | appURL = appName
21 |
22 | // sanitize the application name (convert url to single word)
23 | if strings.Contains(appName, "/") {
24 | exploded := strings.SplitAfter(appName, "/")
25 | appName = exploded[(len(exploded) - 1)]
26 | }
27 |
28 | log.Println("App name is", appName)
29 |
30 | // git clone the skeleton application
31 | color.Green("\tCloning repository...")
32 | _, err := git.PlainClone("./"+appName, false, &git.CloneOptions{
33 | URL: "https://github.com/Dominic-Wassef/ghostly-skeleton.git",
34 | Progress: os.Stdout,
35 | Depth: 1,
36 | })
37 | if err != nil {
38 | exitGracefully(err)
39 | }
40 |
41 | // remove .git directory
42 | err = os.RemoveAll(fmt.Sprintf("./%s/.git", appName))
43 | if err != nil {
44 | exitGracefully(err)
45 | }
46 |
47 | // create a ready to go .env file
48 | color.Yellow("\tCreating .env file...")
49 | data, err := templateFS.ReadFile("templates/env.txt")
50 | if err != nil {
51 | exitGracefully(err)
52 | }
53 |
54 | env := string(data)
55 | env = strings.ReplaceAll(env, "${APP_NAME}", appName)
56 | env = strings.ReplaceAll(env, "${KEY}", gho.RandomString(32))
57 |
58 | err = copyDataToFile([]byte(env), fmt.Sprintf("./%s/.env", appName))
59 | if err != nil {
60 | exitGracefully(err)
61 | }
62 |
63 | // create a makefile
64 | if runtime.GOOS == "windows" {
65 | source, err := os.Open(fmt.Sprintf("./%s/Makefile.windows", appName))
66 | if err != nil {
67 | exitGracefully(err)
68 | }
69 | defer source.Close()
70 |
71 | destination, err := os.Create(fmt.Sprintf("./%s/Makefile", appName))
72 | if err != nil {
73 | exitGracefully(err)
74 | }
75 | defer destination.Close()
76 |
77 | _, err = io.Copy(destination, source)
78 | if err != nil {
79 | exitGracefully(err)
80 | }
81 | } else {
82 | source, err := os.Open(fmt.Sprintf("./%s/Makefile.mac", appName))
83 | if err != nil {
84 | exitGracefully(err)
85 | }
86 | defer source.Close()
87 |
88 | destination, err := os.Create(fmt.Sprintf("./%s/Makefile", appName))
89 | if err != nil {
90 | exitGracefully(err)
91 | }
92 | defer destination.Close()
93 |
94 | _, err = io.Copy(destination, source)
95 | if err != nil {
96 | exitGracefully(err)
97 | }
98 | }
99 | _ = os.Remove("./" + appName + "/Makefile.mac")
100 | _ = os.Remove("./" + appName + "/Makefile.windows")
101 |
102 | // update the go.mod file
103 | color.Yellow("\tCreating go.mod file...")
104 | _ = os.Remove("./" + appName + "/go.mod")
105 |
106 | data, err = templateFS.ReadFile("templates/go.mod.txt")
107 | if err != nil {
108 | exitGracefully(err)
109 | }
110 |
111 | mod := string(data)
112 | mod = strings.ReplaceAll(mod, "${APP_NAME}", appURL)
113 |
114 | err = copyDataToFile([]byte(mod), "./"+appName+"/go.mod")
115 | if err != nil {
116 | exitGracefully(err)
117 | }
118 |
119 | // update existing .go files with correct name/imports
120 | color.Yellow("\tUpdating source files...")
121 | os.Chdir("./" + appName)
122 | updateSource()
123 |
124 | // run go mod tidy in the project directory
125 | color.Yellow("\tRunning go mod tidy...")
126 | cmd := exec.Command("go", "mod", "tidy")
127 | err = cmd.Start()
128 | if err != nil {
129 | exitGracefully(err)
130 | }
131 |
132 | color.Green("Done building " + appURL)
133 | color.Green("Going Ghostly")
134 | }
135 |
--------------------------------------------------------------------------------
/cmd/cli/make.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "io/ioutil"
7 | "strings"
8 | "time"
9 |
10 | "github.com/fatih/color"
11 | "github.com/gertd/go-pluralize"
12 | "github.com/iancoleman/strcase"
13 | )
14 |
15 | func doMake(arg2, arg3 string) error {
16 |
17 | switch arg2 {
18 | case "key":
19 | rnd := gho.RandomString(32)
20 | color.Yellow("32 character encryption key: %s", rnd)
21 |
22 | case "migration":
23 | dbType := gho.DB.DataType
24 | if arg3 == "" {
25 | exitGracefully(errors.New("you must give the migration a name"))
26 | }
27 |
28 | fileName := fmt.Sprintf("%d_%s", time.Now().UnixMicro(), arg3)
29 |
30 | upFile := gho.RootPath + "/migrations/" + fileName + "." + dbType + ".up.sql"
31 | downFile := gho.RootPath + "/migrations/" + fileName + "." + dbType + ".down.sql"
32 |
33 | err := copyFilefromTemplate("templates/migrations/migration."+dbType+".up.sql", upFile)
34 | if err != nil {
35 | exitGracefully(err)
36 | }
37 |
38 | err = copyFilefromTemplate("templates/migrations/migration."+dbType+".down.sql", downFile)
39 | if err != nil {
40 | exitGracefully(err)
41 | }
42 |
43 | case "auth":
44 | err := doAuth()
45 | if err != nil {
46 | exitGracefully(err)
47 | }
48 |
49 | case "handler":
50 | if arg3 == "" {
51 | exitGracefully(errors.New("you must give the handler a name"))
52 | }
53 |
54 | fileName := gho.RootPath + "/handlers/" + strings.ToLower(arg3) + ".go"
55 | if fileExists(fileName) {
56 | exitGracefully(errors.New(fileName + " already exists!"))
57 | }
58 |
59 | data, err := templateFS.ReadFile("templates/handlers/handler.go.txt")
60 | if err != nil {
61 | exitGracefully(err)
62 | }
63 |
64 | handler := string(data)
65 | handler = strings.ReplaceAll(handler, "$HANDLERNAME$", strcase.ToCamel(arg3))
66 |
67 | err = ioutil.WriteFile(fileName, []byte(handler), 0644)
68 | if err != nil {
69 | exitGracefully(err)
70 | }
71 |
72 | case "model":
73 | if arg3 == "" {
74 | exitGracefully(errors.New("you must give the model a name"))
75 | }
76 |
77 | data, err := templateFS.ReadFile("templates/data/model.go.txt")
78 | if err != nil {
79 | exitGracefully(err)
80 | }
81 |
82 | model := string(data)
83 |
84 | plur := pluralize.NewClient()
85 |
86 | var modelName = arg3
87 | var tableName = arg3
88 |
89 | if plur.IsPlural(arg3) {
90 | modelName = plur.Singular(arg3)
91 | tableName = strings.ToLower(tableName)
92 | } else {
93 | tableName = strings.ToLower(plur.Plural(arg3))
94 | }
95 |
96 | fileName := gho.RootPath + "/data/" + strings.ToLower(modelName) + ".go"
97 | if fileExists(fileName) {
98 | exitGracefully(errors.New(fileName + " already exists!"))
99 | }
100 |
101 | model = strings.ReplaceAll(model, "$MODELNAME$", strcase.ToCamel(modelName))
102 | model = strings.ReplaceAll(model, "$TABLENAME$", tableName)
103 |
104 | err = copyDataToFile([]byte(model), fileName)
105 | if err != nil {
106 | exitGracefully(err)
107 | }
108 |
109 | case "mail":
110 | if arg3 == "" {
111 | exitGracefully(errors.New("you must give the mail template a name"))
112 | }
113 | htmlMail := gho.RootPath + "/mail/" + strings.ToLower(arg3) + ".html.tmpl"
114 | plainMail := gho.RootPath + "/mail/" + strings.ToLower(arg3) + ".plain.tmpl"
115 |
116 | err := copyFilefromTemplate("templates/mailer/mail.html.tmpl", htmlMail)
117 | if err != nil {
118 | exitGracefully(err)
119 | }
120 |
121 | err = copyFilefromTemplate("templates/mailer/mail.plain.tmpl", plainMail)
122 | if err != nil {
123 | exitGracefully(err)
124 | }
125 |
126 | case "session":
127 | err := doSessionTable()
128 | if err != nil {
129 | exitGracefully(err)
130 | }
131 | }
132 |
133 | return nil
134 | }
135 |
--------------------------------------------------------------------------------
/filesystems/miniofilesystem/minio.go:
--------------------------------------------------------------------------------
1 | package miniofilesystem
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "log"
7 | "path"
8 | "strings"
9 |
10 | "github.com/dominic-wassef/ghostly/filesystems"
11 | "github.com/minio/minio-go/v7"
12 | "github.com/minio/minio-go/v7/pkg/credentials"
13 | )
14 |
15 | // Minio is the overall type for the minio filesystem, and contains
16 | // the connection credentials, endpoint, and the bucket to use
17 | type Minio struct {
18 | Endpoint string
19 | Key string
20 | Secret string
21 | UseSSL bool
22 | Region string
23 | Bucket string
24 | }
25 |
26 | // getCredentials generates a minio client using the credentials stored in
27 | // the Minio type
28 | func (m *Minio) getCredentials() *minio.Client {
29 | client, err := minio.New(m.Endpoint, &minio.Options{
30 | Creds: credentials.NewStaticV4(m.Key, m.Secret, ""),
31 | Secure: m.UseSSL,
32 | })
33 | if err != nil {
34 | log.Println(err)
35 | }
36 | return client
37 | }
38 |
39 | // Put transfers a file to the remote file system
40 | func (m *Minio) Put(fileName, folder string) error {
41 | ctx, cancel := context.WithCancel(context.Background())
42 | defer cancel()
43 |
44 | objectName := path.Base(fileName)
45 | client := m.getCredentials()
46 | uploadInfo, err := client.FPutObject(ctx, m.Bucket, fmt.Sprintf("%s/%s", folder, objectName), fileName, minio.PutObjectOptions{})
47 | if err != nil {
48 | log.Println("Failed with FPutObject")
49 | log.Println(err)
50 | log.Println("UploadInfo:", uploadInfo)
51 | return err
52 | }
53 |
54 | return nil
55 | }
56 |
57 | // List returns a listing of all files in the remote bucket with the
58 | // given prefix, except for files with a leading . in the name
59 | func (m *Minio) List(prefix string) ([]filesystems.Listing, error) {
60 | var listing []filesystems.Listing
61 |
62 | ctx, cancel := context.WithCancel(context.Background())
63 | defer cancel()
64 |
65 | client := m.getCredentials()
66 |
67 | objectCh := client.ListObjects(ctx, m.Bucket, minio.ListObjectsOptions{
68 | Prefix: prefix,
69 | Recursive: true,
70 | })
71 |
72 | for object := range objectCh {
73 | if object.Err != nil {
74 | fmt.Println(object.Err)
75 | return listing, object.Err
76 | }
77 |
78 | if !strings.HasPrefix(object.Key, ".") {
79 | b := float64(object.Size)
80 | kb := b / 1024
81 | mb := kb / 1024
82 | item := filesystems.Listing{
83 | Etag: object.ETag,
84 | LastModified: object.LastModified,
85 | Key: object.Key,
86 | Size: mb,
87 | }
88 | listing = append(listing, item)
89 | }
90 | }
91 |
92 | return listing, nil
93 | }
94 |
95 | // Delete removes one or more files from the remote filesystem
96 | func (m *Minio) Delete(itemsToDelete []string) bool {
97 | ctx, cancel := context.WithCancel(context.Background())
98 | defer cancel()
99 |
100 | client := m.getCredentials()
101 |
102 | opts := minio.RemoveObjectOptions{
103 | GovernanceBypass: true,
104 | }
105 |
106 | for _, item := range itemsToDelete {
107 | err := client.RemoveObject(ctx, m.Bucket, item, opts)
108 | if err != nil {
109 | fmt.Println(err)
110 | return false
111 | }
112 | }
113 | return true
114 | }
115 |
116 | // Get pulls a file from the remote file system and saves it somewhere on our server
117 | func (m *Minio) Get(destination string, items ...string) error {
118 | ctx, cancel := context.WithCancel(context.Background())
119 | defer cancel()
120 |
121 | client := m.getCredentials()
122 |
123 | for _, item := range items {
124 | err := client.FGetObject(ctx, m.Bucket, item, fmt.Sprintf("%s/%s", destination, path.Base(item)), minio.GetObjectOptions{})
125 | if err != nil {
126 | fmt.Println(err)
127 | return err
128 | }
129 | }
130 | return nil
131 | }
132 |
--------------------------------------------------------------------------------
/cache/cache.go:
--------------------------------------------------------------------------------
1 | package cache
2 |
3 | import (
4 | "bytes"
5 | "encoding/gob"
6 | "fmt"
7 |
8 | "github.com/gomodule/redigo/redis"
9 | )
10 |
11 | type Cache interface {
12 | Has(string) (bool, error)
13 | Get(string) (interface{}, error)
14 | Set(string, interface{}, ...int) error
15 | Forget(string) error
16 | EmptyByMatch(string) error
17 | Empty() error
18 | }
19 |
20 | type RedisCache struct {
21 | Conn *redis.Pool
22 | Prefix string
23 | }
24 |
25 | type Entry map[string]interface{}
26 |
27 | func (c *RedisCache) Has(str string) (bool, error) {
28 | key := fmt.Sprintf("%s:%s", c.Prefix, str)
29 | conn := c.Conn.Get()
30 | defer conn.Close()
31 |
32 | ok, err := redis.Bool(conn.Do("EXISTS", key))
33 | if err != nil {
34 | return false, err
35 | }
36 |
37 | return ok, nil
38 | }
39 |
40 | func encode(item Entry) ([]byte, error) {
41 | b := bytes.Buffer{}
42 | e := gob.NewEncoder(&b)
43 | err := e.Encode(item)
44 | if err != nil {
45 | return nil, err
46 | }
47 | return b.Bytes(), nil
48 | }
49 |
50 | func decode(str string) (Entry, error) {
51 | item := Entry{}
52 | b := bytes.Buffer{}
53 | b.Write([]byte(str))
54 | d := gob.NewDecoder(&b)
55 | err := d.Decode(&item)
56 | if err != nil {
57 | return nil, err
58 | }
59 | return item, nil
60 | }
61 |
62 | func (c *RedisCache) Get(str string) (interface{}, error) {
63 | key := fmt.Sprintf("%s:%s", c.Prefix, str)
64 | conn := c.Conn.Get()
65 | defer conn.Close()
66 |
67 | cacheEntry, err := redis.Bytes(conn.Do("GET", key))
68 | if err != nil {
69 | return nil, err
70 | }
71 |
72 | decoded, err := decode(string(cacheEntry))
73 | if err != nil {
74 | return nil, err
75 | }
76 |
77 | item := decoded[key]
78 |
79 | return item, nil
80 | }
81 |
82 | func (c *RedisCache) Set(str string, value interface{}, expires ...int) error {
83 | key := fmt.Sprintf("%s:%s", c.Prefix, str)
84 | conn := c.Conn.Get()
85 | defer conn.Close()
86 |
87 | entry := Entry{}
88 | entry[key] = value
89 | encoded, err := encode(entry)
90 | if err != nil {
91 | return err
92 | }
93 |
94 | if len(expires) > 0 {
95 | _, err := conn.Do("SETEX", key, expires[0], string(encoded))
96 | if err != nil {
97 | return err
98 | }
99 | } else {
100 | _, err := conn.Do("SET", key, string(encoded))
101 | if err != nil {
102 | return err
103 | }
104 | }
105 |
106 | return nil
107 | }
108 |
109 | func (c *RedisCache) Forget(str string) error {
110 | key := fmt.Sprintf("%s:%s", c.Prefix, str)
111 | conn := c.Conn.Get()
112 | defer conn.Close()
113 |
114 | _, err := conn.Do("DEL", key)
115 | if err != nil {
116 | return err
117 | }
118 |
119 | return nil
120 | }
121 |
122 | func (c *RedisCache) EmptyByMatch(str string) error {
123 | key := fmt.Sprintf("%s:%s", c.Prefix, str)
124 | conn := c.Conn.Get()
125 | defer conn.Close()
126 |
127 | keys, err := c.getKeys(key)
128 | if err != nil {
129 | return err
130 | }
131 |
132 | for _, x := range keys {
133 | _, err := conn.Do("DEL", x)
134 | if err != nil {
135 | return err
136 | }
137 | }
138 |
139 | return nil
140 | }
141 |
142 | func (c *RedisCache) Empty() error {
143 | key := fmt.Sprintf("%s:", c.Prefix)
144 | conn := c.Conn.Get()
145 | defer conn.Close()
146 |
147 | keys, err := c.getKeys(key)
148 | if err != nil {
149 | return err
150 | }
151 |
152 | for _, x := range keys {
153 | _, err := conn.Do("DEL", x)
154 | if err != nil {
155 | return err
156 | }
157 | }
158 |
159 | return nil
160 | }
161 |
162 | func (c *RedisCache) getKeys(pattern string) ([]string, error) {
163 | conn := c.Conn.Get()
164 | defer conn.Close()
165 |
166 | iter := 0
167 | keys := []string{}
168 |
169 | for {
170 | arr, err := redis.Values(conn.Do("SCAN", iter, "MATCH", fmt.Sprintf("%s*", pattern)))
171 | if err != nil {
172 | return keys, err
173 | }
174 |
175 | iter, _ = redis.Int(arr[0], nil)
176 | k, _ := redis.Strings(arr[1], nil)
177 | keys = append(keys, k...)
178 |
179 | if iter == 0 {
180 | break
181 | }
182 | }
183 |
184 | return keys, nil
185 | }
186 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | # Ghostly
5 | -----------------------------------------------------------------------------
6 | ## Ghostly is a simple, lightweight, and fast full-stack framework for Golang
7 |
8 | ## Functionality:
9 | > Object Relation Mapper (ORM) that is database agnostic
10 |
11 | > A fully functional Database Migration system
12 |
13 | > A fully featured user authentication system that can be installed with a single command, which includes:
14 |
15 | > A password reset system
16 |
17 | > Session based authentication (for web based applications)
18 |
19 | > Token based authentication (for APIs and systems built with front ends like React and Vue)
20 |
21 | > A fully featured templating system (using both Go templates and Jet templates)
22 |
23 | > A complete caching system that supports Redis and Badger
24 |
25 | > Easy session management, with cookie, database (MySQL and Postgres), Redis stores
26 |
27 | > Simple response types for HTML, XML, JSON, and file downloads
28 |
29 | > Form validation
30 |
31 | > JSON validation
32 |
33 | > A complete mailing system which supports SMTP servers, and third party APIs including MailGun, SparkPost, and SendGrid
34 |
35 | > A command line application which allows for easy generation of emails, handlers, database models
36 |
37 | > the command line application will allow us to create a ready-to-go web application by tying a single command: ghostly new
38 |
39 | ## Notice
40 | There is coverage and CI for both Linux, Mac and Windows environments, but I make no guarantees about the bin version working on Windows.
41 | Must be Go version 1.17 or higher
42 |
43 | ## Installation
44 |
45 | As a library
46 |
47 | ```shell
48 | go get github.com/dominic-wassef/ghostly@latest
49 | ```
50 |
51 | or if you want to use it as a bin command I will list the exact steps below:
52 |
53 |
54 | Step 1.
55 | Make a workfolder on your Desktop and cd into it
56 | ```shell
57 | mkdir Ghostly-App
58 | ```
59 | ```shell
60 | cd Ghostly-App
61 | ```
62 |
63 | Step 2.
64 | Clone the repository
65 | ```shell
66 | git clone git@github.com:Dominic-Wassef/ghostly.git
67 | ```
68 |
69 | Step 3.
70 | cd into directory and build the binary with the Makefile at root level of the ghostly project
71 | ```shell
72 | cd ghostly
73 | ```
74 | ```shell
75 | make build
76 | ```
77 |
78 | Step 4.
79 | cd into the dist directory of the ghostly application and copy it to your Desktop
80 | ```shell
81 | cd dist
82 | ```
83 | ```shell
84 | cp ./ghostly ~/Desktop
85 | ```
86 |
87 | ## Usage
88 |
89 | Once above steps have been followed, you can show all ghostly command by going to your Desktop and run:
90 | ```shell
91 | ./ghostly
92 | ```
93 |
94 | Making a new project:
95 | ```shell
96 | ./ghostly new $("PROJECT-NAME")
97 | ```
98 |
99 | Then cd into your newly made Go project:
100 | ```shell
101 | cd $("PROJECT-NAME")
102 | ```
103 |
104 | Run the project by using the makefile in your new project directory
105 | ```shell
106 | make start
107 | ```
108 |
109 | Here are the types for the Ghostly Framework
110 |
111 | ```go
112 | type Ghostly struct {
113 | AppName string
114 | Debug bool
115 | Version string
116 | ErrorLog *log.Logger
117 | InfoLog *log.Logger
118 | RootPath string
119 | Routes *chi.Mux
120 | Render *render.Render
121 | Session *scs.SessionManager
122 | DB Database
123 | JetViews *jet.Set
124 | config config
125 | EncryptionKey string
126 | Cache cache.Cache
127 | Scheduler *cron.Cron
128 | Mail mailer.Mail
129 | Server Server
130 | }
131 | ```
132 |
133 | Below types are for Server and Config:
134 |
135 | ```go
136 | type Server struct {
137 | ServerName string
138 | Port string
139 | Secure bool
140 | URL string
141 | }
142 |
143 | type config struct {
144 | port string
145 | renderer string
146 | cookie cookieConfig
147 | sessionType string
148 | database databaseConfig
149 | redis redisConfig
150 | }
151 | ```
152 |
153 | For full documentation please refer to the package on:
154 | [Ghostly Documentation](https://pkg.go.dev/github.com/dominic-wassef/ghostly@v1.3.0)
155 |
156 | ## Who?
157 |
158 | The full library [ghostly](https://github.com/dominic-wassef/ghostly) was written by [Dominic-Wassef](https://github.com/Dominic-Wassef)
--------------------------------------------------------------------------------
/cmd/cli/templates/go.mod.txt:
--------------------------------------------------------------------------------
1 | module ${APP_NAME}
2 |
3 | go 1.17
4 |
5 | require (
6 | github.com/CloudyKit/jet/v6 v6.1.0
7 | github.com/DATA-DOG/go-sqlmock v1.5.0
8 | github.com/go-chi/chi/v5 v5.0.4
9 | github.com/jackc/pgconn v1.10.0
10 | github.com/jackc/pgx/v4 v4.13.0
11 | github.com/justinas/nosurf v1.1.1
12 | github.com/ory/dockertest/v3 v3.8.0
13 | github.com/dominic-wassef/ghostly main
14 | github.com/upper/db/v4 v4.2.1
15 | golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97
16 | )
17 |
18 | require (
19 | github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect
20 | github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect
21 | github.com/Microsoft/go-winio v0.5.0 // indirect
22 | github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
23 | github.com/PuerkitoBio/goquery v1.5.1 // indirect
24 | github.com/SparkPost/gosparkpost v0.2.0 // indirect
25 | github.com/ainsleyclark/go-mail v1.0.3 // indirect
26 | github.com/alexedwards/scs/mysqlstore v0.0.0-20210904201103-9ffa4cfa9323 // indirect
27 | github.com/alexedwards/scs/postgresstore v0.0.0-20210904201103-9ffa4cfa9323 // indirect
28 | github.com/alexedwards/scs/redisstore v0.0.0-20210904201103-9ffa4cfa9323 // indirect
29 | github.com/alexedwards/scs/v2 v2.4.0 // indirect
30 | github.com/andybalholm/cascadia v1.1.0 // indirect
31 | github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
32 | github.com/bwmarrin/go-alone v0.0.0-20190806015146-742bb55d1631 // indirect
33 | github.com/cenkalti/backoff/v4 v4.1.1 // indirect
34 | github.com/cespare/xxhash v1.1.0 // indirect
35 | github.com/cespare/xxhash/v2 v2.1.1 // indirect
36 | github.com/containerd/continuity v0.2.0 // indirect
37 | github.com/dgraph-io/badger/v3 v3.2103.1 // indirect
38 | github.com/dgraph-io/ristretto v0.1.0 // indirect
39 | github.com/docker/cli v20.10.8+incompatible // indirect
40 | github.com/docker/docker v20.10.7+incompatible // indirect
41 | github.com/docker/go-connections v0.4.0 // indirect
42 | github.com/docker/go-units v0.4.0 // indirect
43 | github.com/dustin/go-humanize v1.0.0 // indirect
44 | github.com/gabriel-vasile/mimetype v1.3.1 // indirect
45 | github.com/go-sql-driver/mysql v1.6.0 // indirect
46 | github.com/gogo/protobuf v1.3.2 // indirect
47 | github.com/golang-migrate/migrate/v4 v4.14.1 // indirect
48 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect
49 | github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
50 | github.com/golang/protobuf v1.5.0 // indirect
51 | github.com/golang/snappy v0.0.3 // indirect
52 | github.com/gomodule/redigo v1.8.5 // indirect
53 | github.com/google/flatbuffers v1.12.0 // indirect
54 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
55 | github.com/gorilla/css v1.0.0 // indirect
56 | github.com/gorilla/mux v1.8.0 // indirect
57 | github.com/hashicorp/errwrap v1.0.0 // indirect
58 | github.com/hashicorp/go-multierror v1.1.0 // indirect
59 | github.com/imdario/mergo v0.3.12 // indirect
60 | github.com/jackc/chunkreader/v2 v2.0.1 // indirect
61 | github.com/jackc/pgio v1.0.0 // indirect
62 | github.com/jackc/pgpassfile v1.0.0 // indirect
63 | github.com/jackc/pgproto3/v2 v2.1.1 // indirect
64 | github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
65 | github.com/jackc/pgtype v1.8.1 // indirect
66 | github.com/joho/godotenv v1.3.0 // indirect
67 | github.com/json-iterator/go v1.1.12 // indirect
68 | github.com/klauspost/compress v1.12.3 // indirect
69 | github.com/lib/pq v1.10.2 // indirect
70 | github.com/mailgun/mailgun-go/v4 v4.5.3 // indirect
71 | github.com/mitchellh/mapstructure v1.4.1 // indirect
72 | github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect
73 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
74 | github.com/modern-go/reflect2 v1.0.2 // indirect
75 | github.com/opencontainers/go-digest v1.0.0 // indirect
76 | github.com/opencontainers/image-spec v1.0.1 // indirect
77 | github.com/opencontainers/runc v1.0.2 // indirect
78 | github.com/pkg/errors v0.9.1 // indirect
79 | github.com/robfig/cron/v3 v3.0.1 // indirect
80 | github.com/sendgrid/rest v2.6.5+incompatible // indirect
81 | github.com/sendgrid/sendgrid-go v3.10.1+incompatible // indirect
82 | github.com/sirupsen/logrus v1.8.1 // indirect
83 | github.com/vanng822/css v1.0.1 // indirect
84 | github.com/vanng822/go-premailer v1.20.1 // indirect
85 | github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
86 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
87 | github.com/xeipuuv/gojsonschema v1.2.0 // indirect
88 | github.com/xhit/go-simple-mail/v2 v2.10.0 // indirect
89 | go.opencensus.io v0.22.5 // indirect
90 | golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b // indirect
91 | golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect
92 | golang.org/x/text v0.3.6 // indirect
93 | google.golang.org/protobuf v1.26.0 // indirect
94 | gopkg.in/yaml.v2 v2.4.0 // indirect
95 | )
96 |
--------------------------------------------------------------------------------
/cmd/cli/templates/data/token.go.txt:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "crypto/sha256"
5 | "encoding/base32"
6 | "errors"
7 | "math/rand"
8 | "net/http"
9 | "strings"
10 | "time"
11 |
12 | up "github.com/upper/db/v4"
13 | )
14 |
15 | type Token struct {
16 | ID int `db:"id,omitempty" json:"id"`
17 | UserID int `db:"user_id" json:"user_id"`
18 | FirstName string `db:"first_name" json:"first_name"`
19 | Email string `db:"email" json:"email"`
20 | PlainText string `db:"token" json:"token"`
21 | Hash []byte `db:"token_hash" json:"-"`
22 | CreatedAt time.Time `db:"created_at" json:"created_at"`
23 | UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
24 | Expires time.Time `db:"expiry" json:"expiry"`
25 | }
26 |
27 | func (t *Token) Table() string {
28 | return "tokens"
29 | }
30 |
31 | func (t *Token) GetUserForToken(token string) (*User, error) {
32 | var u User
33 | var theToken Token
34 |
35 | collection := upper.Collection(t.Table())
36 | res := collection.Find(up.Cond{"token": token})
37 | err := res.One(&theToken)
38 | if err != nil {
39 | return nil, err
40 | }
41 |
42 | collection = upper.Collection("users")
43 | res = collection.Find(up.Cond{"id": theToken.UserID})
44 | err = res.One(&u)
45 | if err != nil {
46 | return nil, err
47 | }
48 |
49 | u.Token = theToken
50 |
51 | return &u, nil
52 | }
53 |
54 | func (t *Token) GetTokensForUser(id int) ([]*Token, error) {
55 | var tokens []*Token
56 | collection := upper.Collection(t.Table())
57 | res := collection.Find(up.Cond{"user_id": id})
58 | err := res.All(&tokens)
59 | if err != nil {
60 | return nil, err
61 | }
62 |
63 | return tokens, nil
64 | }
65 |
66 | func (t *Token) Get(id int) (*Token, error) {
67 | var token Token
68 | collection := upper.Collection(t.Table())
69 | res := collection.Find(up.Cond{"id": id})
70 | err := res.One(&token)
71 | if err != nil {
72 | return nil, err
73 | }
74 |
75 | return &token, nil
76 | }
77 |
78 | func (t *Token) GetByToken(plainText string) (*Token, error) {
79 | var token Token
80 | collection := upper.Collection(t.Table())
81 | res := collection.Find(up.Cond{"token": plainText})
82 | err := res.One(&token)
83 | if err != nil {
84 | return nil, err
85 | }
86 |
87 | return &token, nil
88 | }
89 |
90 | func (t *Token) Delete(id int) error {
91 | collection := upper.Collection(t.Table())
92 | res := collection.Find(id)
93 | err := res.Delete()
94 | if err != nil {
95 | return err
96 | }
97 |
98 | return nil
99 | }
100 |
101 | func (t *Token) DeleteByToken(plainText string) error {
102 | collection := upper.Collection(t.Table())
103 | res := collection.Find(up.Cond{"token": plainText})
104 | err := res.Delete()
105 | if err != nil {
106 | return err
107 | }
108 |
109 | return nil
110 | }
111 |
112 | func (t *Token) Insert(token Token, u User) error {
113 | collection := upper.Collection(t.Table())
114 |
115 | // delete existing tokens
116 | res := collection.Find(up.Cond{"user_id": u.ID})
117 | err := res.Delete()
118 | if err != nil {
119 | return err
120 | }
121 |
122 | token.CreatedAt = time.Now()
123 | token.UpdatedAt = time.Now()
124 | token.FirstName = u.FirstName
125 | token.Email = u.Email
126 |
127 | _, err = collection.Insert(token)
128 | if err != nil {
129 | return err
130 | }
131 |
132 | return nil
133 | }
134 |
135 | func (t *Token) GenerateToken(userID int, ttl time.Duration) (*Token, error) {
136 | token := &Token{
137 | UserID: userID,
138 | Expires: time.Now().Add(ttl),
139 | }
140 |
141 | randomBytes := make([]byte, 16)
142 | _, err := rand.Read(randomBytes)
143 | if err != nil {
144 | return nil, err
145 | }
146 |
147 | token.PlainText = base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(randomBytes)
148 | hash := sha256.Sum256([]byte(token.PlainText))
149 | token.Hash = hash[:]
150 |
151 | return token, nil
152 | }
153 |
154 | func (t *Token) AuthenticateToken(r *http.Request) (*User, error) {
155 | authorizationHeader := r.Header.Get("Authorization")
156 | if authorizationHeader == "" {
157 | return nil, errors.New("no authorization header received")
158 | }
159 |
160 | headerParts := strings.Split(authorizationHeader, " ")
161 | if len(headerParts) != 2 || headerParts[0] != "Bearer" {
162 | return nil, errors.New("no authorization header received")
163 | }
164 |
165 | token := headerParts[1]
166 |
167 | if len(token) != 26 {
168 | return nil, errors.New("token wrong size")
169 | }
170 |
171 | tkn, err := t.GetByToken(token)
172 | if err != nil {
173 | return nil, errors.New("no matching token found")
174 | }
175 |
176 | if tkn.Expires.Before(time.Now()) {
177 | return nil, errors.New("expired token")
178 | }
179 |
180 | user, err := t.GetUserForToken(token)
181 | if err != nil {
182 | return nil, errors.New("no matching user found")
183 | }
184 |
185 | return user, nil
186 | }
187 |
188 | func (t *Token) ValidToken(token string) (bool, error) {
189 | user, err := t.GetUserForToken(token)
190 | if err != nil {
191 | return false, errors.New("no matching user found")
192 | }
193 |
194 | if user.Token.PlainText == "" {
195 | return false, errors.New("no matching token found")
196 | }
197 |
198 | if user.Token.Expires.Before(time.Now()) {
199 | return false, errors.New("expired token")
200 | }
201 |
202 | return true, nil
203 | }
204 |
--------------------------------------------------------------------------------
/cmd/cli/templates/data/user.go.txt:
--------------------------------------------------------------------------------
1 | package data
2 |
3 | import (
4 | "errors"
5 | "time"
6 |
7 | up "github.com/upper/db/v4"
8 | "golang.org/x/crypto/bcrypt"
9 | )
10 |
11 | // User is the type for a user
12 | type User struct {
13 | ID int `db:"id,omitempty"`
14 | FirstName string `db:"first_name"`
15 | LastName string `db:"last_name"`
16 | Email string `db:"email"`
17 | Active int `db:"user_active"`
18 | Password string `db:"password"`
19 | CreatedAt time.Time `db:"created_at"`
20 | UpdatedAt time.Time `db:"updated_at"`
21 | Token Token `db:"-"`
22 | }
23 |
24 | // Table returns the table name associated with this model in the database
25 | func (u *User) Table() string {
26 | return "users"
27 | }
28 |
29 | // GetAll returns a slice of all users
30 | func (u *User) GetAll() ([]*User, error) {
31 | collection := upper.Collection(u.Table())
32 |
33 | var all []*User
34 |
35 | res := collection.Find().OrderBy("last_name")
36 | err := res.All(&all)
37 | if err != nil {
38 | return nil, err
39 | }
40 |
41 | return all, nil
42 | }
43 |
44 | // GetByEmail gets one user, by email
45 | func (u *User) GetByEmail(email string) (*User, error) {
46 | var theUser User
47 | collection := upper.Collection(u.Table())
48 | res := collection.Find(up.Cond{"email =": email})
49 | err := res.One(&theUser)
50 | if err != nil {
51 | return nil, err
52 | }
53 |
54 | var token Token
55 | collection = upper.Collection(token.Table())
56 | res = collection.Find(up.Cond{"user_id =": theUser.ID, "expiry >": time.Now()}).OrderBy("created_at desc")
57 | err = res.One(&token)
58 | if err != nil {
59 | if err != up.ErrNilRecord && err != up.ErrNoMoreRows {
60 | return nil, err
61 | }
62 | }
63 |
64 | theUser.Token = token
65 |
66 | return &theUser, nil
67 | }
68 |
69 | // Get gets one user by id
70 | func (u *User) Get(id int) (*User, error) {
71 | var theUser User
72 | collection := upper.Collection(u.Table())
73 | res := collection.Find(up.Cond{"id =": id})
74 |
75 | err := res.One(&theUser)
76 | if err != nil {
77 | return nil, err
78 | }
79 |
80 | var token Token
81 | collection = upper.Collection(token.Table())
82 | res = collection.Find(up.Cond{"user_id =": theUser.ID, "expiry >": time.Now()}).OrderBy("created_at desc")
83 | err = res.One(&token)
84 | if err != nil {
85 | if err != up.ErrNilRecord && err != up.ErrNoMoreRows {
86 | return nil, err
87 | }
88 | }
89 |
90 | theUser.Token = token
91 |
92 | return &theUser, nil
93 | }
94 |
95 | // Update updates a user record in the database
96 | func (u *User) Update(theUser User) error {
97 | theUser.UpdatedAt = time.Now()
98 | collection := upper.Collection(u.Table())
99 | res := collection.Find(theUser.ID)
100 | err := res.Update(&theUser)
101 | if err != nil {
102 | return err
103 | }
104 | return nil
105 | }
106 |
107 | // Delete deletes a user by id
108 | func (u *User) Delete(id int) error {
109 | collection := upper.Collection(u.Table())
110 | res := collection.Find(id)
111 | err := res.Delete()
112 | if err != nil {
113 | return err
114 | }
115 | return nil
116 |
117 | }
118 |
119 | // Insert inserts a new user, and returns the newly inserted id
120 | func (u *User) Insert(theUser User) (int, error) {
121 | newHash, err := bcrypt.GenerateFromPassword([]byte(theUser.Password), 12)
122 | if err != nil {
123 | return 0, err
124 | }
125 |
126 | theUser.CreatedAt = time.Now()
127 | theUser.UpdatedAt = time.Now()
128 | theUser.Password = string(newHash)
129 |
130 | collection := upper.Collection(u.Table())
131 | res, err := collection.Insert(theUser)
132 | if err != nil {
133 | return 0, err
134 | }
135 |
136 | id := getInsertID(res.ID())
137 |
138 | return id, nil
139 | }
140 |
141 | // ResetPassword resets a users's password, by id, using supplied password
142 | func (u *User) ResetPassword(id int, password string) error {
143 | newHash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
144 | if err != nil {
145 | return err
146 | }
147 |
148 | theUser, err := u.Get(id)
149 | if err != nil {
150 | return err
151 | }
152 |
153 | u.Password = string(newHash)
154 |
155 | err = theUser.Update(*u)
156 | if err != nil {
157 | return err
158 | }
159 |
160 | return nil
161 | }
162 |
163 | // PasswordMatches verifies a supplied password against the hash stored in the database.
164 | // It returns true if valid, and false if the password does not match, or if there is an
165 | // error. Note that an error is only returned if something goes wrong (since an invalid password
166 | // is not an error -- it's just the wrong password))
167 | func (u *User) PasswordMatches(plainText string) (bool, error) {
168 | err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(plainText))
169 | if err != nil {
170 | switch {
171 | case errors.Is(err, bcrypt.ErrMismatchedHashAndPassword):
172 | // invalid password
173 | return false, nil
174 | default:
175 | // some kind of error occurred
176 | return false, err
177 | }
178 | }
179 |
180 | return true, nil
181 | }
182 |
183 | func (u *User) CheckForRememberToken(id int, token string) bool {
184 | var rememberToken RememberToken
185 | rt := RememberToken{}
186 | collection := upper.Collection(rt.Table())
187 | res := collection.Find(up.Cond{"user_id": id, "remember_token": token})
188 | err := res.One(&rememberToken)
189 | return err == nil
190 | }
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/dominic-wassef/ghostly
2 |
3 | go 1.17
4 |
5 | require (
6 | github.com/CloudyKit/jet/v6 v6.1.0
7 | github.com/ainsleyclark/go-mail v1.0.3
8 | github.com/alexedwards/scs/mysqlstore v0.0.0-20210904201103-9ffa4cfa9323
9 | github.com/alexedwards/scs/postgresstore v0.0.0-20210904201103-9ffa4cfa9323
10 | github.com/alexedwards/scs/redisstore v0.0.0-20210904201103-9ffa4cfa9323
11 | github.com/alexedwards/scs/v2 v2.4.0
12 | github.com/alicebob/miniredis/v2 v2.15.1
13 | github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d
14 | github.com/bwmarrin/go-alone v0.0.0-20190806015146-742bb55d1631
15 | github.com/dgraph-io/badger/v3 v3.2103.1
16 | github.com/fatih/color v1.12.0
17 | github.com/gertd/go-pluralize v0.1.7
18 | github.com/go-chi/chi/v5 v5.0.4
19 | github.com/go-git/go-git/v5 v5.4.2
20 | github.com/go-sql-driver/mysql v1.5.0
21 | github.com/golang-migrate/migrate/v4 v4.14.1
22 | github.com/gomodule/redigo v1.8.5
23 | github.com/iancoleman/strcase v0.2.0
24 | github.com/jackc/pgconn v1.10.0
25 | github.com/jackc/pgx/v4 v4.13.0
26 | github.com/joho/godotenv v1.3.0
27 | github.com/justinas/nosurf v1.1.1
28 | github.com/minio/minio-go/v7 v7.0.43
29 | github.com/ory/dockertest/v3 v3.8.0
30 | github.com/robfig/cron/v3 v3.0.1
31 | github.com/vanng822/go-premailer v1.20.1
32 | github.com/xhit/go-simple-mail/v2 v2.10.0
33 | )
34 |
35 | require (
36 | github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect
37 | github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect
38 | github.com/Microsoft/go-winio v0.5.0 // indirect
39 | github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect
40 | github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7 // indirect
41 | github.com/PuerkitoBio/goquery v1.5.1 // indirect
42 | github.com/SparkPost/gosparkpost v0.2.0 // indirect
43 | github.com/acomagu/bufpipe v1.0.3 // indirect
44 | github.com/alicebob/gopher-json v0.0.0-20200520072559-a9ecdc9d1d3a // indirect
45 | github.com/andybalholm/cascadia v1.1.0 // indirect
46 | github.com/cenkalti/backoff/v4 v4.1.1 // indirect
47 | github.com/cespare/xxhash v1.1.0 // indirect
48 | github.com/cespare/xxhash/v2 v2.1.1 // indirect
49 | github.com/containerd/continuity v0.2.0 // indirect
50 | github.com/dgraph-io/ristretto v0.1.0 // indirect
51 | github.com/docker/cli v20.10.8+incompatible // indirect
52 | github.com/docker/docker v20.10.7+incompatible // indirect
53 | github.com/docker/go-connections v0.4.0 // indirect
54 | github.com/docker/go-units v0.4.0 // indirect
55 | github.com/dustin/go-humanize v1.0.0 // indirect
56 | github.com/emirpasic/gods v1.12.0 // indirect
57 | github.com/gabriel-vasile/mimetype v1.3.1 // indirect
58 | github.com/go-git/gcfg v1.5.0 // indirect
59 | github.com/go-git/go-billy/v5 v5.3.1 // indirect
60 | github.com/gogo/protobuf v1.3.2 // indirect
61 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect
62 | github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect
63 | github.com/golang/protobuf v1.5.0 // indirect
64 | github.com/golang/snappy v0.0.3 // indirect
65 | github.com/google/flatbuffers v1.12.0 // indirect
66 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
67 | github.com/google/uuid v1.3.0 // indirect
68 | github.com/gorilla/css v1.0.0 // indirect
69 | github.com/gorilla/mux v1.8.0 // indirect
70 | github.com/hashicorp/errwrap v1.0.0 // indirect
71 | github.com/hashicorp/go-multierror v1.1.0 // indirect
72 | github.com/imdario/mergo v0.3.12 // indirect
73 | github.com/jackc/chunkreader/v2 v2.0.1 // indirect
74 | github.com/jackc/pgio v1.0.0 // indirect
75 | github.com/jackc/pgpassfile v1.0.0 // indirect
76 | github.com/jackc/pgproto3/v2 v2.1.1 // indirect
77 | github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
78 | github.com/jackc/pgtype v1.8.1 // indirect
79 | github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
80 | github.com/json-iterator/go v1.1.12 // indirect
81 | github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 // indirect
82 | github.com/klauspost/compress v1.15.9 // indirect
83 | github.com/klauspost/cpuid/v2 v2.1.0 // indirect
84 | github.com/lib/pq v1.10.2 // indirect
85 | github.com/mailgun/mailgun-go/v4 v4.5.3 // indirect
86 | github.com/mattn/go-colorable v0.1.8 // indirect
87 | github.com/mattn/go-isatty v0.0.12 // indirect
88 | github.com/minio/md5-simd v1.1.2 // indirect
89 | github.com/minio/sha256-simd v1.0.0 // indirect
90 | github.com/mitchellh/go-homedir v1.1.0 // indirect
91 | github.com/mitchellh/mapstructure v1.4.1 // indirect
92 | github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect
93 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
94 | github.com/modern-go/reflect2 v1.0.2 // indirect
95 | github.com/opencontainers/go-digest v1.0.0 // indirect
96 | github.com/opencontainers/image-spec v1.0.1 // indirect
97 | github.com/opencontainers/runc v1.0.2 // indirect
98 | github.com/pkg/errors v0.9.1 // indirect
99 | github.com/rs/xid v1.4.0 // indirect
100 | github.com/sendgrid/rest v2.6.5+incompatible // indirect
101 | github.com/sendgrid/sendgrid-go v3.10.1+incompatible // indirect
102 | github.com/sergi/go-diff v1.1.0 // indirect
103 | github.com/sirupsen/logrus v1.9.0 // indirect
104 | github.com/vanng822/css v1.0.1 // indirect
105 | github.com/xanzy/ssh-agent v0.3.0 // indirect
106 | github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
107 | github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
108 | github.com/xeipuuv/gojsonschema v1.2.0 // indirect
109 | github.com/yuin/gopher-lua v0.0.0-20200816102855-ee81675732da // indirect
110 | go.opencensus.io v0.22.5 // indirect
111 | golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // indirect
112 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b // indirect
113 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
114 | golang.org/x/text v0.3.7 // indirect
115 | google.golang.org/protobuf v1.26.0 // indirect
116 | gopkg.in/ini.v1 v1.66.6 // indirect
117 | gopkg.in/warnings.v0 v0.1.2 // indirect
118 | gopkg.in/yaml.v2 v2.3.0 // indirect
119 | )
120 |
--------------------------------------------------------------------------------
/cmd/cli/templates/handlers/auth-handlers.go.txt:
--------------------------------------------------------------------------------
1 | package handlers
2 |
3 | import (
4 | "crypto/sha256"
5 | "encoding/base64"
6 | "fmt"
7 | "myapp/data"
8 | "net/http"
9 | "time"
10 |
11 | "github.com/CloudyKit/jet/v6"
12 | "github.com/dominic-wassef/ghostly/mailer"
13 | "github.com/dominic-wassef/ghostly/urlsigner"
14 | )
15 |
16 | // UserLogin displays the login page
17 | func (h *Handlers) UserLogin(w http.ResponseWriter, r *http.Request) {
18 | err := h.App.Render.Page(w, r, "login", nil, nil)
19 | if err != nil {
20 | h.App.ErrorLog.Println(err)
21 | }
22 | }
23 |
24 | // PostUserLogin attempts to log a user in
25 | func (h *Handlers) PostUserLogin(w http.ResponseWriter, r *http.Request) {
26 | err := r.ParseForm()
27 | if err != nil {
28 | w.Write([]byte(err.Error()))
29 | return
30 | }
31 |
32 | email := r.Form.Get("email")
33 | password := r.Form.Get("password")
34 |
35 | user, err := h.Models.Users.GetByEmail(email)
36 | if err != nil {
37 | w.Write([]byte(err.Error()))
38 | return
39 | }
40 |
41 | matches, err := user.PasswordMatches(password)
42 | if err != nil {
43 | w.Write([]byte("Error validating password"))
44 | return
45 | }
46 |
47 | if !matches {
48 | w.Write([]byte("Invalid password!"))
49 | return
50 | }
51 |
52 | // did the user check remember me?
53 | if r.Form.Get("remember") == "remember" {
54 | randomString := h.randomString(12)
55 | hasher := sha256.New()
56 | _, err := hasher.Write([]byte(randomString))
57 | if err != nil {
58 | h.App.ErrorStatus(w, http.StatusBadRequest)
59 | return
60 | }
61 |
62 | sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
63 | rm := data.RememberToken{}
64 | err = rm.InsertToken(user.ID, sha)
65 | if err != nil {
66 | h.App.ErrorStatus(w, http.StatusBadRequest)
67 | return
68 | }
69 |
70 | // set a cookie
71 | expire := time.Now().Add(365 * 24 * 60 * 60 * time.Second)
72 | cookie := http.Cookie{
73 | Name: fmt.Sprintf("_%s_remember", h.App.AppName),
74 | Value: fmt.Sprintf("%d|%s", user.ID, sha),
75 | Path: "/",
76 | Expires: expire,
77 | HttpOnly: true,
78 | Domain: h.App.Session.Cookie.Domain,
79 | MaxAge: 315350000,
80 | Secure: h.App.Session.Cookie.Secure,
81 | SameSite: http.SameSiteStrictMode,
82 | }
83 | http.SetCookie(w, &cookie)
84 | // save hash in session
85 | h.App.Session.Put(r.Context(), "remember_token", sha)
86 | }
87 |
88 | h.App.Session.Put(r.Context(), "userID", user.ID)
89 |
90 | http.Redirect(w, r, "/", http.StatusSeeOther)
91 |
92 | }
93 |
94 | // Logout logs the user out, removes any remember me cookie, and deletes
95 | // remember token from the database, if it exists
96 | func (h *Handlers) Logout(w http.ResponseWriter, r *http.Request) {
97 | // delete the remember token if it exists
98 | if h.App.Session.Exists(r.Context(), "remember_token") {
99 | rt := data.RememberToken{}
100 | _ = rt.Delete(h.App.Session.GetString(r.Context(), "remember_token"))
101 | }
102 |
103 | // delete cookie
104 | newCookie := http.Cookie{
105 | Name: fmt.Sprintf("_%s_remember", h.App.AppName),
106 | Value: "",
107 | Path: "/",
108 | Expires: time.Now().Add(-100 * time.Hour),
109 | HttpOnly: true,
110 | Domain: h.App.Session.Cookie.Domain,
111 | MaxAge: -1,
112 | Secure: h.App.Session.Cookie.Secure,
113 | SameSite: http.SameSiteStrictMode,
114 | }
115 | http.SetCookie(w, &newCookie)
116 |
117 | h.App.Session.RenewToken(r.Context())
118 | h.App.Session.Remove(r.Context(), "userID")
119 | h.App.Session.Remove(r.Context(), "remember_token")
120 | h.App.Session.Destroy(r.Context())
121 | h.App.Session.RenewToken(r.Context())
122 |
123 | http.Redirect(w, r, "/users/login", http.StatusSeeOther)
124 | }
125 |
126 | func (h *Handlers) Forgot(w http.ResponseWriter, r *http.Request) {
127 | err := h.render(w, r, "forgot", nil, nil)
128 | if err != nil {
129 | h.App.ErrorLog.Println("Error rendering: ", err)
130 | h.App.Error500(w, r)
131 | }
132 | }
133 |
134 | // PostForgot looks up a user by email, and if the user is found, generates
135 | // an email with a singed link to the reset password form
136 | func (h *Handlers) PostForgot(w http.ResponseWriter, r *http.Request) {
137 | // parse form
138 | err := r.ParseForm()
139 | if err != nil {
140 | h.App.ErrorStatus(w, http.StatusBadRequest)
141 | return
142 | }
143 |
144 | // verify that supplied email exists
145 | var u *data.User
146 | email := r.Form.Get("email")
147 | u, err = u.GetByEmail(email)
148 | if err != nil {
149 | h.App.ErrorStatus(w, http.StatusBadRequest)
150 | return
151 | }
152 |
153 | // create a link to password reset form
154 | link := fmt.Sprintf("%s/users/reset-password?email=%s", h.App.Server.URL, email)
155 |
156 | // sign the link
157 | sign := urlsigner.Signer{
158 | Secret: []byte(h.App.EncryptionKey),
159 | }
160 |
161 | signedLink := sign.GenerateTokenFromString(link)
162 | h.App.InfoLog.Println("Signed link is", signedLink)
163 |
164 | // email the message
165 | var data struct {
166 | Link string
167 | }
168 | data.Link = signedLink
169 |
170 | msg := mailer.Message{
171 | To: u.Email,
172 | Subject: "Password reset",
173 | Template: "password-reset",
174 | Data: data,
175 | From: "admin@example.com",
176 | }
177 |
178 | h.App.Mail.Jobs <- msg
179 | res := <-h.App.Mail.Results
180 | if res.Error != nil {
181 | h.App.ErrorStatus(w, http.StatusBadRequest)
182 | return
183 | }
184 |
185 | // redirect the user
186 | http.Redirect(w, r, "/users/login", http.StatusSeeOther)
187 | }
188 |
189 | // ResetPasswordForm validates a signed url, and displays the password reset form, if appropriate
190 | func (h *Handlers) ResetPasswordForm(w http.ResponseWriter, r *http.Request) {
191 | // get form values
192 | email := r.URL.Query().Get("email")
193 | theURL := r.RequestURI
194 | testURL := fmt.Sprintf("%s%s", h.App.Server.URL, theURL)
195 |
196 | // validate the url
197 | signer := urlsigner.Signer{
198 | Secret: []byte(h.App.EncryptionKey),
199 | }
200 |
201 | valid := signer.VerifyToken(testURL)
202 | if !valid {
203 | h.App.ErrorLog.Print("Invalid url")
204 | h.App.ErrorUnauthorized(w, r)
205 | return
206 | }
207 |
208 | /// make sure it's not expired
209 | expired := signer.Expired(testURL, 60)
210 | if expired {
211 | h.App.ErrorLog.Print("Link expired")
212 | h.App.ErrorUnauthorized(w, r)
213 | return
214 | }
215 |
216 | // display form
217 | encryptedEmail, _ := h.encrypt(email)
218 |
219 | vars := make(jet.VarMap)
220 | vars.Set("email", encryptedEmail)
221 |
222 | err := h.render(w, r, "reset-password", vars, nil)
223 | if err != nil {
224 | return
225 | }
226 | }
227 |
228 | func (h *Handlers) PostResetPassword(w http.ResponseWriter, r *http.Request) {
229 | // parse the form
230 | err := r.ParseForm()
231 | if err != nil {
232 | h.App.Error500(w, r)
233 | return
234 | }
235 |
236 | // get and decrypt the email
237 | email, err := h.decrypt(r.Form.Get("email"))
238 | if err != nil {
239 | h.App.Error500(w, r)
240 | return
241 | }
242 |
243 | // get the user
244 | var u data.User
245 | user, err := u.GetByEmail(email)
246 | if err != nil {
247 | h.App.Error500(w, r)
248 | return
249 | }
250 |
251 | // reset the password
252 | err = user.ResetPassword(user.ID, r.Form.Get("password"))
253 | if err != nil {
254 | h.App.Error500(w, r)
255 | return
256 | }
257 |
258 | // redirect
259 | h.App.Session.Put(r.Context(), "flash", "Password reset. You can now log in.")
260 | http.Redirect(w, r, "/users/login", http.StatusSeeOther)
261 | }
--------------------------------------------------------------------------------
/mailer/mail.go:
--------------------------------------------------------------------------------
1 | package mailer
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "html/template"
7 | "io/ioutil"
8 | "path/filepath"
9 | "time"
10 |
11 | apimail "github.com/ainsleyclark/go-mail"
12 | "github.com/vanng822/go-premailer/premailer"
13 | mail "github.com/xhit/go-simple-mail/v2"
14 | )
15 |
16 | // Mail holds the information necessary to connect to an SMTP server
17 | type Mail struct {
18 | Domain string
19 | Templates string
20 | Host string
21 | Port int
22 | Username string
23 | Password string
24 | Encryption string
25 | FromAddress string
26 | FromName string
27 | Jobs chan Message
28 | Results chan Result
29 | API string
30 | APIKey string
31 | APIUrl string
32 | }
33 |
34 | // Message is the type for an email message
35 | type Message struct {
36 | From string
37 | FromName string
38 | To string
39 | Subject string
40 | Template string
41 | Attachments []string
42 | Data interface{}
43 | }
44 |
45 | // Result contains information regarding the status of the sent email message
46 | type Result struct {
47 | Success bool
48 | Error error
49 | }
50 |
51 | // ListenForMail listens to the mail channel and sends mail
52 | // when it receives a payload. It runs continually in the background,
53 | // and sends error/success messages back on the Results channel.
54 | // Note that if api and api key are set, it will prefer using
55 | // an api to send mail
56 | func (m *Mail) ListenForMail() {
57 | for {
58 | msg := <-m.Jobs
59 | err := m.Send(msg)
60 | if err != nil {
61 | m.Results <- Result{false, err}
62 | } else {
63 | m.Results <- Result{true, nil}
64 | }
65 | }
66 | }
67 |
68 | // Send sends an email message using correct method. If API values are set,
69 | // it will send using the appropriate api; otherwise, it sends via smtp
70 | func (m *Mail) Send(msg Message) error {
71 | if len(m.API) > 0 && len(m.APIKey) > 0 && len(m.APIUrl) > 0 && m.API != "smtp" {
72 | return m.ChooseAPI(msg)
73 | }
74 | return m.SendSMTPMessage(msg)
75 | }
76 |
77 | // ChooseAPI chooses api to use (specified in .env)
78 | func (m *Mail) ChooseAPI(msg Message) error {
79 | switch m.API {
80 | case "mailgun", "sparkpost", "sendgrid":
81 | return m.SendUsingAPI(msg, m.API)
82 | default:
83 | return fmt.Errorf("unknown api %s; only mailgun, sparkpost or sendgrid accepted", m.API)
84 | }
85 | }
86 |
87 | // SendUsingAPI sends a message using the appropriate API. It can be called directly, if necessary.
88 | // transport can be one of sparkpost, sendgrid, or mailgun
89 | func (m *Mail) SendUsingAPI(msg Message, transport string) error {
90 | if msg.From == "" {
91 | msg.From = m.FromAddress
92 | }
93 |
94 | if msg.FromName == "" {
95 | msg.FromName = m.FromName
96 | }
97 |
98 | cfg := apimail.Config{
99 | URL: m.APIUrl,
100 | APIKey: m.APIKey,
101 | Domain: m.Domain,
102 | FromAddress: msg.From,
103 | FromName: msg.FromName,
104 | }
105 |
106 | driver, err := apimail.NewClient(transport, cfg)
107 | if err != nil {
108 | return err
109 | }
110 |
111 | formattedMessage, err := m.buildHTMLMessage(msg)
112 | if err != nil {
113 | return err
114 | }
115 |
116 | plainMessage, err := m.buildPlainTextMessage(msg)
117 | if err != nil {
118 | return err
119 | }
120 |
121 | tx := &apimail.Transmission{
122 | Recipients: []string{msg.To},
123 | Subject: msg.Subject,
124 | HTML: formattedMessage,
125 | PlainText: plainMessage,
126 | }
127 |
128 | // add attachments
129 | err = m.addAPIAttachments(msg, tx)
130 | if err != nil {
131 | return err
132 | }
133 |
134 | _, err = driver.Send(tx)
135 | if err != nil {
136 | return err
137 | }
138 |
139 | return nil
140 | }
141 |
142 | // addAPIAttachments adds attachments, if any, to mail being sent via api
143 | func (m *Mail) addAPIAttachments(msg Message, tx *apimail.Transmission) error {
144 | if len(msg.Attachments) > 0 {
145 | var attachments []apimail.Attachment
146 |
147 | for _, x := range msg.Attachments {
148 | var attach apimail.Attachment
149 | content, err := ioutil.ReadFile(x)
150 | if err != nil {
151 | return err
152 | }
153 |
154 | fileName := filepath.Base(x)
155 | attach.Bytes = content
156 | attach.Filename = fileName
157 | attachments = append(attachments, attach)
158 | }
159 |
160 | tx.Attachments = attachments
161 | }
162 |
163 | return nil
164 | }
165 |
166 | // SendSMTPMessage builds and sends an email message using SMTP. This is called by ListenForMail,
167 | // and can also be called directly when necessary
168 | func (m *Mail) SendSMTPMessage(msg Message) error {
169 | formattedMessage, err := m.buildHTMLMessage(msg)
170 | if err != nil {
171 | return err
172 | }
173 |
174 | plainMessage, err := m.buildPlainTextMessage(msg)
175 | if err != nil {
176 | return err
177 | }
178 |
179 | server := mail.NewSMTPClient()
180 | server.Host = m.Host
181 | server.Port = m.Port
182 | server.Username = m.Username
183 | server.Password = m.Password
184 | server.Encryption = m.getEncryption(m.Encryption)
185 | server.KeepAlive = false
186 | server.ConnectTimeout = 10 * time.Second
187 | server.SendTimeout = 10 * time.Second
188 |
189 | smtpClient, err := server.Connect()
190 | if err != nil {
191 | return err
192 | }
193 |
194 | email := mail.NewMSG()
195 | email.SetFrom(msg.From).
196 | AddTo(msg.To).
197 | SetSubject(msg.Subject)
198 |
199 | email.SetBody(mail.TextHTML, formattedMessage)
200 | email.AddAlternative(mail.TextPlain, plainMessage)
201 |
202 | if len(msg.Attachments) > 0 {
203 | for _, x := range msg.Attachments {
204 | email.AddAttachment(x)
205 | }
206 | }
207 |
208 | err = email.Send(smtpClient)
209 | if err != nil {
210 | return err
211 | }
212 |
213 | return nil
214 | }
215 |
216 | // getEncryption returns the appropriate encryption type based on a string value
217 | func (m *Mail) getEncryption(e string) mail.Encryption {
218 | switch e {
219 | case "tls":
220 | return mail.EncryptionSTARTTLS
221 | case "ssl":
222 | return mail.EncryptionSSL
223 | case "none":
224 | return mail.EncryptionNone
225 | default:
226 | return mail.EncryptionSTARTTLS
227 | }
228 | }
229 |
230 | // buildHTMLMessage creates the html version of the message
231 | func (m *Mail) buildHTMLMessage(msg Message) (string, error) {
232 | templateToRender := fmt.Sprintf("%s/%s.html.tmpl", m.Templates, msg.Template)
233 |
234 | t, err := template.New("email-html").ParseFiles(templateToRender)
235 | if err != nil {
236 | return "", err
237 | }
238 |
239 | var tpl bytes.Buffer
240 | if err = t.ExecuteTemplate(&tpl, "body", msg.Data); err != nil {
241 | return "", err
242 | }
243 |
244 | formattedMessage := tpl.String()
245 | formattedMessage, err = m.inlineCSS(formattedMessage)
246 | if err != nil {
247 | return "", err
248 | }
249 |
250 | return formattedMessage, nil
251 | }
252 |
253 | // buildPlainTextMessage creates the plaintext version of the message
254 | func (m *Mail) buildPlainTextMessage(msg Message) (string, error) {
255 | templateToRender := fmt.Sprintf("%s/%s.plain.tmpl", m.Templates, msg.Template)
256 |
257 | t, err := template.New("email-html").ParseFiles(templateToRender)
258 | if err != nil {
259 | return "", err
260 | }
261 |
262 | var tpl bytes.Buffer
263 | if err = t.ExecuteTemplate(&tpl, "body", msg.Data); err != nil {
264 | return "", err
265 | }
266 |
267 | plainMessage := tpl.String()
268 |
269 | return plainMessage, nil
270 | }
271 |
272 | // inlineCSS takes html input as a string, and inlines css where possible
273 | func (m *Mail) inlineCSS(s string) (string, error) {
274 | options := premailer.Options{
275 | RemoveClasses: false,
276 | CssToAttributes: false,
277 | KeepBangImportant: true,
278 | }
279 |
280 | prem, err := premailer.NewPremailerFromString(s, &options)
281 | if err != nil {
282 | return "", err
283 | }
284 |
285 | html, err := prem.Transform()
286 | if err != nil {
287 | return "", err
288 | }
289 |
290 | return html, nil
291 | }
292 |
--------------------------------------------------------------------------------
/ghostly.go:
--------------------------------------------------------------------------------
1 | package ghostly
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "net/http"
7 | "os"
8 | "strconv"
9 | "strings"
10 | "time"
11 |
12 | "github.com/CloudyKit/jet/v6"
13 | "github.com/alexedwards/scs/v2"
14 | "github.com/dgraph-io/badger/v3"
15 | "github.com/dominic-wassef/ghostly/cache"
16 | "github.com/dominic-wassef/ghostly/mailer"
17 | "github.com/dominic-wassef/ghostly/render"
18 | "github.com/dominic-wassef/ghostly/session"
19 | "github.com/go-chi/chi/v5"
20 | "github.com/gomodule/redigo/redis"
21 | "github.com/joho/godotenv"
22 | "github.com/robfig/cron/v3"
23 | )
24 |
25 | const version = "1.0.0"
26 |
27 | var myRedisCache *cache.RedisCache
28 | var myBadgerCache *cache.BadgerCache
29 | var redisPool *redis.Pool
30 | var badgerConn *badger.DB
31 |
32 | // Ghostly is the overall type for the Ghostly package. Members that are exported in this type
33 | // are available to any application that uses it.
34 | type Ghostly struct {
35 | AppName string
36 | Debug bool
37 | Version string
38 | ErrorLog *log.Logger
39 | InfoLog *log.Logger
40 | RootPath string
41 | Routes *chi.Mux
42 | Render *render.Render
43 | Session *scs.SessionManager
44 | DB Database
45 | JetViews *jet.Set
46 | config config
47 | EncryptionKey string
48 | Cache cache.Cache
49 | Scheduler *cron.Cron
50 | Mail mailer.Mail
51 | Server Server
52 | }
53 |
54 | type Server struct {
55 | ServerName string
56 | Port string
57 | Secure bool
58 | URL string
59 | }
60 |
61 | type config struct {
62 | port string
63 | renderer string
64 | cookie cookieConfig
65 | sessionType string
66 | database databaseConfig
67 | redis redisConfig
68 | }
69 |
70 | // New reads the .env file, creates our application config, populates the Ghostly type with settings
71 | // based on .env values, and creates necessary folders and files if they don't exist
72 | func (g *Ghostly) New(rootPath string) error {
73 | pathConfig := initPaths{
74 | rootPath: rootPath,
75 | folderNames: []string{"handlers", "migrations", "views", "mail", "data", "public", "tmp", "logs", "middleware"},
76 | }
77 |
78 | err := g.Init(pathConfig)
79 | if err != nil {
80 | return err
81 | }
82 |
83 | err = g.checkDotEnv(rootPath)
84 | if err != nil {
85 | return err
86 | }
87 |
88 | // read .env
89 | err = godotenv.Load(rootPath + "/.env")
90 | if err != nil {
91 | return err
92 | }
93 |
94 | // create loggers
95 | infoLog, errorLog := g.startLoggers()
96 |
97 | // connect to database
98 | if os.Getenv("DATABASE_TYPE") != "" {
99 | db, err := g.OpenDB(os.Getenv("DATABASE_TYPE"), g.BuildDSN())
100 | if err != nil {
101 | errorLog.Println(err)
102 | os.Exit(1)
103 | }
104 | g.DB = Database{
105 | DataType: os.Getenv("DATABASE_TYPE"),
106 | Pool: db,
107 | }
108 | }
109 |
110 | scheduler := cron.New()
111 | g.Scheduler = scheduler
112 |
113 | if os.Getenv("CACHE") == "redis" || os.Getenv("SESSION_TYPE") == "redis" {
114 | myRedisCache = g.createClientRedisCache()
115 | g.Cache = myRedisCache
116 | redisPool = myRedisCache.Conn
117 | }
118 |
119 | if os.Getenv("CACHE") == "badger" {
120 | myBadgerCache = g.createClientBadgerCache()
121 | g.Cache = myBadgerCache
122 | badgerConn = myBadgerCache.Conn
123 |
124 | _, err = g.Scheduler.AddFunc("@daily", func() {
125 | _ = myBadgerCache.Conn.RunValueLogGC(0.7)
126 | })
127 | if err != nil {
128 | return err
129 | }
130 | }
131 |
132 | g.InfoLog = infoLog
133 | g.ErrorLog = errorLog
134 | g.Debug, _ = strconv.ParseBool(os.Getenv("DEBUG"))
135 | g.Version = version
136 | g.RootPath = rootPath
137 | g.Mail = g.createMailer()
138 | g.Routes = g.routes().(*chi.Mux)
139 |
140 | g.config = config{
141 | port: os.Getenv("PORT"),
142 | renderer: os.Getenv("RENDERER"),
143 | cookie: cookieConfig{
144 | name: os.Getenv("COOKIE_NAME"),
145 | lifetime: os.Getenv("COOKIE_LIFETIME"),
146 | persist: os.Getenv("COOKIE_PERSISTS"),
147 | secure: os.Getenv("COOKIE_SECURE"),
148 | domain: os.Getenv("COOKIE_DOMAIN"),
149 | },
150 | sessionType: os.Getenv("SESSION_TYPE"),
151 | database: databaseConfig{
152 | database: os.Getenv("DATABASE_TYPE"),
153 | dsn: g.BuildDSN(),
154 | },
155 | redis: redisConfig{
156 | host: os.Getenv("REDIS_HOST"),
157 | password: os.Getenv("REDIS_PASSWORD"),
158 | prefix: os.Getenv("REDIS_PREFIX"),
159 | },
160 | }
161 |
162 | secure := true
163 | if strings.ToLower(os.Getenv("SECURE")) == "false" {
164 | secure = false
165 | }
166 |
167 | g.Server = Server{
168 | ServerName: os.Getenv("SERVER_NAME"),
169 | Port: os.Getenv("PORT"),
170 | Secure: secure,
171 | URL: os.Getenv("APP_URL"),
172 | }
173 |
174 | // create session
175 |
176 | sess := session.Session{
177 | CookieLifetime: g.config.cookie.lifetime,
178 | CookiePersist: g.config.cookie.persist,
179 | CookieName: g.config.cookie.name,
180 | SessionType: g.config.sessionType,
181 | CookieDomain: g.config.cookie.domain,
182 | }
183 |
184 | switch g.config.sessionType {
185 | case "redis":
186 | sess.RedisPool = myRedisCache.Conn
187 | case "mysql", "postgres", "mariadb", "postgresql":
188 | sess.DBPool = g.DB.Pool
189 | }
190 |
191 | g.Session = sess.InitSession()
192 | g.EncryptionKey = os.Getenv("KEY")
193 |
194 | if g.Debug {
195 | var views = jet.NewSet(
196 | jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
197 | jet.InDevelopmentMode(),
198 | )
199 | g.JetViews = views
200 | } else {
201 | var views = jet.NewSet(
202 | jet.NewOSFileSystemLoader(fmt.Sprintf("%s/views", rootPath)),
203 | )
204 | g.JetViews = views
205 | }
206 |
207 | g.createRenderer()
208 | go g.Mail.ListenForMail()
209 |
210 | return nil
211 | }
212 |
213 | // Init creates necessary folders for our Ghostly application
214 | func (g *Ghostly) Init(p initPaths) error {
215 | root := p.rootPath
216 | for _, path := range p.folderNames {
217 | // create folder if it doesn't exist
218 | err := g.CreateDirIfNotExist(root + "/" + path)
219 | if err != nil {
220 | return err
221 | }
222 | }
223 | return nil
224 | }
225 |
226 | // ListenAndServe starts the web server
227 | func (g *Ghostly) ListenAndServe() {
228 | srv := &http.Server{
229 | Addr: fmt.Sprintf(":%s", os.Getenv("PORT")),
230 | ErrorLog: g.ErrorLog,
231 | Handler: g.Routes,
232 | IdleTimeout: 30 * time.Second,
233 | ReadTimeout: 30 * time.Second,
234 | WriteTimeout: 600 * time.Second,
235 | }
236 |
237 | if g.DB.Pool != nil {
238 | defer g.DB.Pool.Close()
239 | }
240 |
241 | if redisPool != nil {
242 | defer redisPool.Close()
243 | }
244 |
245 | if badgerConn != nil {
246 | defer badgerConn.Close()
247 | }
248 |
249 | g.InfoLog.Printf("Listening on port %s", os.Getenv("PORT"))
250 | err := srv.ListenAndServe()
251 | g.ErrorLog.Fatal(err)
252 | }
253 |
254 | func (g *Ghostly) checkDotEnv(path string) error {
255 | err := g.CreateFileIfNotExists(fmt.Sprintf("%s/.env", path))
256 | if err != nil {
257 | return err
258 | }
259 | return nil
260 | }
261 |
262 | func (g *Ghostly) startLoggers() (*log.Logger, *log.Logger) {
263 | var infoLog *log.Logger
264 | var errorLog *log.Logger
265 |
266 | infoLog = log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
267 | errorLog = log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
268 |
269 | return infoLog, errorLog
270 | }
271 |
272 | func (g *Ghostly) createRenderer() {
273 | myRenderer := render.Render{
274 | Renderer: g.config.renderer,
275 | RootPath: g.RootPath,
276 | Port: g.config.port,
277 | JetViews: g.JetViews,
278 | Session: g.Session,
279 | }
280 | g.Render = &myRenderer
281 | }
282 |
283 | func (g *Ghostly) createMailer() mailer.Mail {
284 | port, _ := strconv.Atoi(os.Getenv("SMTP_PORT"))
285 | m := mailer.Mail{
286 | Domain: os.Getenv("MAIL_DOMAIN"),
287 | Templates: g.RootPath + "/mail",
288 | Host: os.Getenv("SMTP_HOST"),
289 | Port: port,
290 | Username: os.Getenv("SMTP_USERNAME"),
291 | Password: os.Getenv("SMTP_PASSWORD"),
292 | Encryption: os.Getenv("SMTP_ENCRYPTION"),
293 | FromName: os.Getenv("FROM_NAME"),
294 | FromAddress: os.Getenv("FROM_ADDRESS"),
295 | Jobs: make(chan mailer.Message, 20),
296 | Results: make(chan mailer.Result, 20),
297 | API: os.Getenv("MAILER_API"),
298 | APIKey: os.Getenv("MAILER_KEY"),
299 | APIUrl: os.Getenv("MAILER_URL"),
300 | }
301 | return m
302 | }
303 |
304 | func (g *Ghostly) createClientRedisCache() *cache.RedisCache {
305 | cacheClient := cache.RedisCache{
306 | Conn: g.createRedisPool(),
307 | Prefix: g.config.redis.prefix,
308 | }
309 | return &cacheClient
310 | }
311 |
312 | func (g *Ghostly) createClientBadgerCache() *cache.BadgerCache {
313 | cacheClient := cache.BadgerCache{
314 | Conn: g.createBadgerConn(),
315 | }
316 | return &cacheClient
317 | }
318 |
319 | func (g *Ghostly) createRedisPool() *redis.Pool {
320 | return &redis.Pool{
321 | MaxIdle: 50,
322 | MaxActive: 10000,
323 | IdleTimeout: 240 * time.Second,
324 | Dial: func() (redis.Conn, error) {
325 | return redis.Dial("tcp",
326 | g.config.redis.host,
327 | redis.DialPassword(g.config.redis.password))
328 | },
329 |
330 | TestOnBorrow: func(conn redis.Conn, t time.Time) error {
331 | _, err := conn.Do("PING")
332 | return err
333 | },
334 | }
335 | }
336 |
337 | func (g *Ghostly) createBadgerConn() *badger.DB {
338 | db, err := badger.Open(badger.DefaultOptions(g.RootPath + "/tmp/badger"))
339 | if err != nil {
340 | return nil
341 | }
342 | return db
343 | }
344 |
345 | // BuildDSN builds the datasource name for our database, and returns it as a string
346 | func (g *Ghostly) BuildDSN() string {
347 | var dsn string
348 |
349 | switch os.Getenv("DATABASE_TYPE") {
350 | case "postgres", "postgresql":
351 | dsn = fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=%s timezone=UTC connect_timeout=5",
352 | os.Getenv("DATABASE_HOST"),
353 | os.Getenv("DATABASE_PORT"),
354 | os.Getenv("DATABASE_USER"),
355 | os.Getenv("DATABASE_NAME"),
356 | os.Getenv("DATABASE_SSL_MODE"))
357 |
358 | // we check to see if a database password has been supplied, since including "password=" with nothing
359 | // after it sometimes causes postgres to fail to allow a connection.
360 | if os.Getenv("DATABASE_PASS") != "" {
361 | dsn = fmt.Sprintf("%s password=%s", dsn, os.Getenv("DATABASE_PASS"))
362 | }
363 |
364 | case "mysql", "mariadb":
365 | dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?collation=utf8_unicode_ci&timeout=5s&parseTime=true&tls=%s&readTimeout=5s",
366 | os.Getenv("DATABASE_USER"),
367 | os.Getenv("DATABASE_PASS"),
368 | os.Getenv("DATABASE_HOST"),
369 | os.Getenv("DATABASE_PORT"),
370 | os.Getenv("DATABASE_NAME"),
371 | os.Getenv("DATABASE_SSL_MODE"))
372 |
373 | default:
374 |
375 | }
376 |
377 | return dsn
378 | }
379 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------