@ -0,0 +1,7 @@ |
||||
version: 2 |
||||
updates: |
||||
- package-ecosystem: "gomod" # See documentation for possible values |
||||
directory: "/" # Location of package manifests |
||||
open-pull-requests-limit: 50 |
||||
schedule: |
||||
interval: "monthly" |
@ -1,3 +0,0 @@ |
||||
[submodule "static/js/mathjax"] |
||||
path = static/js/mathjax |
||||
url = https://github.com/mathjax/MathJax.git |
@ -0,0 +1,195 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"html/template" |
||||
"io" |
||||
"io/ioutil" |
||||
"net/http" |
||||
"os" |
||||
"path/filepath" |
||||
"strings" |
||||
"time" |
||||
|
||||
"github.com/hashicorp/go-multierror" |
||||
"github.com/writeas/impart" |
||||
wfimport "github.com/writeas/import" |
||||
"github.com/writeas/web-core/log" |
||||
) |
||||
|
||||
func viewImport(app *App, u *User, w http.ResponseWriter, r *http.Request) error { |
||||
// Fetch extra user data
|
||||
p := NewUserPage(app, r, u, "Import Posts", nil) |
||||
|
||||
c, err := app.db.GetCollections(u, app.Config().App.Host) |
||||
if err != nil { |
||||
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("unable to fetch collections: %v", err)} |
||||
} |
||||
|
||||
d := struct { |
||||
*UserPage |
||||
Collections *[]Collection |
||||
Flashes []template.HTML |
||||
Message string |
||||
InfoMsg bool |
||||
}{ |
||||
UserPage: p, |
||||
Collections: c, |
||||
Flashes: []template.HTML{}, |
||||
} |
||||
|
||||
flashes, _ := getSessionFlashes(app, w, r, nil) |
||||
for _, flash := range flashes { |
||||
if strings.HasPrefix(flash, "SUCCESS: ") { |
||||
d.Message = strings.TrimPrefix(flash, "SUCCESS: ") |
||||
} else if strings.HasPrefix(flash, "INFO: ") { |
||||
d.Message = strings.TrimPrefix(flash, "INFO: ") |
||||
d.InfoMsg = true |
||||
} else { |
||||
d.Flashes = append(d.Flashes, template.HTML(flash)) |
||||
} |
||||
} |
||||
|
||||
showUserPage(w, "import", d) |
||||
return nil |
||||
} |
||||
|
||||
func handleImport(app *App, u *User, w http.ResponseWriter, r *http.Request) error { |
||||
// limit 10MB per submission
|
||||
r.ParseMultipartForm(10 << 20) |
||||
|
||||
collAlias := r.PostFormValue("collection") |
||||
coll := &Collection{ |
||||
ID: 0, |
||||
} |
||||
var err error |
||||
if collAlias != "" { |
||||
coll, err = app.db.GetCollection(collAlias) |
||||
if err != nil { |
||||
log.Error("Unable to get collection for import: %s", err) |
||||
return err |
||||
} |
||||
// Only allow uploading to collection if current user is owner
|
||||
if coll.OwnerID != u.ID { |
||||
err := ErrUnauthorizedGeneral |
||||
_ = addSessionFlash(app, w, r, err.Message, nil) |
||||
return err |
||||
} |
||||
coll.hostName = app.cfg.App.Host |
||||
} |
||||
|
||||
fileDates := make(map[string]int64) |
||||
err = json.Unmarshal([]byte(r.FormValue("fileDates")), &fileDates) |
||||
if err != nil { |
||||
log.Error("invalid form data for file dates: %v", err) |
||||
return impart.HTTPError{http.StatusBadRequest, "form data for file dates was invalid"} |
||||
} |
||||
files := r.MultipartForm.File["files"] |
||||
var fileErrs []error |
||||
filesSubmitted := len(files) |
||||
var filesImported int |
||||
for _, formFile := range files { |
||||
fname := "" |
||||
ok := func() bool { |
||||
file, err := formFile.Open() |
||||
if err != nil { |
||||
fileErrs = append(fileErrs, fmt.Errorf("Unable to read file %s", formFile.Filename)) |
||||
log.Error("import file: open from form: %v", err) |
||||
return false |
||||
} |
||||
defer file.Close() |
||||
|
||||
tempFile, err := ioutil.TempFile("", "post-upload-*.txt") |
||||
if err != nil { |
||||
fileErrs = append(fileErrs, fmt.Errorf("Internal error for %s", formFile.Filename)) |
||||
log.Error("import file: create temp file %s: %v", formFile.Filename, err) |
||||
return false |
||||
} |
||||
defer tempFile.Close() |
||||
|
||||
_, err = io.Copy(tempFile, file) |
||||
if err != nil { |
||||
fileErrs = append(fileErrs, fmt.Errorf("Internal error for %s", formFile.Filename)) |
||||
log.Error("import file: copy to temp location %s: %v", formFile.Filename, err) |
||||
return false |
||||
} |
||||
|
||||
info, err := tempFile.Stat() |
||||
if err != nil { |
||||
fileErrs = append(fileErrs, fmt.Errorf("Internal error for %s", formFile.Filename)) |
||||
log.Error("import file: stat temp file %s: %v", formFile.Filename, err) |
||||
return false |
||||
} |
||||
fname = info.Name() |
||||
return true |
||||
}() |
||||
if !ok { |
||||
continue |
||||
} |
||||
|
||||
post, err := wfimport.FromFile(filepath.Join(os.TempDir(), fname)) |
||||
if err == wfimport.ErrEmptyFile { |
||||
// not a real error so don't log
|
||||
_ = addSessionFlash(app, w, r, fmt.Sprintf("%s was empty, import skipped", formFile.Filename), nil) |
||||
continue |
||||
} else if err == wfimport.ErrInvalidContentType { |
||||
// same as above
|
||||
_ = addSessionFlash(app, w, r, fmt.Sprintf("%s is not a supported post file", formFile.Filename), nil) |
||||
continue |
||||
} else if err != nil { |
||||
fileErrs = append(fileErrs, fmt.Errorf("failed to read copy of %s", formFile.Filename)) |
||||
log.Error("import textfile: file to post: %v", err) |
||||
continue |
||||
} |
||||
|
||||
if collAlias != "" { |
||||
post.Collection = collAlias |
||||
} |
||||
dateTime := time.Unix(fileDates[formFile.Filename], 0) |
||||
post.Created = &dateTime |
||||
created := post.Created.Format("2006-01-02T15:04:05Z") |
||||
submittedPost := SubmittedPost{ |
||||
Title: &post.Title, |
||||
Content: &post.Content, |
||||
Font: "norm", |
||||
Created: &created, |
||||
} |
||||
rp, err := app.db.CreatePost(u.ID, coll.ID, &submittedPost) |
||||
if err != nil { |
||||
fileErrs = append(fileErrs, fmt.Errorf("failed to create post from %s", formFile.Filename)) |
||||
log.Error("import textfile: create db post: %v", err) |
||||
continue |
||||
} |
||||
|
||||
// Federate post, if necessary
|
||||
if app.cfg.App.Federation && coll.ID > 0 { |
||||
go federatePost( |
||||
app, |
||||
&PublicPost{ |
||||
Post: rp, |
||||
Collection: &CollectionObj{ |
||||
Collection: *coll, |
||||
}, |
||||
}, |
||||
coll.ID, |
||||
false, |
||||
) |
||||
} |
||||
filesImported++ |
||||
} |
||||
if len(fileErrs) != 0 { |
||||
_ = addSessionFlash(app, w, r, multierror.ListFormatFunc(fileErrs), nil) |
||||
} |
||||
|
||||
if filesImported == filesSubmitted { |
||||
verb := "posts" |
||||
if filesSubmitted == 1 { |
||||
verb = "post" |
||||
} |
||||
_ = addSessionFlash(app, w, r, fmt.Sprintf("SUCCESS: Import complete, %d %s imported.", filesImported, verb), nil) |
||||
} else if filesImported > 0 { |
||||
_ = addSessionFlash(app, w, r, fmt.Sprintf("INFO: %d of %d posts imported, see details below.", filesImported, filesSubmitted), nil) |
||||
} |
||||
return impart.HTTPError{http.StatusFound, "/me/import"} |
||||
} |
@ -0,0 +1,61 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"github.com/writeas/writefreely" |
||||
|
||||
"github.com/urfave/cli/v2" |
||||
) |
||||
|
||||
var ( |
||||
cmdConfig cli.Command = cli.Command{ |
||||
Name: "config", |
||||
Usage: "config management tools", |
||||
Subcommands: []*cli.Command{ |
||||
&cmdConfigGenerate, |
||||
&cmdConfigInteractive, |
||||
}, |
||||
} |
||||
|
||||
cmdConfigGenerate cli.Command = cli.Command{ |
||||
Name: "generate", |
||||
Aliases: []string{"gen"}, |
||||
Usage: "Generate a basic configuration", |
||||
Action: genConfigAction, |
||||
} |
||||
|
||||
cmdConfigInteractive cli.Command = cli.Command{ |
||||
Name: "start", |
||||
Usage: "Interactive configuration process", |
||||
Action: interactiveConfigAction, |
||||
Flags: []cli.Flag{ |
||||
&cli.StringFlag{ |
||||
Name: "sections", |
||||
Value: "server db app", |
||||
Usage: "Which sections of the configuration to go through\n" + |
||||
"valid values of sections flag are any combination of 'server', 'db' and 'app' \n" + |
||||
"example: writefreely config start --sections \"db app\"", |
||||
}, |
||||
}, |
||||
} |
||||
) |
||||
|
||||
func genConfigAction(c *cli.Context) error { |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.CreateConfig(app) |
||||
} |
||||
|
||||
func interactiveConfigAction(c *cli.Context) error { |
||||
app := writefreely.NewApp(c.String("c")) |
||||
writefreely.DoConfig(app, c.String("sections")) |
||||
return nil |
||||
} |
@ -0,0 +1,50 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"github.com/writeas/writefreely" |
||||
|
||||
"github.com/urfave/cli/v2" |
||||
) |
||||
|
||||
var ( |
||||
cmdDB cli.Command = cli.Command{ |
||||
Name: "db", |
||||
Usage: "db management tools", |
||||
Subcommands: []*cli.Command{ |
||||
&cmdDBInit, |
||||
&cmdDBMigrate, |
||||
}, |
||||
} |
||||
|
||||
cmdDBInit cli.Command = cli.Command{ |
||||
Name: "init", |
||||
Usage: "Initialize Database", |
||||
Action: initDBAction, |
||||
} |
||||
|
||||
cmdDBMigrate cli.Command = cli.Command{ |
||||
Name: "migrate", |
||||
Usage: "Migrate Database", |
||||
Action: migrateDBAction, |
||||
} |
||||
) |
||||
|
||||
func initDBAction(c *cli.Context) error { |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.CreateSchema(app) |
||||
} |
||||
|
||||
func migrateDBAction(c *cli.Context) error { |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.Migrate(app) |
||||
} |
@ -0,0 +1,39 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"github.com/writeas/writefreely" |
||||
|
||||
"github.com/urfave/cli/v2" |
||||
) |
||||
|
||||
var ( |
||||
cmdKeys cli.Command = cli.Command{ |
||||
Name: "keys", |
||||
Usage: "key management tools", |
||||
Subcommands: []*cli.Command{ |
||||
&cmdGenerateKeys, |
||||
}, |
||||
} |
||||
|
||||
cmdGenerateKeys cli.Command = cli.Command{ |
||||
Name: "generate", |
||||
Aliases: []string{"gen"}, |
||||
Usage: "Generate encryption and authentication keys", |
||||
Action: genKeysAction, |
||||
} |
||||
) |
||||
|
||||
func genKeysAction(c *cli.Context) error { |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.GenerateKeyFiles(app) |
||||
} |
@ -0,0 +1,97 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"fmt" |
||||
|
||||
"github.com/writeas/writefreely" |
||||
|
||||
"github.com/urfave/cli/v2" |
||||
) |
||||
|
||||
var ( |
||||
cmdUser cli.Command = cli.Command{ |
||||
Name: "user", |
||||
Usage: "user management tools", |
||||
Subcommands: []*cli.Command{ |
||||
&cmdAddUser, |
||||
&cmdDelUser, |
||||
&cmdResetPass, |
||||
// TODO: possibly add a user list command
|
||||
}, |
||||
} |
||||
|
||||
cmdAddUser cli.Command = cli.Command{ |
||||
Name: "create", |
||||
Usage: "Add new user", |
||||
Aliases: []string{"a", "add"}, |
||||
Flags: []cli.Flag{ |
||||
&cli.BoolFlag{ |
||||
Name: "admin", |
||||
Value: false, |
||||
Usage: "Create admin user", |
||||
}, |
||||
}, |
||||
Action: addUserAction, |
||||
} |
||||
|
||||
cmdDelUser cli.Command = cli.Command{ |
||||
Name: "delete", |
||||
Usage: "Delete user", |
||||
Aliases: []string{"del", "d"}, |
||||
Action: delUserAction, |
||||
} |
||||
|
||||
cmdResetPass cli.Command = cli.Command{ |
||||
Name: "reset-pass", |
||||
Usage: "Reset user's password", |
||||
Aliases: []string{"resetpass", "reset"}, |
||||
Action: resetPassAction, |
||||
} |
||||
) |
||||
|
||||
func addUserAction(c *cli.Context) error { |
||||
credentials := "" |
||||
if c.NArg() > 0 { |
||||
credentials = c.Args().Get(0) |
||||
} else { |
||||
return fmt.Errorf("No user passed. Example: writefreely user add [USER]:[PASSWORD]") |
||||
} |
||||
username, password, err := parseCredentials(credentials) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.CreateUser(app, username, password, c.Bool("admin")) |
||||
} |
||||
|
||||
func delUserAction(c *cli.Context) error { |
||||
username := "" |
||||
if c.NArg() > 0 { |
||||
username = c.Args().Get(0) |
||||
} else { |
||||
return fmt.Errorf("No user passed. Example: writefreely user delete [USER]") |
||||
} |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.DoDeleteAccount(app, username) |
||||
} |
||||
|
||||
func resetPassAction(c *cli.Context) error { |
||||
username := "" |
||||
if c.NArg() > 0 { |
||||
username = c.Args().Get(0) |
||||
} else { |
||||
return fmt.Errorf("No user passed. Example: writefreely user reset-pass [USER]") |
||||
} |
||||
app := writefreely.NewApp(c.String("c")) |
||||
return writefreely.ResetPassword(app, username) |
||||
} |
@ -0,0 +1,49 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package main |
||||
|
||||
import ( |
||||
"github.com/writeas/web-core/log" |
||||
"github.com/writeas/writefreely" |
||||
|
||||
"github.com/gorilla/mux" |
||||
"github.com/urfave/cli/v2" |
||||
) |
||||
|
||||
var ( |
||||
cmdServe cli.Command = cli.Command{ |
||||
Name: "serve", |
||||
Aliases: []string{"web"}, |
||||
Usage: "Run web application", |
||||
Action: serveAction, |
||||
} |
||||
) |
||||
|
||||
func serveAction(c *cli.Context) error { |
||||
// Initialize the application
|
||||
app := writefreely.NewApp(c.String("c")) |
||||
var err error |
||||
log.Info("Starting %s...", writefreely.FormatVersion()) |
||||
app, err = writefreely.Initialize(app, c.Bool("debug")) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
// Set app routes
|
||||
r := mux.NewRouter() |
||||
writefreely.InitRoutes(app, r) |
||||
app.InitStaticRoutes(r) |
||||
|
||||
// Serve the application
|
||||
writefreely.Serve(app, r) |
||||
|
||||
return nil |
||||
} |
@ -0,0 +1,50 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
"github.com/stretchr/testify/assert" |
||||
"testing" |
||||
) |
||||
|
||||
func TestOAuthDatastore(t *testing.T) { |
||||
if !runMySQLTests() { |
||||
t.Skip("skipping mysql tests") |
||||
} |
||||
withTestDB(t, func(db *sql.DB) { |
||||
ctx := context.Background() |
||||
ds := &datastore{ |
||||
DB: db, |
||||
driverName: "", |
||||
} |
||||
|
||||
state, err := ds.GenerateOAuthState(ctx, "test", "development", 0, "") |
||||
assert.NoError(t, err) |
||||
assert.Len(t, state, 24) |
||||
|
||||
countRows(t, ctx, db, 1, "SELECT COUNT(*) FROM `oauth_client_states` WHERE `state` = ? AND `used` = false", state) |
||||
|
||||
_, _, _, _, err = ds.ValidateOAuthState(ctx, state) |
||||
assert.NoError(t, err) |
||||
|
||||
countRows(t, ctx, db, 1, "SELECT COUNT(*) FROM `oauth_client_states` WHERE `state` = ? AND `used` = true", state) |
||||
|
||||
var localUserID int64 = 99 |
||||
var remoteUserID = "100" |
||||
err = ds.RecordRemoteUserID(ctx, localUserID, remoteUserID, "test", "test", "access_token_a") |
||||
assert.NoError(t, err) |
||||
|
||||
countRows(t, ctx, db, 1, "SELECT COUNT(*) FROM `oauth_users` WHERE `user_id` = ? AND `remote_user_id` = ? AND access_token = 'access_token_a'", localUserID, remoteUserID) |
||||
|
||||
err = ds.RecordRemoteUserID(ctx, localUserID, remoteUserID, "test", "test", "access_token_b") |
||||
assert.NoError(t, err) |
||||
|
||||
countRows(t, ctx, db, 1, "SELECT COUNT(*) FROM `oauth_users` WHERE `user_id` = ? AND `remote_user_id` = ? AND access_token = 'access_token_b'", localUserID, remoteUserID) |
||||
|
||||
countRows(t, ctx, db, 1, "SELECT COUNT(*) FROM `oauth_users`") |
||||
|
||||
foundUserID, err := ds.GetIDForRemoteUser(ctx, remoteUserID, "test", "test") |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, localUserID, foundUserID) |
||||
}) |
||||
} |
@ -0,0 +1,52 @@ |
||||
package db |
||||
|
||||
import ( |
||||
"fmt" |
||||
"strings" |
||||
) |
||||
|
||||
type AlterTableSqlBuilder struct { |
||||
Dialect DialectType |
||||
Name string |
||||
Changes []string |
||||
} |
||||
|
||||
func (b *AlterTableSqlBuilder) AddColumn(col *Column) *AlterTableSqlBuilder { |
||||
if colVal, err := col.String(); err == nil { |
||||
b.Changes = append(b.Changes, fmt.Sprintf("ADD COLUMN %s", colVal)) |
||||
} |
||||
return b |
||||
} |
||||
|
||||
func (b *AlterTableSqlBuilder) ChangeColumn(name string, col *Column) *AlterTableSqlBuilder { |
||||
if colVal, err := col.String(); err == nil { |
||||
b.Changes = append(b.Changes, fmt.Sprintf("CHANGE COLUMN %s %s", name, colVal)) |
||||
} |
||||
return b |
||||
} |
||||
|
||||
func (b *AlterTableSqlBuilder) AddUniqueConstraint(name string, columns ...string) *AlterTableSqlBuilder { |
||||
b.Changes = append(b.Changes, fmt.Sprintf("ADD CONSTRAINT %s UNIQUE (%s)", name, strings.Join(columns, ", "))) |
||||
return b |
||||
} |
||||
|
||||
func (b *AlterTableSqlBuilder) ToSQL() (string, error) { |
||||
var str strings.Builder |
||||
|
||||
str.WriteString("ALTER TABLE ") |
||||
str.WriteString(b.Name) |
||||
str.WriteString(" ") |
||||
|
||||
if len(b.Changes) == 0 { |
||||
return "", fmt.Errorf("no changes provide for table: %s", b.Name) |
||||
} |
||||
changeCount := len(b.Changes) |
||||
for i, thing := range b.Changes { |
||||
str.WriteString(thing) |
||||
if i < changeCount-1 { |
||||
str.WriteString(", ") |
||||
} |
||||
} |
||||
|
||||
return str.String(), nil |
||||
} |
@ -0,0 +1,56 @@ |
||||
package db |
||||
|
||||
import "testing" |
||||
|
||||
func TestAlterTableSqlBuilder_ToSQL(t *testing.T) { |
||||
type fields struct { |
||||
Dialect DialectType |
||||
Name string |
||||
Changes []string |
||||
} |
||||
tests := []struct { |
||||
name string |
||||
builder *AlterTableSqlBuilder |
||||
want string |
||||
wantErr bool |
||||
}{ |
||||
{ |
||||
name: "MySQL add int", |
||||
builder: DialectMySQL. |
||||
AlterTable("the_table"). |
||||
AddColumn(DialectMySQL.Column("the_col", ColumnTypeInteger, UnsetSize)), |
||||
want: "ALTER TABLE the_table ADD COLUMN the_col INT NOT NULL", |
||||
wantErr: false, |
||||
}, |
||||
{ |
||||
name: "MySQL add string", |
||||
builder: DialectMySQL. |
||||
AlterTable("the_table"). |
||||
AddColumn(DialectMySQL.Column("the_col", ColumnTypeVarChar, OptionalInt{true, 128})), |
||||
want: "ALTER TABLE the_table ADD COLUMN the_col VARCHAR(128) NOT NULL", |
||||
wantErr: false, |
||||
}, |
||||
|
||||
{ |
||||
name: "MySQL add int and string", |
||||
builder: DialectMySQL. |
||||
AlterTable("the_table"). |
||||
AddColumn(DialectMySQL.Column("first_col", ColumnTypeInteger, UnsetSize)). |
||||
AddColumn(DialectMySQL.Column("second_col", ColumnTypeVarChar, OptionalInt{true, 128})), |
||||
want: "ALTER TABLE the_table ADD COLUMN first_col INT NOT NULL, ADD COLUMN second_col VARCHAR(128) NOT NULL", |
||||
wantErr: false, |
||||
}, |
||||
} |
||||
for _, tt := range tests { |
||||
t.Run(tt.name, func(t *testing.T) { |
||||
got, err := tt.builder.ToSQL() |
||||
if (err != nil) != tt.wantErr { |
||||
t.Errorf("ToSQL() error = %v, wantErr %v", err, tt.wantErr) |
||||
return |
||||
} |
||||
if got != tt.want { |
||||
t.Errorf("ToSQL() got = %v, want %v", got, tt.want) |
||||
} |
||||
}) |
||||
} |
||||
} |
@ -0,0 +1,266 @@ |
||||
/* |
||||
* Copyright © 2019-2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package db |
||||
|
||||
import ( |
||||
"fmt" |
||||
"strings" |
||||
) |
||||
|
||||
type ColumnType int |
||||
|
||||
type OptionalInt struct { |
||||
Set bool |
||||
Value int |
||||
} |
||||
|
||||
type OptionalString struct { |
||||
Set bool |
||||
Value string |
||||
} |
||||
|
||||
type SQLBuilder interface { |
||||
ToSQL() (string, error) |
||||
} |
||||
|
||||
type Column struct { |
||||
Dialect DialectType |
||||
Name string |
||||
Nullable bool |
||||
Default OptionalString |
||||
Type ColumnType |
||||
Size OptionalInt |
||||
PrimaryKey bool |
||||
} |
||||
|
||||
type CreateTableSqlBuilder struct { |
||||
Dialect DialectType |
||||
Name string |
||||
IfNotExists bool |
||||
ColumnOrder []string |
||||
Columns map[string]*Column |
||||
Constraints []string |
||||
} |
||||
|
||||
const ( |
||||
ColumnTypeBool ColumnType = iota |
||||
ColumnTypeSmallInt ColumnType = iota |
||||
ColumnTypeInteger ColumnType = iota |
||||
ColumnTypeChar ColumnType = iota |
||||
ColumnTypeVarChar ColumnType = iota |
||||
ColumnTypeText ColumnType = iota |
||||
ColumnTypeDateTime ColumnType = iota |
||||
) |
||||
|
||||
var _ SQLBuilder = &CreateTableSqlBuilder{} |
||||
|
||||
var UnsetSize OptionalInt = OptionalInt{Set: false, Value: 0} |
||||
var UnsetDefault OptionalString = OptionalString{Set: false, Value: ""} |
||||
|
||||
func (d ColumnType) Format(dialect DialectType, size OptionalInt) (string, error) { |
||||
if dialect != DialectMySQL && dialect != DialectSQLite { |
||||
return "", fmt.Errorf("unsupported column type %d for dialect %d and size %v", d, dialect, size) |
||||
} |
||||
switch d { |
||||
case ColumnTypeSmallInt: |
||||
{ |
||||
if dialect == DialectSQLite { |
||||
return "INTEGER", nil |
||||
} |
||||
mod := "" |
||||
if size.Set { |
||||
mod = fmt.Sprintf("(%d)", size.Value) |
||||
} |
||||
return "SMALLINT" + mod, nil |
||||
} |
||||
case ColumnTypeInteger: |
||||
{ |
||||
if dialect == DialectSQLite { |
||||
return "INTEGER", nil |
||||
} |
||||
mod := "" |
||||
if size.Set { |
||||
mod = fmt.Sprintf("(%d)", size.Value) |
||||
} |
||||
return "INT" + mod, nil |
||||
} |
||||
case ColumnTypeChar: |
||||
{ |
||||
if dialect == DialectSQLite { |
||||
return "TEXT", nil |
||||
} |
||||
mod := "" |
||||
if size.Set { |
||||
mod = fmt.Sprintf("(%d)", size.Value) |
||||
} |
||||
return "CHAR" + mod, nil |
||||
} |
||||
case ColumnTypeVarChar: |
||||
{ |
||||
if dialect == DialectSQLite { |
||||
return "TEXT", nil |
||||
} |
||||
mod := "" |
||||
if size.Set { |
||||
mod = fmt.Sprintf("(%d)", size.Value) |
||||
} |
||||
return "VARCHAR" + mod, nil |
||||
} |
||||
case ColumnTypeBool: |
||||
{ |
||||
if dialect == DialectSQLite { |
||||
return "INTEGER", nil |
||||
} |
||||
return "TINYINT(1)", nil |
||||
} |
||||
case ColumnTypeDateTime: |
||||
return "DATETIME", nil |
||||
case ColumnTypeText: |
||||
return "TEXT", nil |
||||
} |
||||
return "", fmt.Errorf("unsupported column type %d for dialect %d and size %v", d, dialect, size) |
||||
} |
||||
|
||||
func (c *Column) SetName(name string) *Column { |
||||
c.Name = name |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) SetNullable(nullable bool) *Column { |
||||
c.Nullable = nullable |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) SetPrimaryKey(pk bool) *Column { |
||||
c.PrimaryKey = pk |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) SetDefault(value string) *Column { |
||||
c.Default = OptionalString{Set: true, Value: value} |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) SetDefaultCurrentTimestamp() *Column { |
||||
def := "NOW()" |
||||
if c.Dialect == DialectSQLite { |
||||
def = "CURRENT_TIMESTAMP" |
||||
} |
||||
c.Default = OptionalString{Set: true, Value: def} |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) SetType(t ColumnType) *Column { |
||||
c.Type = t |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) SetSize(size int) *Column { |
||||
c.Size = OptionalInt{Set: true, Value: size} |
||||
return c |
||||
} |
||||
|
||||
func (c *Column) String() (string, error) { |
||||
var str strings.Builder |
||||
|
||||
str.WriteString(c.Name) |
||||
|
||||
str.WriteString(" ") |
||||
typeStr, err := c.Type.Format(c.Dialect, c.Size) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
|
||||
str.WriteString(typeStr) |
||||
|
||||
if !c.Nullable { |
||||
str.WriteString(" NOT NULL") |
||||
} |
||||
|
||||
if c.Default.Set { |
||||
str.WriteString(" DEFAULT ") |
||||
val := c.Default.Value |
||||
if val == "" { |
||||
val = "''" |
||||
} |
||||
str.WriteString(val) |
||||
} |
||||
|
||||
if c.PrimaryKey { |
||||
str.WriteString(" PRIMARY KEY") |
||||
} |
||||
|
||||
return str.String(), nil |
||||
} |
||||
|
||||
func (b *CreateTableSqlBuilder) Column(column *Column) *CreateTableSqlBuilder { |
||||
if b.Columns == nil { |
||||
b.Columns = make(map[string]*Column) |
||||
} |
||||
b.Columns[column.Name] = column |
||||
b.ColumnOrder = append(b.ColumnOrder, column.Name) |
||||
return b |
||||
} |
||||
|
||||
func (b *CreateTableSqlBuilder) UniqueConstraint(columns ...string) *CreateTableSqlBuilder { |
||||
for _, column := range columns { |
||||
if _, ok := b.Columns[column]; !ok { |
||||
// This fails silently.
|
||||
return b |
||||
} |
||||
} |
||||
b.Constraints = append(b.Constraints, fmt.Sprintf("UNIQUE(%s)", strings.Join(columns, ","))) |
||||
return b |
||||
} |
||||
|
||||
func (b *CreateTableSqlBuilder) SetIfNotExists(ine bool) *CreateTableSqlBuilder { |
||||
b.IfNotExists = ine |
||||
return b |
||||
} |
||||
|
||||
func (b *CreateTableSqlBuilder) ToSQL() (string, error) { |
||||
var str strings.Builder |
||||
|
||||
str.WriteString("CREATE TABLE ") |
||||
if b.IfNotExists { |
||||
str.WriteString("IF NOT EXISTS ") |
||||
} |
||||
str.WriteString(b.Name) |
||||
|
||||
var things []string |
||||
for _, columnName := range b.ColumnOrder { |
||||
column, ok := b.Columns[columnName] |
||||
if !ok { |
||||
return "", fmt.Errorf("column not found: %s", columnName) |
||||
} |
||||
columnStr, err := column.String() |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
things = append(things, columnStr) |
||||
} |
||||
for _, constraint := range b.Constraints { |
||||
things = append(things, constraint) |
||||
} |
||||
|
||||
if thingLen := len(things); thingLen > 0 { |
||||
str.WriteString(" ( ") |
||||
for i, thing := range things { |
||||
str.WriteString(thing) |
||||
if i < thingLen-1 { |
||||
str.WriteString(", ") |
||||
} |
||||
} |
||||
str.WriteString(" )") |
||||
} |
||||
|
||||
return str.String(), nil |
||||
} |
@ -0,0 +1,146 @@ |
||||
package db |
||||
|
||||
import ( |
||||
"github.com/stretchr/testify/assert" |
||||
"testing" |
||||
) |
||||
|
||||
func TestDialect_Column(t *testing.T) { |
||||
c1 := DialectSQLite.Column("foo", ColumnTypeBool, UnsetSize) |
||||
assert.Equal(t, DialectSQLite, c1.Dialect) |
||||
c2 := DialectMySQL.Column("foo", ColumnTypeBool, UnsetSize) |
||||
assert.Equal(t, DialectMySQL, c2.Dialect) |
||||
} |
||||
|
||||
func TestColumnType_Format(t *testing.T) { |
||||
type args struct { |
||||
dialect DialectType |
||||
size OptionalInt |
||||
} |
||||
tests := []struct { |
||||
name string |
||||
d ColumnType |
||||
args args |
||||
want string |
||||
wantErr bool |
||||
}{ |
||||
{"Sqlite bool", ColumnTypeBool, args{dialect: DialectSQLite}, "INTEGER", false}, |
||||
{"Sqlite small int", ColumnTypeSmallInt, args{dialect: DialectSQLite}, "INTEGER", false}, |
||||
{"Sqlite int", ColumnTypeInteger, args{dialect: DialectSQLite}, "INTEGER", false}, |
||||
{"Sqlite char", ColumnTypeChar, args{dialect: DialectSQLite}, "TEXT", false}, |
||||
{"Sqlite varchar", ColumnTypeVarChar, args{dialect: DialectSQLite}, "TEXT", false}, |
||||
{"Sqlite text", ColumnTypeText, args{dialect: DialectSQLite}, "TEXT", false}, |
||||
{"Sqlite datetime", ColumnTypeDateTime, args{dialect: DialectSQLite}, "DATETIME", false}, |
||||
|
||||
{"MySQL bool", ColumnTypeBool, args{dialect: DialectMySQL}, "TINYINT(1)", false}, |
||||
{"MySQL small int", ColumnTypeSmallInt, args{dialect: DialectMySQL}, "SMALLINT", false}, |
||||
{"MySQL small int with param", ColumnTypeSmallInt, args{dialect: DialectMySQL, size: OptionalInt{true, 3}}, "SMALLINT(3)", false}, |
||||
{"MySQL int", ColumnTypeInteger, args{dialect: DialectMySQL}, "INT", false}, |
||||
{"MySQL int with param", ColumnTypeInteger, args{dialect: DialectMySQL, size: OptionalInt{true, 11}}, "INT(11)", false}, |
||||
{"MySQL char", ColumnTypeChar, args{dialect: DialectMySQL}, "CHAR", false}, |
||||
{"MySQL char with param", ColumnTypeChar, args{dialect: DialectMySQL, size: OptionalInt{true, 4}}, "CHAR(4)", false}, |
||||
{"MySQL varchar", ColumnTypeVarChar, args{dialect: DialectMySQL}, "VARCHAR", false}, |
||||
{"MySQL varchar with param", ColumnTypeVarChar, args{dialect: DialectMySQL, size: OptionalInt{true, 25}}, "VARCHAR(25)", false}, |
||||
{"MySQL text", ColumnTypeText, args{dialect: DialectMySQL}, "TEXT", false}, |
||||
{"MySQL datetime", ColumnTypeDateTime, args{dialect: DialectMySQL}, "DATETIME", false}, |
||||
|
||||
{"invalid column type", 10000, args{dialect: DialectMySQL}, "", true}, |
||||
{"invalid dialect", ColumnTypeBool, args{dialect: 10000}, "", true}, |
||||
} |
||||
for _, tt := range tests { |
||||
t.Run(tt.name, func(t *testing.T) { |
||||
got, err := tt.d.Format(tt.args.dialect, tt.args.size) |
||||
if (err != nil) != tt.wantErr { |
||||
t.Errorf("Format() error = %v, wantErr %v", err, tt.wantErr) |
||||
return |
||||
} |
||||
if got != tt.want { |
||||
t.Errorf("Format() got = %v, want %v", got, tt.want) |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func TestColumn_Build(t *testing.T) { |
||||
type fields struct { |
||||
Dialect DialectType |
||||
Name string |
||||
Nullable bool |
||||
Default OptionalString |
||||
Type ColumnType |
||||
Size OptionalInt |
||||
PrimaryKey bool |
||||
} |
||||
tests := []struct { |
||||
name string |
||||
fields fields |
||||
want string |
||||
wantErr bool |
||||
}{ |
||||
{"Sqlite bool", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeBool, UnsetSize, false}, "foo INTEGER NOT NULL", false}, |
||||
{"Sqlite bool nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeBool, UnsetSize, false}, "foo INTEGER", false}, |
||||
{"Sqlite small int", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeSmallInt, UnsetSize, true}, "foo INTEGER NOT NULL PRIMARY KEY", false}, |
||||
{"Sqlite small int nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeSmallInt, UnsetSize, false}, "foo INTEGER", false}, |
||||
{"Sqlite int", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeInteger, UnsetSize, false}, "foo INTEGER NOT NULL", false}, |
||||
{"Sqlite int nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeInteger, UnsetSize, false}, "foo INTEGER", false}, |
||||
{"Sqlite char", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeChar, UnsetSize, false}, "foo TEXT NOT NULL", false}, |
||||
{"Sqlite char nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeChar, UnsetSize, false}, "foo TEXT", false}, |
||||
{"Sqlite varchar", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeVarChar, UnsetSize, false}, "foo TEXT NOT NULL", false}, |
||||
{"Sqlite varchar nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeVarChar, UnsetSize, false}, "foo TEXT", false}, |
||||
{"Sqlite text", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeText, UnsetSize, false}, "foo TEXT NOT NULL", false}, |
||||
{"Sqlite text nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeText, UnsetSize, false}, "foo TEXT", false}, |
||||
{"Sqlite datetime", fields{DialectSQLite, "foo", false, UnsetDefault, ColumnTypeDateTime, UnsetSize, false}, "foo DATETIME NOT NULL", false}, |
||||
{"Sqlite datetime nullable", fields{DialectSQLite, "foo", true, UnsetDefault, ColumnTypeDateTime, UnsetSize, false}, "foo DATETIME", false}, |
||||
|
||||
{"MySQL bool", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeBool, UnsetSize, false}, "foo TINYINT(1) NOT NULL", false}, |
||||
{"MySQL bool nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeBool, UnsetSize, false}, "foo TINYINT(1)", false}, |
||||
{"MySQL small int", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeSmallInt, UnsetSize, true}, "foo SMALLINT NOT NULL PRIMARY KEY", false}, |
||||
{"MySQL small int nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeSmallInt, UnsetSize, false}, "foo SMALLINT", false}, |
||||
{"MySQL int", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeInteger, UnsetSize, false}, "foo INT NOT NULL", false}, |
||||
{"MySQL int nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeInteger, UnsetSize, false}, "foo INT", false}, |
||||
{"MySQL char", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeChar, UnsetSize, false}, "foo CHAR NOT NULL", false}, |
||||
{"MySQL char nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeChar, UnsetSize, false}, "foo CHAR", false}, |
||||
{"MySQL varchar", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeVarChar, UnsetSize, false}, "foo VARCHAR NOT NULL", false}, |
||||
{"MySQL varchar nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeVarChar, UnsetSize, false}, "foo VARCHAR", false}, |
||||
{"MySQL text", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeText, UnsetSize, false}, "foo TEXT NOT NULL", false}, |
||||
{"MySQL text nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeText, UnsetSize, false}, "foo TEXT", false}, |
||||
{"MySQL datetime", fields{DialectMySQL, "foo", false, UnsetDefault, ColumnTypeDateTime, UnsetSize, false}, "foo DATETIME NOT NULL", false}, |
||||
{"MySQL datetime nullable", fields{DialectMySQL, "foo", true, UnsetDefault, ColumnTypeDateTime, UnsetSize, false}, "foo DATETIME", false}, |
||||
} |
||||
for _, tt := range tests { |
||||
t.Run(tt.name, func(t *testing.T) { |
||||
c := &Column{ |
||||
Dialect: tt.fields.Dialect, |
||||
Name: tt.fields.Name, |
||||
Nullable: tt.fields.Nullable, |
||||
Default: tt.fields.Default, |
||||
Type: tt.fields.Type, |
||||
Size: tt.fields.Size, |
||||
PrimaryKey: tt.fields.PrimaryKey, |
||||
} |
||||
if got, err := c.String(); got != tt.want { |
||||
if (err != nil) != tt.wantErr { |
||||
t.Errorf("String() error = %v, wantErr %v", err, tt.wantErr) |
||||
return |
||||
} |
||||
if got != tt.want { |
||||
t.Errorf("String() got = %v, want %v", got, tt.want) |
||||
} |
||||
} |
||||
}) |
||||
} |
||||
} |
||||
|
||||
func TestCreateTableSqlBuilder_ToSQL(t *testing.T) { |
||||
sql, err := DialectMySQL. |
||||
Table("foo"). |
||||
SetIfNotExists(true). |
||||
Column(DialectMySQL.Column("bar", ColumnTypeInteger, UnsetSize).SetPrimaryKey(true)). |
||||
Column(DialectMySQL.Column("baz", ColumnTypeText, UnsetSize)). |
||||
Column(DialectMySQL.Column("qux", ColumnTypeDateTime, UnsetSize).SetDefault("NOW()")). |
||||
UniqueConstraint("bar"). |
||||
UniqueConstraint("bar", "baz"). |
||||
ToSQL() |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, "CREATE TABLE IF NOT EXISTS foo ( bar INT NOT NULL PRIMARY KEY, baz TEXT NOT NULL, qux DATETIME NOT NULL DEFAULT NOW(), UNIQUE(bar), UNIQUE(bar,baz) )", sql) |
||||
} |
@ -0,0 +1,76 @@ |
||||
package db |
||||
|
||||
import "fmt" |
||||
|
||||
type DialectType int |
||||
|
||||
const ( |
||||
DialectSQLite DialectType = iota |
||||
DialectMySQL DialectType = iota |
||||
) |
||||
|
||||
func (d DialectType) Column(name string, t ColumnType, size OptionalInt) *Column { |
||||
switch d { |
||||
case DialectSQLite: |
||||
return &Column{Dialect: DialectSQLite, Name: name, Type: t, Size: size} |
||||
case DialectMySQL: |
||||
return &Column{Dialect: DialectMySQL, Name: name, Type: t, Size: size} |
||||
default: |
||||
panic(fmt.Sprintf("unexpected dialect: %d", d)) |
||||
} |
||||
} |
||||
|
||||
func (d DialectType) Table(name string) *CreateTableSqlBuilder { |
||||
switch d { |
||||
case DialectSQLite: |
||||
return &CreateTableSqlBuilder{Dialect: DialectSQLite, Name: name} |
||||
case DialectMySQL: |
||||
return &CreateTableSqlBuilder{Dialect: DialectMySQL, Name: name} |
||||
default: |
||||
panic(fmt.Sprintf("unexpected dialect: %d", d)) |
||||
} |
||||
} |
||||
|
||||
func (d DialectType) AlterTable(name string) *AlterTableSqlBuilder { |
||||
switch d { |
||||
case DialectSQLite: |
||||
return &AlterTableSqlBuilder{Dialect: DialectSQLite, Name: name} |
||||
case DialectMySQL: |
||||
return &AlterTableSqlBuilder{Dialect: DialectMySQL, Name: name} |
||||
default: |
||||
panic(fmt.Sprintf("unexpected dialect: %d", d)) |
||||
} |
||||
} |
||||
|
||||
func (d DialectType) CreateUniqueIndex(name, table string, columns ...string) *CreateIndexSqlBuilder { |
||||
switch d { |
||||
case DialectSQLite: |
||||
return &CreateIndexSqlBuilder{Dialect: DialectSQLite, Name: name, Table: table, Unique: true, Columns: columns} |
||||
case DialectMySQL: |
||||
return &CreateIndexSqlBuilder{Dialect: DialectMySQL, Name: name, Table: table, Unique: true, Columns: columns} |
||||
default: |
||||
panic(fmt.Sprintf("unexpected dialect: %d", d)) |
||||
} |
||||
} |
||||
|
||||
func (d DialectType) CreateIndex(name, table string, columns ...string) *CreateIndexSqlBuilder { |
||||
switch d { |
||||
case DialectSQLite: |
||||
return &CreateIndexSqlBuilder{Dialect: DialectSQLite, Name: name, Table: table, Unique: false, Columns: columns} |
||||
case DialectMySQL: |
||||
return &CreateIndexSqlBuilder{Dialect: DialectMySQL, Name: name, Table: table, Unique: false, Columns: columns} |
||||
default: |
||||
panic(fmt.Sprintf("unexpected dialect: %d", d)) |
||||
} |
||||
} |
||||
|
||||
func (d DialectType) DropIndex(name, table string) *DropIndexSqlBuilder { |
||||
switch d { |
||||
case DialectSQLite: |
||||
return &DropIndexSqlBuilder{Dialect: DialectSQLite, Name: name, Table: table} |
||||
case DialectMySQL: |
||||
return &DropIndexSqlBuilder{Dialect: DialectMySQL, Name: name, Table: table} |
||||
default: |
||||
panic(fmt.Sprintf("unexpected dialect: %d", d)) |
||||
} |
||||
} |
@ -0,0 +1,53 @@ |
||||
package db |
||||
|
||||
import ( |
||||
"fmt" |
||||
"strings" |
||||
) |
||||
|
||||
type CreateIndexSqlBuilder struct { |
||||
Dialect DialectType |
||||
Name string |
||||
Table string |
||||
Unique bool |
||||
Columns []string |
||||
} |
||||
|
||||
type DropIndexSqlBuilder struct { |
||||
Dialect DialectType |
||||
Name string |
||||
Table string |
||||
} |
||||
|
||||
func (b *CreateIndexSqlBuilder) ToSQL() (string, error) { |
||||
var str strings.Builder |
||||
|
||||
str.WriteString("CREATE ") |
||||
if b.Unique { |
||||
str.WriteString("UNIQUE ") |
||||
} |
||||
str.WriteString("INDEX ") |
||||
str.WriteString(b.Name) |
||||
str.WriteString(" on ") |
||||
str.WriteString(b.Table) |
||||
|
||||
if len(b.Columns) == 0 { |
||||
return "", fmt.Errorf("columns provided for this index: %s", b.Name) |
||||
} |
||||
|
||||
str.WriteString(" (") |
||||
columnCount := len(b.Columns) |
||||
for i, thing := range b.Columns { |
||||
str.WriteString(thing) |
||||
if i < columnCount-1 { |
||||
str.WriteString(", ") |
||||
} |
||||
} |
||||
str.WriteString(")") |
||||
|
||||
return str.String(), nil |
||||
} |
||||
|
||||
func (b *DropIndexSqlBuilder) ToSQL() (string, error) { |
||||
return fmt.Sprintf("DROP INDEX %s on %s", b.Name, b.Table), nil |
||||
} |
@ -0,0 +1,9 @@ |
||||
package db |
||||
|
||||
type RawSqlBuilder struct { |
||||
Query string |
||||
} |
||||
|
||||
func (b *RawSqlBuilder) ToSQL() (string, error) { |
||||
return b.Query, nil |
||||
} |
@ -0,0 +1,26 @@ |
||||
package db |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
) |
||||
|
||||
// TransactionScopedWork describes code executed within a database transaction.
|
||||
type TransactionScopedWork func(ctx context.Context, db *sql.Tx) error |
||||
|
||||
// RunTransactionWithOptions executes a block of code within a database transaction.
|
||||
func RunTransactionWithOptions(ctx context.Context, db *sql.DB, txOpts *sql.TxOptions, txWork TransactionScopedWork) error { |
||||
tx, err := db.BeginTx(ctx, txOpts) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
if err = txWork(ctx, tx); err != nil { |
||||
if txErr := tx.Rollback(); txErr != nil { |
||||
return txErr |
||||
} |
||||
return err |
||||
} |
||||
return tx.Commit() |
||||
} |
||||
|
@ -1,60 +1,61 @@ |
||||
module github.com/writeas/writefreely |
||||
|
||||
require ( |
||||
github.com/BurntSushi/toml v0.3.1 // indirect |
||||
github.com/alecthomas/gometalinter v3.0.0+incompatible // indirect |
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf // indirect |
||||
github.com/captncraig/cors v0.0.0-20180620154129-376d45073b49 // indirect |
||||
github.com/clbanning/mxj v1.8.4 // indirect |
||||
github.com/dustin/go-humanize v1.0.0 |
||||
github.com/fatih/color v1.7.0 |
||||
github.com/go-sql-driver/mysql v1.4.1 |
||||
github.com/fatih/color v1.9.0 |
||||
github.com/go-sql-driver/mysql v1.5.0 |
||||
github.com/go-test/deep v1.0.1 // indirect |
||||
github.com/golang/lint v0.0.0-20181217174547-8f45f776aaf1 // indirect |
||||
github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect |
||||
github.com/gorilla/feeds v1.1.0 |
||||
github.com/gorilla/mux v1.7.0 |
||||
github.com/gorilla/schema v1.0.2 |
||||
github.com/gorilla/sessions v1.1.3 |
||||
github.com/guregu/null v3.4.0+incompatible |
||||
github.com/gorilla/feeds v1.1.1 |
||||
github.com/gorilla/mux v1.7.4 |
||||
github.com/gorilla/schema v1.2.0 |
||||
github.com/gorilla/sessions v1.2.0 |
||||
github.com/guregu/null v3.5.0+incompatible |
||||
github.com/hashicorp/go-multierror v1.1.0 |
||||
github.com/ikeikeikeike/go-sitemap-generator/v2 v2.0.2 |
||||
github.com/jteeuwen/go-bindata v3.0.7+incompatible // indirect |
||||
github.com/jtolds/gls v4.2.1+incompatible // indirect |
||||
github.com/kylemcc/twitter-text-go v0.0.0-20180726194232-7f582f6736ec |
||||
github.com/lunixbochs/vtclean v1.0.0 // indirect |
||||
github.com/manifoldco/promptui v0.3.2 |
||||
github.com/mattn/go-colorable v0.1.0 // indirect |
||||
github.com/mattn/go-sqlite3 v1.10.0 |
||||
github.com/microcosm-cc/bluemonday v1.0.2 |
||||
github.com/manifoldco/promptui v0.7.0 |
||||
github.com/mattn/go-sqlite3 v1.14.2 |
||||
github.com/microcosm-cc/bluemonday v1.0.3 |
||||
github.com/mitchellh/go-wordwrap v1.0.0 |
||||
github.com/nicksnyder/go-i18n v1.10.0 // indirect |
||||
github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d |
||||
github.com/pelletier/go-toml v1.2.0 // indirect |
||||
github.com/pkg/errors v0.8.1 // indirect |
||||
github.com/prologic/go-gopher v0.0.0-20200721020712-3e11dcff0469 |
||||
github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be // indirect |
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect |
||||
github.com/smartystreets/assertions v0.0.0-20190116191733-b6c0e53d7304 // indirect |
||||
github.com/smartystreets/goconvey v0.0.0-20181108003508-044398e4856c // indirect |
||||
github.com/stretchr/testify v1.3.0 // indirect |
||||
github.com/stretchr/testify v1.6.1 |
||||
github.com/urfave/cli/v2 v2.2.0 |
||||
github.com/writeas/activity v0.1.2 |
||||
github.com/writeas/activityserve v0.0.0-20200409150223-d7ab3eaa4481 |
||||
github.com/writeas/go-strip-markdown v2.0.1+incompatible |
||||
github.com/writeas/go-webfinger v0.0.0-20190106002315-85cf805c86d2 |
||||
github.com/writeas/go-webfinger v1.1.0 |
||||
github.com/writeas/httpsig v1.0.0 |
||||
github.com/writeas/impart v1.1.0 |
||||
github.com/writeas/impart v1.1.1 |
||||
github.com/writeas/import v0.2.1 |
||||
github.com/writeas/monday v0.0.0-20181024183321-54a7dd579219 |
||||
github.com/writeas/nerds v1.0.0 |
||||
github.com/writeas/openssl-go v1.0.0 // indirect |
||||
github.com/writeas/saturday v1.7.1 |
||||
github.com/writeas/saturday v1.7.2-0.20200427193424-392b95a03320 |
||||
github.com/writeas/slug v1.2.0 |
||||
github.com/writeas/web-core v1.2.0 |
||||
github.com/writeas/web-core v1.2.1-0.20200813161734-68a680d1b03c |
||||
github.com/writefreely/go-nodeinfo v1.2.0 |
||||
golang.org/x/crypto v0.0.0-20190208162236-193df9c0f06f |
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 |
||||
golang.org/x/lint v0.0.0-20181217174547-8f45f776aaf1 // indirect |
||||
golang.org/x/net v0.0.0-20190206173232-65e2d4e15006 // indirect |
||||
golang.org/x/sys v0.0.0-20190209173611-3b5209105503 // indirect |
||||
golang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirect |
||||
golang.org/x/tools v0.0.0-20190208222737-3744606dbb67 // indirect |
||||
google.golang.org/appengine v1.4.0 // indirect |
||||
gopkg.in/alecthomas/kingpin.v3-unstable v3.0.0-20180810215634-df19058c872c // indirect |
||||
gopkg.in/ini.v1 v1.41.0 |
||||
gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0 // indirect |
||||
gopkg.in/yaml.v2 v2.2.2 // indirect |
||||
gopkg.in/ini.v1 v1.57.0 |
||||
src.techknowlogick.com/xgo v0.0.0-20200129005940-d0fae26e014b // indirect |
||||
) |
||||
|
||||
go 1.13 |
||||
|
@ -0,0 +1,146 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package writefreely |
||||
|
||||
import ( |
||||
"bytes" |
||||
"fmt" |
||||
"io" |
||||
"strings" |
||||
|
||||
"github.com/prologic/go-gopher" |
||||
"github.com/writeas/web-core/log" |
||||
) |
||||
|
||||
func initGopher(apper Apper) { |
||||
handler := NewWFHandler(apper) |
||||
|
||||
gopher.HandleFunc("/", handler.Gopher(handleGopher)) |
||||
log.Info("Serving on gopher://localhost:%d", apper.App().Config().Server.GopherPort) |
||||
gopher.ListenAndServe(fmt.Sprintf(":%d", apper.App().Config().Server.GopherPort), nil) |
||||
} |
||||
|
||||
func handleGopher(app *App, w gopher.ResponseWriter, r *gopher.Request) error { |
||||
parts := strings.Split(r.Selector, "/") |
||||
if app.cfg.App.SingleUser { |
||||
if parts[1] != "" { |
||||
return handleGopherCollectionPost(app, w, r) |
||||
} |
||||
return handleGopherCollection(app, w, r) |
||||
} |
||||
|
||||
// Show all public collections (a gopher Reader view, essentially)
|
||||
if len(parts) == 3 { |
||||
return handleGopherCollection(app, w, r) |
||||
} |
||||
|
||||
w.WriteInfo(fmt.Sprintf("Welcome to %s", app.cfg.App.SiteName)) |
||||
|
||||
colls, err := app.db.GetPublicCollections(app.cfg.App.Host) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
for _, c := range *colls { |
||||
w.WriteItem(&gopher.Item{ |
||||
Type: gopher.DIRECTORY, |
||||
Description: c.DisplayTitle(), |
||||
Selector: "/" + c.Alias + "/", |
||||
}) |
||||
} |
||||
return w.End() |
||||
} |
||||
|
||||
func handleGopherCollection(app *App, w gopher.ResponseWriter, r *gopher.Request) error { |
||||
var collAlias, slug string |
||||
var c *Collection |
||||
var err error |
||||
var baseSel = "/" |
||||
|
||||
parts := strings.Split(r.Selector, "/") |
||||
if app.cfg.App.SingleUser { |
||||
// sanity check
|
||||
slug = parts[1] |
||||
if slug != "" { |
||||
return handleGopherCollectionPost(app, w, r) |
||||
} |
||||
|
||||
c, err = app.db.GetCollectionByID(1) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
} else { |
||||
collAlias = parts[1] |
||||
slug = parts[2] |
||||
if slug != "" { |
||||
return handleGopherCollectionPost(app, w, r) |
||||
} |
||||
|
||||
c, err = app.db.GetCollection(collAlias) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
baseSel = "/" + c.Alias + "/" |
||||
} |
||||
c.hostName = app.cfg.App.Host |
||||
|
||||
posts, err := app.db.GetPosts(app.cfg, c, 0, false, false, false) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
for _, p := range *posts { |
||||
w.WriteItem(&gopher.Item{ |
||||
Type: gopher.FILE, |
||||
Description: p.CreatedDate() + " - " + p.DisplayTitle(), |
||||
Selector: baseSel + p.Slug.String, |
||||
}) |
||||
} |
||||
return w.End() |
||||
} |
||||
|
||||
func handleGopherCollectionPost(app *App, w gopher.ResponseWriter, r *gopher.Request) error { |
||||
var collAlias, slug string |
||||
var c *Collection |
||||
var err error |
||||
|
||||
parts := strings.Split(r.Selector, "/") |
||||
if app.cfg.App.SingleUser { |
||||
slug = parts[1] |
||||
c, err = app.db.GetCollectionByID(1) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
} else { |
||||
collAlias = parts[1] |
||||
slug = parts[2] |
||||
c, err = app.db.GetCollection(collAlias) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
} |
||||
c.hostName = app.cfg.App.Host |
||||
|
||||
p, err := app.db.GetPost(slug, c.ID) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
b := bytes.Buffer{} |
||||
if p.Title.String != "" { |
||||
b.WriteString(p.Title.String + "\n") |
||||
} |
||||
b.WriteString(p.DisplayDate + "\n\n") |
||||
b.WriteString(p.Content) |
||||
io.Copy(w, &b) |
||||
|
||||
return w.End() |
||||
} |
@ -0,0 +1,91 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
.row.signinbtns { |
||||
justify-content: center; |
||||
font-size: 1em; |
||||
margin-top: 2em; |
||||
margin-bottom: 1em; |
||||
flex-wrap: wrap; |
||||
|
||||
.loginbtn { |
||||
height: 40px; |
||||
margin: 0.5em; |
||||
|
||||
&.btn { |
||||
box-sizing: border-box; |
||||
font-size: 17px; |
||||
white-space: nowrap; |
||||
|
||||
img { |
||||
height: 1.5em; |
||||
vertical-align: middle; |
||||
} |
||||
} |
||||
|
||||
&#writeas-login, &#slack-login { |
||||
img { |
||||
margin-top: -0.2em; |
||||
} |
||||
} |
||||
|
||||
&#gitlab-login { |
||||
background-color: #fc6d26; |
||||
border-color: #fc6d26; |
||||
&:hover { |
||||
background-color: darken(#fc6d26, 5%); |
||||
border-color: darken(#fc6d26, 5%); |
||||
} |
||||
} |
||||
|
||||
&#gitea-login { |
||||
background-color: #2ecc71; |
||||
border-color: #2ecc71; |
||||
&:hover { |
||||
background-color: #2cc26b; |
||||
border-color: #2cc26b; |
||||
} |
||||
} |
||||
|
||||
&#slack-login, &#gitlab-login, &#gitea-login, &#generic-oauth-login { |
||||
font-size: 0.86em; |
||||
font-family: @sansFont; |
||||
} |
||||
|
||||
&#slack-login, &#generic-oauth-login { |
||||
color: @lightTextColor; |
||||
background-color: @lightNavBG; |
||||
border-color: @lightNavBorder; |
||||
&:hover { |
||||
background-color: @lightNavHoverBG; |
||||
} |
||||
} |
||||
} |
||||
} |
||||
|
||||
.or { |
||||
text-align: center; |
||||
margin-bottom: 3.5em; |
||||
|
||||
p { |
||||
display: inline-block; |
||||
background-color: white; |
||||
padding: 0 1em; |
||||
} |
||||
|
||||
hr { |
||||
margin-top: -1.6em; |
||||
margin-bottom: 0; |
||||
} |
||||
|
||||
hr.short { |
||||
max-width: 30rem; |
||||
} |
||||
} |
@ -0,0 +1,153 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
"encoding/gob" |
||||
"errors" |
||||
"fmt" |
||||
uuid "github.com/nu7hatch/gouuid" |
||||
"github.com/stretchr/testify/assert" |
||||
"math/rand" |
||||
"os" |
||||
"strings" |
||||
"testing" |
||||
"time" |
||||
) |
||||
|
||||
var testDB *sql.DB |
||||
|
||||
type ScopedTestBody func(*sql.DB) |
||||
|
||||
// TestMain provides testing infrastructure within this package.
|
||||
func TestMain(m *testing.M) { |
||||
rand.Seed(time.Now().UTC().UnixNano()) |
||||
gob.Register(&User{}) |
||||
|
||||
if runMySQLTests() { |
||||
var err error |
||||
|
||||
testDB, err = initMySQL(os.Getenv("WF_USER"), os.Getenv("WF_PASSWORD"), os.Getenv("WF_DB"), os.Getenv("WF_HOST")) |
||||
if err != nil { |
||||
fmt.Println(err) |
||||
return |
||||
} |
||||
} |
||||
|
||||
code := m.Run() |
||||
if runMySQLTests() { |
||||
if closeErr := testDB.Close(); closeErr != nil { |
||||
fmt.Println(closeErr) |
||||
} |
||||
} |
||||
os.Exit(code) |
||||
} |
||||
|
||||
func runMySQLTests() bool { |
||||
return len(os.Getenv("TEST_MYSQL")) > 0 |
||||
} |
||||
|
||||
func initMySQL(dbUser, dbPassword, dbName, dbHost string) (*sql.DB, error) { |
||||
if dbUser == "" || dbPassword == "" { |
||||
return nil, errors.New("database user or password not set") |
||||
} |
||||
if dbHost == "" { |
||||
dbHost = "localhost" |
||||
} |
||||
if dbName == "" { |
||||
dbName = "writefreely" |
||||
} |
||||
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8mb4&parseTime=true", dbUser, dbPassword, dbHost, dbName) |
||||
db, err := sql.Open("mysql", dsn) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if err := ensureMySQL(db); err != nil { |
||||
return nil, err |
||||
} |
||||
return db, nil |
||||
} |
||||
|
||||
func ensureMySQL(db *sql.DB) error { |
||||
if err := db.Ping(); err != nil { |
||||
return err |
||||
} |
||||
db.SetMaxOpenConns(250) |
||||
return nil |
||||
} |
||||
|
||||
// withTestDB provides a scoped database connection.
|
||||
func withTestDB(t *testing.T, testBody ScopedTestBody) { |
||||
db, cleanup, err := newTestDatabase(testDB, |
||||
os.Getenv("WF_USER"), |
||||
os.Getenv("WF_PASSWORD"), |
||||
os.Getenv("WF_DB"), |
||||
os.Getenv("WF_HOST"), |
||||
) |
||||
assert.NoError(t, err) |
||||
defer func() { |
||||
assert.NoError(t, cleanup()) |
||||
}() |
||||
|
||||
testBody(db) |
||||
} |
||||
|
||||
// newTestDatabase creates a new temporary test database. When a test
|
||||
// database connection is returned, it will have created a new database and
|
||||
// initialized it with tables from a reference database.
|
||||
func newTestDatabase(base *sql.DB, dbUser, dbPassword, dbName, dbHost string) (*sql.DB, func() error, error) { |
||||
var err error |
||||
var baseName = dbName |
||||
|
||||
if baseName == "" { |
||||
row := base.QueryRow("SELECT DATABASE()") |
||||
err := row.Scan(&baseName) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
} |
||||
tUUID, _ := uuid.NewV4() |
||||
suffix := strings.Replace(tUUID.String(), "-", "_", -1) |
||||
newDBName := baseName + suffix |
||||
_, err = base.Exec("CREATE DATABASE " + newDBName) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
newDB, err := initMySQL(dbUser, dbPassword, newDBName, dbHost) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
|
||||
rows, err := base.Query("SHOW TABLES IN " + baseName) |
||||
if err != nil { |
||||
return nil, nil, err |
||||
} |
||||
for rows.Next() { |
||||
var tableName string |
||||
if err := rows.Scan(&tableName); err != nil { |
||||
return nil, nil, err |
||||
} |
||||
query := fmt.Sprintf("CREATE TABLE %s LIKE %s.%s", tableName, baseName, tableName) |
||||
if _, err := newDB.Exec(query); err != nil { |
||||
return nil, nil, err |
||||
} |
||||
} |
||||
|
||||
cleanup := func() error { |
||||
if closeErr := newDB.Close(); closeErr != nil { |
||||
fmt.Println(closeErr) |
||||
} |
||||
|
||||
_, err = base.Exec("DROP DATABASE " + newDBName) |
||||
return err |
||||
} |
||||
return newDB, cleanup, nil |
||||
} |
||||
|
||||
func countRows(t *testing.T, ctx context.Context, db *sql.DB, count int, query string, args ...interface{}) { |
||||
var returned int |
||||
err := db.QueryRowContext(ctx, query, args...).Scan(&returned) |
||||
assert.NoError(t, err, "error executing query %s and args %s", query, args) |
||||
assert.Equal(t, count, returned, "unexpected return count %d, expected %d from %s and args %s", returned, count, query, args) |
||||
} |
@ -0,0 +1,33 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package migrations |
||||
|
||||
func supportPostSignatures(db *datastore) error { |
||||
t, err := db.Begin() |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
_, err = t.Exec(`ALTER TABLE collections ADD COLUMN post_signature ` + db.typeText() + db.collateMultiByte() + ` NULL` + db.after("script")) |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
err = t.Commit() |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
return nil |
||||
} |
@ -0,0 +1,54 @@ |
||||
/* |
||||
* Copyright © 2019-2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package migrations |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
|
||||
wf_db "github.com/writeas/writefreely/db" |
||||
) |
||||
|
||||
func oauth(db *datastore) error { |
||||
dialect := wf_db.DialectMySQL |
||||
if db.driverName == driverSQLite { |
||||
dialect = wf_db.DialectSQLite |
||||
} |
||||
return wf_db.RunTransactionWithOptions(context.Background(), db.DB, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error { |
||||
createTableUsersOauth, err := dialect. |
||||
Table("oauth_users"). |
||||
SetIfNotExists(false). |
||||
Column(dialect.Column("user_id", wf_db.ColumnTypeInteger, wf_db.UnsetSize)). |
||||
Column(dialect.Column("remote_user_id", wf_db.ColumnTypeInteger, wf_db.UnsetSize)). |
||||
ToSQL() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
createTableOauthClientState, err := dialect. |
||||
Table("oauth_client_states"). |
||||
SetIfNotExists(false). |
||||
Column(dialect.Column("state", wf_db.ColumnTypeVarChar, wf_db.OptionalInt{Set: true, Value: 255})). |
||||
Column(dialect.Column("used", wf_db.ColumnTypeBool, wf_db.UnsetSize)). |
||||
Column(dialect.Column("created_at", wf_db.ColumnTypeDateTime, wf_db.UnsetSize).SetDefaultCurrentTimestamp()). |
||||
UniqueConstraint("state"). |
||||
ToSQL() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
|
||||
for _, table := range []string{createTableUsersOauth, createTableOauthClientState} { |
||||
if _, err := tx.ExecContext(ctx, table); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
return nil |
||||
}) |
||||
} |
@ -0,0 +1,88 @@ |
||||
/* |
||||
* Copyright © 2019-2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package migrations |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
|
||||
wf_db "github.com/writeas/writefreely/db" |
||||
) |
||||
|
||||
func oauthSlack(db *datastore) error { |
||||
dialect := wf_db.DialectMySQL |
||||
if db.driverName == driverSQLite { |
||||
dialect = wf_db.DialectSQLite |
||||
} |
||||
return wf_db.RunTransactionWithOptions(context.Background(), db.DB, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error { |
||||
builders := []wf_db.SQLBuilder{ |
||||
dialect. |
||||
AlterTable("oauth_client_states"). |
||||
AddColumn(dialect. |
||||
Column( |
||||
"provider", |
||||
wf_db.ColumnTypeVarChar, |
||||
wf_db.OptionalInt{Set: true, Value: 24}).SetDefault("")), |
||||
dialect. |
||||
AlterTable("oauth_client_states"). |
||||
AddColumn(dialect. |
||||
Column( |
||||
"client_id", |
||||
wf_db.ColumnTypeVarChar, |
||||
wf_db.OptionalInt{Set: true, Value: 128}).SetDefault("")), |
||||
dialect. |
||||
AlterTable("oauth_users"). |
||||
AddColumn(dialect. |
||||
Column( |
||||
"provider", |
||||
wf_db.ColumnTypeVarChar, |
||||
wf_db.OptionalInt{Set: true, Value: 24}).SetDefault("")), |
||||
dialect. |
||||
AlterTable("oauth_users"). |
||||
AddColumn(dialect. |
||||
Column( |
||||
"client_id", |
||||
wf_db.ColumnTypeVarChar, |
||||
wf_db.OptionalInt{Set: true, Value: 128}).SetDefault("")), |
||||
dialect. |
||||
AlterTable("oauth_users"). |
||||
AddColumn(dialect. |
||||
Column( |
||||
"access_token", |
||||
wf_db.ColumnTypeVarChar, |
||||
wf_db.OptionalInt{Set: true, Value: 512}).SetDefault("")), |
||||
dialect.CreateUniqueIndex("oauth_users_uk", "oauth_users", "user_id", "provider", "client_id"), |
||||
} |
||||
|
||||
if dialect != wf_db.DialectSQLite { |
||||
// This updates the length of the `remote_user_id` column. It isn't needed for SQLite databases.
|
||||
builders = append(builders, dialect. |
||||
AlterTable("oauth_users"). |
||||
ChangeColumn("remote_user_id", |
||||
dialect. |
||||
Column( |
||||
"remote_user_id", |
||||
wf_db.ColumnTypeVarChar, |
||||
wf_db.OptionalInt{Set: true, Value: 128}))) |
||||
} |
||||
|
||||
for _, builder := range builders { |
||||
query, err := builder.ToSQL() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if _, err := tx.ExecContext(ctx, query); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
return nil |
||||
}) |
||||
} |
@ -0,0 +1,29 @@ |
||||
/* |
||||
* Copyright © 2019-2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package migrations |
||||
|
||||
func supportActivityPubMentions(db *datastore) error { |
||||
t, err := db.Begin() |
||||
|
||||
_, err = t.Exec(`ALTER TABLE remoteusers ADD COLUMN handle ` + db.typeVarChar(255) + ` NULL`) |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
err = t.Commit() |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
return nil |
||||
} |
@ -0,0 +1,36 @@ |
||||
package migrations |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
|
||||
wf_db "github.com/writeas/writefreely/db" |
||||
) |
||||
|
||||
func oauthAttach(db *datastore) error { |
||||
dialect := wf_db.DialectMySQL |
||||
if db.driverName == driverSQLite { |
||||
dialect = wf_db.DialectSQLite |
||||
} |
||||
return wf_db.RunTransactionWithOptions(context.Background(), db.DB, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error { |
||||
builders := []wf_db.SQLBuilder{ |
||||
dialect. |
||||
AlterTable("oauth_client_states"). |
||||
AddColumn(dialect. |
||||
Column( |
||||
"attach_user_id", |
||||
wf_db.ColumnTypeInteger, |
||||
wf_db.OptionalInt{Set: true, Value: 24}).SetNullable(true)), |
||||
} |
||||
for _, builder := range builders { |
||||
query, err := builder.ToSQL() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if _, err := tx.ExecContext(ctx, query); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
return nil |
||||
}) |
||||
} |
@ -0,0 +1,45 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package migrations |
||||
|
||||
import ( |
||||
"context" |
||||
"database/sql" |
||||
|
||||
wf_db "github.com/writeas/writefreely/db" |
||||
) |
||||
|
||||
func oauthInvites(db *datastore) error { |
||||
dialect := wf_db.DialectMySQL |
||||
if db.driverName == driverSQLite { |
||||
dialect = wf_db.DialectSQLite |
||||
} |
||||
return wf_db.RunTransactionWithOptions(context.Background(), db.DB, &sql.TxOptions{}, func(ctx context.Context, tx *sql.Tx) error { |
||||
builders := []wf_db.SQLBuilder{ |
||||
dialect. |
||||
AlterTable("oauth_client_states"). |
||||
AddColumn(dialect.Column("invite_code", wf_db.ColumnTypeChar, wf_db.OptionalInt{ |
||||
Set: true, |
||||
Value: 6, |
||||
}).SetNullable(true)), |
||||
} |
||||
for _, builder := range builders { |
||||
query, err := builder.ToSQL() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if _, err := tx.ExecContext(ctx, query); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
return nil |
||||
}) |
||||
} |
@ -0,0 +1,37 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package migrations |
||||
|
||||
func optimizeDrafts(db *datastore) error { |
||||
t, err := db.Begin() |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
if db.driverName == driverSQLite { |
||||
_, err = t.Exec(`CREATE INDEX key_owner_post_id ON posts (owner_id, id)`) |
||||
} else { |
||||
_, err = t.Exec(`ALTER TABLE posts ADD INDEX(owner_id, id)`) |
||||
} |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
err = t.Commit() |
||||
if err != nil { |
||||
t.Rollback() |
||||
return err |
||||
} |
||||
|
||||
return nil |
||||
} |
@ -0,0 +1,462 @@ |
||||
/* |
||||
* Copyright © 2019-2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"encoding/json" |
||||
"fmt" |
||||
"io" |
||||
"io/ioutil" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
"time" |
||||
|
||||
"github.com/gorilla/mux" |
||||
"github.com/gorilla/sessions" |
||||
"github.com/writeas/impart" |
||||
"github.com/writeas/web-core/log" |
||||
"github.com/writeas/writefreely/config" |
||||
) |
||||
|
||||
// OAuthButtons holds display information for different OAuth providers we support.
|
||||
type OAuthButtons struct { |
||||
SlackEnabled bool |
||||
WriteAsEnabled bool |
||||
GitLabEnabled bool |
||||
GitLabDisplayName string |
||||
GiteaEnabled bool |
||||
GiteaDisplayName string |
||||
GenericEnabled bool |
||||
GenericDisplayName string |
||||
} |
||||
|
||||
// NewOAuthButtons creates a new OAuthButtons struct based on our app configuration.
|
||||
func NewOAuthButtons(cfg *config.Config) *OAuthButtons { |
||||
return &OAuthButtons{ |
||||
SlackEnabled: cfg.SlackOauth.ClientID != "", |
||||
WriteAsEnabled: cfg.WriteAsOauth.ClientID != "", |
||||
GitLabEnabled: cfg.GitlabOauth.ClientID != "", |
||||
GitLabDisplayName: config.OrDefaultString(cfg.GitlabOauth.DisplayName, gitlabDisplayName), |
||||
GiteaEnabled: cfg.GiteaOauth.ClientID != "", |
||||
GiteaDisplayName: config.OrDefaultString(cfg.GiteaOauth.DisplayName, giteaDisplayName), |
||||
GenericEnabled: cfg.GenericOauth.ClientID != "", |
||||
GenericDisplayName: config.OrDefaultString(cfg.GenericOauth.DisplayName, genericOauthDisplayName), |
||||
} |
||||
} |
||||
|
||||
// TokenResponse contains data returned when a token is created either
|
||||
// through a code exchange or using a refresh token.
|
||||
type TokenResponse struct { |
||||
AccessToken string `json:"access_token"` |
||||
ExpiresIn int `json:"expires_in"` |
||||
RefreshToken string `json:"refresh_token"` |
||||
TokenType string `json:"token_type"` |
||||
Error string `json:"error"` |
||||
} |
||||
|
||||
// InspectResponse contains data returned when an access token is inspected.
|
||||
type InspectResponse struct { |
||||
ClientID string `json:"client_id"` |
||||
UserID string `json:"user_id"` |
||||
ExpiresAt time.Time `json:"expires_at"` |
||||
Username string `json:"username"` |
||||
DisplayName string `json:"-"` |
||||
Email string `json:"email"` |
||||
Error string `json:"error"` |
||||
} |
||||
|
||||
// tokenRequestMaxLen is the most bytes that we'll read from the /oauth/token
|
||||
// endpoint. One megabyte is plenty.
|
||||
const tokenRequestMaxLen = 1000000 |
||||
|
||||
// infoRequestMaxLen is the most bytes that we'll read from the
|
||||
// /oauth/inspect endpoint.
|
||||
const infoRequestMaxLen = 1000000 |
||||
|
||||
// OAuthDatastoreProvider provides a minimal interface of data store, config,
|
||||
// and session store for use with the oauth handlers.
|
||||
type OAuthDatastoreProvider interface { |
||||
DB() OAuthDatastore |
||||
Config() *config.Config |
||||
SessionStore() sessions.Store |
||||
} |
||||
|
||||
// OAuthDatastore provides a minimal interface of data store methods used in
|
||||
// oauth functionality.
|
||||
type OAuthDatastore interface { |
||||
GetIDForRemoteUser(context.Context, string, string, string) (int64, error) |
||||
RecordRemoteUserID(context.Context, int64, string, string, string, string) error |
||||
ValidateOAuthState(context.Context, string) (string, string, int64, string, error) |
||||
GenerateOAuthState(context.Context, string, string, int64, string) (string, error) |
||||
|
||||
CreateUser(*config.Config, *User, string) error |
||||
GetUserByID(int64) (*User, error) |
||||
} |
||||
|
||||
type HttpClient interface { |
||||
Do(req *http.Request) (*http.Response, error) |
||||
} |
||||
|
||||
type oauthClient interface { |
||||
GetProvider() string |
||||
GetClientID() string |
||||
GetCallbackLocation() string |
||||
buildLoginURL(state string) (string, error) |
||||
exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) |
||||
inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) |
||||
} |
||||
|
||||
type callbackProxyClient struct { |
||||
server string |
||||
callbackLocation string |
||||
httpClient HttpClient |
||||
} |
||||
|
||||
type oauthHandler struct { |
||||
Config *config.Config |
||||
DB OAuthDatastore |
||||
Store sessions.Store |
||||
EmailKey []byte |
||||
oauthClient oauthClient |
||||
callbackProxy *callbackProxyClient |
||||
} |
||||
|
||||
func (h oauthHandler) viewOauthInit(app *App, w http.ResponseWriter, r *http.Request) error { |
||||
ctx := r.Context() |
||||
|
||||
var attachUser int64 |
||||
if attach := r.URL.Query().Get("attach"); attach == "t" { |
||||
user, _ := getUserAndSession(app, r) |
||||
if user == nil { |
||||
return impart.HTTPError{http.StatusInternalServerError, "cannot attach auth to user: user not found in session"} |
||||
} |
||||
attachUser = user.ID |
||||
} |
||||
|
||||
state, err := h.DB.GenerateOAuthState(ctx, h.oauthClient.GetProvider(), h.oauthClient.GetClientID(), attachUser, r.FormValue("invite_code")) |
||||
if err != nil { |
||||
log.Error("viewOauthInit error: %s", err) |
||||
return impart.HTTPError{http.StatusInternalServerError, "could not prepare oauth redirect url"} |
||||
} |
||||
|
||||
if h.callbackProxy != nil { |
||||
if err := h.callbackProxy.register(ctx, state); err != nil { |
||||
log.Error("viewOauthInit error: %s", err) |
||||
return impart.HTTPError{http.StatusInternalServerError, "could not register state server"} |
||||
} |
||||
} |
||||
|
||||
location, err := h.oauthClient.buildLoginURL(state) |
||||
if err != nil { |
||||
log.Error("viewOauthInit error: %s", err) |
||||
return impart.HTTPError{http.StatusInternalServerError, "could not prepare oauth redirect url"} |
||||
} |
||||
return impart.HTTPError{http.StatusTemporaryRedirect, location} |
||||
} |
||||
|
||||
func configureSlackOauth(parentHandler *Handler, r *mux.Router, app *App) { |
||||
if app.Config().SlackOauth.ClientID != "" { |
||||
callbackLocation := app.Config().App.Host + "/oauth/callback/slack" |
||||
|
||||
var stateRegisterClient *callbackProxyClient = nil |
||||
if app.Config().SlackOauth.CallbackProxyAPI != "" { |
||||
stateRegisterClient = &callbackProxyClient{ |
||||
server: app.Config().SlackOauth.CallbackProxyAPI, |
||||
callbackLocation: app.Config().App.Host + "/oauth/callback/slack", |
||||
httpClient: config.DefaultHTTPClient(), |
||||
} |
||||
callbackLocation = app.Config().SlackOauth.CallbackProxy |
||||
} |
||||
oauthClient := slackOauthClient{ |
||||
ClientID: app.Config().SlackOauth.ClientID, |
||||
ClientSecret: app.Config().SlackOauth.ClientSecret, |
||||
TeamID: app.Config().SlackOauth.TeamID, |
||||
HttpClient: config.DefaultHTTPClient(), |
||||
CallbackLocation: callbackLocation, |
||||
} |
||||
configureOauthRoutes(parentHandler, r, app, oauthClient, stateRegisterClient) |
||||
} |
||||
} |
||||
|
||||
func configureWriteAsOauth(parentHandler *Handler, r *mux.Router, app *App) { |
||||
if app.Config().WriteAsOauth.ClientID != "" { |
||||
callbackLocation := app.Config().App.Host + "/oauth/callback/write.as" |
||||
|
||||
var callbackProxy *callbackProxyClient = nil |
||||
if app.Config().WriteAsOauth.CallbackProxy != "" { |
||||
callbackProxy = &callbackProxyClient{ |
||||
server: app.Config().WriteAsOauth.CallbackProxyAPI, |
||||
callbackLocation: app.Config().App.Host + "/oauth/callback/write.as", |
||||
httpClient: config.DefaultHTTPClient(), |
||||
} |
||||
callbackLocation = app.Config().WriteAsOauth.CallbackProxy |
||||
} |
||||
|
||||
oauthClient := writeAsOauthClient{ |
||||
ClientID: app.Config().WriteAsOauth.ClientID, |
||||
ClientSecret: app.Config().WriteAsOauth.ClientSecret, |
||||
ExchangeLocation: config.OrDefaultString(app.Config().WriteAsOauth.TokenLocation, writeAsExchangeLocation), |
||||
InspectLocation: config.OrDefaultString(app.Config().WriteAsOauth.InspectLocation, writeAsIdentityLocation), |
||||
AuthLocation: config.OrDefaultString(app.Config().WriteAsOauth.AuthLocation, writeAsAuthLocation), |
||||
HttpClient: config.DefaultHTTPClient(), |
||||
CallbackLocation: callbackLocation, |
||||
} |
||||
configureOauthRoutes(parentHandler, r, app, oauthClient, callbackProxy) |
||||
} |
||||
} |
||||
|
||||
func configureGitlabOauth(parentHandler *Handler, r *mux.Router, app *App) { |
||||
if app.Config().GitlabOauth.ClientID != "" { |
||||
callbackLocation := app.Config().App.Host + "/oauth/callback/gitlab" |
||||
|
||||
var callbackProxy *callbackProxyClient = nil |
||||
if app.Config().GitlabOauth.CallbackProxy != "" { |
||||
callbackProxy = &callbackProxyClient{ |
||||
server: app.Config().GitlabOauth.CallbackProxyAPI, |
||||
callbackLocation: app.Config().App.Host + "/oauth/callback/gitlab", |
||||
httpClient: config.DefaultHTTPClient(), |
||||
} |
||||
callbackLocation = app.Config().GitlabOauth.CallbackProxy |
||||
} |
||||
|
||||
address := config.OrDefaultString(app.Config().GitlabOauth.Host, gitlabHost) |
||||
oauthClient := gitlabOauthClient{ |
||||
ClientID: app.Config().GitlabOauth.ClientID, |
||||
ClientSecret: app.Config().GitlabOauth.ClientSecret, |
||||
ExchangeLocation: address + "/oauth/token", |
||||
InspectLocation: address + "/api/v4/user", |
||||
AuthLocation: address + "/oauth/authorize", |
||||
HttpClient: config.DefaultHTTPClient(), |
||||
CallbackLocation: callbackLocation, |
||||
} |
||||
configureOauthRoutes(parentHandler, r, app, oauthClient, callbackProxy) |
||||
} |
||||
} |
||||
|
||||
func configureGenericOauth(parentHandler *Handler, r *mux.Router, app *App) { |
||||
if app.Config().GenericOauth.ClientID != "" { |
||||
callbackLocation := app.Config().App.Host + "/oauth/callback/generic" |
||||
|
||||
var callbackProxy *callbackProxyClient = nil |
||||
if app.Config().GenericOauth.CallbackProxy != "" { |
||||
callbackProxy = &callbackProxyClient{ |
||||
server: app.Config().GenericOauth.CallbackProxyAPI, |
||||
callbackLocation: app.Config().App.Host + "/oauth/callback/generic", |
||||
httpClient: config.DefaultHTTPClient(), |
||||
} |
||||
callbackLocation = app.Config().GenericOauth.CallbackProxy |
||||
} |
||||
|
||||
oauthClient := genericOauthClient{ |
||||
ClientID: app.Config().GenericOauth.ClientID, |
||||
ClientSecret: app.Config().GenericOauth.ClientSecret, |
||||
ExchangeLocation: app.Config().GenericOauth.Host + app.Config().GenericOauth.TokenEndpoint, |
||||
InspectLocation: app.Config().GenericOauth.Host + app.Config().GenericOauth.InspectEndpoint, |
||||
AuthLocation: app.Config().GenericOauth.Host + app.Config().GenericOauth.AuthEndpoint, |
||||
HttpClient: config.DefaultHTTPClient(), |
||||
CallbackLocation: callbackLocation, |
||||
} |
||||
configureOauthRoutes(parentHandler, r, app, oauthClient, callbackProxy) |
||||
} |
||||
} |
||||
|
||||
func configureGiteaOauth(parentHandler *Handler, r *mux.Router, app *App) { |
||||
if app.Config().GiteaOauth.ClientID != "" { |
||||
callbackLocation := app.Config().App.Host + "/oauth/callback/gitea" |
||||
|
||||
var callbackProxy *callbackProxyClient = nil |
||||
if app.Config().GiteaOauth.CallbackProxy != "" { |
||||
callbackProxy = &callbackProxyClient{ |
||||
server: app.Config().GiteaOauth.CallbackProxyAPI, |
||||
callbackLocation: app.Config().App.Host + "/oauth/callback/gitea", |
||||
httpClient: config.DefaultHTTPClient(), |
||||
} |
||||
callbackLocation = app.Config().GiteaOauth.CallbackProxy |
||||
} |
||||
|
||||
oauthClient := giteaOauthClient{ |
||||
ClientID: app.Config().GiteaOauth.ClientID, |
||||
ClientSecret: app.Config().GiteaOauth.ClientSecret, |
||||
ExchangeLocation: app.Config().GiteaOauth.Host + "/login/oauth/access_token", |
||||
InspectLocation: app.Config().GiteaOauth.Host + "/api/v1/user", |
||||
AuthLocation: app.Config().GiteaOauth.Host + "/login/oauth/authorize", |
||||
HttpClient: config.DefaultHTTPClient(), |
||||
CallbackLocation: callbackLocation, |
||||
} |
||||
configureOauthRoutes(parentHandler, r, app, oauthClient, callbackProxy) |
||||
} |
||||
} |
||||
|
||||
func configureOauthRoutes(parentHandler *Handler, r *mux.Router, app *App, oauthClient oauthClient, callbackProxy *callbackProxyClient) { |
||||
handler := &oauthHandler{ |
||||
Config: app.Config(), |
||||
DB: app.DB(), |
||||
Store: app.SessionStore(), |
||||
oauthClient: oauthClient, |
||||
EmailKey: app.keys.EmailKey, |
||||
callbackProxy: callbackProxy, |
||||
} |
||||
r.HandleFunc("/oauth/"+oauthClient.GetProvider(), parentHandler.OAuth(handler.viewOauthInit)).Methods("GET") |
||||
r.HandleFunc("/oauth/callback/"+oauthClient.GetProvider(), parentHandler.OAuth(handler.viewOauthCallback)).Methods("GET") |
||||
r.HandleFunc("/oauth/signup", parentHandler.OAuth(handler.viewOauthSignup)).Methods("POST") |
||||
} |
||||
|
||||
func (h oauthHandler) viewOauthCallback(app *App, w http.ResponseWriter, r *http.Request) error { |
||||
ctx := r.Context() |
||||
|
||||
code := r.FormValue("code") |
||||
state := r.FormValue("state") |
||||
|
||||
provider, clientID, attachUserID, inviteCode, err := h.DB.ValidateOAuthState(ctx, state) |
||||
if err != nil { |
||||
log.Error("Unable to ValidateOAuthState: %s", err) |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
|
||||
tokenResponse, err := h.oauthClient.exchangeOauthCode(ctx, code) |
||||
if err != nil { |
||||
log.Error("Unable to exchangeOauthCode: %s", err) |
||||
// TODO: show user friendly message if needed
|
||||
// TODO: show NO message for cases like user pressing "Cancel" on authorize step
|
||||
addSessionFlash(app, w, r, err.Error(), nil) |
||||
if attachUserID > 0 { |
||||
return impart.HTTPError{http.StatusFound, "/me/settings"} |
||||
} |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
|
||||
// Now that we have the access token, let's use it real quick to make sure
|
||||
// it really really works.
|
||||
tokenInfo, err := h.oauthClient.inspectOauthAccessToken(ctx, tokenResponse.AccessToken) |
||||
if err != nil { |
||||
log.Error("Unable to inspectOauthAccessToken: %s", err) |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
|
||||
localUserID, err := h.DB.GetIDForRemoteUser(ctx, tokenInfo.UserID, provider, clientID) |
||||
if err != nil { |
||||
log.Error("Unable to GetIDForRemoteUser: %s", err) |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
|
||||
if localUserID != -1 && attachUserID > 0 { |
||||
if err = addSessionFlash(app, w, r, "This Slack account is already attached to another user.", nil); err != nil { |
||||
return impart.HTTPError{Status: http.StatusInternalServerError, Message: err.Error()} |
||||
} |
||||
return impart.HTTPError{http.StatusFound, "/me/settings"} |
||||
} |
||||
|
||||
if localUserID != -1 { |
||||
// Existing user, so log in now
|
||||
user, err := h.DB.GetUserByID(localUserID) |
||||
if err != nil { |
||||
log.Error("Unable to GetUserByID %d: %s", localUserID, err) |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
if err = loginOrFail(h.Store, w, r, user); err != nil { |
||||
log.Error("Unable to loginOrFail %d: %s", localUserID, err) |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
return nil |
||||
} |
||||
if attachUserID > 0 { |
||||
log.Info("attaching to user %d", attachUserID) |
||||
err = h.DB.RecordRemoteUserID(r.Context(), attachUserID, tokenInfo.UserID, provider, clientID, tokenResponse.AccessToken) |
||||
if err != nil { |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
return impart.HTTPError{http.StatusFound, "/me/settings"} |
||||
} |
||||
|
||||
// New user registration below.
|
||||
// First, verify that user is allowed to register
|
||||
if inviteCode != "" { |
||||
// Verify invite code is valid
|
||||
i, err := app.db.GetUserInvite(inviteCode) |
||||
if err != nil { |
||||
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||
} |
||||
if !i.Active(app.db) { |
||||
return impart.HTTPError{http.StatusNotFound, "Invite link has expired."} |
||||
} |
||||
} else if !app.cfg.App.OpenRegistration { |
||||
addSessionFlash(app, w, r, ErrUserNotFound.Error(), nil) |
||||
return impart.HTTPError{http.StatusFound, "/login"} |
||||
} |
||||
|
||||
displayName := tokenInfo.DisplayName |
||||
if len(displayName) == 0 { |
||||
displayName = tokenInfo.Username |
||||
} |
||||
|
||||
tp := &oauthSignupPageParams{ |
||||
AccessToken: tokenResponse.AccessToken, |
||||
TokenUsername: tokenInfo.Username, |
||||
TokenAlias: tokenInfo.DisplayName, |
||||
TokenEmail: tokenInfo.Email, |
||||
TokenRemoteUser: tokenInfo.UserID, |
||||
Provider: provider, |
||||
ClientID: clientID, |
||||
InviteCode: inviteCode, |
||||
} |
||||
tp.TokenHash = tp.HashTokenParams(h.Config.Server.HashSeed) |
||||
|
||||
return h.showOauthSignupPage(app, w, r, tp, nil) |
||||
} |
||||
|
||||
func (r *callbackProxyClient) register(ctx context.Context, state string) error { |
||||
form := url.Values{} |
||||
form.Add("state", state) |
||||
form.Add("location", r.callbackLocation) |
||||
req, err := http.NewRequestWithContext(ctx, "POST", r.server, strings.NewReader(form.Encode())) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
||||
|
||||
resp, err := r.httpClient.Do(req) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if resp.StatusCode != http.StatusCreated { |
||||
return fmt.Errorf("unable register state location: %d", resp.StatusCode) |
||||
} |
||||
|
||||
return nil |
||||
} |
||||
|
||||
func limitedJsonUnmarshal(body io.ReadCloser, n int, thing interface{}) error { |
||||
lr := io.LimitReader(body, int64(n+1)) |
||||
data, err := ioutil.ReadAll(lr) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if len(data) == n+1 { |
||||
return fmt.Errorf("content larger than max read allowance: %d", n) |
||||
} |
||||
return json.Unmarshal(data, thing) |
||||
} |
||||
|
||||
func loginOrFail(store sessions.Store, w http.ResponseWriter, r *http.Request, user *User) error { |
||||
// An error may be returned, but a valid session should always be returned.
|
||||
session, _ := store.Get(r, cookieName) |
||||
session.Values[cookieUserVal] = user.Cookie() |
||||
if err := session.Save(r, w); err != nil { |
||||
fmt.Println("error saving session", err) |
||||
return err |
||||
} |
||||
http.Redirect(w, r, "/", http.StatusTemporaryRedirect) |
||||
return nil |
||||
} |
@ -0,0 +1,10 @@ |
||||
package oauth |
||||
|
||||
import "context" |
||||
|
||||
// ClientStateStore provides state management used by the OAuth client.
|
||||
type ClientStateStore interface { |
||||
Generate(ctx context.Context) (string, error) |
||||
Validate(ctx context.Context, state string) error |
||||
} |
||||
|
@ -0,0 +1,114 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"errors" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
) |
||||
|
||||
type genericOauthClient struct { |
||||
ClientID string |
||||
ClientSecret string |
||||
AuthLocation string |
||||
ExchangeLocation string |
||||
InspectLocation string |
||||
CallbackLocation string |
||||
HttpClient HttpClient |
||||
} |
||||
|
||||
var _ oauthClient = genericOauthClient{} |
||||
|
||||
const ( |
||||
genericOauthDisplayName = "OAuth" |
||||
) |
||||
|
||||
func (c genericOauthClient) GetProvider() string { |
||||
return "generic" |
||||
} |
||||
|
||||
func (c genericOauthClient) GetClientID() string { |
||||
return c.ClientID |
||||
} |
||||
|
||||
func (c genericOauthClient) GetCallbackLocation() string { |
||||
return c.CallbackLocation |
||||
} |
||||
|
||||
func (c genericOauthClient) buildLoginURL(state string) (string, error) { |
||||
u, err := url.Parse(c.AuthLocation) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
q := u.Query() |
||||
q.Set("client_id", c.ClientID) |
||||
q.Set("redirect_uri", c.CallbackLocation) |
||||
q.Set("response_type", "code") |
||||
q.Set("state", state) |
||||
q.Set("scope", "read_user") |
||||
u.RawQuery = q.Encode() |
||||
return u.String(), nil |
||||
} |
||||
|
||||
func (c genericOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { |
||||
form := url.Values{} |
||||
form.Add("grant_type", "authorization_code") |
||||
form.Add("redirect_uri", c.CallbackLocation) |
||||
form.Add("scope", "read_user") |
||||
form.Add("code", code) |
||||
req, err := http.NewRequest("POST", c.ExchangeLocation, strings.NewReader(form.Encode())) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
||||
req.SetBasicAuth(c.ClientID, c.ClientSecret) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to exchange code for access token") |
||||
} |
||||
|
||||
var tokenResponse TokenResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if tokenResponse.Error != "" { |
||||
return nil, errors.New(tokenResponse.Error) |
||||
} |
||||
return &tokenResponse, nil |
||||
} |
||||
|
||||
func (c genericOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { |
||||
req, err := http.NewRequest("GET", c.InspectLocation, nil) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Authorization", "Bearer "+accessToken) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to inspect access token") |
||||
} |
||||
|
||||
var inspectResponse InspectResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if inspectResponse.Error != "" { |
||||
return nil, errors.New(inspectResponse.Error) |
||||
} |
||||
return &inspectResponse, nil |
||||
} |
@ -0,0 +1,114 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"errors" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
) |
||||
|
||||
type giteaOauthClient struct { |
||||
ClientID string |
||||
ClientSecret string |
||||
AuthLocation string |
||||
ExchangeLocation string |
||||
InspectLocation string |
||||
CallbackLocation string |
||||
HttpClient HttpClient |
||||
} |
||||
|
||||
var _ oauthClient = giteaOauthClient{} |
||||
|
||||
const ( |
||||
giteaDisplayName = "Gitea" |
||||
) |
||||
|
||||
func (c giteaOauthClient) GetProvider() string { |
||||
return "gitea" |
||||
} |
||||
|
||||
func (c giteaOauthClient) GetClientID() string { |
||||
return c.ClientID |
||||
} |
||||
|
||||
func (c giteaOauthClient) GetCallbackLocation() string { |
||||
return c.CallbackLocation |
||||
} |
||||
|
||||
func (c giteaOauthClient) buildLoginURL(state string) (string, error) { |
||||
u, err := url.Parse(c.AuthLocation) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
q := u.Query() |
||||
q.Set("client_id", c.ClientID) |
||||
q.Set("redirect_uri", c.CallbackLocation) |
||||
q.Set("response_type", "code") |
||||
q.Set("state", state) |
||||
// q.Set("scope", "read_user")
|
||||
u.RawQuery = q.Encode() |
||||
return u.String(), nil |
||||
} |
||||
|
||||
func (c giteaOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { |
||||
form := url.Values{} |
||||
form.Add("grant_type", "authorization_code") |
||||
form.Add("redirect_uri", c.CallbackLocation) |
||||
// form.Add("scope", "read_user")
|
||||
form.Add("code", code) |
||||
req, err := http.NewRequest("POST", c.ExchangeLocation, strings.NewReader(form.Encode())) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
||||
req.SetBasicAuth(c.ClientID, c.ClientSecret) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to exchange code for access token") |
||||
} |
||||
|
||||
var tokenResponse TokenResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if tokenResponse.Error != "" { |
||||
return nil, errors.New(tokenResponse.Error) |
||||
} |
||||
return &tokenResponse, nil |
||||
} |
||||
|
||||
func (c giteaOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { |
||||
req, err := http.NewRequest("GET", c.InspectLocation, nil) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Authorization", "Bearer "+accessToken) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to inspect access token") |
||||
} |
||||
|
||||
var inspectResponse InspectResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if inspectResponse.Error != "" { |
||||
return nil, errors.New(inspectResponse.Error) |
||||
} |
||||
return &inspectResponse, nil |
||||
} |
@ -0,0 +1,115 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"errors" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
) |
||||
|
||||
type gitlabOauthClient struct { |
||||
ClientID string |
||||
ClientSecret string |
||||
AuthLocation string |
||||
ExchangeLocation string |
||||
InspectLocation string |
||||
CallbackLocation string |
||||
HttpClient HttpClient |
||||
} |
||||
|
||||
var _ oauthClient = gitlabOauthClient{} |
||||
|
||||
const ( |
||||
gitlabHost = "https://gitlab.com" |
||||
gitlabDisplayName = "GitLab" |
||||
) |
||||
|
||||
func (c gitlabOauthClient) GetProvider() string { |
||||
return "gitlab" |
||||
} |
||||
|
||||
func (c gitlabOauthClient) GetClientID() string { |
||||
return c.ClientID |
||||
} |
||||
|
||||
func (c gitlabOauthClient) GetCallbackLocation() string { |
||||
return c.CallbackLocation |
||||
} |
||||
|
||||
func (c gitlabOauthClient) buildLoginURL(state string) (string, error) { |
||||
u, err := url.Parse(c.AuthLocation) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
q := u.Query() |
||||
q.Set("client_id", c.ClientID) |
||||
q.Set("redirect_uri", c.CallbackLocation) |
||||
q.Set("response_type", "code") |
||||
q.Set("state", state) |
||||
q.Set("scope", "read_user") |
||||
u.RawQuery = q.Encode() |
||||
return u.String(), nil |
||||
} |
||||
|
||||
func (c gitlabOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { |
||||
form := url.Values{} |
||||
form.Add("grant_type", "authorization_code") |
||||
form.Add("redirect_uri", c.CallbackLocation) |
||||
form.Add("scope", "read_user") |
||||
form.Add("code", code) |
||||
req, err := http.NewRequest("POST", c.ExchangeLocation, strings.NewReader(form.Encode())) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
||||
req.SetBasicAuth(c.ClientID, c.ClientSecret) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to exchange code for access token") |
||||
} |
||||
|
||||
var tokenResponse TokenResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if tokenResponse.Error != "" { |
||||
return nil, errors.New(tokenResponse.Error) |
||||
} |
||||
return &tokenResponse, nil |
||||
} |
||||
|
||||
func (c gitlabOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { |
||||
req, err := http.NewRequest("GET", c.InspectLocation, nil) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Authorization", "Bearer "+accessToken) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to inspect access token") |
||||
} |
||||
|
||||
var inspectResponse InspectResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if inspectResponse.Error != "" { |
||||
return nil, errors.New(inspectResponse.Error) |
||||
} |
||||
return &inspectResponse, nil |
||||
} |
@ -0,0 +1,231 @@ |
||||
/* |
||||
* Copyright © 2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package writefreely |
||||
|
||||
import ( |
||||
"crypto/sha256" |
||||
"encoding/hex" |
||||
"fmt" |
||||
"github.com/writeas/impart" |
||||
"github.com/writeas/web-core/auth" |
||||
"github.com/writeas/web-core/log" |
||||
"github.com/writeas/writefreely/page" |
||||
"html/template" |
||||
"net/http" |
||||
"strings" |
||||
"time" |
||||
) |
||||
|
||||
type viewOauthSignupVars struct { |
||||
page.StaticPage |
||||
To string |
||||
Message template.HTML |
||||
Flashes []template.HTML |
||||
|
||||
AccessToken string |
||||
TokenUsername string |
||||
TokenAlias string // TODO: rename this to match the data it represents: the collection title
|
||||
TokenEmail string |
||||
TokenRemoteUser string |
||||
Provider string |
||||
ClientID string |
||||
TokenHash string |
||||
InviteCode string |
||||
|
||||
LoginUsername string |
||||
Alias string // TODO: rename this to match the data it represents: the collection title
|
||||
Email string |
||||
} |
||||
|
||||
const ( |
||||
oauthParamAccessToken = "access_token" |
||||
oauthParamTokenUsername = "token_username" |
||||
oauthParamTokenAlias = "token_alias" |
||||
oauthParamTokenEmail = "token_email" |
||||
oauthParamTokenRemoteUserID = "token_remote_user" |
||||
oauthParamClientID = "client_id" |
||||
oauthParamProvider = "provider" |
||||
oauthParamHash = "signature" |
||||
oauthParamUsername = "username" |
||||
oauthParamAlias = "alias" |
||||
oauthParamEmail = "email" |
||||
oauthParamPassword = "password" |
||||
oauthParamInviteCode = "invite_code" |
||||
) |
||||
|
||||
type oauthSignupPageParams struct { |
||||
AccessToken string |
||||
TokenUsername string |
||||
TokenAlias string // TODO: rename this to match the data it represents: the collection title
|
||||
TokenEmail string |
||||
TokenRemoteUser string |
||||
ClientID string |
||||
Provider string |
||||
TokenHash string |
||||
InviteCode string |
||||
} |
||||
|
||||
func (p oauthSignupPageParams) HashTokenParams(key string) string { |
||||
hasher := sha256.New() |
||||
hasher.Write([]byte(key)) |
||||
hasher.Write([]byte(p.AccessToken)) |
||||
hasher.Write([]byte(p.TokenUsername)) |
||||
hasher.Write([]byte(p.TokenAlias)) |
||||
hasher.Write([]byte(p.TokenEmail)) |
||||
hasher.Write([]byte(p.TokenRemoteUser)) |
||||
hasher.Write([]byte(p.ClientID)) |
||||
hasher.Write([]byte(p.Provider)) |
||||
return hex.EncodeToString(hasher.Sum(nil)) |
||||
} |
||||
|
||||
func (h oauthHandler) viewOauthSignup(app *App, w http.ResponseWriter, r *http.Request) error { |
||||
tp := &oauthSignupPageParams{ |
||||
AccessToken: r.FormValue(oauthParamAccessToken), |
||||
TokenUsername: r.FormValue(oauthParamTokenUsername), |
||||
TokenAlias: r.FormValue(oauthParamTokenAlias), |
||||
TokenEmail: r.FormValue(oauthParamTokenEmail), |
||||
TokenRemoteUser: r.FormValue(oauthParamTokenRemoteUserID), |
||||
ClientID: r.FormValue(oauthParamClientID), |
||||
Provider: r.FormValue(oauthParamProvider), |
||||
InviteCode: r.FormValue(oauthParamInviteCode), |
||||
} |
||||
if tp.HashTokenParams(h.Config.Server.HashSeed) != r.FormValue(oauthParamHash) { |
||||
return impart.HTTPError{Status: http.StatusBadRequest, Message: "Request has been tampered with."} |
||||
} |
||||
tp.TokenHash = tp.HashTokenParams(h.Config.Server.HashSeed) |
||||
if err := h.validateOauthSignup(r); err != nil { |
||||
return h.showOauthSignupPage(app, w, r, tp, err) |
||||
} |
||||
|
||||
var err error |
||||
hashedPass := []byte{} |
||||
clearPass := r.FormValue(oauthParamPassword) |
||||
hasPass := clearPass != "" |
||||
if hasPass { |
||||
hashedPass, err = auth.HashPass([]byte(clearPass)) |
||||
if err != nil { |
||||
return h.showOauthSignupPage(app, w, r, tp, fmt.Errorf("unable to hash password")) |
||||
} |
||||
} |
||||
newUser := &User{ |
||||
Username: r.FormValue(oauthParamUsername), |
||||
HashedPass: hashedPass, |
||||
HasPass: hasPass, |
||||
Email: prepareUserEmail(r.FormValue(oauthParamEmail), h.EmailKey), |
||||
Created: time.Now().Truncate(time.Second).UTC(), |
||||
} |
||||
displayName := r.FormValue(oauthParamAlias) |
||||
if len(displayName) == 0 { |
||||
displayName = r.FormValue(oauthParamUsername) |
||||
} |
||||
|
||||
err = h.DB.CreateUser(h.Config, newUser, displayName) |
||||
if err != nil { |
||||
return h.showOauthSignupPage(app, w, r, tp, err) |
||||
} |
||||
|
||||
// Log invite if needed
|
||||
if tp.InviteCode != "" { |
||||
err = app.db.CreateInvitedUser(tp.InviteCode, newUser.ID) |
||||
if err != nil { |
||||
return err |
||||
} |
||||
} |
||||
|
||||
err = h.DB.RecordRemoteUserID(r.Context(), newUser.ID, r.FormValue(oauthParamTokenRemoteUserID), r.FormValue(oauthParamProvider), r.FormValue(oauthParamClientID), r.FormValue(oauthParamAccessToken)) |
||||
if err != nil { |
||||
return h.showOauthSignupPage(app, w, r, tp, err) |
||||
} |
||||
|
||||
if err := loginOrFail(h.Store, w, r, newUser); err != nil { |
||||
return h.showOauthSignupPage(app, w, r, tp, err) |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (h oauthHandler) validateOauthSignup(r *http.Request) error { |
||||
username := r.FormValue(oauthParamUsername) |
||||
if len(username) < h.Config.App.MinUsernameLen { |
||||
return impart.HTTPError{Status: http.StatusBadRequest, Message: "Username is too short."} |
||||
} |
||||
if len(username) > 100 { |
||||
return impart.HTTPError{Status: http.StatusBadRequest, Message: "Username is too long."} |
||||
} |
||||
collTitle := r.FormValue(oauthParamAlias) |
||||
if len(collTitle) == 0 { |
||||
collTitle = username |
||||
} |
||||
email := r.FormValue(oauthParamEmail) |
||||
if len(email) > 0 { |
||||
parts := strings.Split(email, "@") |
||||
if len(parts) != 2 || (len(parts[0]) < 1 || len(parts[1]) < 1) { |
||||
return impart.HTTPError{Status: http.StatusBadRequest, Message: "Invalid email address"} |
||||
} |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (h oauthHandler) showOauthSignupPage(app *App, w http.ResponseWriter, r *http.Request, tp *oauthSignupPageParams, errMsg error) error { |
||||
username := tp.TokenUsername |
||||
collTitle := tp.TokenAlias |
||||
email := tp.TokenEmail |
||||
|
||||
session, err := app.sessionStore.Get(r, cookieName) |
||||
if err != nil { |
||||
// Ignore this
|
||||
log.Error("Unable to get session; ignoring: %v", err) |
||||
} |
||||
|
||||
if tmpValue := r.FormValue(oauthParamUsername); len(tmpValue) > 0 { |
||||
username = tmpValue |
||||
} |
||||
if tmpValue := r.FormValue(oauthParamAlias); len(tmpValue) > 0 { |
||||
collTitle = tmpValue |
||||
} |
||||
if tmpValue := r.FormValue(oauthParamEmail); len(tmpValue) > 0 { |
||||
email = tmpValue |
||||
} |
||||
|
||||
p := &viewOauthSignupVars{ |
||||
StaticPage: pageForReq(app, r), |
||||
To: r.FormValue("to"), |
||||
Flashes: []template.HTML{}, |
||||
|
||||
AccessToken: tp.AccessToken, |
||||
TokenUsername: tp.TokenUsername, |
||||
TokenAlias: tp.TokenAlias, |
||||
TokenEmail: tp.TokenEmail, |
||||
TokenRemoteUser: tp.TokenRemoteUser, |
||||
Provider: tp.Provider, |
||||
ClientID: tp.ClientID, |
||||
TokenHash: tp.TokenHash, |
||||
InviteCode: tp.InviteCode, |
||||
|
||||
LoginUsername: username, |
||||
Alias: collTitle, |
||||
Email: email, |
||||
} |
||||
|
||||
// Display any error messages
|
||||
flashes, _ := getSessionFlashes(app, w, r, session) |
||||
for _, flash := range flashes { |
||||
p.Flashes = append(p.Flashes, template.HTML(flash)) |
||||
} |
||||
if errMsg != nil { |
||||
p.Flashes = append(p.Flashes, template.HTML(errMsg.Error())) |
||||
} |
||||
err = pages["signup-oauth.tmpl"].ExecuteTemplate(w, "base", p) |
||||
if err != nil { |
||||
log.Error("Unable to render signup-oauth: %v", err) |
||||
return err |
||||
} |
||||
return nil |
||||
} |
@ -0,0 +1,178 @@ |
||||
/* |
||||
* Copyright © 2019-2020 A Bunch Tell LLC. |
||||
* |
||||
* This file is part of WriteFreely. |
||||
* |
||||
* WriteFreely is free software: you can redistribute it and/or modify |
||||
* it under the terms of the GNU Affero General Public License, included |
||||
* in the LICENSE file in this source code package. |
||||
*/ |
||||
|
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"errors" |
||||
"github.com/writeas/slug" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
) |
||||
|
||||
type slackOauthClient struct { |
||||
ClientID string |
||||
ClientSecret string |
||||
TeamID string |
||||
CallbackLocation string |
||||
HttpClient HttpClient |
||||
} |
||||
|
||||
type slackExchangeResponse struct { |
||||
OK bool `json:"ok"` |
||||
AccessToken string `json:"access_token"` |
||||
Scope string `json:"scope"` |
||||
TeamName string `json:"team_name"` |
||||
TeamID string `json:"team_id"` |
||||
Error string `json:"error"` |
||||
} |
||||
|
||||
type slackIdentity struct { |
||||
Name string `json:"name"` |
||||
ID string `json:"id"` |
||||
Email string `json:"email"` |
||||
} |
||||
|
||||
type slackTeam struct { |
||||
Name string `json:"name"` |
||||
ID string `json:"id"` |
||||
} |
||||
|
||||
type slackUserIdentityResponse struct { |
||||
OK bool `json:"ok"` |
||||
User slackIdentity `json:"user"` |
||||
Team slackTeam `json:"team"` |
||||
Error string `json:"error"` |
||||
} |
||||
|
||||
const ( |
||||
slackAuthLocation = "https://slack.com/oauth/authorize" |
||||
slackExchangeLocation = "https://slack.com/api/oauth.access" |
||||
slackIdentityLocation = "https://slack.com/api/users.identity" |
||||
) |
||||
|
||||
var _ oauthClient = slackOauthClient{} |
||||
|
||||
func (c slackOauthClient) GetProvider() string { |
||||
return "slack" |
||||
} |
||||
|
||||
func (c slackOauthClient) GetClientID() string { |
||||
return c.ClientID |
||||
} |
||||
|
||||
func (c slackOauthClient) GetCallbackLocation() string { |
||||
return c.CallbackLocation |
||||
} |
||||
|
||||
func (c slackOauthClient) buildLoginURL(state string) (string, error) { |
||||
u, err := url.Parse(slackAuthLocation) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
q := u.Query() |
||||
q.Set("client_id", c.ClientID) |
||||
q.Set("scope", "identity.basic identity.email identity.team") |
||||
q.Set("redirect_uri", c.CallbackLocation) |
||||
q.Set("state", state) |
||||
|
||||
// If this param is not set, the user can select which team they
|
||||
// authenticate through and then we'd have to match the configured team
|
||||
// against the profile get. That is extra work in the post-auth phase
|
||||
// that we don't want to do.
|
||||
q.Set("team", c.TeamID) |
||||
|
||||
// The Slack OAuth docs don't explicitly list this one, but it is part of
|
||||
// the spec, so we include it anyway.
|
||||
q.Set("response_type", "code") |
||||
u.RawQuery = q.Encode() |
||||
return u.String(), nil |
||||
} |
||||
|
||||
func (c slackOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { |
||||
form := url.Values{} |
||||
// The oauth.access documentation doesn't explicitly mention this
|
||||
// parameter, but it is part of the spec, so we include it anyway.
|
||||
// https://api.slack.com/methods/oauth.access
|
||||
form.Add("grant_type", "authorization_code") |
||||
form.Add("redirect_uri", c.CallbackLocation) |
||||
form.Add("code", code) |
||||
req, err := http.NewRequest("POST", slackExchangeLocation, strings.NewReader(form.Encode())) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
||||
req.SetBasicAuth(c.ClientID, c.ClientSecret) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to exchange code for access token") |
||||
} |
||||
|
||||
var tokenResponse slackExchangeResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if !tokenResponse.OK { |
||||
return nil, errors.New(tokenResponse.Error) |
||||
} |
||||
return tokenResponse.TokenResponse(), nil |
||||
} |
||||
|
||||
func (c slackOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { |
||||
req, err := http.NewRequest("GET", slackIdentityLocation, nil) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Authorization", "Bearer "+accessToken) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to inspect access token") |
||||
} |
||||
|
||||
var inspectResponse slackUserIdentityResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if !inspectResponse.OK { |
||||
return nil, errors.New(inspectResponse.Error) |
||||
} |
||||
return inspectResponse.InspectResponse(), nil |
||||
} |
||||
|
||||
func (resp slackUserIdentityResponse) InspectResponse() *InspectResponse { |
||||
return &InspectResponse{ |
||||
UserID: resp.User.ID, |
||||
Username: slug.Make(resp.User.Name), |
||||
DisplayName: resp.User.Name, |
||||
Email: resp.User.Email, |
||||
} |
||||
} |
||||
|
||||
func (resp slackExchangeResponse) TokenResponse() *TokenResponse { |
||||
return &TokenResponse{ |
||||
AccessToken: resp.AccessToken, |
||||
} |
||||
} |
@ -0,0 +1,251 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"fmt" |
||||
"github.com/gorilla/sessions" |
||||
"github.com/stretchr/testify/assert" |
||||
"github.com/writeas/impart" |
||||
"github.com/writeas/nerds/store" |
||||
"github.com/writeas/writefreely/config" |
||||
"net/http" |
||||
"net/http/httptest" |
||||
"net/url" |
||||
"strings" |
||||
"testing" |
||||
) |
||||
|
||||
type MockOAuthDatastoreProvider struct { |
||||
DoDB func() OAuthDatastore |
||||
DoConfig func() *config.Config |
||||
DoSessionStore func() sessions.Store |
||||
} |
||||
|
||||
type MockOAuthDatastore struct { |
||||
DoGenerateOAuthState func(context.Context, string, string, int64, string) (string, error) |
||||
DoValidateOAuthState func(context.Context, string) (string, string, int64, string, error) |
||||
DoGetIDForRemoteUser func(context.Context, string, string, string) (int64, error) |
||||
DoCreateUser func(*config.Config, *User, string) error |
||||
DoRecordRemoteUserID func(context.Context, int64, string, string, string, string) error |
||||
DoGetUserByID func(int64) (*User, error) |
||||
} |
||||
|
||||
var _ OAuthDatastore = &MockOAuthDatastore{} |
||||
|
||||
type StringReadCloser struct { |
||||
*strings.Reader |
||||
} |
||||
|
||||
func (src *StringReadCloser) Close() error { |
||||
return nil |
||||
} |
||||
|
||||
type MockHTTPClient struct { |
||||
DoDo func(req *http.Request) (*http.Response, error) |
||||
} |
||||
|
||||
func (m *MockHTTPClient) Do(req *http.Request) (*http.Response, error) { |
||||
if m.DoDo != nil { |
||||
return m.DoDo(req) |
||||
} |
||||
return &http.Response{}, nil |
||||
} |
||||
|
||||
func (m *MockOAuthDatastoreProvider) SessionStore() sessions.Store { |
||||
if m.DoSessionStore != nil { |
||||
return m.DoSessionStore() |
||||
} |
||||
return sessions.NewCookieStore([]byte("secret-key")) |
||||
} |
||||
|
||||
func (m *MockOAuthDatastoreProvider) DB() OAuthDatastore { |
||||
if m.DoDB != nil { |
||||
return m.DoDB() |
||||
} |
||||
return &MockOAuthDatastore{} |
||||
} |
||||
|
||||
func (m *MockOAuthDatastoreProvider) Config() *config.Config { |
||||
if m.DoConfig != nil { |
||||
return m.DoConfig() |
||||
} |
||||
cfg := config.New() |
||||
cfg.UseSQLite(true) |
||||
cfg.WriteAsOauth = config.WriteAsOauthCfg{ |
||||
ClientID: "development", |
||||
ClientSecret: "development", |
||||
AuthLocation: "https://write.as/oauth/login", |
||||
TokenLocation: "https://write.as/oauth/token", |
||||
InspectLocation: "https://write.as/oauth/inspect", |
||||
} |
||||
cfg.SlackOauth = config.SlackOauthCfg{ |
||||
ClientID: "development", |
||||
ClientSecret: "development", |
||||
TeamID: "development", |
||||
} |
||||
return cfg |
||||
} |
||||
|
||||
func (m *MockOAuthDatastore) ValidateOAuthState(ctx context.Context, state string) (string, string, int64, string, error) { |
||||
if m.DoValidateOAuthState != nil { |
||||
return m.DoValidateOAuthState(ctx, state) |
||||
} |
||||
return "", "", 0, "", nil |
||||
} |
||||
|
||||
func (m *MockOAuthDatastore) GetIDForRemoteUser(ctx context.Context, remoteUserID, provider, clientID string) (int64, error) { |
||||
if m.DoGetIDForRemoteUser != nil { |
||||
return m.DoGetIDForRemoteUser(ctx, remoteUserID, provider, clientID) |
||||
} |
||||
return -1, nil |
||||
} |
||||
|
||||
func (m *MockOAuthDatastore) CreateUser(cfg *config.Config, u *User, username string) error { |
||||
if m.DoCreateUser != nil { |
||||
return m.DoCreateUser(cfg, u, username) |
||||
} |
||||
u.ID = 1 |
||||
return nil |
||||
} |
||||
|
||||
func (m *MockOAuthDatastore) RecordRemoteUserID(ctx context.Context, localUserID int64, remoteUserID, provider, clientID, accessToken string) error { |
||||
if m.DoRecordRemoteUserID != nil { |
||||
return m.DoRecordRemoteUserID(ctx, localUserID, remoteUserID, provider, clientID, accessToken) |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
func (m *MockOAuthDatastore) GetUserByID(userID int64) (*User, error) { |
||||
if m.DoGetUserByID != nil { |
||||
return m.DoGetUserByID(userID) |
||||
} |
||||
user := &User{} |
||||
return user, nil |
||||
} |
||||
|
||||
func (m *MockOAuthDatastore) GenerateOAuthState(ctx context.Context, provider string, clientID string, attachUserID int64, inviteCode string) (string, error) { |
||||
if m.DoGenerateOAuthState != nil { |
||||
return m.DoGenerateOAuthState(ctx, provider, clientID, attachUserID, inviteCode) |
||||
} |
||||
return store.Generate62RandomString(14), nil |
||||
} |
||||
|
||||
func TestViewOauthInit(t *testing.T) { |
||||
|
||||
t.Run("success", func(t *testing.T) { |
||||
app := &MockOAuthDatastoreProvider{} |
||||
h := oauthHandler{ |
||||
Config: app.Config(), |
||||
DB: app.DB(), |
||||
Store: app.SessionStore(), |
||||
EmailKey: []byte{0xd, 0xe, 0xc, 0xa, 0xf, 0xf, 0xb, 0xa, 0xd}, |
||||
oauthClient: writeAsOauthClient{ |
||||
ClientID: app.Config().WriteAsOauth.ClientID, |
||||
ClientSecret: app.Config().WriteAsOauth.ClientSecret, |
||||
ExchangeLocation: app.Config().WriteAsOauth.TokenLocation, |
||||
InspectLocation: app.Config().WriteAsOauth.InspectLocation, |
||||
AuthLocation: app.Config().WriteAsOauth.AuthLocation, |
||||
CallbackLocation: "http://localhost/oauth/callback", |
||||
HttpClient: nil, |
||||
}, |
||||
} |
||||
req, err := http.NewRequest("GET", "/oauth/client", nil) |
||||
assert.NoError(t, err) |
||||
rr := httptest.NewRecorder() |
||||
err = h.viewOauthInit(nil, rr, req) |
||||
assert.NotNil(t, err) |
||||
httpErr, ok := err.(impart.HTTPError) |
||||
assert.True(t, ok) |
||||
assert.Equal(t, http.StatusTemporaryRedirect, httpErr.Status) |
||||
assert.NotEmpty(t, httpErr.Message) |
||||
locURI, err := url.Parse(httpErr.Message) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, "/oauth/login", locURI.Path) |
||||
assert.Equal(t, "development", locURI.Query().Get("client_id")) |
||||
assert.Equal(t, "http://localhost/oauth/callback", locURI.Query().Get("redirect_uri")) |
||||
assert.Equal(t, "code", locURI.Query().Get("response_type")) |
||||
assert.NotEmpty(t, locURI.Query().Get("state")) |
||||
}) |
||||
|
||||
t.Run("state failure", func(t *testing.T) { |
||||
app := &MockOAuthDatastoreProvider{ |
||||
DoDB: func() OAuthDatastore { |
||||
return &MockOAuthDatastore{ |
||||
DoGenerateOAuthState: func(ctx context.Context, provider, clientID string, attachUserID int64, inviteCode string) (string, error) { |
||||
return "", fmt.Errorf("pretend unable to write state error") |
||||
}, |
||||
} |
||||
}, |
||||
} |
||||
h := oauthHandler{ |
||||
Config: app.Config(), |
||||
DB: app.DB(), |
||||
Store: app.SessionStore(), |
||||
EmailKey: []byte{0xd, 0xe, 0xc, 0xa, 0xf, 0xf, 0xb, 0xa, 0xd}, |
||||
oauthClient: writeAsOauthClient{ |
||||
ClientID: app.Config().WriteAsOauth.ClientID, |
||||
ClientSecret: app.Config().WriteAsOauth.ClientSecret, |
||||
ExchangeLocation: app.Config().WriteAsOauth.TokenLocation, |
||||
InspectLocation: app.Config().WriteAsOauth.InspectLocation, |
||||
AuthLocation: app.Config().WriteAsOauth.AuthLocation, |
||||
CallbackLocation: "http://localhost/oauth/callback", |
||||
HttpClient: nil, |
||||
}, |
||||
} |
||||
req, err := http.NewRequest("GET", "/oauth/client", nil) |
||||
assert.NoError(t, err) |
||||
rr := httptest.NewRecorder() |
||||
err = h.viewOauthInit(nil, rr, req) |
||||
httpErr, ok := err.(impart.HTTPError) |
||||
assert.True(t, ok) |
||||
assert.NotEmpty(t, httpErr.Message) |
||||
assert.Equal(t, http.StatusInternalServerError, httpErr.Status) |
||||
assert.Equal(t, "could not prepare oauth redirect url", httpErr.Message) |
||||
}) |
||||
} |
||||
|
||||
func TestViewOauthCallback(t *testing.T) { |
||||
t.Run("success", func(t *testing.T) { |
||||
app := &MockOAuthDatastoreProvider{} |
||||
h := oauthHandler{ |
||||
Config: app.Config(), |
||||
DB: app.DB(), |
||||
Store: app.SessionStore(), |
||||
EmailKey: []byte{0xd, 0xe, 0xc, 0xa, 0xf, 0xf, 0xb, 0xa, 0xd}, |
||||
oauthClient: writeAsOauthClient{ |
||||
ClientID: app.Config().WriteAsOauth.ClientID, |
||||
ClientSecret: app.Config().WriteAsOauth.ClientSecret, |
||||
ExchangeLocation: app.Config().WriteAsOauth.TokenLocation, |
||||
InspectLocation: app.Config().WriteAsOauth.InspectLocation, |
||||
AuthLocation: app.Config().WriteAsOauth.AuthLocation, |
||||
CallbackLocation: "http://localhost/oauth/callback", |
||||
HttpClient: &MockHTTPClient{ |
||||
DoDo: func(req *http.Request) (*http.Response, error) { |
||||
switch req.URL.String() { |
||||
case "https://write.as/oauth/token": |
||||
return &http.Response{ |
||||
StatusCode: 200, |
||||
Body: &StringReadCloser{strings.NewReader(`{"access_token": "access_token", "expires_in": 1000, "refresh_token": "refresh_token", "token_type": "access"}`)}, |
||||
}, nil |
||||
case "https://write.as/oauth/inspect": |
||||
return &http.Response{ |
||||
StatusCode: 200, |
||||
Body: &StringReadCloser{strings.NewReader(`{"client_id": "development", "user_id": "1", "expires_at": "2019-12-19T11:42:01Z", "username": "nick", "email": "nick@testing.write.as"}`)}, |
||||
}, nil |
||||
} |
||||
|
||||
return &http.Response{ |
||||
StatusCode: http.StatusNotFound, |
||||
}, nil |
||||
}, |
||||
}, |
||||
}, |
||||
} |
||||
req, err := http.NewRequest("GET", "/oauth/callback", nil) |
||||
assert.NoError(t, err) |
||||
rr := httptest.NewRecorder() |
||||
err = h.viewOauthCallback(nil, rr, req) |
||||
assert.NoError(t, err) |
||||
assert.Equal(t, http.StatusTemporaryRedirect, rr.Code) |
||||
}) |
||||
} |
@ -0,0 +1,114 @@ |
||||
package writefreely |
||||
|
||||
import ( |
||||
"context" |
||||
"errors" |
||||
"net/http" |
||||
"net/url" |
||||
"strings" |
||||
) |
||||
|
||||
type writeAsOauthClient struct { |
||||
ClientID string |
||||
ClientSecret string |
||||
AuthLocation string |
||||
ExchangeLocation string |
||||
InspectLocation string |
||||
CallbackLocation string |
||||
HttpClient HttpClient |
||||
} |
||||
|
||||
var _ oauthClient = writeAsOauthClient{} |
||||
|
||||
const ( |
||||
writeAsAuthLocation = "https://write.as/oauth/login" |
||||
writeAsExchangeLocation = "https://write.as/oauth/token" |
||||
writeAsIdentityLocation = "https://write.as/oauth/inspect" |
||||
) |
||||
|
||||
func (c writeAsOauthClient) GetProvider() string { |
||||
return "write.as" |
||||
} |
||||
|
||||
func (c writeAsOauthClient) GetClientID() string { |
||||
return c.ClientID |
||||
} |
||||
|
||||
func (c writeAsOauthClient) GetCallbackLocation() string { |
||||
return c.CallbackLocation |
||||
} |
||||
|
||||
func (c writeAsOauthClient) buildLoginURL(state string) (string, error) { |
||||
u, err := url.Parse(c.AuthLocation) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
q := u.Query() |
||||
q.Set("client_id", c.ClientID) |
||||
q.Set("redirect_uri", c.CallbackLocation) |
||||
q.Set("response_type", "code") |
||||
q.Set("state", state) |
||||
u.RawQuery = q.Encode() |
||||
return u.String(), nil |
||||
} |
||||
|
||||
func (c writeAsOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { |
||||
form := url.Values{} |
||||
form.Add("grant_type", "authorization_code") |
||||
form.Add("redirect_uri", c.CallbackLocation) |
||||
form.Add("code", code) |
||||
req, err := http.NewRequest("POST", c.ExchangeLocation, strings.NewReader(form.Encode())) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
||||
req.SetBasicAuth(c.ClientID, c.ClientSecret) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to exchange code for access token") |
||||
} |
||||
|
||||
var tokenResponse TokenResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if tokenResponse.Error != "" { |
||||
return nil, errors.New(tokenResponse.Error) |
||||
} |
||||
return &tokenResponse, nil |
||||
} |
||||
|
||||
func (c writeAsOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { |
||||
req, err := http.NewRequest("GET", c.InspectLocation, nil) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
req.WithContext(ctx) |
||||
req.Header.Set("User-Agent", ServerUserAgent("")) |
||||
req.Header.Set("Accept", "application/json") |
||||
req.Header.Set("Authorization", "Bearer "+accessToken) |
||||
|
||||
resp, err := c.HttpClient.Do(req) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
if resp.StatusCode != http.StatusOK { |
||||
return nil, errors.New("unable to inspect access token") |
||||
} |
||||
|
||||
var inspectResponse InspectResponse |
||||
if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { |
||||
return nil, err |
||||
} |
||||
if inspectResponse.Error != "" { |
||||
return nil, errors.New(inspectResponse.Error) |
||||
} |
||||
return &inspectResponse, nil |
||||
} |
@ -0,0 +1,7 @@ |
||||
{{define "head"}}<title>Temporarily Unavailable — {{.SiteMetaName}}</title>{{end}} |
||||
{{define "content"}} |
||||
<div class="error-page"> |
||||
<p class="msg">The words aren't coming to me. 🗅</p> |
||||
<p>We couldn't serve this page due to high server load. This should only be temporary.</p> |
||||
</div> |
||||
{{end}} |
@ -0,0 +1,186 @@ |
||||
{{define "head"}}<title>Finish Creating Account — {{.SiteName}}</title> |
||||
<style>input{margin-bottom:0.5em;}</style> |
||||
<style type="text/css"> |
||||
h2 { |
||||
font-weight: normal; |
||||
} |
||||
#pricing.content-container div.form-container #payment-form { |
||||
display: block !important; |
||||
} |
||||
#pricing #signup-form table { |
||||
max-width: inherit !important; |
||||
width: 100%; |
||||
} |
||||
#pricing #payment-form table { |
||||
margin-top: 0 !important; |
||||
max-width: inherit !important; |
||||
width: 100%; |
||||
} |
||||
tr.subscription { |
||||
border-spacing: 0; |
||||
} |
||||
#pricing.content-container tr.subscription button { |
||||
margin-top: 0 !important; |
||||
margin-bottom: 0 !important; |
||||
width: 100%; |
||||
} |
||||
#pricing tr.subscription td { |
||||
padding: 0 0.5em; |
||||
} |
||||
#pricing table.billing > tbody > tr > td:first-child { |
||||
vertical-align: middle !important; |
||||
} |
||||
.billing-section { |
||||
display: none; |
||||
} |
||||
.billing-section.bill-me { |
||||
display: table-row; |
||||
} |
||||
#btn-create { |
||||
color: white !important; |
||||
} |
||||
#total-price { |
||||
padding-left: 0.5em; |
||||
} |
||||
#alias-site.demo { |
||||
color: #999; |
||||
} |
||||
#alias-site { |
||||
text-align: left; |
||||
margin: 0.5em 0; |
||||
} |
||||
form dd { |
||||
margin: 0; |
||||
} |
||||
</style> |
||||
{{end}} |
||||
{{define "content"}} |
||||
<div id="pricing" class="tight content-container"> |
||||
<h1>Finish creating account</h1> |
||||
|
||||
{{if .Flashes}}<ul class="errors"> |
||||
{{range .Flashes}}<li class="urgent">{{.}}</li>{{end}} |
||||
</ul>{{end}} |
||||
|
||||
<div id="billing"> |
||||
<form action="/oauth/signup" method="post" style="text-align: center;margin-top:1em;" onsubmit="return disableSubmit()"> |
||||
<input type="hidden" name="access_token" value="{{ .AccessToken }}" /> |
||||
<input type="hidden" name="token_username" value="{{ .TokenUsername }}" /> |
||||
<input type="hidden" name="token_alias" value="{{ .TokenAlias }}" /> |
||||
<input type="hidden" name="token_email" value="{{ .TokenEmail }}" /> |
||||
<input type="hidden" name="token_remote_user" value="{{ .TokenRemoteUser }}" /> |
||||
<input type="hidden" name="provider" value="{{ .Provider }}" /> |
||||
<input type="hidden" name="client_id" value="{{ .ClientID }}" /> |
||||
<input type="hidden" name="signature" value="{{ .TokenHash }}" /> |
||||
{{if .InviteCode}}<input type="hidden" name="invite_code" value="{{ .InviteCode }}" />{{end}} |
||||
|
||||
<dl class="billing"> |
||||
<label> |
||||
<dt>Display Name</dt> |
||||
<dd> |
||||
<input type="text" style="width: 100%; box-sizing: border-box;" name="alias" placeholder="Name"{{ if .Alias }} value="{{.Alias}}"{{ end }} /> |
||||
</dd> |
||||
</label> |
||||
<label> |
||||
<dt>Username</dt> |
||||
<dd> |
||||
<input type="text" id="username" name="username" style="width: 100%; box-sizing: border-box;" placeholder="Username" value="{{.LoginUsername}}" /><br /> |
||||
{{if .Federation}}<p id="alias-site" class="demo">@<strong>your-username</strong>@{{.FriendlyHost}}</p>{{else}}<p id="alias-site" class="demo">{{.FriendlyHost}}/<strong>your-username</strong></p>{{end}} |
||||
</dd> |
||||
</label> |
||||
<label> |
||||
<dt>Email</dt> |
||||
<dd> |
||||
<input type="text" name="email" style="width: 100%; box-sizing: border-box;" placeholder="Email"{{ if .Email }} value="{{.Email}}"{{ end }} /> |
||||
</dd> |
||||
</label> |
||||
<dt> |
||||
<input type="submit" id="btn-login" value="Next" /> |
||||
</dt> |
||||
</dl> |
||||
</form> |
||||
</div> |
||||
|
||||
<script type="text/javascript" src="/js/h.js"></script> |
||||
<script type="text/javascript"> |
||||
// Copied from signup.tmpl |
||||
// NOTE: this element is named "alias" on signup.tmpl and "username" here |
||||
var $alias = H.getEl('username'); |
||||
|
||||
function disableSubmit() { |
||||
// Validate input |
||||
if (!aliasOK) { |
||||
var $a = $alias; |
||||
$a.el.className = 'error'; |
||||
$a.el.focus(); |
||||
$a.el.scrollIntoView(); |
||||
return false; |
||||
} |
||||
|
||||
var $btn = document.getElementById("btn-login"); |
||||
$btn.value = "Logging in..."; |
||||
$btn.disabled = true; |
||||
return true; |
||||
} |
||||
|
||||
// Copied from signup.tmpl |
||||
var $aliasSite = document.getElementById('alias-site'); |
||||
var aliasOK = true; |
||||
var typingTimer; |
||||
var doneTypingInterval = 750; |
||||
var doneTyping = function(genID) { |
||||
// Check on username |
||||
var alias = $alias.el.value; |
||||
if (alias != "") { |
||||
var params = { |
||||
username: alias |
||||
}; |
||||
var http = new XMLHttpRequest(); |
||||
http.open("POST", '/api/alias', true); |
||||
|
||||
// Send the proper header information along with the request |
||||
http.setRequestHeader("Content-type", "application/json"); |
||||
|
||||
http.onreadystatechange = function() { |
||||
if (http.readyState == 4) { |
||||
data = JSON.parse(http.responseText); |
||||
if (http.status == 200) { |
||||
aliasOK = true; |
||||
$alias.removeClass('error'); |
||||
$aliasSite.className = $aliasSite.className.replace(/(?:^|\s)demo(?!\S)/g, ''); |
||||
$aliasSite.className = $aliasSite.className.replace(/(?:^|\s)error(?!\S)/g, ''); |
||||
$aliasSite.innerHTML = '{{ if .Federation }}@<strong>' + data.data + '</strong>@{{.FriendlyHost}}{{ else }}{{.FriendlyHost}}/<strong>' + data.data + '</strong>/{{ end }}'; |
||||
} else { |
||||
if (genID === true) { |
||||
$alias.el.value = alias + "-" + randStr(4); |
||||
doneTyping(); |
||||
return; |
||||
} |
||||
aliasOK = false; |
||||
$alias.setClass('error'); |
||||
$aliasSite.className = 'error'; |
||||
$aliasSite.textContent = data.error_msg; |
||||
} |
||||
} |
||||
} |
||||
http.send(JSON.stringify(params)); |
||||
} else { |
||||
$aliasSite.className += ' demo'; |
||||
$aliasSite.innerHTML = '{{ if .Federation }}@<strong>your-username</strong>@{{.FriendlyHost}}{{ else }}{{.FriendlyHost}}/<strong>your-username</strong>/{{ end }}'; |
||||
} |
||||
}; |
||||
$alias.on('keyup input', function() { |
||||
clearTimeout(typingTimer); |
||||
typingTimer = setTimeout(doneTyping, doneTypingInterval); |
||||
}); |
||||
function randStr(len) { |
||||
var res = ''; |
||||
var chars = '23456789bcdfghjklmnpqrstvwxyz'; |
||||
for (var i=0; i<len; i++) { |
||||
res += chars.charAt(Math.floor(Math.random() * chars.length)); |
||||
} |
||||
return res; |
||||
} |
||||
doneTyping(true); |
||||
</script> |
||||
{{end}} |
@ -0,0 +1,37 @@ |
||||
#!/bin/bash |
||||
# |
||||
# Copyright © 2020 A Bunch Tell LLC. |
||||
# |
||||
# This file is part of WriteFreely. |
||||
# |
||||
# WriteFreely is free software: you can redistribute it and/or modify |
||||
# it under the terms of the GNU Affero General Public License, included |
||||
# in the LICENSE file in this source code package. |
||||
# |
||||
############################################################################### |
||||
# |
||||
# WriteFreely CSS invalidation script |
||||
# |
||||
# usage: ./invalidate-css.sh <build-directory> |
||||
# |
||||
# This script provides an automated way to invalidate stylesheets cached in the |
||||
# browser. It uses the last git commit hashes of the most frequently modified |
||||
# LESS files in the project and appends them to the stylesheet `href` in all |
||||
# template files. |
||||
# |
||||
# This is designed to be used when building a WriteFreely release. |
||||
# |
||||
############################################################################### |
||||
|
||||
# Get parent build directory from first argument |
||||
buildDir=$1 |
||||
|
||||
# Get short hash of each primary LESS file's last commit |
||||
cssHash=$(git log -n 1 --pretty=format:%h -- less/core.less) |
||||
cssNewHash=$(git log -n 1 --pretty=format:%h -- less/new-core.less) |
||||
cssPadHash=$(git log -n 1 --pretty=format:%h -- less/pad.less) |
||||
|
||||
echo "Adding write.css version ($cssHash $cssNewHash $cssPadHash) to .tmpl files..." |
||||
cd "$buildDir/templates" || exit 1 |
||||
find . -type f -name "*.tmpl" -print0 | xargs -0 sed -i "s/write.css/write.css?${cssHash}${cssNewHash}${cssPadHash}/g" |
||||
find . -type f -name "*.tmpl" -print0 | xargs -0 sed -i "s/{{.Theme}}.css/{{.Theme}}.css?${cssHash}${cssNewHash}${cssPadHash}/g" |
@ -0,0 +1,315 @@ |
||||
// Copyright 2018 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package semver implements comparison of semantic version strings.
|
||||
// In this package, semantic version strings must begin with a leading "v",
|
||||
// as in "v1.0.0".
|
||||
//
|
||||
// The general form of a semantic version string accepted by this package is
|
||||
//
|
||||
// vMAJOR[.MINOR[.PATCH[-PRERELEASE][+BUILD]]]
|
||||
//
|
||||
// where square brackets indicate optional parts of the syntax;
|
||||
// MAJOR, MINOR, and PATCH are decimal integers without extra leading zeros;
|
||||
// PRERELEASE and BUILD are each a series of non-empty dot-separated identifiers
|
||||
// using only alphanumeric characters and hyphens; and
|
||||
// all-numeric PRERELEASE identifiers must not have leading zeros.
|
||||
//
|
||||
// This package follows Semantic Versioning 2.0.0 (see semver.org)
|
||||
// with two exceptions. First, it requires the "v" prefix. Second, it recognizes
|
||||
// vMAJOR and vMAJOR.MINOR (with no prerelease or build suffixes)
|
||||
// as shorthands for vMAJOR.0.0 and vMAJOR.MINOR.0.
|
||||
|
||||
// Package writefreely
|
||||
// copied from
|
||||
// https://github.com/golang/tools/blob/master/internal/semver/semver.go
|
||||
// slight modifications made
|
||||
package writefreely |
||||
|
||||
// parsed returns the parsed form of a semantic version string.
|
||||
type parsed struct { |
||||
major string |
||||
minor string |
||||
patch string |
||||
short string |
||||
prerelease string |
||||
build string |
||||
err string |
||||
} |
||||
|
||||
// IsValid reports whether v is a valid semantic version string.
|
||||
func IsValid(v string) bool { |
||||
_, ok := semParse(v) |
||||
return ok |
||||
} |
||||
|
||||
// CompareSemver returns an integer comparing two versions according to
|
||||
// according to semantic version precedence.
|
||||
// The result will be 0 if v == w, -1 if v < w, or +1 if v > w.
|
||||
//
|
||||
// An invalid semantic version string is considered less than a valid one.
|
||||
// All invalid semantic version strings compare equal to each other.
|
||||
func CompareSemver(v, w string) int { |
||||
pv, ok1 := semParse(v) |
||||
pw, ok2 := semParse(w) |
||||
if !ok1 && !ok2 { |
||||
return 0 |
||||
} |
||||
if !ok1 { |
||||
return -1 |
||||
} |
||||
if !ok2 { |
||||
return +1 |
||||
} |
||||
if c := compareInt(pv.major, pw.major); c != 0 { |
||||
return c |
||||
} |
||||
if c := compareInt(pv.minor, pw.minor); c != 0 { |
||||
return c |
||||
} |
||||
if c := compareInt(pv.patch, pw.patch); c != 0 { |
||||
return c |
||||
} |
||||
return comparePrerelease(pv.prerelease, pw.prerelease) |
||||
} |
||||
|
||||
func semParse(v string) (p parsed, ok bool) { |
||||
if v == "" || v[0] != 'v' { |
||||
p.err = "missing v prefix" |
||||
return |
||||
} |
||||
p.major, v, ok = parseInt(v[1:]) |
||||
if !ok { |
||||
p.err = "bad major version" |
||||
return |
||||
} |
||||
if v == "" { |
||||
p.minor = "0" |
||||
p.patch = "0" |
||||
p.short = ".0.0" |
||||
return |
||||
} |
||||
if v[0] != '.' { |
||||
p.err = "bad minor prefix" |
||||
ok = false |
||||
return |
||||
} |
||||
p.minor, v, ok = parseInt(v[1:]) |
||||
if !ok { |
||||
p.err = "bad minor version" |
||||
return |
||||
} |
||||
if v == "" { |
||||
p.patch = "0" |
||||
p.short = ".0" |
||||
return |
||||
} |
||||
if v[0] != '.' { |
||||
p.err = "bad patch prefix" |
||||
ok = false |
||||
return |
||||
} |
||||
p.patch, v, ok = parseInt(v[1:]) |
||||
if !ok { |
||||
p.err = "bad patch version" |
||||
return |
||||
} |
||||
if len(v) > 0 && v[0] == '-' { |
||||
p.prerelease, v, ok = parsePrerelease(v) |
||||
if !ok { |
||||
p.err = "bad prerelease" |
||||
return |
||||
} |
||||
} |
||||
if len(v) > 0 && v[0] == '+' { |
||||
p.build, v, ok = parseBuild(v) |
||||
if !ok { |
||||
p.err = "bad build" |
||||
return |
||||
} |
||||
} |
||||
if v != "" { |
||||
p.err = "junk on end" |
||||
ok = false |
||||
return |
||||
} |
||||
ok = true |
||||
return |
||||
} |
||||
|
||||
func parseInt(v string) (t, rest string, ok bool) { |
||||
if v == "" { |
||||
return |
||||
} |
||||
if v[0] < '0' || '9' < v[0] { |
||||
return |
||||
} |
||||
i := 1 |
||||
for i < len(v) && '0' <= v[i] && v[i] <= '9' { |
||||
i++ |
||||
} |
||||
if v[0] == '0' && i != 1 { |
||||
return |
||||
} |
||||
return v[:i], v[i:], true |
||||
} |
||||
|
||||
func parsePrerelease(v string) (t, rest string, ok bool) { |
||||
// "A pre-release version MAY be denoted by appending a hyphen and
|
||||
// a series of dot separated identifiers immediately following the patch version.
|
||||
// Identifiers MUST comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-].
|
||||
// Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes."
|
||||
if v == "" || v[0] != '-' { |
||||
return |
||||
} |
||||
i := 1 |
||||
start := 1 |
||||
for i < len(v) && v[i] != '+' { |
||||
if !isIdentChar(v[i]) && v[i] != '.' { |
||||
return |
||||
} |
||||
if v[i] == '.' { |
||||
if start == i || isBadNum(v[start:i]) { |
||||
return |
||||
} |
||||
start = i + 1 |
||||
} |
||||
i++ |
||||
} |
||||
if start == i || isBadNum(v[start:i]) { |
||||
return |
||||
} |
||||
return v[:i], v[i:], true |
||||
} |
||||
|
||||
func parseBuild(v string) (t, rest string, ok bool) { |
||||
if v == "" || v[0] != '+' { |
||||
return |
||||
} |
||||
i := 1 |
||||
start := 1 |
||||
for i < len(v) { |
||||
if !isIdentChar(v[i]) { |
||||
return |
||||
} |
||||
if v[i] == '.' { |
||||
if start == i { |
||||
return |
||||
} |
||||
start = i + 1 |
||||
} |
||||
i++ |
||||
} |
||||
if start == i { |
||||
return |
||||
} |
||||
return v[:i], v[i:], true |
||||
} |
||||
|
||||
func isIdentChar(c byte) bool { |
||||
return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '-' |
||||
} |
||||
|
||||
func isBadNum(v string) bool { |
||||
i := 0 |
||||
for i < len(v) && '0' <= v[i] && v[i] <= '9' { |
||||
i++ |
||||
} |
||||
return i == len(v) && i > 1 && v[0] == '0' |
||||
} |
||||
|
||||
func isNum(v string) bool { |
||||
i := 0 |
||||
for i < len(v) && '0' <= v[i] && v[i] <= '9' { |
||||
i++ |
||||
} |
||||
return i == len(v) |
||||
} |
||||
|
||||
func compareInt(x, y string) int { |
||||
if x == y { |
||||
return 0 |
||||
} |
||||
if len(x) < len(y) { |
||||
return -1 |
||||
} |
||||
if len(x) > len(y) { |
||||
return +1 |
||||
} |
||||
if x < y { |
||||
return -1 |
||||
} else { |
||||
return +1 |
||||
} |
||||
} |
||||
|
||||
func comparePrerelease(x, y string) int { |
||||
// "When major, minor, and patch are equal, a pre-release version has
|
||||
// lower precedence than a normal version.
|
||||
// Example: 1.0.0-alpha < 1.0.0.
|
||||
// Precedence for two pre-release versions with the same major, minor,
|
||||
// and patch version MUST be determined by comparing each dot separated
|
||||
// identifier from left to right until a difference is found as follows:
|
||||
// identifiers consisting of only digits are compared numerically and
|
||||
// identifiers with letters or hyphens are compared lexically in ASCII
|
||||
// sort order. Numeric identifiers always have lower precedence than
|
||||
// non-numeric identifiers. A larger set of pre-release fields has a
|
||||
// higher precedence than a smaller set, if all of the preceding
|
||||
// identifiers are equal.
|
||||
// Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta <
|
||||
// 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0."
|
||||
if x == y { |
||||
return 0 |
||||
} |
||||
if x == "" { |
||||
return +1 |
||||
} |
||||
if y == "" { |
||||
return -1 |
||||
} |
||||
for x != "" && y != "" { |
||||
x = x[1:] // skip - or .
|
||||
y = y[1:] // skip - or .
|
||||
var dx, dy string |
||||
dx, x = nextIdent(x) |
||||
dy, y = nextIdent(y) |
||||
if dx != dy { |
||||
ix := isNum(dx) |
||||
iy := isNum(dy) |
||||
if ix != iy { |
||||
if ix { |
||||
return -1 |
||||
} else { |
||||
return +1 |
||||
} |
||||
} |
||||
if ix { |
||||
if len(dx) < len(dy) { |
||||
return -1 |
||||
} |
||||
if len(dx) > len(dy) { |
||||
return +1 |
||||
} |
||||
} |
||||
if dx < dy { |
||||
return -1 |
||||
} else { |
||||
return +1 |
||||
} |
||||
} |
||||
} |
||||
if x == "" { |
||||
return -1 |
||||
} else { |
||||
return +1 |
||||
} |
||||
} |
||||
|
||||
func nextIdent(x string) (dx, rest string) { |
||||
i := 0 |
||||
for i < len(x) && x[i] != '.' { |
||||
i++ |
||||
} |
||||
return x[:i], x[i:] |
||||
} |
After Width: | Height: | Size: 4.6 KiB |
After Width: | Height: | Size: 1005 B |
After Width: | Height: | Size: 2.2 KiB |
After Width: | Height: | Size: 2.7 KiB |
After Width: | Height: | Size: 2.8 KiB |
After Width: | Height: | Size: 2.5 KiB |
After Width: | Height: | Size: 5.0 KiB |
@ -0,0 +1,16 @@ |
||||
function toLocalDate(dateEl, displayEl) { |
||||
var d = new Date(dateEl.getAttribute("datetime")); |
||||
displayEl.textContent = d.toLocaleDateString(navigator.language || "en-US", { year: 'numeric', month: 'long', day: 'numeric' }); |
||||
} |
||||
|
||||
// Adjust dates on individual post pages, and on posts in a list *with* an explicit title
|
||||
var $dates = document.querySelectorAll("article > time"); |
||||
for (var i=0; i < $dates.length; i++) { |
||||
toLocalDate($dates[i], $dates[i]); |
||||
} |
||||
|
||||
// Adjust dates on posts in a list without an explicit title, where they act as the header
|
||||
$dates = document.querySelectorAll("h2.post-title > time"); |
||||
for (i=0; i < $dates.length; i++) { |
||||
toLocalDate($dates[i], $dates[i].querySelector('a')); |
||||
} |
@ -1 +0,0 @@ |
||||
Subproject commit 419b0a6eee7eefc0f85e47f7d4f8227ec28b8e57 |
@ -0,0 +1,34 @@ |
||||
var menuItems = document.querySelectorAll('li.has-submenu'); |
||||
var menuTimer; |
||||
function closeMenu($menu) { |
||||
$menu.querySelector('a').setAttribute('aria-expanded', "false"); |
||||
$menu.className = "has-submenu"; |
||||
} |
||||
Array.prototype.forEach.call(menuItems, function(el, i){ |
||||
el.addEventListener("mouseover", function(event){ |
||||
let $menu = document.querySelectorAll(".has-submenu.open"); |
||||
if ($menu.length > 0) { |
||||
closeMenu($menu[0]); |
||||
} |
||||
this.className = "has-submenu open"; |
||||
this.querySelector('a').setAttribute('aria-expanded', "true"); |
||||
clearTimeout(menuTimer); |
||||
}); |
||||
el.addEventListener("mouseout", function(event){ |
||||
menuTimer = setTimeout(function(event){ |
||||
let $menu = document.querySelector(".has-submenu.open"); |
||||
closeMenu($menu); |
||||
}, 500); |
||||
}); |
||||
el.querySelector('a').addEventListener("click", function(event){ |
||||
if (this.parentNode.className == "has-submenu") { |
||||
this.parentNode.className = "has-submenu open"; |
||||
this.setAttribute('aria-expanded', "true"); |
||||
} else { |
||||
this.parentNode.className = "has-submenu"; |
||||
this.setAttribute('aria-expanded', "false"); |
||||
} |
||||
event.preventDefault(); |
||||
return false; |
||||
}); |
||||
}); |