1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- // Copyright 2022 The Gogs Authors. All rights reserved.
- // Use of this source code is governed by a MIT-style
- // license that can be found in the LICENSE file.
- package userutil
- import (
- "crypto/sha256"
- "crypto/subtle"
- "encoding/hex"
- "fmt"
- "image/png"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "github.com/pkg/errors"
- "golang.org/x/crypto/pbkdf2"
- "gogs.io/gogs/internal/avatar"
- "gogs.io/gogs/internal/conf"
- "gogs.io/gogs/internal/tool"
- )
- // DashboardURLPath returns the URL path to the user or organization dashboard.
- func DashboardURLPath(name string, isOrganization bool) string {
- if isOrganization {
- return conf.Server.Subpath + "/org/" + name + "/dashboard/"
- }
- return conf.Server.Subpath + "/"
- }
- // GenerateActivateCode generates an activate code based on user information and
- // the given email.
- func GenerateActivateCode(userID int64, email, name, password, rands string) string {
- code := tool.CreateTimeLimitCode(
- fmt.Sprintf("%d%s%s%s%s", userID, email, strings.ToLower(name), password, rands),
- conf.Auth.ActivateCodeLives,
- nil,
- )
- // Add tailing hex username
- code += hex.EncodeToString([]byte(strings.ToLower(name)))
- return code
- }
- // CustomAvatarPath returns the absolute path of the user custom avatar file.
- func CustomAvatarPath(userID int64) string {
- return filepath.Join(conf.Picture.AvatarUploadPath, strconv.FormatInt(userID, 10))
- }
- // GenerateRandomAvatar generates a random avatar and stores to local file
- // system using given user information.
- func GenerateRandomAvatar(userID int64, name, email string) error {
- seed := email
- if seed == "" {
- seed = name
- }
- img, err := avatar.RandomImage([]byte(seed))
- if err != nil {
- return errors.Wrap(err, "generate random image")
- }
- avatarPath := CustomAvatarPath(userID)
- err = os.MkdirAll(filepath.Dir(avatarPath), os.ModePerm)
- if err != nil {
- return errors.Wrap(err, "create avatar directory")
- }
- f, err := os.Create(avatarPath)
- if err != nil {
- return errors.Wrap(err, "create avatar file")
- }
- defer func() { _ = f.Close() }()
- if err = png.Encode(f, img); err != nil {
- return errors.Wrap(err, "encode avatar image to file")
- }
- return nil
- }
- // EncodePassword encodes password using PBKDF2 SHA256 with given salt.
- func EncodePassword(password, salt string) string {
- newPasswd := pbkdf2.Key([]byte(password), []byte(salt), 10000, 50, sha256.New)
- return fmt.Sprintf("%x", newPasswd)
- }
- // ValidatePassword returns true if the given password matches the encoded
- // version with given salt.
- func ValidatePassword(encoded, salt, password string) bool {
- got := EncodePassword(password, salt)
- return subtle.ConstantTimeCompare([]byte(encoded), []byte(got)) == 1
- }
|