Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: upload custom avatar (#699)

Guilherme Oenning97f18bb154c0
diff --git a/app/actions/oauth.go b/app/actions/oauth.go
index c4124092d..41df49eb3 100644
--- a/app/actions/oauth.go
+++ b/app/actions/oauth.go
@@ -45,7 +45,12 @@ func (input *CreateEditOAuthConfig) Validate(user *models.User, services *app.Se
input.Model.Provider = "_" + strings.ToLower(rand.String(10))
}
- messages, err := validate.ImageUpload(input.Model.Logo, 24, 24, 50)
+ messages, err := validate.ImageUpload(input.Model.Logo, validate.ImageUploadOpts{
+ IsRequired: false,
+ MinHeight: 24,
+ MinWidth: 24,
+ MaxKilobytes: 50,
+ })
if err != nil {
return validate.Error(err)
}
diff --git a/app/actions/settings.go b/app/actions/settings.go
index aed332b83..de4b12390 100644
--- a/app/actions/settings.go
+++ b/app/actions/settings.go
@@ -16,6 +16,7 @@ type UpdateUserSettings struct {
// Initialize the model
func (input *UpdateUserSettings) Initialize() interface{} {
input.Model = new(models.UpdateUserSettings)
+ input.Model.Avatar = &models.ImageUpload{}
return input.Model
}
@@ -40,6 +41,18 @@ func (input *UpdateUserSettings) Validate(user *models.User, services *app.Servi
result.AddFieldFailure("name", "Name must have less than 50 characters.")
}
+ input.Model.Avatar.BlobKey = user.AvatarBlobKey
+ messages, err := validate.ImageUpload(input.Model.Avatar, validate.ImageUploadOpts{
+ IsRequired: input.Model.AvatarType == models.AvatarTypeCustom,
+ MinHeight: 50,
+ MinWidth: 50,
+ MaxKilobytes: 100,
+ })
+ if err != nil {
+ return validate.Error(err)
+ }
+ result.AddFieldFailure("avatar", messages...)
+
if input.Model.Settings != nil {
for k, v := range input.Model.Settings {
ok := false
diff --git a/app/actions/settings_test.go b/app/actions/settings_test.go
index cd601553c..7feb757ec 100644
--- a/app/actions/settings_test.go
+++ b/app/actions/settings_test.go
@@ -15,13 +15,12 @@ func TestInvalidUserNames(t *testing.T) {
"",
"123456789012345678901234567890123456789012345678901", // 51 chars
} {
- action := &actions.UpdateUserSettings{
- Model: &models.UpdateUserSettings{
- Name: name,
- AvatarType: models.AvatarTypeGravatar,
- },
- }
- result := action.Validate(nil, services)
+
+ action := actions.UpdateUserSettings{}
+ action.Initialize()
+ action.Model.Name = name
+ action.Model.AvatarType = models.AvatarTypeGravatar
+ result := action.Validate(&models.User{}, services)
ExpectFailed(result, "name")
}
}
@@ -33,13 +32,11 @@ func TestValidUserNames(t *testing.T) {
"Jon Snow",
"Arya",
} {
- action := &actions.UpdateUserSettings{
- Model: &models.UpdateUserSettings{
- Name: name,
- AvatarType: models.AvatarTypeGravatar,
- },
- }
- result := action.Validate(nil, services)
+ action := actions.UpdateUserSettings{}
+ action.Initialize()
+ action.Model.Name = name
+ action.Model.AvatarType = models.AvatarTypeGravatar
+ result := action.Validate(&models.User{}, services)
ExpectSuccess(result)
}
}
@@ -55,13 +52,11 @@ func TestInvalidSettings(t *testing.T) {
models.NotificationEventNewComment.UserSettingsKeyName: "4",
},
} {
- action := &actions.UpdateUserSettings{
- Model: &models.UpdateUserSettings{
- Name: "John Snow",
- Settings: settings,
- },
- }
- result := action.Validate(nil, services)
+ action := actions.UpdateUserSettings{}
+ action.Initialize()
+ action.Model.Name = "John Snow"
+ action.Model.Settings = settings
+ result := action.Validate(&models.User{}, services)
ExpectFailed(result, "settings", "avatarType")
}
}
@@ -80,14 +75,17 @@ func TestValidSettings(t *testing.T) {
models.NotificationEventNewComment.UserSettingsKeyName: models.NotificationEventNewComment.DefaultSettingValue,
},
} {
- action := &actions.UpdateUserSettings{
- Model: &models.UpdateUserSettings{
- Name: "John Snow",
- Settings: settings,
- AvatarType: models.AvatarTypeGravatar,
- },
- }
- result := action.Validate(nil, services)
+ action := actions.UpdateUserSettings{}
+ action.Initialize()
+ action.Model.Name = "John Snow"
+ action.Model.Settings = settings
+ action.Model.AvatarType = models.AvatarTypeGravatar
+
+ result := action.Validate(&models.User{
+ AvatarBlobKey: "jon.png",
+ }, services)
+
ExpectSuccess(result)
+ Expect(action.Model.Avatar.BlobKey).Equals("jon.png")
}
}
diff --git a/app/actions/tenant.go b/app/actions/tenant.go
index 5a31d8d31..2bea9067b 100644
--- a/app/actions/tenant.go
+++ b/app/actions/tenant.go
@@ -100,7 +100,12 @@ func (input *UpdateTenantSettings) Validate(user *models.User, services *app.Ser
if services.Tenants.Current() != nil {
input.Model.Logo.BlobKey = services.Tenants.Current().LogoBlobKey
}
- messages, err := validate.ImageUpload(input.Model.Logo, 200, 200, 100)
+ messages, err := validate.ImageUpload(input.Model.Logo, validate.ImageUploadOpts{
+ IsRequired: false,
+ MinHeight: 200,
+ MinWidth: 200,
+ MaxKilobytes: 100,
+ })
if err != nil {
return validate.Error(err)
}
diff --git a/app/handlers/admin.go b/app/handlers/admin.go
index dbfda1aab..ee3830c01 100644
--- a/app/handlers/admin.go
+++ b/app/handlers/admin.go
@@ -37,7 +37,7 @@ func UpdateSettings() web.HandlerFunc {
return c.HandleValidation(result)
}
- err := handleImageUpload(c, input.Model.Logo)
+ err := handleImageUpload(c, input.Model.Logo, "logos")
if err != nil {
return errors.Wrap(err, "failed to upload new tenant logo")
}
@@ -141,7 +141,7 @@ func SaveOAuthConfig() web.HandlerFunc {
return c.HandleValidation(result)
}
- err := handleImageUpload(c, input.Model.Logo)
+ err := handleImageUpload(c, input.Model.Logo, "logos")
if err != nil {
return errors.Wrap(err, "failed to upload new OAuth logo")
}
diff --git a/app/handlers/common.go b/app/handlers/common.go
index 603f47590..c33f84680 100644
--- a/app/handlers/common.go
+++ b/app/handlers/common.go
@@ -156,11 +156,11 @@ func validateKey(kind models.EmailVerificationKind, c web.Context) (*models.Emai
return result, nil
}
-func handleImageUpload(c web.Context, img *models.ImageUpload) error {
+func handleImageUpload(c web.Context, img *models.ImageUpload, preffix string) error {
if img.Remove {
img.BlobKey = ""
} else if img.Upload != nil && len(img.Upload.Content) > 0 {
- bkey := fmt.Sprintf("logos/%s-%s", rand.String(64), blob.SanitizeFileName(img.Upload.FileName))
+ bkey := fmt.Sprintf("%s/%s-%s", preffix, rand.String(64), blob.SanitizeFileName(img.Upload.FileName))
err := c.Services().Blobs.Put(bkey, img.Upload.Content, img.Upload.ContentType)
if err != nil {
return err
diff --git a/app/handlers/settings.go b/app/handlers/settings.go
index b8a8a8119..272dbfdae 100644
--- a/app/handlers/settings.go
+++ b/app/handlers/settings.go
@@ -7,6 +7,7 @@ import (
"github.com/getfider/fider/app/tasks"
"github.com/getfider/fider/app/actions"
+ "github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/web"
)
@@ -75,18 +76,22 @@ func UserSettings() web.HandlerFunc {
// UpdateUserSettings updates current user settings
func UpdateUserSettings() web.HandlerFunc {
return func(c web.Context) error {
+ var err error
+
input := new(actions.UpdateUserSettings)
if result := c.BindTo(input); !result.Ok {
return c.HandleValidation(result)
}
- err := c.Services().Users.Update(input.Model)
- if err != nil {
+ if err = handleImageUpload(c, input.Model.Avatar, "avatars"); err != nil {
+ return errors.Wrap(err, "failed to upload new user custom avatar")
+ }
+
+ if err = c.Services().Users.Update(input.Model); err != nil {
return c.Failure(err)
}
- err = c.Services().Users.UpdateSettings(input.Model.Settings)
- if err != nil {
+ if err = c.Services().Users.UpdateSettings(input.Model.Settings); err != nil {
return c.Failure(err)
}
diff --git a/app/models/identity.go b/app/models/identity.go
index a75a6df39..4d93c536d 100644
--- a/app/models/identity.go
+++ b/app/models/identity.go
@@ -39,15 +39,16 @@ type Upload struct {
//User represents an user inside our application
type User struct {
- ID int `json:"id"`
- Name string `json:"name"`
- Tenant *Tenant `json:"-"`
- Email string `json:"-"`
- Role Role `json:"role"`
- Providers []*UserProvider `json:"-"`
- AvatarType AvatarType `json:"-"`
- AvatarURL string `json:"avatarURL,omitempty"`
- Status UserStatus `json:"status"`
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Tenant *Tenant `json:"-"`
+ Email string `json:"-"`
+ Role Role `json:"role"`
+ Providers []*UserProvider `json:"-"`
+ AvatarBlobKey string `json:"-"`
+ AvatarType AvatarType `json:"-"`
+ AvatarURL string `json:"avatarURL,omitempty"`
+ Status UserStatus `json:"status"`
}
//AvatarType are the possible types of a user avatar
@@ -375,6 +376,7 @@ type CompleteProfile struct {
type UpdateUserSettings struct {
Name string `json:"name"`
AvatarType AvatarType `json:"avatarType"`
+ Avatar *ImageUpload `json:"avatar"`
Settings map[string]string `json:"settings"`
}
diff --git a/app/pkg/validate/upload.go b/app/pkg/validate/upload.go
index aae697dfb..16ae5b037 100644
--- a/app/pkg/validate/upload.go
+++ b/app/pkg/validate/upload.go
@@ -7,10 +7,24 @@ import (
"github.com/getfider/fider/app/pkg/img"
)
+// ImageUploadOpts arguments to validate given upload
+type ImageUploadOpts struct {
+ IsRequired bool
+ MinWidth int
+ MinHeight int
+ MaxKilobytes int
+}
+
//ImageUpload validates given image upload
-func ImageUpload(upload *models.ImageUpload, minWidth, minHeight, maxKilobytes int) ([]string, error) {
+func ImageUpload(upload *models.ImageUpload, opts ImageUploadOpts) ([]string, error) {
messages := []string{}
+ if opts.IsRequired {
+ if upload == nil || (upload.BlobKey == "" && upload.Upload == nil) || upload.Remove {
+ messages = append(messages, "An image is required.")
+ }
+ }
+
if upload != nil && upload.Upload != nil && len(upload.Upload.Content) > 0 {
logo, err := img.Parse(upload.Upload.Content)
if err != nil {
@@ -20,16 +34,16 @@ func ImageUpload(upload *models.ImageUpload, minWidth, minHeight, maxKilobytes i
return nil, err
}
} else {
- if logo.Width < minWidth || logo.Height < minHeight {
- messages = append(messages, fmt.Sprintf("The image must have minimum dimensions of %dx%d pixels.", minWidth, minHeight))
+ if logo.Width < opts.MinWidth || logo.Height < opts.MinHeight {
+ messages = append(messages, fmt.Sprintf("The image must have minimum dimensions of %dx%d pixels.", opts.MinWidth, opts.MinHeight))
}
if logo.Width != logo.Height {
messages = append(messages, "The image must have an aspect ratio of 1:1.")
}
- if logo.Size > (maxKilobytes * 1024) {
- messages = append(messages, fmt.Sprintf("The image size must be smaller than %dKB.", maxKilobytes))
+ if logo.Size > (opts.MaxKilobytes * 1024) {
+ messages = append(messages, fmt.Sprintf("The image size must be smaller than %dKB.", opts.MaxKilobytes))
}
}
}
diff --git a/app/pkg/validate/upload_test.go b/app/pkg/validate/upload_test.go
index 689231db1..7d6e33041 100644
--- a/app/pkg/validate/upload_test.go
+++ b/app/pkg/validate/upload_test.go
@@ -34,7 +34,11 @@ func TestValidateImageUpload(t *testing.T) {
Content: img,
},
}
- messages, err := validate.ImageUpload(upload, 200, 200, 100)
+ messages, err := validate.ImageUpload(upload, validate.ImageUploadOpts{
+ MinHeight: 200,
+ MinWidth: 200,
+ MaxKilobytes: 100,
+ })
Expect(messages).HasLen(testCase.count)
Expect(err).IsNil()
}
@@ -43,11 +47,48 @@ func TestValidateImageUpload(t *testing.T) {
func TestValidateImageUpload_Nil(t *testing.T) {
RegisterT(t)
- messages, err := validate.ImageUpload(nil, 200, 200, 50)
+ messages, err := validate.ImageUpload(nil, validate.ImageUploadOpts{
+ IsRequired: false,
+ MinHeight: 200,
+ MinWidth: 200,
+ MaxKilobytes: 50,
+ })
Expect(messages).HasLen(0)
Expect(err).IsNil()
- messages, err = validate.ImageUpload(&models.ImageUpload{}, 200, 200, 50)
+ messages, err = validate.ImageUpload(&models.ImageUpload{}, validate.ImageUploadOpts{
+ IsRequired: false,
+ MinHeight: 200,
+ MinWidth: 200,
+ MaxKilobytes: 50,
+ })
Expect(messages).HasLen(0)
Expect(err).IsNil()
}
+
+func TestValidateImageUpload_Required(t *testing.T) {
+ RegisterT(t)
+
+ var testCases = []struct {
+ upload *models.ImageUpload
+ count int
+ }{
+ {nil, 1},
+ {&models.ImageUpload{}, 1},
+ {&models.ImageUpload{
+ BlobKey: "some-file.png",
+ Remove: true,
+ }, 1},
+ }
+
+ for _, testCase := range testCases {
+ messages, err := validate.ImageUpload(testCase.upload, validate.ImageUploadOpts{
+ IsRequired: true,
+ MinHeight: 200,
+ MinWidth: 200,
+ MaxKilobytes: 50,
+ })
+ Expect(messages).HasLen(testCase.count)
+ Expect(err).IsNil()
+ }
+}
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index 4a96c0b60..1092754e2 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -228,6 +228,7 @@ func (r *Renderer) Render(w io.Writer, name string, props Props, ctx *Context) {
"status": u.Status,
"avatarType": u.AvatarType,
"avatarURL": u.AvatarURL,
+ "avatarBlobKey": u.AvatarBlobKey,
"isAdministrator": u.IsAdministrator(),
"isCollaborator": u.IsCollaborator(),
}
diff --git a/app/pkg/web/testdata/user.html b/app/pkg/web/testdata/user.html
index 6fa85ba69..1ec8c5ac4 100755
--- a/app/pkg/web/testdata/user.html
+++ b/app/pkg/web/testdata/user.html
@@ -38,7 +38,7 @@
<script id="server-data" type="application/json">
- {"__assets":{"CSS":["/assets/css/file1.css"],"JS":["/assets/js/file1.js","/assets/js/file2.js"]},"__contextID":"CONTEXT_ID","__currentURL":"https://demo.test.fider.io:3000/","__description":"My Page Description","__favicon":"https://demo.test.fider.io:3000/favicon","__logo":"https://getfider.com/images/logo-100x100.png","__props":null,"__settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"__tenant":null,"__title":"My Page Title · Fider","__user":{"avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"name":"Jon Snow","role":"administrator","status":"active"}}
+ {"__assets":{"CSS":["/assets/css/file1.css"],"JS":["/assets/js/file1.js","/assets/js/file2.js"]},"__contextID":"CONTEXT_ID","__currentURL":"https://demo.test.fider.io:3000/","__description":"My Page Description","__favicon":"https://demo.test.fider.io:3000/favicon","__logo":"https://getfider.com/images/logo-100x100.png","__props":null,"__settings":{"baseURL":"https://demo.test.fider.io:3000","buildTime":"","compiler":"","domain":"","environment":"","globalAssetsURL":"https://demo.test.fider.io:3000","googleAnalytics":"","hasLegal":false,"mode":"","oauth":[],"tenantAssetsURL":"https://demo.test.fider.io:3000","version":""},"__tenant":null,"__title":"My Page Title · Fider","__user":{"avatarBlobKey":"","avatarType":"gravatar","avatarURL":"https://demo.test.fider.io:3000/avatars/gravatar/5/Jon%20Snow","email":"[email protected]","id":5,"isAdministrator":true,"isCollaborator":true,"name":"Jon Snow","role":"administrator","status":"active"}}
</script>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,fetch" crossorigin="anonymous"></script>
diff --git a/app/storage/postgres/common.go b/app/storage/postgres/common.go
index 2360ac0a1..82d351727 100644
--- a/app/storage/postgres/common.go
+++ b/app/storage/postgres/common.go
@@ -67,9 +67,14 @@ func getViewData(view string) (string, []models.PostStatus, string) {
return condition, statuses, sort
}
-func buildAvatarURL(ctx storage.Context, avatarType models.AvatarType, id int, name string) string {
+func buildAvatarURL(ctx storage.Context, avatarType models.AvatarType, id int, name, avatarBlobKey string) string {
if name == "" {
name = "-"
}
- return ctx.TenantAssetsURL("/avatars/%s/%d/%s", avatarType.String(), id, url.PathEscape(name))
+
+ if avatarType == models.AvatarTypeCustom {
+ return ctx.TenantAssetsURL("/images/%s", avatarBlobKey)
+ } else {
+ return ctx.TenantAssetsURL("/avatars/%s/%d/%s", avatarType.String(), id, url.PathEscape(name))
+ }
}
diff --git a/app/storage/postgres/post.go b/app/storage/postgres/post.go
index 44c8056f4..6a31dd0eb 100644
--- a/app/storage/postgres/post.go
+++ b/app/storage/postgres/post.go
@@ -103,10 +103,11 @@ type dbStatusCount struct {
type dbVote struct {
User *struct {
- ID int `db:"id"`
- Name string `db:"name"`
- Email string `db:"email"`
- AvatarType int64 `db:"avatar_type"`
+ ID int `db:"id"`
+ Name string `db:"name"`
+ Email string `db:"email"`
+ AvatarType int64 `db:"avatar_type"`
+ AvatarBlobKey string `db:"avatar_bkey"`
} `db:"user"`
CreatedAt time.Time `db:"created_at"`
}
@@ -118,7 +119,7 @@ func (v *dbVote) toModel(ctx storage.Context) *models.Vote {
ID: v.User.ID,
Name: v.User.Name,
Email: v.User.Email,
- AvatarURL: buildAvatarURL(ctx, models.AvatarType(v.User.AvatarType), v.User.ID, v.User.Name),
+ AvatarURL: buildAvatarURL(ctx, models.AvatarType(v.User.AvatarType), v.User.ID, v.User.Name, v.User.AvatarBlobKey),
},
}
return vote
@@ -206,6 +207,7 @@ var (
u.role AS user_role,
u.status AS user_status,
u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey,
p.response,
p.response_date,
r.id AS response_user_id,
@@ -214,6 +216,7 @@ var (
r.role AS response_user_role,
r.status AS response_user_status,
r.avatar_type AS response_user_avatar_type,
+ r.avatar_bkey AS response_user_avatar_bkey,
d.number AS original_number,
d.title AS original_title,
d.slug AS original_slug,
@@ -375,13 +378,15 @@ func (s *PostStorage) GetCommentsByPost(post *models.Post) ([]*models.Comment, e
u.email AS user_email,
u.role AS user_role,
u.status AS user_status,
- u.avatar_type AS user_avatar_type,
+ u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey,
e.id AS edited_by_id,
e.name AS edited_by_name,
e.email AS edited_by_email,
e.role AS edited_by_role,
e.status AS edited_by_status,
- e.avatar_type AS edited_by_avatar_type
+ e.avatar_type AS edited_by_avatar_type,
+ e.avatar_bkey AS edited_by_avatar_bkey
FROM comments c
INNER JOIN posts p
ON p.id = c.post_id
@@ -486,14 +491,16 @@ func (s *PostStorage) GetCommentByID(id int) (*models.Comment, error) {
u.name AS user_name,
u.email AS user_email,
u.role AS user_role,
- u.status AS user_status,
+ u.status AS user_status,
u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey,
e.id AS edited_by_id,
e.name AS edited_by_name,
e.email AS edited_by_email,
e.role AS edited_by_role,
e.status AS edited_by_status,
- e.avatar_type AS edited_by_avatar_type
+ e.avatar_type AS edited_by_avatar_type,
+ e.avatar_bkey AS edited_by_avatar_bkey
FROM comments c
INNER JOIN users u
ON u.id = c.user_id
@@ -769,7 +776,8 @@ func (s *PostStorage) ListVotes(post *models.Post, limit int) ([]*models.Vote, e
u.id AS user_id,
u.name AS user_name,
u.email AS user_email,
- u.avatar_type AS user_avatar_type
+ u.avatar_type AS user_avatar_type,
+ u.avatar_bkey AS user_avatar_bkey
FROM post_votes pv
INNER JOIN users u
ON u.id = pv.user_id
diff --git a/app/storage/postgres/user.go b/app/storage/postgres/user.go
index 72581aec4..0f885fbbf 100644
--- a/app/storage/postgres/user.go
+++ b/app/storage/postgres/user.go
@@ -15,14 +15,15 @@ import (
)
type dbUser struct {
- ID sql.NullInt64 `db:"id"`
- Name sql.NullString `db:"name"`
- Email sql.NullString `db:"email"`
- Tenant *dbTenant `db:"tenant"`
- Role sql.NullInt64 `db:"role"`
- Status sql.NullInt64 `db:"status"`
- AvatarType sql.NullInt64 `db:"avatar_type"`
- Providers []*dbUserProvider
+ ID sql.NullInt64 `db:"id"`
+ Name sql.NullString `db:"name"`
+ Email sql.NullString `db:"email"`
+ Tenant *dbTenant `db:"tenant"`
+ Role sql.NullInt64 `db:"role"`
+ Status sql.NullInt64 `db:"status"`
+ AvatarType sql.NullInt64 `db:"avatar_type"`
+ AvatarBlobKey sql.NullString `db:"avatar_bkey"`
+ Providers []*dbUserProvider
}
type dbUserProvider struct {
@@ -37,15 +38,16 @@ func (u *dbUser) toModel(ctx storage.Context) *models.User {
avatarType := models.AvatarType(u.AvatarType.Int64)
user := &models.User{
- ID: int(u.ID.Int64),
- Name: u.Name.String,
- Email: u.Email.String,
- Tenant: u.Tenant.toModel(),
- Role: models.Role(u.Role.Int64),
- Providers: make([]*models.UserProvider, len(u.Providers)),
- Status: models.UserStatus(u.Status.Int64),
- AvatarType: avatarType,
- AvatarURL: buildAvatarURL(ctx, avatarType, int(u.ID.Int64), u.Name.String),
+ ID: int(u.ID.Int64),
+ Name: u.Name.String,
+ Email: u.Email.String,
+ Tenant: u.Tenant.toModel(),
+ Role: models.Role(u.Role.Int64),
+ Providers: make([]*models.UserProvider, len(u.Providers)),
+ Status: models.UserStatus(u.Status.Int64),
+ AvatarType: avatarType,
+ AvatarBlobKey: u.AvatarBlobKey.String,
+ AvatarURL: buildAvatarURL(ctx, avatarType, int(u.ID.Int64), u.Name.String, u.AvatarBlobKey.String),
}
for i, p := range u.Providers {
@@ -154,8 +156,8 @@ func (s *UserStorage) RegisterProvider(userID int, provider *models.UserProvider
// Update user profile
func (s *UserStorage) Update(settings *models.UpdateUserSettings) error {
- cmd := "UPDATE users SET name = $3, avatar_type = $4 WHERE id = $1 AND tenant_id = $2"
- _, err := s.trx.Execute(cmd, s.user.ID, s.tenant.ID, settings.Name, settings.AvatarType)
+ cmd := "UPDATE users SET name = $3, avatar_type = $4, avatar_bkey = $5 WHERE id = $1 AND tenant_id = $2"
+ _, err := s.trx.Execute(cmd, s.user.ID, s.tenant.ID, settings.Name, settings.AvatarType, settings.Avatar.BlobKey)
if err != nil {
return errors.Wrap(err, "failed to update user")
}
@@ -232,7 +234,7 @@ func (s *UserStorage) ChangeEmail(userID int, email string) error {
// GetByID returns a user based on given id
func (s *UserStorage) getUser(trx *dbx.Trx, filter string, args ...interface{}) (*models.User, error) {
user := dbUser{}
- sql := fmt.Sprintf("SELECT id, name, email, tenant_id, role, status, avatar_type FROM users WHERE status != %d AND ", models.UserDeleted)
+ sql := fmt.Sprintf("SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey FROM users WHERE status != %d AND ", models.UserDeleted)
err := trx.Get(&user, sql+filter, args...)
if err != nil {
return nil, err
@@ -250,7 +252,7 @@ func (s *UserStorage) getUser(trx *dbx.Trx, filter string, args ...interface{})
func (s *UserStorage) GetAll() ([]*models.User, error) {
var users []*dbUser
err := s.trx.Select(&users, `
- SELECT id, name, email, tenant_id, role, status, avatar_type
+ SELECT id, name, email, tenant_id, role, status, avatar_type, avatar_bkey
FROM users
WHERE tenant_id = $1
AND status != $2
diff --git a/app/storage/postgres/user_test.go b/app/storage/postgres/user_test.go
index fbd5ab458..e79a09d77 100644
--- a/app/storage/postgres/user_test.go
+++ b/app/storage/postgres/user_test.go
@@ -207,12 +207,18 @@ func TestUserStorage_UpdateSettings(t *testing.T) {
users.SetCurrentTenant(demoTenant)
users.SetCurrentUser(jonSnow)
- err := users.Update(&models.UpdateUserSettings{Name: "Jon Stark"})
+ err := users.Update(&models.UpdateUserSettings{
+ Name: "Jon Stark",
+ Avatar: &models.ImageUpload{
+ BlobKey: "jon.png",
+ },
+ })
Expect(err).IsNil()
user, err := users.GetByEmail("[email protected]")
Expect(err).IsNil()
Expect(user.Name).Equals("Jon Stark")
+ Expect(user.AvatarBlobKey).Equals("jon.png")
}
func TestUserStorage_ChangeRole(t *testing.T) {
diff --git a/public/components/common/form/ImageUploader.tsx b/public/components/common/form/ImageUploader.tsx
index d4136dde0..47f98177e 100644
--- a/public/components/common/form/ImageUploader.tsx
+++ b/public/components/common/form/ImageUploader.tsx
@@ -56,6 +56,10 @@ export class ImageUploader extends React.Component<ImageUploaderProps, ImageUplo
};
public removeFile = async (e: ButtonClickEvent) => {
+ if (this.fileSelector) {
+ this.fileSelector.value = "";
+ }
+
this.setState(
{
bkey: this.props.bkey,
diff --git a/public/models/identity.ts b/public/models/identity.ts
index 2ea8c4932..8e0ec3b61 100644
--- a/public/models/identity.ts
+++ b/public/models/identity.ts
@@ -44,6 +44,7 @@ export interface CurrentUser {
name: string;
email: string;
avatarType: UserAvatarType;
+ avatarBlobKey: string;
avatarURL: string;
role: UserRole;
status: UserStatus;
diff --git a/public/pages/Administration/pages/GeneralSettings.page.tsx b/public/pages/Administration/pages/GeneralSettings.page.tsx
index 12596d79e..e8ff20930 100644
--- a/public/pages/Administration/pages/GeneralSettings.page.tsx
+++ b/public/pages/Administration/pages/GeneralSettings.page.tsx
@@ -3,7 +3,7 @@ import "./GeneralSettings.page.scss";
import React from "react";
import { Button, ButtonClickEvent, TextArea, Form, Input, ImageUploader } from "@fider/components/common";
-import { actions, Failure, fileToBase64, Fider } from "@fider/services";
+import { actions, Failure, Fider } from "@fider/services";
import { FaCogs } from "react-icons/fa";
import { AdminBasePage } from "../components/AdminBasePage";
import { ImageUpload } from "@fider/models";
@@ -18,8 +18,6 @@ interface GeneralSettingsPageState {
}
export default class GeneralSettingsPage extends AdminBasePage<{}, GeneralSettingsPageState> {
- private fileSelector?: HTMLInputElement | null;
-
public id = "p-admin-general";
public name = "general";
public icon = FaCogs;
@@ -47,39 +45,6 @@ export default class GeneralSettingsPage extends AdminBasePage<{}, GeneralSettin
}
};
- public fileChanged = async (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files && e.target.files[0]) {
- const file = e.target.files[0];
- const base64 = await fileToBase64(file);
- this.setState({
- logo: {
- upload: {
- content: base64,
- contentType: file.type,
- action: "upload"
- },
- ignore: false,
- remove: false
- }
- });
- }
- };
-
- public removeFile = async (e: ButtonClickEvent) => {
- this.setState({
- logo: {
- ignore: false,
- remove: true
- }
- });
- };
-
- public selectFile = async (e: ButtonClickEvent) => {
- if (this.fileSelector) {
- this.fileSelector.click();
- }
- };
-
public dnsInstructions(): JSX.Element {
const isApex = this.state.cname.split(".").length <= 2;
const recordType = isApex ? "ALIAS" : "CNAME";
diff --git a/public/pages/MySettings/MySettings.page.tsx b/public/pages/MySettings/MySettings.page.tsx
index a01ab8da1..409b89754 100644
--- a/public/pages/MySettings/MySettings.page.tsx
+++ b/public/pages/MySettings/MySettings.page.tsx
@@ -2,9 +2,9 @@ import "./MySettings.page.scss";
import React from "react";
-import { Modal, Form, Button, Heading, Input, Select, SelectOption } from "@fider/components";
+import { Modal, Form, Button, Heading, Input, Select, SelectOption, ImageUploader } from "@fider/components";
-import { UserSettings, UserAvatarType } from "@fider/models";
+import { UserSettings, UserAvatarType, ImageUpload } from "@fider/models";
import { Failure, actions, Fider } from "@fider/services";
import { FaRegAddressCard } from "react-icons/fa";
import { NotificationSettings } from "./components/NotificationSettings";
@@ -15,6 +15,7 @@ interface MySettingsPageState {
showModal: boolean;
name: string;
newEmail: string;
+ avatar?: ImageUpload;
avatarType: UserAvatarType;
changingEmail: boolean;
error?: Failure;
@@ -39,7 +40,12 @@ export default class MySettingsPage extends React.Component<MySettingsPageProps,
}
private confirm = async () => {
- const result = await actions.updateUserSettings(this.state.name, this.state.avatarType, this.state.userSettings);
+ const result = await actions.updateUserSettings({
+ name: this.state.name,
+ avatarType: this.state.avatarType,
+ avatar: this.state.avatar,
+ settings: this.state.userSettings
+ });
if (result.ok) {
location.reload();
} else if (result.error) {
@@ -94,6 +100,10 @@ export default class MySettingsPage extends React.Component<MySettingsPageProps,
this.setState({ newEmail });
};
+ private setAvatar = (avatar: ImageUpload): void => {
+ this.setState({ avatar });
+ };
+
public render() {
const changeEmail = (
<span className="ui info clickable" onClick={this.startChangeEmail}>
@@ -136,7 +146,7 @@ export default class MySettingsPage extends React.Component<MySettingsPageProps,
>
<p className="info">
{Fider.session.user.email || this.state.changingEmail
- ? "Your email is private and will never be publicly displayed"
+ ? "Your email is private and will never be publicly displayed."
: "Your account doesn't have an email."}
</p>
{this.state.changingEmail && (
@@ -159,7 +169,8 @@ export default class MySettingsPage extends React.Component<MySettingsPageProps,
defaultValue={this.state.avatarType}
options={[
{ label: "Letter", value: UserAvatarType.Letter },
- { label: "Gravatar", value: UserAvatarType.Gravatar }
+ { label: "Gravatar", value: UserAvatarType.Gravatar },
+ { label: "Custom", value: UserAvatarType.Custom }
]}
onChange={this.avatarTypeChanged}
>
@@ -176,6 +187,19 @@ export default class MySettingsPage extends React.Component<MySettingsPageProps,
{this.state.avatarType === UserAvatarType.Letter && (
<p className="info">A letter avatar based on your initials is generated for you.</p>
)}
+ {this.state.avatarType === UserAvatarType.Custom && (
+ <ImageUploader
+ field="avatar"
+ previewMaxWidth={80}
+ onChange={this.setAvatar}
+ bkey={Fider.session.user.avatarBlobKey}
+ >
+ <p className="info">
+ We accept JPG, GIF and PNG images, smaller than 100KB and with an aspect ratio of 1:1 with minimum
+ dimensions of 50x50 pixels.
+ </p>
+ </ImageUploader>
+ )}
</Select>
<NotificationSettings
diff --git a/public/services/actions/user.ts b/public/services/actions/user.ts
index 2fd1d7f18..94dbfc6f0 100644
--- a/public/services/actions/user.ts
+++ b/public/services/actions/user.ts
@@ -1,16 +1,15 @@
import { http, Result } from "@fider/services/http";
-import { UserSettings, UserAvatarType } from "@fider/models";
+import { UserSettings, UserAvatarType, ImageUpload } from "@fider/models";
-export const updateUserSettings = async (
- name: string,
- avatarType: UserAvatarType,
- settings: UserSettings
-): Promise<Result> => {
- return await http.post("/_api/user/settings", {
- name,
- avatarType,
- settings
- });
+interface UpdateUserSettings {
+ name: string;
+ avatar?: ImageUpload;
+ avatarType: UserAvatarType;
+ settings: UserSettings;
+}
+
+export const updateUserSettings = async (request: UpdateUserSettings): Promise<Result> => {
+ return await http.post("/_api/user/settings", request);
};
export const changeUserEmail = async (email: string): Promise<Result> => {