Unify hashing for avatar (#22289)

- Unify the hashing code for repository and user avatars into a
function.
- Use a sane hash function instead of MD5.
- Only require hashing once instead of twice(w.r.t. hashing for user
avatar).
- Improve the comment for the hashing code of why it works.

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Yarden Shoham <hrsi88@gmail.com>
This commit is contained in:
Gusted 2023-01-02 22:46:39 +01:00 committed by GitHub
parent fcd6ceef2b
commit 96797fed31
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 11 deletions

View file

@ -5,7 +5,6 @@ package user
import (
"context"
"crypto/md5"
"fmt"
"image/png"
"io"
@ -241,11 +240,7 @@ func UploadAvatar(u *user_model.User, data []byte) error {
defer committer.Close()
u.UseCustomAvatar = true
// Different users can upload same image as avatar
// If we prefix it with u.ID, it will be separated
// Otherwise, if any of the users delete his avatar
// Other users will lose their avatars too.
u.Avatar = fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", u.ID, md5.Sum(data)))))
u.Avatar = avatar.HashAvatar(u.ID, data)
if err = user_model.UpdateUserCols(ctx, u, "use_custom_avatar", "avatar"); err != nil {
return fmt.Errorf("updateUser: %w", err)
}