mirror of https://github.com/writeas/writefreely
commit
68d63d3fef
@ -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,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") |
||||||
|
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,244 @@ |
|||||||
|
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) 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 ") |
||||||
|
str.WriteString(c.Default.Value) |
||||||
|
} |
||||||
|
|
||||||
|
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() |
||||||
|
} |
||||||
|
|
@ -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) |
||||||
|
} |
@ -1,29 +1,46 @@ |
|||||||
/* |
|
||||||
* Copyright © 2019 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 |
package migrations |
||||||
|
|
||||||
func supportActivityPubMentions(db *datastore) error { |
import ( |
||||||
t, err := db.Begin() |
"context" |
||||||
|
"database/sql" |
||||||
|
|
||||||
_, err = t.Exec(`ALTER TABLE remoteusers ADD COLUMN handle ` + db.typeVarChar(255) + ` DEFAULT '' NOT NULL`) |
wf_db "github.com/writeas/writefreely/db" |
||||||
if err != nil { |
) |
||||||
t.Rollback() |
|
||||||
return err |
|
||||||
} |
|
||||||
|
|
||||||
err = t.Commit() |
func oauth(db *datastore) error { |
||||||
if err != nil { |
dialect := wf_db.DialectMySQL |
||||||
t.Rollback() |
if db.driverName == driverSQLite { |
||||||
return err |
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(true). |
||||||
|
Column(dialect.Column("user_id", wf_db.ColumnTypeInteger, wf_db.UnsetSize)). |
||||||
|
Column(dialect.Column("remote_user_id", wf_db.ColumnTypeInteger, wf_db.UnsetSize)). |
||||||
|
UniqueConstraint("user_id"). |
||||||
|
UniqueConstraint("remote_user_id"). |
||||||
|
ToSQL() |
||||||
|
if err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
createTableOauthClientState, err := dialect. |
||||||
|
Table("oauth_client_states"). |
||||||
|
SetIfNotExists(true). |
||||||
|
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).SetDefault("NOW()")). |
||||||
|
UniqueConstraint("state"). |
||||||
|
ToSQL() |
||||||
|
if err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
return nil |
for _, table := range []string{createTableUsersOauth, createTableOauthClientState} { |
||||||
|
if _, err := tx.ExecContext(ctx, table); err != nil { |
||||||
|
return err |
||||||
|
} |
||||||
|
} |
||||||
|
return nil |
||||||
|
}) |
||||||
} |
} |
||||||
|
@ -0,0 +1,67 @@ |
|||||||
|
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,})). |
||||||
|
AddColumn(dialect. |
||||||
|
Column( |
||||||
|
"client_id", |
||||||
|
wf_db.ColumnTypeVarChar, |
||||||
|
wf_db.OptionalInt{Set: true, Value: 128,})), |
||||||
|
dialect. |
||||||
|
AlterTable("oauth_users"). |
||||||
|
ChangeColumn("remote_user_id", |
||||||
|
dialect. |
||||||
|
Column( |
||||||
|
"remote_user_id", |
||||||
|
wf_db.ColumnTypeVarChar, |
||||||
|
wf_db.OptionalInt{Set: true, Value: 128,})). |
||||||
|
AddColumn(dialect. |
||||||
|
Column( |
||||||
|
"provider", |
||||||
|
wf_db.ColumnTypeVarChar, |
||||||
|
wf_db.OptionalInt{Set: true, Value: 24,})). |
||||||
|
AddColumn(dialect. |
||||||
|
Column( |
||||||
|
"client_id", |
||||||
|
wf_db.ColumnTypeVarChar, |
||||||
|
wf_db.OptionalInt{Set: true, Value: 128,})). |
||||||
|
AddColumn(dialect. |
||||||
|
Column( |
||||||
|
"access_token", |
||||||
|
wf_db.ColumnTypeVarChar, |
||||||
|
wf_db.OptionalInt{Set: true, Value: 512,})), |
||||||
|
dialect.DropIndex("remote_user_id", "oauth_users"), |
||||||
|
dialect.DropIndex("user_id", "oauth_users"), |
||||||
|
dialect.CreateUniqueIndex("oauth_users", "oauth_users", "user_id", "provider", "client_id"), |
||||||
|
} |
||||||
|
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 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) + ` DEFAULT '' NOT NULL`) |
||||||
|
if err != nil { |
||||||
|
t.Rollback() |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
err = t.Commit() |
||||||
|
if err != nil { |
||||||
|
t.Rollback() |
||||||
|
return err |
||||||
|
} |
||||||
|
|
||||||
|
return nil |
||||||
|
} |
@ -0,0 +1,291 @@ |
|||||||
|
package writefreely |
||||||
|
|
||||||
|
import ( |
||||||
|
"context" |
||||||
|
"encoding/json" |
||||||
|
"fmt" |
||||||
|
"github.com/gorilla/mux" |
||||||
|
"github.com/gorilla/sessions" |
||||||
|
"github.com/writeas/impart" |
||||||
|
"github.com/writeas/web-core/log" |
||||||
|
"github.com/writeas/writefreely/config" |
||||||
|
"io" |
||||||
|
"io/ioutil" |
||||||
|
"net/http" |
||||||
|
"net/url" |
||||||
|
"strings" |
||||||
|
"time" |
||||||
|
) |
||||||
|
|
||||||
|
// 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, error) |
||||||
|
GenerateOAuthState(context.Context, string, 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() |
||||||
|
state, err := h.DB.GenerateOAuthState(ctx, h.oauthClient.GetProvider(), h.oauthClient.GetClientID()) |
||||||
|
if err != nil { |
||||||
|
return impart.HTTPError{http.StatusInternalServerError, "could not prepare oauth redirect url"} |
||||||
|
} |
||||||
|
|
||||||
|
if h.callbackProxy != nil { |
||||||
|
if err := h.callbackProxy.register(ctx, state); err != nil { |
||||||
|
return impart.HTTPError{http.StatusInternalServerError, "could not register state server"} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
location, err := h.oauthClient.buildLoginURL(state) |
||||||
|
if err != nil { |
||||||
|
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().SlackOauth.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 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, 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) |
||||||
|
return impart.HTTPError{http.StatusInternalServerError, err.Error()} |
||||||
|
} |
||||||
|
|
||||||
|
// Now that we have the access token, let's use it real quick to make sur
|
||||||
|
// 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 { |
||||||
|
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 |
||||||
|
} |
||||||
|
|
||||||
|
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, |
||||||
|
} |
||||||
|
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", "writefreely") |
||||||
|
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,218 @@ |
|||||||
|
/* |
||||||
|
* 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 |
||||||
|
|
||||||
|
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" |
||||||
|
) |
||||||
|
|
||||||
|
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 |
||||||
|
} |
||||||
|
|
||||||
|
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), |
||||||
|
} |
||||||
|
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) |
||||||
|
} |
||||||
|
|
||||||
|
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, |
||||||
|
|
||||||
|
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,180 @@ |
|||||||
|
/* |
||||||
|
* 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" |
||||||
|
"fmt" |
||||||
|
"github.com/writeas/nerds/store" |
||||||
|
"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", "writefreely") |
||||||
|
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", "writefreely") |
||||||
|
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: fmt.Sprintf("%s-%s", slug.Make(resp.User.Name), store.GenerateRandomString("0123456789bcdfghjklmnpqrstvwxyz", 5)), |
||||||
|
DisplayName: resp.User.Name, |
||||||
|
Email: resp.User.Email, |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
func (resp slackExchangeResponse) TokenResponse() *TokenResponse { |
||||||
|
return &TokenResponse{ |
||||||
|
AccessToken: resp.AccessToken, |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,253 @@ |
|||||||
|
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) (string, error) |
||||||
|
DoValidateOAuthState func(context.Context, string) (string, 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, error) { |
||||||
|
if m.DoValidateOAuthState != nil { |
||||||
|
return m.DoValidateOAuthState(ctx, state) |
||||||
|
} |
||||||
|
return "", "", 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) (string, error) { |
||||||
|
if m.DoGenerateOAuthState != nil { |
||||||
|
return m.DoGenerateOAuthState(ctx, provider, clientID) |
||||||
|
} |
||||||
|
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) (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", "writefreely") |
||||||
|
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", "writefreely") |
||||||
|
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,174 @@ |
|||||||
|
{{define "head"}}<title>Log in — {{.SiteName}}</title> |
||||||
|
<meta name="description" content="Log in to {{.SiteName}}."> |
||||||
|
<meta itemprop="description" content="Log in to {{.SiteName}}."> |
||||||
|
<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>Log in to {{.SiteName}}</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 }}" /> |
||||||
|
|
||||||
|
<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="Login" /> |
||||||
|
</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() { |
||||||
|
// 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 { |
||||||
|
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); |
||||||
|
}); |
||||||
|
doneTyping(); |
||||||
|
</script> |
||||||
|
{{end}} |
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')); |
||||||
|
} |
@ -0,0 +1,61 @@ |
|||||||
|
{{define "import"}} |
||||||
|
{{template "header" .}} |
||||||
|
<style> |
||||||
|
input[type=file] { |
||||||
|
padding: 0; |
||||||
|
font-size: 0.86em; |
||||||
|
display: block; |
||||||
|
margin: 0.5rem 0; |
||||||
|
} |
||||||
|
label { |
||||||
|
display: block; |
||||||
|
margin: 1em 0; |
||||||
|
} |
||||||
|
</style> |
||||||
|
|
||||||
|
<div class="snug content-container"> |
||||||
|
<h1 id="import-header">Import posts</h1> |
||||||
|
{{if .Message}} |
||||||
|
<div class="alert {{if .InfoMsg}}info{{else}}success{{end}}"> |
||||||
|
<p>{{.Message}}</p> |
||||||
|
</div> |
||||||
|
{{end}} |
||||||
|
{{if .Flashes}} |
||||||
|
<ul class="errors"> |
||||||
|
{{range .Flashes}}<li class="urgent">{{.}}</li>{{end}} |
||||||
|
</ul> |
||||||
|
{{end}} |
||||||
|
<p>Publish plain text or Markdown files to your account by uploading them below.</p> |
||||||
|
<div class="formContainer"> |
||||||
|
<form id="importPosts" class="prominent" enctype="multipart/form-data" action="/api/me/import" method="POST"> |
||||||
|
<label>Select some files to import: |
||||||
|
<input id="fileInput" class="fileInput" name="files" type="file" multiple accept="text/markdown, text/plain"/> |
||||||
|
</label> |
||||||
|
<input id="fileDates" name="fileDates" hidden/> |
||||||
|
<label> |
||||||
|
Import these posts to: |
||||||
|
<select name="collection"> |
||||||
|
{{range $i, $el := .Collections}} |
||||||
|
<option value="{{.Alias}}" {{if eq $i 0}}selected{{end}}>{{.DisplayTitle}}</option> |
||||||
|
{{end}} |
||||||
|
<option value="">Drafts</option> |
||||||
|
</select> |
||||||
|
</label> |
||||||
|
<script> |
||||||
|
const fileInput = document.getElementById('fileInput'); |
||||||
|
const fileDates = document.getElementById('fileDates'); |
||||||
|
fileInput.addEventListener('change', (e) => { |
||||||
|
const files = e.target.files; |
||||||
|
let dateMap = {}; |
||||||
|
for (let file of files) { |
||||||
|
dateMap[file.name] = file.lastModified / 1000; |
||||||
|
} |
||||||
|
fileDates.value = JSON.stringify(dateMap); |
||||||
|
}) |
||||||
|
</script> |
||||||
|
<input type="submit" value="Import" /> |
||||||
|
</form> |
||||||
|
</div> |
||||||
|
</div> |
||||||
|
{{template "footer" .}} |
||||||
|
{{end}} |
Loading…
Reference in new issue