Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add API for changing Avatars #25369

Merged
merged 9 commits into from
Jun 29, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions modules/structs/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,3 +380,9 @@ type NewIssuePinsAllowed struct {
Issues bool `json:"issues"`
PullRequests bool `json:"pull_requests"`
}

// UpdateRepoAvatarUserOption options when updating the repo avatar
type UpdateRepoAvatarOption struct {
// image must be base64 encoded
Image string `json:"image" binding:"Required"`
}
6 changes: 6 additions & 0 deletions modules/structs/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,9 @@ type RenameUserOption struct {
// unique: true
NewName string `json:"new_username" binding:"Required"`
}

// UpdateUserAvatarUserOption options when updating the user avatar
type UpdateUserAvatarOption struct {
// image must be base64 encoded
Image string `json:"image" binding:"Required"`
}
silverwind marked this conversation as resolved.
Show resolved Hide resolved
13 changes: 13 additions & 0 deletions routers/api/v1/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,11 @@ func Routes() *web.Route {
Patch(bind(api.EditHookOption{}), user.EditHook).
Delete(user.DeleteHook)
}, reqWebhooksEnabled())

m.Group("/avatar", func() {
m.Post("", bind(api.UpdateUserAvatarOption{}), user.UpdateAvatar)
m.Delete("", user.DeleteAvatar)
}, reqToken())
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryUser), reqToken())

// Repositories (requires repo scope, org scope)
Expand Down Expand Up @@ -1134,6 +1139,10 @@ func Routes() *web.Route {
m.Get("/languages", reqRepoReader(unit.TypeCode), repo.GetLanguages)
m.Get("/activities/feeds", repo.ListRepoActivityFeeds)
m.Get("/new_pin_allowed", repo.AreNewIssuePinsAllowed)
m.Group("/avatar", func() {
m.Post("", bind(api.UpdateRepoAvatarOption{}), repo.UpdateAvatar)
m.Delete("", repo.DeleteAvatar)
}, reqAdmin(), reqToken())
}, repoAssignment())
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryRepository))

Expand Down Expand Up @@ -1314,6 +1323,10 @@ func Routes() *web.Route {
Patch(bind(api.EditHookOption{}), org.EditHook).
Delete(org.DeleteHook)
}, reqToken(), reqOrgOwnership(), reqWebhooksEnabled())
m.Group("/avatar", func() {
m.Post("", bind(api.UpdateUserAvatarOption{}), org.UpdateAvatar)
m.Delete("", org.DeleteAvatar)
}, reqToken(), reqOrgOwnership())
m.Get("/activities/feeds", org.ListOrgActivityFeeds)
}, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryOrganization), orgAssignment(true))
m.Group("/teams/{teamid}", func() {
Expand Down
84 changes: 84 additions & 0 deletions routers/api/v1/org/avatar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package org

import (
"encoding/base64"
"fmt"
"net/http"

"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/typesniffer"
"code.gitea.io/gitea/modules/web"
user_service "code.gitea.io/gitea/services/user"
)

// UpdateAvatarupdates the Avatar of an Organisation
func UpdateAvatar(ctx *context.APIContext) {
// swagger:operation POST /orgs/{org}/avatar organization orgUpdateAvatar
// ---
// summary: Update Avatar
// produces:
// - application/json
// parameters:
// - name: org
// in: path
// description: name of the organization
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/UpdateUserAvatarOption"
// responses:
// "204":
// "$ref": "#/responses/empty"
form := web.GetForm(ctx).(*api.UpdateUserAvatarOption)

content, err := base64.StdEncoding.DecodeString(form.Image)
if err != nil {
ctx.Error(http.StatusBadRequest, "DecodeImage", err)
return
}

if int64(len(content)) > setting.Avatar.MaxFileSize {
ctx.Error(http.StatusBadRequest, "AvatarTooBig", fmt.Errorf("The avatar is to big"))
return
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is also a height/width check (4000x4000 default). Can we maybe combine these checks so we don't have to duplicate them?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All "pre-check" code for uploaded avatar can be removed.

The UploadAvatar calls ProcessAvatarImage, which already handle type-check, size-limit, resizing, etc, correctly.


st := typesniffer.DetectContentType(content)
if !(st.IsImage() && !st.IsSvgImage()) {
Copy link
Member

@silverwind silverwind Jun 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we actually support SVG avatars on UI avatar upload, so it should not accept them here as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code was just copied from the Web UI

ctx.Error(http.StatusBadRequest, "NotAnImage", fmt.Errorf("The avatar is not an image"))
return
}

err = user_service.UploadAvatar(ctx.Org.Organization.AsUser(), content)
if err != nil {
ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
}

ctx.Status(http.StatusNoContent)
}

// DeleteAvatar deletes the Avatar of an Organisation
func DeleteAvatar(ctx *context.APIContext) {
// swagger:operation DELETE /orgs/{org}/avatar organization orgDeleteAvatar
// ---
// summary: Delete Avatar
// produces:
// - application/json
// parameters:
// - name: org
// in: path
// description: name of the organization
// responses:
// "204":
// "$ref": "#/responses/empty"
err := user_service.DeleteAvatar(ctx.Org.Organization.AsUser())
if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
}

ctx.Status(http.StatusNoContent)
}
98 changes: 98 additions & 0 deletions routers/api/v1/repo/avatar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package repo

import (
"encoding/base64"
"fmt"
"net/http"

"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/typesniffer"
"code.gitea.io/gitea/modules/web"
repo_service "code.gitea.io/gitea/services/repository"
)

// UpdateVatar updates the Avatar of an Repo
func UpdateAvatar(ctx *context.APIContext) {
// swagger:operation POST /repos/{owner}/{repo}/avatar repository repoUpdateAvatar
// ---
// summary: Update avatar
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repo
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repo
// type: string
// required: true
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/UpdateRepoAvatarOption"
// responses:
// "204":
// "$ref": "#/responses/empty"
form := web.GetForm(ctx).(*api.UpdateRepoAvatarOption)

content, err := base64.StdEncoding.DecodeString(form.Image)
if err != nil {
ctx.Error(http.StatusBadRequest, "DecodeImage", err)
return
}

if int64(len(content)) > setting.Avatar.MaxFileSize {
ctx.Error(http.StatusBadRequest, "AvatarTooBig", fmt.Errorf("The avatar is to big"))
return
}

st := typesniffer.DetectContentType(content)
if !(st.IsImage() && !st.IsSvgImage()) {
ctx.Error(http.StatusBadRequest, "NotAnImage", fmt.Errorf("The avatar is not an image"))
return
}

err = repo_service.UploadAvatar(ctx, ctx.Repo.Repository, content)
if err != nil {
ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
}

ctx.Status(http.StatusNoContent)
}

// UpdateAvatar deletes the Avatar of an Repo
func DeleteAvatar(ctx *context.APIContext) {
// swagger:operation DELETE /repos/{owner}/{repo}/avatar repository repoDeleteAvatar
// ---
// summary: Delete avatar
// produces:
// - application/json
// parameters:
// - name: owner
// in: path
// description: owner of the repo
// type: string
// required: true
// - name: repo
// in: path
// description: name of the repo
// type: string
// required: true
// responses:
// "204":
// "$ref": "#/responses/empty"
err := repo_service.DeleteAvatar(ctx, ctx.Repo.Repository)
if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
}

ctx.Status(http.StatusNoContent)
}
6 changes: 6 additions & 0 deletions routers/api/v1/swagger/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,4 +181,10 @@ type swaggerParameterBodies struct {

// in:body
CreatePushMirrorOption api.CreatePushMirrorOption

// in:body
UpdateUserAvatarOptions api.UpdateUserAvatarOption

// in:body
UpdateRepoAvatarOptions api.UpdateRepoAvatarOption
}
77 changes: 77 additions & 0 deletions routers/api/v1/user/avatar.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package user

import (
"encoding/base64"
"fmt"
"net/http"

"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/typesniffer"
"code.gitea.io/gitea/modules/web"
user_service "code.gitea.io/gitea/services/user"
)

// UpdateAvatar updates the Avatar of an User
func UpdateAvatar(ctx *context.APIContext) {
// swagger:operation POST /user/avatar user userUpdateAvatar
// ---
// summary: Update Avatar
// produces:
// - application/json
// parameters:
// - name: body
// in: body
// schema:
// "$ref": "#/definitions/UpdateUserAvatarOption"
// responses:
// "204":
// "$ref": "#/responses/empty"
form := web.GetForm(ctx).(*api.UpdateUserAvatarOption)

content, err := base64.StdEncoding.DecodeString(form.Image)
if err != nil {
ctx.Error(http.StatusBadRequest, "DecodeImage", err)
return
}

if int64(len(content)) > setting.Avatar.MaxFileSize {
ctx.Error(http.StatusBadRequest, "AvatarTooBig", fmt.Errorf("The avatar is to big"))
return
}

st := typesniffer.DetectContentType(content)
if !(st.IsImage() && !st.IsSvgImage()) {
ctx.Error(http.StatusBadRequest, "NotAnImage", fmt.Errorf("The avatar is not an image"))
return
}

err = user_service.UploadAvatar(ctx.Doer, content)
if err != nil {
ctx.Error(http.StatusInternalServerError, "UploadAvatar", err)
}

ctx.Status(http.StatusNoContent)
}

// DeleteAvatar deletes the Avatar of an User
func DeleteAvatar(ctx *context.APIContext) {
// swagger:operation DELETE /user/avatar user userDeleteAvatar
// ---
// summary: Delete Avatar
// produces:
// - application/json
// responses:
// "204":
// "$ref": "#/responses/empty"
err := user_service.DeleteAvatar(ctx.Doer)
if err != nil {
ctx.Error(http.StatusInternalServerError, "DeleteAvatar", err)
}

ctx.Status(http.StatusNoContent)
}
Loading