Skip to content

Commit

Permalink
Auto generate avatarURL when it's not avaliable
Browse files Browse the repository at this point in the history
  • Loading branch information
slhmy committed Jul 31, 2024
1 parent 39e856b commit 8910b52
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion models/user/user_db.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package user_model

import (
"crypto/md5"
"fmt"
"net/url"
"strings"

"github.com/alexedwards/argon2id"
Expand All @@ -11,6 +13,8 @@ import (
"gorm.io/gorm/clause"
)

const gravatarURLFormat = "https://www.gravatar.com/avatar/%x?d=identicon&s=512"

// Account, Password, Roles will be used to create a new user.
func CreateUser(tx *gorm.DB, request User) (*User, error) {
user := User{
Expand All @@ -21,6 +25,17 @@ func CreateUser(tx *gorm.DB, request User) (*User, error) {
AvatarURL: request.AvatarURL,
}

_, err := url.Parse(user.AvatarURL)
if err != nil || user.AvatarURL == "" {
if user.Email != nil {
md5sum := md5.Sum([]byte(*user.Email))
user.AvatarURL = fmt.Sprintf(gravatarURLFormat, md5sum)
} else {
md5sum := md5.Sum([]byte(user.Account))
user.AvatarURL = fmt.Sprintf(gravatarURLFormat, md5sum)
}
}

if request.Password != nil {
hashedPassword, err := argon2id.CreateHash(*request.Password, argon2id.DefaultParams)
if err != nil {
Expand All @@ -29,7 +44,7 @@ func CreateUser(tx *gorm.DB, request User) (*User, error) {
user.HashedPassword = hashedPassword
}

err := tx.Create(&user).Error
err = tx.Create(&user).Error
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 8910b52

Please sign in to comment.