repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/confirm_test.go | internal/ui/dialog/confirm_test.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"testing"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
"github.com/stretchr/testify/assert"
)
func TestConfirmDialog(t *testing.T) {
a := tview.NewApplication()
p := ui.NewPages()
a.SetRoot(p, false)
ShowConfirm(new(config.Dialog), p, "Blee", "Yo", func() {}, func() {})
d := p.GetPrimitive(dialogKey).(*tview.ModalForm)
assert.NotNil(t, d)
dismiss(p)
assert.Nil(t, p.GetPrimitive(dialogKey))
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/transfer.go | internal/ui/dialog/transfer.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"strconv"
"strings"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
)
const confirmKey = "confirm"
type TransferFn func(TransferArgs) bool
type TransferArgs struct {
From, To, CO string
Download, NoPreserve bool
Retries int
}
type TransferDialogOpts struct {
Containers []string
Pod string
Title, Message string
Retries int
Ack TransferFn
Cancel cancelFunc
}
func ShowUploads(styles *config.Dialog, pages *ui.Pages, opts *TransferDialogOpts) {
f := tview.NewForm()
f.SetItemPadding(0)
f.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(styles.FieldFgColor.Color())
f.AddButton("Cancel", func() {
dismissConfirm(pages)
opts.Cancel()
})
modal := tview.NewModalForm("<"+opts.Title+">", f)
args := TransferArgs{
From: opts.Pod,
Retries: opts.Retries,
}
var fromField, toField *tview.InputField
args.Download = true
f.AddCheckbox("Download:", args.Download, func(_ string, flag bool) {
if flag {
modal.SetText(strings.Replace(opts.Message, "Upload", "Download", 1))
} else {
modal.SetText(strings.Replace(opts.Message, "Download", "Upload", 1))
}
args.Download = flag
args.From, args.To = args.To, args.From
fromField.SetText(args.From)
toField.SetText(args.To)
})
f.AddInputField("From:", args.From, 40, nil, func(v string) {
args.From = v
})
f.AddInputField("To:", args.To, 40, nil, func(v string) {
args.To = v
})
fromField, _ = f.GetFormItemByLabel("From:").(*tview.InputField)
toField, _ = f.GetFormItemByLabel("To:").(*tview.InputField)
f.AddCheckbox("NoPreserve:", args.NoPreserve, func(_ string, f bool) {
args.NoPreserve = f
})
if len(opts.Containers) > 0 {
args.CO = opts.Containers[0]
}
f.AddInputField("Container:", args.CO, 30, nil, func(v string) {
args.CO = v
})
retries := strconv.Itoa(opts.Retries)
f.AddInputField("Retries:", retries, 30, nil, func(v string) {
retries = v
if retriesInt, err := strconv.Atoi(retries); err == nil {
args.Retries = retriesInt
}
})
f.AddButton("OK", func() {
if !opts.Ack(args) {
return
}
dismissConfirm(pages)
opts.Cancel()
})
for i := range 2 {
b := f.GetButton(i)
if b == nil {
continue
}
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
f.SetFocus(0)
message := opts.Message
if len(opts.Containers) > 1 {
message += "\nAvailable Containers:" + strings.Join(opts.Containers, ",")
}
modal.SetText(message)
modal.SetTextColor(styles.FgColor.Color())
modal.SetDoneFunc(func(int, string) {
dismissConfirm(pages)
opts.Cancel()
})
pages.AddPage(confirmKey, modal, false, false)
pages.ShowPage(confirmKey)
}
func dismissConfirm(pages *ui.Pages) {
pages.RemovePage(confirmKey)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/confirm.go | internal/ui/dialog/confirm.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
)
const dialogKey = "dialog"
type confirmFunc func()
func ShowConfirmAck(app *ui.App, pages *ui.Pages, acceptStr string, override bool, title, msg string, ack confirmFunc, cancel cancelFunc) {
styles := app.Styles.Dialog()
f := tview.NewForm()
f.SetItemPadding(0)
f.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(styles.FieldFgColor.Color())
f.AddButton("Cancel", func() {
dismissConfirm(pages)
cancel()
})
var accept bool
if override {
changedFn := func(t string) {
accept = (t == acceptStr)
}
f.AddInputField("Confirm:", "", 30, nil, changedFn)
} else {
accept = true
}
f.AddButton("OK", func() {
if !accept {
return
}
ack()
dismissConfirm(pages)
cancel()
})
for i := range 2 {
b := f.GetButton(i)
if b == nil {
continue
}
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
f.SetFocus(0)
modal := tview.NewModalForm("<"+title+">", f)
modal.SetText(msg)
modal.SetTextColor(styles.FgColor.Color())
modal.SetDoneFunc(func(int, string) {
dismissConfirm(pages)
cancel()
})
pages.AddPage(confirmKey, modal, false, false)
pages.ShowPage(confirmKey)
}
// ShowConfirm pops a confirmation dialog.
func ShowConfirm(styles *config.Dialog, pages *ui.Pages, title, msg string, ack confirmFunc, cancel cancelFunc) {
f := tview.NewForm().
SetItemPadding(0).
SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(styles.FieldFgColor.Color()).
SetFieldBackgroundColor(styles.BgColor.Color())
f.AddButton("Cancel", func() {
dismiss(pages)
cancel()
})
f.AddButton("OK", func() {
ack()
dismiss(pages)
cancel()
})
for i := range 2 {
if b := f.GetButton(i); b != nil {
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
}
f.SetFocus(0)
modal := tview.NewModalForm("<"+title+">", f)
modal.SetText(msg)
modal.SetTextColor(styles.FgColor.Color())
modal.SetDoneFunc(func(int, string) {
dismiss(pages)
cancel()
})
pages.AddPage(dialogKey, modal, false, false)
pages.ShowPage(dialogKey)
}
func dismiss(pages *ui.Pages) {
pages.RemovePage(dialogKey)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/selection.go | internal/ui/dialog/selection.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
)
type SelectAction func(index int)
func ShowSelection(styles *config.Dialog, pages *ui.Pages, title string, options []string, action SelectAction) {
list := tview.NewList()
list.ShowSecondaryText(false)
list.SetSelectedTextColor(styles.ButtonFocusFgColor.Color())
list.SetSelectedBackgroundColor(styles.ButtonFocusBgColor.Color())
for _, option := range options {
list.AddItem(option, "", 0, nil)
list.AddItem(option, "", 0, nil)
}
modal := ui.NewModalList("<"+title+">", list)
modal.SetDoneFunc(func(i int, _ string) {
dismiss(pages)
action(i)
})
pages.AddPage(dialogKey, modal, false, false)
pages.ShowPage(dialogKey)
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
derailed/k9s | https://github.com/derailed/k9s/blob/3784c12ae74593e8aca597c3c347e8714ad3d6b7/internal/ui/dialog/prompt.go | internal/ui/dialog/prompt.go | // SPDX-License-Identifier: Apache-2.0
// Copyright Authors of K9s
package dialog
import (
"context"
"github.com/derailed/k9s/internal/config"
"github.com/derailed/k9s/internal/ui"
"github.com/derailed/tview"
)
type promptAction func(ctx context.Context)
// ShowPrompt pops a prompt dialog.
func ShowPrompt(styles *config.Dialog, pages *ui.Pages, title, msg string, action promptAction, cancel cancelFunc) {
f := tview.NewForm()
f.SetItemPadding(0)
f.SetButtonsAlign(tview.AlignCenter).
SetButtonBackgroundColor(styles.ButtonBgColor.Color()).
SetButtonTextColor(styles.ButtonFgColor.Color()).
SetLabelColor(styles.LabelFgColor.Color()).
SetFieldTextColor(styles.FieldFgColor.Color())
ctx, cancelCtx := context.WithCancel(context.Background())
f.AddButton("Cancel", func() {
dismiss(pages)
cancelCtx()
cancel()
})
for i := range f.GetButtonCount() {
b := f.GetButton(i)
if b == nil {
continue
}
b.SetBackgroundColorActivated(styles.ButtonFocusBgColor.Color())
b.SetLabelColorActivated(styles.ButtonFocusFgColor.Color())
}
f.SetFocus(0)
modal := tview.NewModalForm("<"+title+">", f)
modal.SetText(msg)
modal.SetTextColor(styles.FgColor.Color())
modal.SetDoneFunc(func(int, string) {
dismiss(pages)
cancelCtx()
cancel()
})
pages.AddPage(dialogKey, modal, false, false)
pages.ShowPage(dialogKey)
go func() {
action(ctx)
dismiss(pages)
}()
}
| go | Apache-2.0 | 3784c12ae74593e8aca597c3c347e8714ad3d6b7 | 2026-01-07T08:36:21.587988Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/experimental.go | experimental.go | package viper
// ExperimentalBindStruct tells Viper to use the new bind struct feature.
func ExperimentalBindStruct() Option {
return optionFunc(func(v *Viper) {
v.experimentalBindStruct = true
})
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/flags.go | flags.go | package viper
import "github.com/spf13/pflag"
// FlagValueSet is an interface that users can implement
// to bind a set of flags to viper.
type FlagValueSet interface {
VisitAll(fn func(FlagValue))
}
// FlagValue is an interface that users can implement
// to bind different flags to viper.
type FlagValue interface {
HasChanged() bool
Name() string
ValueString() string
ValueType() string
}
// pflagValueSet is a wrapper around *pflag.ValueSet
// that implements FlagValueSet.
type pflagValueSet struct {
flags *pflag.FlagSet
}
// VisitAll iterates over all *pflag.Flag inside the *pflag.FlagSet.
func (p pflagValueSet) VisitAll(fn func(flag FlagValue)) {
p.flags.VisitAll(func(flag *pflag.Flag) {
fn(pflagValue{flag})
})
}
// pflagValue is a wrapper around *pflag.flag
// that implements FlagValue.
type pflagValue struct {
flag *pflag.Flag
}
// HasChanged returns whether the flag has changes or not.
func (p pflagValue) HasChanged() bool {
return p.flag.Changed
}
// Name returns the name of the flag.
func (p pflagValue) Name() string {
return p.flag.Name
}
// ValueString returns the value of the flag as a string.
func (p pflagValue) ValueString() string {
return p.flag.Value.String()
}
// ValueType returns the type of the flag as a string.
func (p pflagValue) ValueType() string {
return p.flag.Value.Type()
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/finder.go | finder.go | package viper
import (
"errors"
"github.com/spf13/afero"
)
// WithFinder sets a custom [Finder].
func WithFinder(f Finder) Option {
return optionFunc(func(v *Viper) {
if f == nil {
return
}
v.finder = f
})
}
// Finder looks for files and directories in an [afero.Fs] filesystem.
type Finder interface {
Find(fsys afero.Fs) ([]string, error)
}
// Finders combines multiple finders into one.
func Finders(finders ...Finder) Finder {
return &combinedFinder{finders: finders}
}
// combinedFinder is a Finder that combines multiple finders.
type combinedFinder struct {
finders []Finder
}
// Find implements the [Finder] interface.
func (c *combinedFinder) Find(fsys afero.Fs) ([]string, error) {
var results []string
var errs []error
for _, finder := range c.finders {
if finder == nil {
continue
}
r, err := finder.Find(fsys)
if err != nil {
errs = append(errs, err)
continue
}
results = append(results, r...)
}
return results, errors.Join(errs...)
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/file.go | file.go | package viper
import (
"os"
"path/filepath"
"github.com/sagikazarmark/locafero"
"github.com/spf13/afero"
)
// ExperimentalFinder tells Viper to use the new Finder interface for finding configuration files.
func ExperimentalFinder() Option {
return optionFunc(func(v *Viper) {
v.experimentalFinder = true
})
}
// Search for a config file.
func (v *Viper) findConfigFile() (string, error) {
finder := v.finder
if finder == nil && v.experimentalFinder {
var names []string
if v.configType != "" {
names = locafero.NameWithOptionalExtensions(v.configName, SupportedExts...)
} else {
names = locafero.NameWithExtensions(v.configName, SupportedExts...)
}
finder = locafero.Finder{
Paths: v.configPaths,
Names: names,
Type: locafero.FileTypeFile,
}
}
if finder != nil {
return v.findConfigFileWithFinder(finder)
}
return v.findConfigFileOld()
}
func (v *Viper) findConfigFileWithFinder(finder Finder) (string, error) {
results, err := finder.Find(v.fs)
if err != nil {
return "", err
}
if len(results) == 0 {
return "", ConfigFileNotFoundError{name: v.configName, locations: v.configPaths}
}
// We call clean on the final result to ensure that the path is in its canonical form.
// This is mostly for consistent path handling and to make sure tests pass.
return results[0], nil
}
// Search all configPaths for any config file.
// Returns the first path that exists (and is a config file).
func (v *Viper) findConfigFileOld() (string, error) {
v.logger.Info("searching for config in paths", "paths", v.configPaths)
for _, cp := range v.configPaths {
file := v.searchInPath(cp)
if file != "" {
return file, nil
}
}
return "", ConfigFileNotFoundError{name: v.configName, locations: v.configPaths}
}
func (v *Viper) searchInPath(in string) (filename string) {
v.logger.Debug("searching for config in path", "path", in)
for _, ext := range SupportedExts {
v.logger.Debug("checking if file exists", "file", filepath.Join(in, v.configName+"."+ext))
if b, _ := exists(v.fs, filepath.Join(in, v.configName+"."+ext)); b {
v.logger.Debug("found file", "file", filepath.Join(in, v.configName+"."+ext))
return filepath.Join(in, v.configName+"."+ext)
}
}
if v.configType != "" {
if b, _ := exists(v.fs, filepath.Join(in, v.configName)); b {
return filepath.Join(in, v.configName)
}
}
return ""
}
// exists checks if file exists.
func exists(fs afero.Fs, path string) (bool, error) {
stat, err := fs.Stat(path)
if err == nil {
return !stat.IsDir(), nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/remote.go | remote.go | package viper
import (
"bytes"
"fmt"
"io"
"reflect"
"slices"
)
// SupportedRemoteProviders are universally supported remote providers.
var SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore", "nats"}
func resetRemote() {
SupportedRemoteProviders = []string{"etcd", "etcd3", "consul", "firestore", "nats"}
}
type remoteConfigFactory interface {
Get(rp RemoteProvider) (io.Reader, error)
Watch(rp RemoteProvider) (io.Reader, error)
WatchChannel(rp RemoteProvider) (<-chan *RemoteResponse, chan bool)
}
// RemoteResponse represents a response from a remote configuration provider.
type RemoteResponse struct {
Value []byte
Error error
}
// RemoteConfig is optional, see the remote package.
var RemoteConfig remoteConfigFactory
// UnsupportedRemoteProviderError denotes encountering an unsupported remote
// provider. Currently only etcd and Consul are supported.
type UnsupportedRemoteProviderError string
// Error returns the formatted remote provider error.
func (str UnsupportedRemoteProviderError) Error() string {
return fmt.Sprintf("Unsupported Remote Provider Type %q", string(str))
}
// RemoteConfigError denotes encountering an error while trying to
// pull the configuration from the remote provider.
type RemoteConfigError string
// Error returns the formatted remote provider error.
func (rce RemoteConfigError) Error() string {
return fmt.Sprintf("Remote Configurations Error: %s", string(rce))
}
type defaultRemoteProvider struct {
provider string
endpoint string
path string
secretKeyring string
}
func (rp defaultRemoteProvider) Provider() string {
return rp.provider
}
func (rp defaultRemoteProvider) Endpoint() string {
return rp.endpoint
}
func (rp defaultRemoteProvider) Path() string {
return rp.path
}
func (rp defaultRemoteProvider) SecretKeyring() string {
return rp.secretKeyring
}
// RemoteProvider stores the configuration necessary
// to connect to a remote key/value store.
// Optional secretKeyring to unencrypt encrypted values
// can be provided.
type RemoteProvider interface {
Provider() string
Endpoint() string
Path() string
SecretKeyring() string
}
// AddRemoteProvider adds a remote configuration source.
// Remote Providers are searched in the order they are added.
// provider is a string value: "etcd", "etcd3", "consul", "firestore" or "nats" are currently supported.
// endpoint is the url. etcd requires http://ip:port, consul requires ip:port, nats requires nats://ip:port
// path is the path in the k/v store to retrieve configuration
// To retrieve a config file called myapp.json from /configs/myapp.json
// you should set path to /configs and set config name (SetConfigName()) to
// "myapp".
func AddRemoteProvider(provider, endpoint, path string) error {
return v.AddRemoteProvider(provider, endpoint, path)
}
// AddRemoteProvider adds a remote configuration source.
// Remote Providers are searched in the order they are added.
// provider is a string value: "etcd", "etcd3", "consul", "firestore" or "nats" are currently supported.
// endpoint is the url. etcd requires http://ip:port, consul requires ip:port, nats requires nats://ip:port
// path is the path in the k/v store to retrieve configuration
// To retrieve a config file called myapp.json from /configs/myapp.json
// you should set path to /configs and set config name (SetConfigName()) to
// "myapp".
func (v *Viper) AddRemoteProvider(provider, endpoint, path string) error {
if !slices.Contains(SupportedRemoteProviders, provider) {
return UnsupportedRemoteProviderError(provider)
}
if provider != "" && endpoint != "" {
v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
rp := &defaultRemoteProvider{
endpoint: endpoint,
provider: provider,
path: path,
}
if !v.providerPathExists(rp) {
v.remoteProviders = append(v.remoteProviders, rp)
}
}
return nil
}
// AddSecureRemoteProvider adds a remote configuration source.
// Secure Remote Providers are searched in the order they are added.
// provider is a string value: "etcd", "etcd3", "consul", "firestore" or "nats" are currently supported.
// endpoint is the url. etcd requires http://ip:port consul requires ip:port
// secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg
// path is the path in the k/v store to retrieve configuration
// To retrieve a config file called myapp.json from /configs/myapp.json
// you should set path to /configs and set config name (SetConfigName()) to
// "myapp".
// Secure Remote Providers are implemented with github.com/sagikazarmark/crypt.
func AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
return v.AddSecureRemoteProvider(provider, endpoint, path, secretkeyring)
}
// AddSecureRemoteProvider adds a remote configuration source.
// Secure Remote Providers are searched in the order they are added.
// provider is a string value: "etcd", "etcd3", "consul", "firestore" or "nats" are currently supported.
// endpoint is the url. etcd requires http://ip:port consul requires ip:port
// secretkeyring is the filepath to your openpgp secret keyring. e.g. /etc/secrets/myring.gpg
// path is the path in the k/v store to retrieve configuration
// To retrieve a config file called myapp.json from /configs/myapp.json
// you should set path to /configs and set config name (SetConfigName()) to
// "myapp".
// Secure Remote Providers are implemented with github.com/sagikazarmark/crypt.
func (v *Viper) AddSecureRemoteProvider(provider, endpoint, path, secretkeyring string) error {
if !slices.Contains(SupportedRemoteProviders, provider) {
return UnsupportedRemoteProviderError(provider)
}
if provider != "" && endpoint != "" {
v.logger.Info("adding remote provider", "provider", provider, "endpoint", endpoint)
rp := &defaultRemoteProvider{
endpoint: endpoint,
provider: provider,
path: path,
secretKeyring: secretkeyring,
}
if !v.providerPathExists(rp) {
v.remoteProviders = append(v.remoteProviders, rp)
}
}
return nil
}
func (v *Viper) providerPathExists(p *defaultRemoteProvider) bool {
for _, y := range v.remoteProviders {
if reflect.DeepEqual(y, p) {
return true
}
}
return false
}
// ReadRemoteConfig attempts to get configuration from a remote source
// and read it in the remote configuration registry.
func ReadRemoteConfig() error { return v.ReadRemoteConfig() }
// ReadRemoteConfig attempts to get configuration from a remote source
// and read it in the remote configuration registry.
func (v *Viper) ReadRemoteConfig() error {
return v.getKeyValueConfig()
}
// WatchRemoteConfig updates configuration from available remote providers.
func WatchRemoteConfig() error { return v.WatchRemoteConfig() }
// WatchRemoteConfig updates configuration from available remote providers.
func (v *Viper) WatchRemoteConfig() error {
return v.watchKeyValueConfig()
}
// WatchRemoteConfigOnChannel updates configuration from available remote providers.
func (v *Viper) WatchRemoteConfigOnChannel() error {
return v.watchKeyValueConfigOnChannel()
}
// Retrieve the first found remote configuration.
func (v *Viper) getKeyValueConfig() error {
if RemoteConfig == nil {
return RemoteConfigError("Enable the remote features by doing a blank import of the viper/remote package: '_ github.com/spf13/viper/remote'")
}
if len(v.remoteProviders) == 0 {
return RemoteConfigError("No Remote Providers")
}
for _, rp := range v.remoteProviders {
val, err := v.getRemoteConfig(rp)
if err != nil {
v.logger.Error(fmt.Errorf("get remote config: %w", err).Error())
continue
}
v.kvstore = val
return nil
}
return RemoteConfigError("No Files Found")
}
func (v *Viper) getRemoteConfig(provider RemoteProvider) (map[string]any, error) {
reader, err := RemoteConfig.Get(provider)
if err != nil {
return nil, err
}
err = v.unmarshalReader(reader, v.kvstore)
return v.kvstore, err
}
// Retrieve the first found remote configuration.
func (v *Viper) watchKeyValueConfigOnChannel() error {
if len(v.remoteProviders) == 0 {
return RemoteConfigError("No Remote Providers")
}
for _, rp := range v.remoteProviders {
respc, _ := RemoteConfig.WatchChannel(rp)
// Todo: Add quit channel
go func(rc <-chan *RemoteResponse) {
for {
b := <-rc
reader := bytes.NewReader(b.Value)
err := v.unmarshalReader(reader, v.kvstore)
if err != nil {
v.logger.Error(fmt.Errorf("failed to unmarshal remote config: %w", err).Error())
}
}
}(respc)
return nil
}
return RemoteConfigError("No Files Found")
}
// Retrieve the first found remote configuration.
func (v *Viper) watchKeyValueConfig() error {
if len(v.remoteProviders) == 0 {
return RemoteConfigError("No Remote Providers")
}
for _, rp := range v.remoteProviders {
val, err := v.watchRemoteConfig(rp)
if err != nil {
v.logger.Error(fmt.Errorf("watch remote config: %w", err).Error())
continue
}
v.kvstore = val
return nil
}
return RemoteConfigError("No Files Found")
}
func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]any, error) {
reader, err := RemoteConfig.Watch(provider)
if err != nil {
return nil, err
}
err = v.unmarshalReader(reader, v.kvstore)
return v.kvstore, err
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/finder_test.go | finder_test.go | package viper
import (
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type finderStub struct {
results []string
}
func (f finderStub) Find(_ afero.Fs) ([]string, error) {
return f.results, nil
}
func TestFinders(t *testing.T) {
finder := Finders(
finderStub{
results: []string{
"/home/user/.viper.yaml",
},
},
finderStub{
results: []string{
"/etc/viper/config.yaml",
},
},
)
results, err := finder.Find(afero.NewMemMapFs())
require.NoError(t, err)
expected := []string{
"/home/user/.viper.yaml",
"/etc/viper/config.yaml",
}
assert.Equal(t, expected, results)
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/viper.go | viper.go | // Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Viper is an application configuration system.
// It believes that applications can be configured a variety of ways
// via flags, ENVIRONMENT variables, configuration files retrieved
// from the file system, or a remote key/value store.
// Each item takes precedence over the item below it:
// overrides
// flag
// env
// config
// key/value store
// default
package viper
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"io"
fs "io/fs"
"log/slog"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/go-viper/mapstructure/v2"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/spf13/pflag"
"github.com/spf13/viper/internal/features"
)
var v *Viper
func init() {
v = New()
}
// A DecoderConfigOption can be passed to viper.Unmarshal to configure
// mapstructure.DecoderConfig options.
type DecoderConfigOption func(*mapstructure.DecoderConfig)
// DecodeHook returns a DecoderConfigOption which overrides the default
// DecoderConfig.DecodeHook value, the default is:
//
// mapstructure.ComposeDecodeHookFunc(
// mapstructure.StringToTimeDurationHookFunc(),
// mapstructure.StringToSliceHookFunc(","),
// )
func DecodeHook(hook mapstructure.DecodeHookFunc) DecoderConfigOption {
return func(c *mapstructure.DecoderConfig) {
c.DecodeHook = hook
}
}
// Viper is a prioritized configuration registry. It
// maintains a set of configuration sources, fetches
// values to populate those, and provides them according
// to the source's priority.
// The priority of the sources is the following:
// 1. overrides
// 2. flags
// 3. env. variables
// 4. config file
// 5. key/value store
// 6. defaults
//
// For example, if values from the following sources were loaded:
//
// Defaults : {
// "secret": "",
// "user": "default",
// "endpoint": "https://localhost"
// }
// Config : {
// "user": "root"
// "secret": "defaultsecret"
// }
// Env : {
// "secret": "somesecretkey"
// }
//
// The resulting config will have the following values:
//
// {
// "secret": "somesecretkey",
// "user": "root",
// "endpoint": "https://localhost"
// }
//
// Note: Vipers are not safe for concurrent Get() and Set() operations.
type Viper struct {
// Delimiter that separates a list of keys
// used to access a nested value in one go
keyDelim string
// A set of paths to look for the config file in
configPaths []string
// The filesystem to read config from.
fs afero.Fs
finder Finder
// A set of remote providers to search for the configuration
remoteProviders []*defaultRemoteProvider
// Name of file to look for inside the path
configName string
configFile string
configType string
configPermissions os.FileMode
envPrefix string
automaticEnvApplied bool
envKeyReplacer StringReplacer
allowEmptyEnv bool
parents []string
config map[string]any
override map[string]any
defaults map[string]any
kvstore map[string]any
pflags map[string]FlagValue
env map[string][]string
aliases map[string]string
typeByDefValue bool
onConfigChange func(fsnotify.Event)
logger *slog.Logger
encoderRegistry EncoderRegistry
decoderRegistry DecoderRegistry
decodeHook mapstructure.DecodeHookFunc
experimentalFinder bool
experimentalBindStruct bool
}
// New returns an initialized Viper instance.
func New() *Viper {
v := new(Viper)
v.keyDelim = "."
v.configName = "config"
v.configPermissions = os.FileMode(0o644)
v.fs = afero.NewOsFs()
v.config = make(map[string]any)
v.parents = []string{}
v.override = make(map[string]any)
v.defaults = make(map[string]any)
v.kvstore = make(map[string]any)
v.pflags = make(map[string]FlagValue)
v.env = make(map[string][]string)
v.aliases = make(map[string]string)
v.typeByDefValue = false
v.logger = slog.New(&discardHandler{})
codecRegistry := NewCodecRegistry()
v.encoderRegistry = codecRegistry
v.decoderRegistry = codecRegistry
v.experimentalFinder = features.Finder
v.experimentalBindStruct = features.BindStruct
return v
}
// Option configures Viper using the functional options paradigm popularized by Rob Pike and Dave Cheney.
// If you're unfamiliar with this style,
// see https://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html and
// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis.
type Option interface {
apply(v *Viper)
}
type optionFunc func(v *Viper)
func (fn optionFunc) apply(v *Viper) {
fn(v)
}
// KeyDelimiter sets the delimiter used for determining key parts.
// By default it's value is ".".
func KeyDelimiter(d string) Option {
return optionFunc(func(v *Viper) {
v.keyDelim = d
})
}
// StringReplacer applies a set of replacements to a string.
type StringReplacer interface {
// Replace returns a copy of s with all replacements performed.
Replace(s string) string
}
// EnvKeyReplacer sets a replacer used for mapping environment variables to internal keys.
func EnvKeyReplacer(r StringReplacer) Option {
return optionFunc(func(v *Viper) {
if r == nil {
return
}
v.envKeyReplacer = r
})
}
// WithDecodeHook sets a default decode hook for mapstructure.
func WithDecodeHook(h mapstructure.DecodeHookFunc) Option {
return optionFunc(func(v *Viper) {
if h == nil {
return
}
v.decodeHook = h
})
}
// NewWithOptions creates a new Viper instance.
func NewWithOptions(opts ...Option) *Viper {
v := New()
for _, opt := range opts {
opt.apply(v)
}
return v
}
// SetOptions sets the options on the global Viper instance.
//
// Be careful when using this function: subsequent calls may override options you set.
// It's always better to use a local Viper instance.
func SetOptions(opts ...Option) {
for _, opt := range opts {
opt.apply(v)
}
}
// Reset is intended for testing, will reset all to default settings.
// In the public interface for the viper package so applications
// can use it in their testing as well.
func Reset() {
v = New()
SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
resetRemote()
}
// SupportedExts are universally supported extensions.
var SupportedExts = []string{"json", "toml", "yaml", "yml", "properties", "props", "prop", "hcl", "tfvars", "dotenv", "env", "ini"}
// OnConfigChange sets the event handler that is called when a config file changes.
func OnConfigChange(run func(in fsnotify.Event)) { v.OnConfigChange(run) }
// OnConfigChange sets the event handler that is called when a config file changes.
func (v *Viper) OnConfigChange(run func(in fsnotify.Event)) {
v.onConfigChange = run
}
// WatchConfig starts watching a config file for changes.
func WatchConfig() { v.WatchConfig() }
// WatchConfig starts watching a config file for changes.
func (v *Viper) WatchConfig() {
initWG := sync.WaitGroup{}
initWG.Add(1)
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
v.logger.Error(fmt.Sprintf("failed to create watcher: %s", err))
os.Exit(1)
}
defer watcher.Close()
// we have to watch the entire directory to pick up renames/atomic saves in a cross-platform way
filename, err := v.getConfigFile()
if err != nil {
v.logger.Error(fmt.Sprintf("get config file: %s", err))
initWG.Done()
return
}
configFile := filepath.Clean(filename)
configDir, _ := filepath.Split(configFile)
realConfigFile, _ := filepath.EvalSymlinks(filename)
eventsWG := sync.WaitGroup{}
eventsWG.Add(1)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok { // 'Events' channel is closed
eventsWG.Done()
return
}
currentConfigFile, _ := filepath.EvalSymlinks(filename)
// we only care about the config file with the following cases:
// 1 - if the config file was modified or created
// 2 - if the real path to the config file changed (eg: k8s ConfigMap replacement)
if (filepath.Clean(event.Name) == configFile &&
(event.Has(fsnotify.Write) || event.Has(fsnotify.Create))) ||
(currentConfigFile != "" && currentConfigFile != realConfigFile) {
realConfigFile = currentConfigFile
err := v.ReadInConfig()
if err != nil {
v.logger.Error(fmt.Sprintf("read config file: %s", err))
}
if v.onConfigChange != nil {
v.onConfigChange(event)
}
} else if filepath.Clean(event.Name) == configFile && event.Has(fsnotify.Remove) {
eventsWG.Done()
return
}
case err, ok := <-watcher.Errors:
if ok { // 'Errors' channel is not closed
v.logger.Error(fmt.Sprintf("watcher error: %s", err))
}
eventsWG.Done()
return
}
}
}()
err = watcher.Add(configDir)
if err != nil {
v.logger.Error(fmt.Sprintf("failed to add watcher: %s", err))
initWG.Done()
return
}
initWG.Done() // done initializing the watch in this go routine, so the parent routine can move on...
eventsWG.Wait() // now, wait for event loop to end in this go-routine...
}()
initWG.Wait() // make sure that the go routine above fully ended before returning
}
// SetConfigFile explicitly defines the path, name and extension of the config file.
// Viper will use this and not check any of the config paths.
func SetConfigFile(in string) { v.SetConfigFile(in) }
// SetConfigFile explicitly defines the path, name and extension of the config file.
// Viper will use this and not check any of the config paths.
func (v *Viper) SetConfigFile(in string) {
if in != "" {
v.configFile = in
}
}
// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
// E.g. if your prefix is "spf", the env registry will look for env
// variables that start with "SPF_".
func SetEnvPrefix(in string) { v.SetEnvPrefix(in) }
// SetEnvPrefix defines a prefix that ENVIRONMENT variables will use.
// E.g. if your prefix is "spf", the env registry will look for env
// variables that start with "SPF_".
func (v *Viper) SetEnvPrefix(in string) {
if in != "" {
v.envPrefix = in
}
}
// GetEnvPrefix returns the environment variable prefix.
func GetEnvPrefix() string { return v.GetEnvPrefix() }
// GetEnvPrefix returns the environment variable prefix.
func (v *Viper) GetEnvPrefix() string {
return v.envPrefix
}
func (v *Viper) mergeWithEnvPrefix(in string) string {
if v.envPrefix != "" {
return strings.ToUpper(v.envPrefix + "_" + in)
}
return strings.ToUpper(in)
}
// AllowEmptyEnv tells Viper to consider set,
// but empty environment variables as valid values instead of falling back.
// For backward compatibility reasons this is false by default.
func AllowEmptyEnv(allowEmptyEnv bool) { v.AllowEmptyEnv(allowEmptyEnv) }
// AllowEmptyEnv tells Viper to consider set,
// but empty environment variables as valid values instead of falling back.
// For backward compatibility reasons this is false by default.
func (v *Viper) AllowEmptyEnv(allowEmptyEnv bool) {
v.allowEmptyEnv = allowEmptyEnv
}
// TODO: should getEnv logic be moved into find(). Can generalize the use of
// rewriting keys many things, Ex: Get('someKey') -> some_key
// (camel case to snake case for JSON keys perhaps)
// getEnv is a wrapper around os.Getenv which replaces characters in the original
// key. This allows env vars which have different keys than the config object
// keys.
func (v *Viper) getEnv(key string) (string, bool) {
if v.envKeyReplacer != nil {
key = v.envKeyReplacer.Replace(key)
}
val, ok := os.LookupEnv(key)
return val, ok && (v.allowEmptyEnv || val != "")
}
// ConfigFileUsed returns the file used to populate the config registry.
func ConfigFileUsed() string { return v.ConfigFileUsed() }
// ConfigFileUsed returns the file used to populate the config registry.
func (v *Viper) ConfigFileUsed() string { return v.configFile }
// AddConfigPath adds a path for Viper to search for the config file in.
// Can be called multiple times to define multiple search paths.
func AddConfigPath(in string) { v.AddConfigPath(in) }
// AddConfigPath adds a path for Viper to search for the config file in.
// Can be called multiple times to define multiple search paths.
func (v *Viper) AddConfigPath(in string) {
if v.finder != nil {
v.logger.Warn("ineffective call to function: custom finder takes precedence", slog.String("function", "AddConfigPath"))
}
if in != "" {
absin := absPathify(v.logger, in)
v.logger.Info("adding path to search paths", "path", absin)
if !slices.Contains(v.configPaths, absin) {
v.configPaths = append(v.configPaths, absin)
}
}
}
// searchMap recursively searches for a value for path in source map.
// Returns nil if not found.
// Note: This assumes that the path entries and map keys are lower cased.
func (v *Viper) searchMap(source map[string]any, path []string) any {
if len(path) == 0 {
return source
}
next, ok := source[path[0]]
if ok {
// Fast path
if len(path) == 1 {
return next
}
// Nested case
switch next := next.(type) {
case map[any]any:
return v.searchMap(cast.ToStringMap(next), path[1:])
case map[string]any:
// Type assertion is safe here since it is only reached
// if the type of `next` is the same as the type being asserted
return v.searchMap(next, path[1:])
default:
// got a value but nested key expected, return "nil" for not found
return nil
}
}
return nil
}
// searchIndexableWithPathPrefixes recursively searches for a value for path in source map/slice.
//
// While searchMap() considers each path element as a single map key or slice index, this
// function searches for, and prioritizes, merged path elements.
// e.g., if in the source, "foo" is defined with a sub-key "bar", and "foo.bar"
// is also defined, this latter value is returned for path ["foo", "bar"].
//
// This should be useful only at config level (other maps may not contain dots
// in their keys).
//
// Note: This assumes that the path entries and map keys are lower cased.
func (v *Viper) searchIndexableWithPathPrefixes(source any, path []string) any {
if len(path) == 0 {
return source
}
// search for path prefixes, starting from the longest one
for i := len(path); i > 0; i-- {
prefixKey := strings.ToLower(strings.Join(path[0:i], v.keyDelim))
var val any
switch sourceIndexable := source.(type) {
case []any:
val = v.searchSliceWithPathPrefixes(sourceIndexable, prefixKey, i, path)
case map[string]any:
val = v.searchMapWithPathPrefixes(sourceIndexable, prefixKey, i, path)
}
if val != nil {
return val
}
}
// not found
return nil
}
// searchSliceWithPathPrefixes searches for a value for path in sourceSlice
//
// This function is part of the searchIndexableWithPathPrefixes recurring search and
// should not be called directly from functions other than searchIndexableWithPathPrefixes.
func (v *Viper) searchSliceWithPathPrefixes(
sourceSlice []any,
prefixKey string,
pathIndex int,
path []string,
) any {
// if the prefixKey is not a number or it is out of bounds of the slice
index, err := strconv.Atoi(prefixKey)
if err != nil || len(sourceSlice) <= index {
return nil
}
next := sourceSlice[index]
// Fast path
if pathIndex == len(path) {
return next
}
switch n := next.(type) {
case map[any]any:
return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
case map[string]any, []any:
return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
default:
// got a value but nested key expected, do nothing and look for next prefix
}
// not found
return nil
}
// searchMapWithPathPrefixes searches for a value for path in sourceMap
//
// This function is part of the searchIndexableWithPathPrefixes recurring search and
// should not be called directly from functions other than searchIndexableWithPathPrefixes.
func (v *Viper) searchMapWithPathPrefixes(
sourceMap map[string]any,
prefixKey string,
pathIndex int,
path []string,
) any {
next, ok := sourceMap[prefixKey]
if !ok {
return nil
}
// Fast path
if pathIndex == len(path) {
return next
}
// Nested case
switch n := next.(type) {
case map[any]any:
return v.searchIndexableWithPathPrefixes(cast.ToStringMap(n), path[pathIndex:])
case map[string]any, []any:
return v.searchIndexableWithPathPrefixes(n, path[pathIndex:])
default:
// got a value but nested key expected, do nothing and look for next prefix
}
// not found
return nil
}
// isPathShadowedInDeepMap makes sure the given path is not shadowed somewhere
// on its path in the map.
// e.g., if "foo.bar" has a value in the given map, it “shadows”
//
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInDeepMap(path []string, m map[string]any) string {
var parentVal any
for i := 1; i < len(path); i++ {
parentVal = v.searchMap(m, path[0:i])
if parentVal == nil {
// not found, no need to add more path elements
return ""
}
switch parentVal.(type) {
case map[any]any:
continue
case map[string]any:
continue
default:
// parentVal is a regular value which shadows "path"
return strings.Join(path[0:i], v.keyDelim)
}
}
return ""
}
// isPathShadowedInFlatMap makes sure the given path is not shadowed somewhere
// in a sub-path of the map.
// e.g., if "foo.bar" has a value in the given map, it “shadows”
//
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInFlatMap(path []string, mi any) string {
// unify input map
var m map[string]interface{}
switch miv := mi.(type) {
case map[string]string:
m = castMapStringToMapInterface(miv)
case map[string]FlagValue:
m = castMapFlagToMapInterface(miv)
default:
return ""
}
// scan paths
var parentKey string
for i := 1; i < len(path); i++ {
parentKey = strings.Join(path[0:i], v.keyDelim)
if _, ok := m[parentKey]; ok {
return parentKey
}
}
return ""
}
// isPathShadowedInAutoEnv makes sure the given path is not shadowed somewhere
// in the environment, when automatic env is on.
// e.g., if "foo.bar" has a value in the environment, it “shadows”
//
// "foo.bar.baz" in a lower-priority map
func (v *Viper) isPathShadowedInAutoEnv(path []string) string {
var parentKey string
for i := 1; i < len(path); i++ {
parentKey = strings.Join(path[0:i], v.keyDelim)
if _, ok := v.getEnv(v.mergeWithEnvPrefix(parentKey)); ok {
return parentKey
}
}
return ""
}
// SetTypeByDefaultValue enables or disables the inference of a key value's
// type when the Get function is used based upon a key's default value as
// opposed to the value returned based on the normal fetch logic.
//
// For example, if a key has a default value of []string{} and the same key
// is set via an environment variable to "a b c", a call to the Get function
// would return a string slice for the key if the key's type is inferred by
// the default value and the Get function would return:
//
// []string {"a", "b", "c"}
//
// Otherwise the Get function would return:
//
// "a b c"
func SetTypeByDefaultValue(enable bool) { v.SetTypeByDefaultValue(enable) }
// SetTypeByDefaultValue enables or disables the inference of a key value's
// type when the Get function is used based upon a key's default value as
// opposed to the value returned based on the normal fetch logic.
//
// For example, if a key has a default value of []string{} and the same key
// is set via an environment variable to "a b c", a call to the Get function
// would return a string slice for the key if the key's type is inferred by
// the default value and the Get function would return:
//
// []string {"a", "b", "c"}
//
// Otherwise the Get function would return:
//
// "a b c"
func (v *Viper) SetTypeByDefaultValue(enable bool) {
v.typeByDefValue = enable
}
// GetViper gets the global Viper instance.
func GetViper() *Viper {
return v
}
// Get can retrieve any value given the key to use.
// Get is case-insensitive for a key.
// Get has the behavior of returning the value associated with the first
// place from where it is set. Viper will check in the following order:
// override, flag, env, config file, key/value store, default
//
// Get returns an interface. For a specific value use one of the Get____ methods.
func Get(key string) any { return v.Get(key) }
// Get retrieves the value associated with the key.
// Get is case-insensitive for a key.
// Get has the behavior of returning the value associated with the first
// place from where it is set. Viper will check in the following order:
// override, flag, env, config file, key/value store, default
//
// Get returns an interface. For a specific value use one of the Get____ methods.
func (v *Viper) Get(key string) any {
lcaseKey := strings.ToLower(key)
val := v.find(lcaseKey, true)
if val == nil {
return nil
}
if v.typeByDefValue {
// TODO(bep) this branch isn't covered by a single test.
valType := val
path := strings.Split(lcaseKey, v.keyDelim)
defVal := v.searchMap(v.defaults, path)
if defVal != nil {
valType = defVal
}
switch valType.(type) {
case bool:
return cast.ToBool(val)
case string:
return cast.ToString(val)
case int32, int16, int8, int:
return cast.ToInt(val)
case uint:
return cast.ToUint(val)
case uint32:
return cast.ToUint32(val)
case uint64:
return cast.ToUint64(val)
case int64:
return cast.ToInt64(val)
case float64, float32:
return cast.ToFloat64(val)
case time.Time:
return cast.ToTime(val)
case time.Duration:
return cast.ToDuration(val)
case []string:
return cast.ToStringSlice(val)
case []int:
return cast.ToIntSlice(val)
case []time.Duration:
return cast.ToDurationSlice(val)
}
}
return val
}
// Sub returns new Viper instance representing a sub tree of this instance.
// Sub is case-insensitive for a key.
func Sub(key string) *Viper { return v.Sub(key) }
// Sub returns a new Viper instance representing a sub tree of this instance.
// Sub is case-insensitive for a key.
func (v *Viper) Sub(key string) *Viper {
subv := New()
data := v.Get(key)
if data == nil {
return nil
}
if reflect.TypeOf(data).Kind() == reflect.Map {
subv.parents = append([]string(nil), v.parents...)
subv.parents = append(subv.parents, strings.ToLower(key))
subv.automaticEnvApplied = v.automaticEnvApplied
subv.envPrefix = v.envPrefix
subv.envKeyReplacer = v.envKeyReplacer
subv.keyDelim = v.keyDelim
subv.config = cast.ToStringMap(data)
return subv
}
return nil
}
// GetString returns the value associated with the key as a string.
func GetString(key string) string { return v.GetString(key) }
// GetString returns the value associated with the key as a string.
func (v *Viper) GetString(key string) string {
return cast.ToString(v.Get(key))
}
// GetBool returns the value associated with the key as a boolean.
func GetBool(key string) bool { return v.GetBool(key) }
// GetBool returns the value associated with the key as a boolean.
func (v *Viper) GetBool(key string) bool {
return cast.ToBool(v.Get(key))
}
// GetInt returns the value associated with the key as an integer.
func GetInt(key string) int { return v.GetInt(key) }
// GetInt returns the value associated with the key as an integer.
func (v *Viper) GetInt(key string) int {
return cast.ToInt(v.Get(key))
}
// GetInt32 returns the value associated with the key as an integer.
func GetInt32(key string) int32 { return v.GetInt32(key) }
// GetInt32 returns the value associated with the key as an integer.
func (v *Viper) GetInt32(key string) int32 {
return cast.ToInt32(v.Get(key))
}
// GetInt64 returns the value associated with the key as an integer.
func GetInt64(key string) int64 { return v.GetInt64(key) }
// GetInt64 returns the value associated with the key as an integer.
func (v *Viper) GetInt64(key string) int64 {
return cast.ToInt64(v.Get(key))
}
// GetUint8 returns the value associated with the key as an unsigned integer.
func GetUint8(key string) uint8 { return v.GetUint8(key) }
// GetUint8 returns the value associated with the key as an unsigned integer.
func (v *Viper) GetUint8(key string) uint8 {
return cast.ToUint8(v.Get(key))
}
// GetUint returns the value associated with the key as an unsigned integer.
func GetUint(key string) uint { return v.GetUint(key) }
// GetUint returns the value associated with the key as an unsigned integer.
func (v *Viper) GetUint(key string) uint {
return cast.ToUint(v.Get(key))
}
// GetUint16 returns the value associated with the key as an unsigned integer.
func GetUint16(key string) uint16 { return v.GetUint16(key) }
// GetUint16 returns the value associated with the key as an unsigned integer.
func (v *Viper) GetUint16(key string) uint16 {
return cast.ToUint16(v.Get(key))
}
// GetUint32 returns the value associated with the key as an unsigned integer.
func GetUint32(key string) uint32 { return v.GetUint32(key) }
// GetUint32 returns the value associated with the key as an unsigned integer.
func (v *Viper) GetUint32(key string) uint32 {
return cast.ToUint32(v.Get(key))
}
// GetUint64 returns the value associated with the key as an unsigned integer.
func GetUint64(key string) uint64 { return v.GetUint64(key) }
// GetUint64 returns the value associated with the key as an unsigned integer.
func (v *Viper) GetUint64(key string) uint64 {
return cast.ToUint64(v.Get(key))
}
// GetFloat64 returns the value associated with the key as a float64.
func GetFloat64(key string) float64 { return v.GetFloat64(key) }
// GetFloat64 returns the value associated with the key as a float64.
func (v *Viper) GetFloat64(key string) float64 {
return cast.ToFloat64(v.Get(key))
}
// GetTime returns the value associated with the key as time.
func GetTime(key string) time.Time { return v.GetTime(key) }
// GetTime returns the value associated with the key as time.
func (v *Viper) GetTime(key string) time.Time {
return cast.ToTime(v.Get(key))
}
// GetDuration returns the value associated with the key as a duration.
func GetDuration(key string) time.Duration { return v.GetDuration(key) }
// GetDuration returns the value associated with the key as a duration.
func (v *Viper) GetDuration(key string) time.Duration {
return cast.ToDuration(v.Get(key))
}
// GetIntSlice returns the value associated with the key as a slice of int values.
func GetIntSlice(key string) []int { return v.GetIntSlice(key) }
// GetIntSlice returns the value associated with the key as a slice of int values.
func (v *Viper) GetIntSlice(key string) []int {
return cast.ToIntSlice(v.Get(key))
}
// GetStringSlice returns the value associated with the key as a slice of strings.
func GetStringSlice(key string) []string { return v.GetStringSlice(key) }
// GetStringSlice returns the value associated with the key as a slice of strings.
func (v *Viper) GetStringSlice(key string) []string {
return cast.ToStringSlice(v.Get(key))
}
// GetStringMap returns the value associated with the key as a map of interfaces.
func GetStringMap(key string) map[string]any { return v.GetStringMap(key) }
// GetStringMap returns the value associated with the key as a map of interfaces.
func (v *Viper) GetStringMap(key string) map[string]any {
return cast.ToStringMap(v.Get(key))
}
// GetStringMapString returns the value associated with the key as a map of strings.
func GetStringMapString(key string) map[string]string { return v.GetStringMapString(key) }
// GetStringMapString returns the value associated with the key as a map of strings.
func (v *Viper) GetStringMapString(key string) map[string]string {
return cast.ToStringMapString(v.Get(key))
}
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func GetStringMapStringSlice(key string) map[string][]string { return v.GetStringMapStringSlice(key) }
// GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func (v *Viper) GetStringMapStringSlice(key string) map[string][]string {
return cast.ToStringMapStringSlice(v.Get(key))
}
// GetSizeInBytes returns the size of the value associated with the given key
// in bytes.
func GetSizeInBytes(key string) uint { return v.GetSizeInBytes(key) }
// GetSizeInBytes returns the size of the value associated with the given key
// in bytes.
func (v *Viper) GetSizeInBytes(key string) uint {
sizeStr := cast.ToString(v.Get(key))
return parseSizeInBytes(sizeStr)
}
// UnmarshalKey takes a single key and unmarshals it into a Struct.
func UnmarshalKey(key string, rawVal any, opts ...DecoderConfigOption) error {
return v.UnmarshalKey(key, rawVal, opts...)
}
// UnmarshalKey takes a single key and unmarshals it into a Struct.
func (v *Viper) UnmarshalKey(key string, rawVal any, opts ...DecoderConfigOption) error {
return decode(v.Get(key), v.defaultDecoderConfig(rawVal, opts...))
}
// Unmarshal unmarshals the config into a Struct. Make sure that the tags
// on the fields of the structure are properly set.
func Unmarshal(rawVal any, opts ...DecoderConfigOption) error {
return v.Unmarshal(rawVal, opts...)
}
// Unmarshal unmarshals the config into a Struct. Make sure that the tags
// on the fields of the structure are properly set.
func (v *Viper) Unmarshal(rawVal any, opts ...DecoderConfigOption) error {
keys := v.AllKeys()
if v.experimentalBindStruct {
// TODO: make this optional?
structKeys, err := v.decodeStructKeys(rawVal, opts...)
if err != nil {
return err
}
keys = append(keys, structKeys...)
}
// TODO: struct keys should be enough?
return decode(v.getSettings(keys), v.defaultDecoderConfig(rawVal, opts...))
}
func (v *Viper) decodeStructKeys(input any, opts ...DecoderConfigOption) ([]string, error) {
var structKeyMap map[string]any
err := decode(input, v.defaultDecoderConfig(&structKeyMap, opts...))
if err != nil {
return nil, err
}
flattenedStructKeyMap := v.flattenAndMergeMap(map[string]bool{}, structKeyMap, "")
r := make([]string, 0, len(flattenedStructKeyMap))
for v := range flattenedStructKeyMap {
r = append(r, v)
}
return r, nil
}
// defaultDecoderConfig returns default mapstructure.DecoderConfig with support
// of time.Duration values & string slices.
func (v *Viper) defaultDecoderConfig(output any, opts ...DecoderConfigOption) *mapstructure.DecoderConfig {
decodeHook := v.decodeHook
if decodeHook == nil {
decodeHook = mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
// mapstructure.StringToSliceHookFunc(","),
stringToWeakSliceHookFunc(","),
)
}
c := &mapstructure.DecoderConfig{
Metadata: nil,
WeaklyTypedInput: true,
DecodeHook: decodeHook,
}
for _, opt := range opts {
opt(c)
}
// Do not allow overwriting the output
c.Result = output
return c
}
// As of mapstructure v2.0.0 StringToSliceHookFunc checks if the return type is a string slice.
// This function removes that check.
// TODO: implement a function that checks if the value can be converted to the return type and use it instead.
func stringToWeakSliceHookFunc(sep string) mapstructure.DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if f.Kind() != reflect.String || t.Kind() != reflect.Slice {
return data, nil
}
raw := data.(string)
if raw == "" {
return []string{}, nil
}
return strings.Split(raw, sep), nil
}
}
// decode is a wrapper around mapstructure.Decode that mimics the WeakDecode functionality.
func decode(input any, config *mapstructure.DecoderConfig) error {
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
// in the destination struct.
func UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
return v.UnmarshalExact(rawVal, opts...)
}
// UnmarshalExact unmarshals the config into a Struct, erroring if a field is nonexistent
// in the destination struct.
func (v *Viper) UnmarshalExact(rawVal any, opts ...DecoderConfigOption) error {
config := v.defaultDecoderConfig(rawVal, opts...)
config.ErrorUnused = true
keys := v.AllKeys()
if v.experimentalBindStruct {
// TODO: make this optional?
structKeys, err := v.decodeStructKeys(rawVal, opts...)
if err != nil {
return err
}
keys = append(keys, structKeys...)
}
// TODO: struct keys should be enough?
return decode(v.getSettings(keys), config)
}
// BindPFlags binds a full flag set to the configuration, using each flag's long
// name as the config key.
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | true |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/viper_test.go | viper_test.go | // Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package viper
import (
"bytes"
"encoding/json"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/fsnotify/fsnotify"
"github.com/go-viper/mapstructure/v2"
"github.com/sagikazarmark/locafero"
"github.com/spf13/afero"
"github.com/spf13/cast"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/spf13/viper/internal/testutil"
)
// var yamlExample = []byte(`Hacker: true
// name: steve
// hobbies:
// - skateboarding
// - snowboarding
// - go
// clothing:
// jacket: leather
// trousers: denim
// pants:
// size: large
// age: 35
// eyes : brown
// beard: true
// `)
var yamlExampleWithExtras = []byte(`Existing: true
Bogus: true
`)
type testUnmarshalExtra struct {
Existing bool
}
var tomlExample = []byte(`
title = "TOML Example"
[owner]
organization = "MongoDB"
Bio = "MongoDB Chief Developer Advocate & Hacker at Large"
dob = 1979-05-27T07:32:00Z # First class dates? Why not?`)
var dotenvExample = []byte(`
TITLE_DOTENV="DotEnv Example"
TYPE_DOTENV=donut
NAME_DOTENV=Cake`)
var jsonExample = []byte(`{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [
{ "type": "Regular" },
{ "type": "Chocolate" },
{ "type": "Blueberry" },
{ "type": "Devil's Food" }
]
}
}`)
var remoteExample = []byte(`{
"id":"0002",
"type":"cronut",
"newkey":"remote"
}`)
func initConfigs(v *Viper) {
var r io.Reader
v.SetConfigType("yaml")
r = bytes.NewReader(yamlExample)
v.unmarshalReader(r, v.config)
v.SetConfigType("json")
r = bytes.NewReader(jsonExample)
v.unmarshalReader(r, v.config)
v.SetConfigType("toml")
r = bytes.NewReader(tomlExample)
v.unmarshalReader(r, v.config)
v.SetConfigType("env")
r = bytes.NewReader(dotenvExample)
v.unmarshalReader(r, v.config)
v.SetConfigType("json")
remote := bytes.NewReader(remoteExample)
v.unmarshalReader(remote, v.kvstore)
}
func initConfig(typ, config string, v *Viper) {
v.SetConfigType(typ)
r := strings.NewReader(config)
if err := v.unmarshalReader(r, v.config); err != nil {
panic(err)
}
}
// initDirs makes directories for testing.
func initDirs(t *testing.T) (string, string) {
var (
testDirs = []string{`a a`, `b`, `C_`}
config = `improbable`
)
if runtime.GOOS != "windows" {
testDirs = append(testDirs, `d\d`)
}
root := t.TempDir()
for _, dir := range testDirs {
innerDir := filepath.Join(root, dir)
err := os.Mkdir(innerDir, 0o750)
require.NoError(t, err)
err = os.WriteFile(
filepath.Join(innerDir, config+".toml"),
[]byte(`key = "value is `+dir+`"`+"\n"),
0o640)
require.NoError(t, err)
}
return root, config
}
// stubs for PFlag Values.
type stringValue string
func newStringValue(val string, p *string) *stringValue {
*p = val
return (*stringValue)(p)
}
func (s *stringValue) Set(val string) error {
*s = stringValue(val)
return nil
}
func (s *stringValue) Type() string {
return "string"
}
func (s *stringValue) String() string {
return string(*s)
}
func TestGetConfigFile(t *testing.T) {
t.Run("config file set", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
v := New()
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
v.SetConfigFile(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/viper/config.yaml"), filename)
assert.NoError(t, err)
})
t.Run("find file", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
v := New()
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/viper/config.yaml"), filename)
assert.NoError(t, err)
})
t.Run("find files only", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/config"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/config/config.yaml"))
require.NoError(t, err)
v := New()
v.SetFs(fs)
v.AddConfigPath("/etc")
v.AddConfigPath("/etc/config")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/config/config.yaml"), filename)
assert.NoError(t, err)
})
t.Run("precedence", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/home/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/home/viper/config.zml"))
require.NoError(t, err)
err = fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.bml"))
require.NoError(t, err)
err = fs.Mkdir(testutil.AbsFilePath(t, "/var/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/var/viper/config.yaml"))
require.NoError(t, err)
v := New()
v.SetFs(fs)
v.AddConfigPath("/home/viper")
v.AddConfigPath("/etc/viper")
v.AddConfigPath("/var/viper")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/var/viper/config.yaml"), filename)
assert.NoError(t, err)
})
t.Run("without extension", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/.dotfilenoext"))
require.NoError(t, err)
v := New()
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
v.SetConfigName(".dotfilenoext")
v.SetConfigType("yaml")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/viper/.dotfilenoext"), filename)
assert.NoError(t, err)
})
t.Run("without extension and config type", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/.dotfilenoext"))
require.NoError(t, err)
v := New()
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
v.SetConfigName(".dotfilenoext")
_, err = v.getConfigFile()
// unless config type is set, files without extension
// are not considered
assert.Error(t, err)
})
t.Run("experimental finder", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
v := NewWithOptions(ExperimentalFinder())
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/viper/config.yaml"), testutil.AbsFilePath(t, filename))
assert.NoError(t, err)
})
t.Run("finder", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
_, err = fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
finder := locafero.Finder{
Paths: []string{testutil.AbsFilePath(t, "/etc/viper")},
Names: locafero.NameWithExtensions("config", SupportedExts...),
Type: locafero.FileTypeFile,
}
v := NewWithOptions(WithFinder(finder))
v.SetFs(fs)
// These should be ineffective
v.AddConfigPath("/etc/something_else")
v.SetConfigName("not-config")
filename, err := v.getConfigFile()
assert.Equal(t, testutil.AbsFilePath(t, "/etc/viper/config.yaml"), testutil.AbsFilePath(t, filename))
assert.NoError(t, err)
})
}
func TestReadInConfig(t *testing.T) {
t.Run("config file set", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
file, err := fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
_, err = file.WriteString(`key: value`)
require.NoError(t, err)
file.Close()
v := New()
v.SetFs(fs)
v.SetConfigFile(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
err = v.ReadInConfig()
require.NoError(t, err)
assert.Equal(t, "value", v.Get("key"))
})
t.Run("find file", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
file, err := fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
_, err = file.WriteString(`key: value`)
require.NoError(t, err)
file.Close()
v := New()
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
err = v.ReadInConfig()
require.NoError(t, err)
assert.Equal(t, "value", v.Get("key"))
})
t.Run("find file with experimental finder", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
file, err := fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
_, err = file.WriteString(`key: value`)
require.NoError(t, err)
file.Close()
v := NewWithOptions(ExperimentalFinder())
v.SetFs(fs)
v.AddConfigPath("/etc/viper")
err = v.ReadInConfig()
require.NoError(t, err)
assert.Equal(t, "value", v.Get("key"))
})
t.Run("find file using a finder", func(t *testing.T) {
fs := afero.NewMemMapFs()
err := fs.Mkdir(testutil.AbsFilePath(t, "/etc/viper"), 0o777)
require.NoError(t, err)
file, err := fs.Create(testutil.AbsFilePath(t, "/etc/viper/config.yaml"))
require.NoError(t, err)
_, err = file.WriteString(`key: value`)
require.NoError(t, err)
file.Close()
finder := locafero.Finder{
Paths: []string{testutil.AbsFilePath(t, "/etc/viper")},
Names: locafero.NameWithExtensions("config", SupportedExts...),
Type: locafero.FileTypeFile,
}
v := NewWithOptions(WithFinder(finder))
v.SetFs(fs)
// These should be ineffective
v.AddConfigPath("/etc/something_else")
v.SetConfigName("not-config")
err = v.ReadInConfig()
require.NoError(t, err)
assert.Equal(t, "value", v.Get("key"))
})
}
func TestDefault(t *testing.T) {
v := New()
v.SetDefault("age", 45)
assert.Equal(t, 45, v.Get("age"))
v.SetDefault("clothing.jacket", "slacks")
assert.Equal(t, "slacks", v.Get("clothing.jacket"))
v.SetConfigType("yaml")
err := v.ReadConfig(bytes.NewBuffer(yamlExample))
require.NoError(t, err)
assert.Equal(t, "leather", v.Get("clothing.jacket"))
}
func TestUnmarshaling(t *testing.T) {
v := New()
v.SetConfigType("yaml")
r := bytes.NewReader(yamlExample)
v.unmarshalReader(r, v.config)
assert.True(t, v.InConfig("name"))
assert.True(t, v.InConfig("clothing.jacket"))
assert.False(t, v.InConfig("state"))
assert.False(t, v.InConfig("clothing.hat"))
assert.Equal(t, "steve", v.Get("name"))
assert.Equal(t, []any{"skateboarding", "snowboarding", "go"}, v.Get("hobbies"))
assert.Equal(t, map[string]any{"jacket": "leather", "trousers": "denim", "pants": map[string]any{"size": "large"}}, v.Get("clothing"))
assert.Equal(t, 35, v.Get("age"))
}
func TestUnmarshalExact(t *testing.T) {
v := New()
target := &testUnmarshalExtra{}
v.SetConfigType("yaml")
r := bytes.NewReader(yamlExampleWithExtras)
v.ReadConfig(r)
err := v.UnmarshalExact(target)
assert.Error(t, err, "UnmarshalExact should error when populating a struct from a conf that contains unused fields")
}
func TestOverrides(t *testing.T) {
v := New()
v.Set("age", 40)
assert.Equal(t, 40, v.Get("age"))
}
func TestDefaultPost(t *testing.T) {
v := New()
assert.NotEqual(t, "NYC", v.Get("state"))
v.SetDefault("state", "NYC")
assert.Equal(t, "NYC", v.Get("state"))
}
func TestAliases(t *testing.T) {
v := New()
v.Set("age", 40)
v.RegisterAlias("years", "age")
assert.Equal(t, 40, v.Get("years"))
v.Set("years", 45)
assert.Equal(t, 45, v.Get("age"))
}
func TestAliasInConfigFile(t *testing.T) {
v := New()
v.SetConfigType("yaml")
// Read the YAML data into Viper configuration
require.NoError(t, v.ReadConfig(bytes.NewBuffer(yamlExample)), "Error reading YAML data")
v.RegisterAlias("beard", "hasbeard")
assert.Equal(t, true, v.Get("hasbeard"))
v.Set("hasbeard", false)
assert.Equal(t, false, v.Get("beard"))
}
func TestYML(t *testing.T) {
v := New()
v.SetConfigType("yaml")
// Read the YAML data into Viper configuration
require.NoError(t, v.ReadConfig(bytes.NewBuffer(yamlExample)), "Error reading YAML data")
assert.Equal(t, "steve", v.Get("name"))
}
func TestJSON(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the JSON data into Viper configuration
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading JSON data")
assert.Equal(t, "0001", v.Get("id"))
}
func TestTOML(t *testing.T) {
v := New()
v.SetConfigType("toml")
// Read the TOML data into Viper configuration
require.NoError(t, v.ReadConfig(bytes.NewBuffer(tomlExample)), "Error reading toml data")
assert.Equal(t, "TOML Example", v.Get("title"))
}
func TestDotEnv(t *testing.T) {
v := New()
v.SetConfigType("env")
// Read the dotenv data into Viper configuration
require.NoError(t, v.ReadConfig(bytes.NewBuffer(dotenvExample)), "Error reading env data")
assert.Equal(t, "DotEnv Example", v.Get("title_dotenv"))
}
func TestRemotePrecedence(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the remote data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading json data")
assert.Equal(t, "0001", v.Get("id"))
// update the kvstore with the remoteExample which should overite the key in v.config
remote := bytes.NewReader(remoteExample)
require.NoError(t, v.unmarshalReader(remote, v.kvstore), "Error reading json data in to kvstore")
assert.Equal(t, "0001", v.Get("id"))
assert.NotEqual(t, "cronut", v.Get("type"))
assert.Equal(t, "remote", v.Get("newkey"))
v.Set("newkey", "newvalue")
assert.NotEqual(t, "remote", v.Get("newkey"))
assert.Equal(t, "newvalue", v.Get("newkey"))
}
func TestEnv(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the JSON data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading json data")
v.BindEnv("id")
v.BindEnv("f", "FOOD", "OLD_FOOD")
t.Setenv("ID", "13")
t.Setenv("FOOD", "apple")
t.Setenv("OLD_FOOD", "banana")
t.Setenv("NAME", "crunk")
assert.Equal(t, "13", v.Get("id"))
assert.Equal(t, "apple", v.Get("f"))
assert.Equal(t, "Cake", v.Get("name"))
v.AutomaticEnv()
assert.Equal(t, "crunk", v.Get("name"))
}
func TestMultipleEnv(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the JSON data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading json data")
v.BindEnv("f", "FOOD", "OLD_FOOD")
t.Setenv("OLD_FOOD", "banana")
assert.Equal(t, "banana", v.Get("f"))
}
func TestEmptyEnv(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the JSON data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading json data")
v.BindEnv("type") // Empty environment variable
v.BindEnv("name") // Bound, but not set environment variable
t.Setenv("TYPE", "")
assert.Equal(t, "donut", v.Get("type"))
assert.Equal(t, "Cake", v.Get("name"))
}
func TestEmptyEnv_Allowed(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the JSON data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading json data")
v.AllowEmptyEnv(true)
v.BindEnv("type") // Empty environment variable
v.BindEnv("name") // Bound, but not set environment variable
t.Setenv("TYPE", "")
assert.Equal(t, "", v.Get("type"))
assert.Equal(t, "Cake", v.Get("name"))
}
func TestEnvPrefix(t *testing.T) {
v := New()
v.SetConfigType("json")
// Read the JSON data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(jsonExample)), "Error reading json data")
v.SetEnvPrefix("foo") // will be uppercased automatically
v.BindEnv("id")
v.BindEnv("f", "FOOD") // not using prefix
t.Setenv("FOO_ID", "13")
t.Setenv("FOOD", "apple")
t.Setenv("FOO_NAME", "crunk")
assert.Equal(t, "13", v.Get("id"))
assert.Equal(t, "apple", v.Get("f"))
assert.Equal(t, "Cake", v.Get("name"))
v.AutomaticEnv()
assert.Equal(t, "crunk", v.Get("name"))
}
func TestAutoEnv(t *testing.T) {
v := New()
v.AutomaticEnv()
t.Setenv("FOO_BAR", "13")
assert.Equal(t, "13", v.Get("foo_bar"))
}
func TestAutoEnvWithPrefix(t *testing.T) {
v := New()
v.AutomaticEnv()
v.SetEnvPrefix("Baz")
t.Setenv("BAZ_BAR", "13")
assert.Equal(t, "13", v.Get("bar"))
}
func TestSetEnvKeyReplacer(t *testing.T) {
v := New()
v.AutomaticEnv()
t.Setenv("REFRESH_INTERVAL", "30s")
replacer := strings.NewReplacer("-", "_")
v.SetEnvKeyReplacer(replacer)
assert.Equal(t, "30s", v.Get("refresh-interval"))
}
func TestEnvKeyReplacer(t *testing.T) {
v := NewWithOptions(EnvKeyReplacer(strings.NewReplacer("-", "_")))
v.AutomaticEnv()
t.Setenv("REFRESH_INTERVAL", "30s")
assert.Equal(t, "30s", v.Get("refresh-interval"))
}
func TestEnvSubConfig(t *testing.T) {
v := New()
v.SetConfigType("yaml")
// Read the YAML data into Viper configuration v.config
require.NoError(t, v.ReadConfig(bytes.NewBuffer(yamlExample)), "Error reading json data")
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
t.Setenv("CLOTHING_PANTS_SIZE", "small")
subv := v.Sub("clothing").Sub("pants")
assert.Equal(t, "small", subv.Get("size"))
// again with EnvPrefix
v.SetEnvPrefix("foo") // will be uppercased automatically
subWithPrefix := v.Sub("clothing").Sub("pants")
t.Setenv("FOO_CLOTHING_PANTS_SIZE", "large")
assert.Equal(t, "large", subWithPrefix.Get("size"))
}
func TestAllKeys(t *testing.T) {
v := New()
initConfigs(v)
ks := []string{
"title",
"newkey",
"owner.organization",
"owner.dob",
"owner.bio",
"name",
"beard",
"ppu",
"batters.batter",
"hobbies",
"clothing.jacket",
"clothing.trousers",
"clothing.pants.size",
"age",
"hacker",
"id",
"type",
"eyes",
"title_dotenv",
"type_dotenv",
"name_dotenv",
}
dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
all := map[string]any{
"owner": map[string]any{
"organization": "MongoDB",
"bio": "MongoDB Chief Developer Advocate & Hacker at Large",
"dob": dob,
},
"title": "TOML Example",
"ppu": 0.55,
"eyes": "brown",
"clothing": map[string]any{
"trousers": "denim",
"jacket": "leather",
"pants": map[string]any{"size": "large"},
},
"id": "0001",
"batters": map[string]any{
"batter": []any{
map[string]any{"type": "Regular"},
map[string]any{"type": "Chocolate"},
map[string]any{"type": "Blueberry"},
map[string]any{"type": "Devil's Food"},
},
},
"hacker": true,
"beard": true,
"hobbies": []any{
"skateboarding",
"snowboarding",
"go",
},
"age": 35,
"type": "donut",
"newkey": "remote",
"name": "Cake",
"title_dotenv": "DotEnv Example",
"type_dotenv": "donut",
"name_dotenv": "Cake",
}
assert.ElementsMatch(t, ks, v.AllKeys())
assert.Equal(t, all, v.AllSettings())
}
func TestAllKeysWithEnv(t *testing.T) {
v := New()
// bind and define environment variables (including a nested one)
v.BindEnv("id")
v.BindEnv("foo.bar")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
t.Setenv("ID", "13")
t.Setenv("FOO_BAR", "baz")
assert.ElementsMatch(t, []string{"id", "foo.bar"}, v.AllKeys())
}
func TestAliasesOfAliases(t *testing.T) {
v := New()
v.Set("Title", "Checking Case")
v.RegisterAlias("Foo", "Bar")
v.RegisterAlias("Bar", "Title")
assert.Equal(t, "Checking Case", v.Get("FOO"))
}
func TestRecursiveAliases(t *testing.T) {
v := New()
v.Set("baz", "bat")
v.RegisterAlias("Baz", "Roo")
v.RegisterAlias("Roo", "baz")
assert.Equal(t, "bat", v.Get("Baz"))
}
func TestUnmarshal(t *testing.T) {
v := New()
v.SetDefault("port", 1313)
v.Set("name", "Steve")
v.Set("duration", "1s1ms")
v.Set("modes", []int{1, 2, 3})
type config struct {
Port int
Name string
Duration time.Duration
Modes []int
}
var C config
require.NoError(t, v.Unmarshal(&C), "unable to decode into struct")
assert.Equal(
t,
&config{
Name: "Steve",
Port: 1313,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
},
&C,
)
v.Set("port", 1234)
require.NoError(t, v.Unmarshal(&C), "unable to decode into struct")
assert.Equal(
t,
&config{
Name: "Steve",
Port: 1234,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
},
&C,
)
}
func TestUnmarshalWithDefaultDecodeHook(t *testing.T) {
opt := mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
// Custom Decode Hook Function
func(rf reflect.Kind, rt reflect.Kind, data any) (any, error) {
if rf != reflect.String || rt != reflect.Map {
return data, nil
}
m := map[string]string{}
raw := data.(string)
if raw == "" {
return m, nil
}
err := json.Unmarshal([]byte(raw), &m)
return m, err
},
)
v := NewWithOptions(WithDecodeHook(opt))
v.Set("credentials", "{\"foo\":\"bar\"}")
type config struct {
Credentials map[string]string
}
var C config
require.NoError(t, v.Unmarshal(&C), "unable to decode into struct")
assert.Equal(t, &config{
Credentials: map[string]string{"foo": "bar"},
}, &C)
}
func TestUnmarshalWithDecoderOptions(t *testing.T) {
v := New()
v.Set("credentials", "{\"foo\":\"bar\"}")
opt := DecodeHook(mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
// Custom Decode Hook Function
func(rf reflect.Kind, rt reflect.Kind, data any) (any, error) {
if rf != reflect.String || rt != reflect.Map {
return data, nil
}
m := map[string]string{}
raw := data.(string)
if raw == "" {
return m, nil
}
err := json.Unmarshal([]byte(raw), &m)
return m, err
},
))
type config struct {
Credentials map[string]string
}
var C config
require.NoError(t, v.Unmarshal(&C, opt), "unable to decode into struct")
assert.Equal(t, &config{
Credentials: map[string]string{"foo": "bar"},
}, &C)
}
func TestUnmarshalWithAutomaticEnv(t *testing.T) {
t.Setenv("PORT", "1313")
t.Setenv("NAME", "Steve")
t.Setenv("DURATION", "1s1ms")
t.Setenv("MODES", "1,2,3")
t.Setenv("SECRET", "42")
t.Setenv("FILESYSTEM_SIZE", "4096")
type AuthConfig struct {
Secret string `mapstructure:"secret"`
}
type StorageConfig struct {
Size int `mapstructure:"size"`
}
type Configuration struct {
Port int `mapstructure:"port"`
Name string `mapstructure:"name"`
Duration time.Duration `mapstructure:"duration"`
// Infer name from struct
Modes []int
// Squash nested struct (omit prefix)
Authentication AuthConfig `mapstructure:",squash"`
// Different key
Storage StorageConfig `mapstructure:"filesystem"`
// Omitted field
Flag bool `mapstructure:"flag"`
}
v := NewWithOptions(ExperimentalBindStruct())
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
t.Run("OK", func(t *testing.T) {
var config Configuration
if err := v.Unmarshal(&config); err != nil {
t.Fatalf("unable to decode into struct, %v", err)
}
assert.Equal(
t,
Configuration{
Name: "Steve",
Port: 1313,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
Authentication: AuthConfig{
Secret: "42",
},
Storage: StorageConfig{
Size: 4096,
},
},
config,
)
})
t.Run("Precedence", func(t *testing.T) {
var config Configuration
v.Set("port", 1234)
if err := v.Unmarshal(&config); err != nil {
t.Fatalf("unable to decode into struct, %v", err)
}
assert.Equal(
t,
Configuration{
Name: "Steve",
Port: 1234,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
Authentication: AuthConfig{
Secret: "42",
},
Storage: StorageConfig{
Size: 4096,
},
},
config,
)
})
t.Run("Unset", func(t *testing.T) {
var config Configuration
err := v.Unmarshal(&config, func(config *mapstructure.DecoderConfig) {
config.ErrorUnset = true
})
assert.Error(t, err, "expected viper.Unmarshal to return error due to unset field 'FLAG'")
})
t.Run("Exact", func(t *testing.T) {
var config Configuration
v.Set("port", 1234)
if err := v.UnmarshalExact(&config); err != nil {
t.Fatalf("unable to decode into struct, %v", err)
}
assert.Equal(
t,
Configuration{
Name: "Steve",
Port: 1234,
Duration: time.Second + time.Millisecond,
Modes: []int{1, 2, 3},
Authentication: AuthConfig{
Secret: "42",
},
Storage: StorageConfig{
Size: 4096,
},
},
config,
)
})
}
func TestBindPFlags(t *testing.T) {
v := New() // create independent Viper object
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
testValues := map[string]*string{
"host": nil,
"port": nil,
"endpoint": nil,
}
mutatedTestValues := map[string]string{
"host": "localhost",
"port": "6060",
"endpoint": "/public",
}
for name := range testValues {
testValues[name] = flagSet.String(name, "", "test")
}
err := v.BindPFlags(flagSet)
require.NoError(t, err, "error binding flag set")
flagSet.VisitAll(func(flag *pflag.Flag) {
flag.Value.Set(mutatedTestValues[flag.Name])
flag.Changed = true
})
for name, expected := range mutatedTestValues {
assert.Equal(t, expected, v.Get(name))
}
}
func TestBindPFlagsStringSlice(t *testing.T) {
tests := []struct {
Expected []string
Value string
}{
{[]string{}, ""},
{[]string{"jeden"}, "jeden"},
{[]string{"dwa", "trzy"}, "dwa,trzy"},
{[]string{"cztery", "piec , szesc"}, "cztery,\"piec , szesc\""},
}
v := New() // create independent Viper object
defaultVal := []string{"default"}
v.SetDefault("stringslice", defaultVal)
for _, testValue := range tests {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.StringSlice("stringslice", testValue.Expected, "test")
for _, changed := range []bool{true, false} {
flagSet.VisitAll(func(f *pflag.Flag) {
f.Value.Set(testValue.Value)
f.Changed = changed
})
err := v.BindPFlags(flagSet)
require.NoError(t, err, "error binding flag set")
type TestStr struct {
StringSlice []string
}
val := &TestStr{}
err = v.Unmarshal(val)
require.NoError(t, err, "cannot unmarshal")
if changed {
assert.Equal(t, testValue.Expected, val.StringSlice)
assert.Equal(t, testValue.Expected, v.Get("stringslice"))
} else {
assert.Equal(t, defaultVal, val.StringSlice)
}
}
}
}
func TestBindPFlagsStringArray(t *testing.T) {
tests := []struct {
Expected []string
Value string
}{
{[]string{}, ""},
{[]string{"jeden"}, "jeden"},
{[]string{"dwa,trzy"}, "dwa,trzy"},
{[]string{"cztery,\"piec , szesc\""}, "cztery,\"piec , szesc\""},
}
v := New() // create independent Viper object
defaultVal := []string{"default"}
v.SetDefault("stringarray", defaultVal)
for _, testValue := range tests {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.StringArray("stringarray", testValue.Expected, "test")
for _, changed := range []bool{true, false} {
flagSet.VisitAll(func(f *pflag.Flag) {
f.Value.Set(testValue.Value)
f.Changed = changed
})
err := v.BindPFlags(flagSet)
require.NoError(t, err, "error binding flag set")
type TestStr struct {
StringArray []string
}
val := &TestStr{}
err = v.Unmarshal(val)
require.NoError(t, err, "cannot unmarshal")
if changed {
assert.Equal(t, testValue.Expected, val.StringArray)
assert.Equal(t, testValue.Expected, v.Get("stringarray"))
} else {
assert.Equal(t, defaultVal, val.StringArray)
}
}
}
}
func TestBindPFlagsSlices(t *testing.T) {
set := pflag.NewFlagSet("test", pflag.ContinueOnError)
set.IntSlice("intslice", []int{}, "")
set.BoolSlice("boolslice", []bool{}, "")
set.Float64Slice("float64slice", []float64{}, "")
set.UintSlice("uintslice", []uint{}, "")
v := New()
v.BindPFlags(set)
set.Set("intslice", "1,2")
assert.Equal(t, []int{1, 2}, v.Get("intslice"))
set.Set("boolslice", "true,false")
assert.Equal(t, []bool{true, false}, v.Get("boolslice"))
set.Set("float64slice", "1.1,2.2")
assert.Equal(t, []float64{1.1, 2.2}, v.Get("float64slice"))
set.Set("uintslice", "1,2")
assert.Equal(t, []uint{1, 2}, v.Get("uintslice"))
}
func TestSliceFlagsReturnCorrectType(t *testing.T) {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.IntSlice("int", []int{1, 2}, "")
flagSet.StringSlice("str", []string{"3", "4"}, "")
flagSet.DurationSlice("duration", []time.Duration{5 * time.Second}, "")
v := New()
v.BindPFlags(flagSet)
all := v.AllSettings()
assert.IsType(t, []int{}, all["int"])
assert.IsType(t, []string{}, all["str"])
assert.IsType(t, []time.Duration{}, all["duration"])
}
func TestBindPFlagsIntSlice(t *testing.T) {
tests := []struct {
Expected []int
Value string
}{
{[]int{}, ""},
{[]int{1}, "1"},
{[]int{2, 3}, "2,3"},
}
v := New() // create independent Viper object
defaultVal := []int{0}
v.SetDefault("intslice", defaultVal)
for _, testValue := range tests {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.IntSlice("intslice", testValue.Expected, "test")
for _, changed := range []bool{true, false} {
flagSet.VisitAll(func(f *pflag.Flag) {
f.Value.Set(testValue.Value)
f.Changed = changed
})
err := v.BindPFlags(flagSet)
require.NoError(t, err, "error binding flag set")
type TestInt struct {
IntSlice []int
}
val := &TestInt{}
err = v.Unmarshal(val)
require.NoError(t, err, "cannot unmarshal")
if changed {
assert.Equal(t, testValue.Expected, val.IntSlice)
assert.Equal(t, testValue.Expected, v.Get("intslice"))
} else {
assert.Equal(t, defaultVal, val.IntSlice)
}
}
}
}
func TestBindPFlag(t *testing.T) {
v := New()
testString := "testing"
testValue := newStringValue(testString, &testString)
flag := &pflag.Flag{
Name: "testflag",
Value: testValue,
Changed: false,
}
v.BindPFlag("testvalue", flag)
assert.Equal(t, testString, v.Get("testvalue"))
flag.Value.Set("testing_mutate")
flag.Changed = true // hack for pflag usage
assert.Equal(t, "testing_mutate", v.Get("testvalue"))
}
func TestBindPFlagDetectNilFlag(t *testing.T) {
v := New()
result := v.BindPFlag("testvalue", nil)
assert.Error(t, result)
}
func TestBindPFlagStringToString(t *testing.T) {
tests := []struct {
Expected map[string]string
Value string
}{
{map[string]string{}, ""},
{map[string]string{"yo": "hi"}, "yo=hi"},
{map[string]string{"yo": "hi", "oh": "hi=there"}, "yo=hi,oh=hi=there"},
{map[string]string{"yo": ""}, "yo="},
{map[string]string{"yo": "", "oh": "hi=there"}, "yo=,oh=hi=there"},
}
v := New() // create independent Viper object
defaultVal := map[string]string{}
v.SetDefault("stringtostring", defaultVal)
for _, testValue := range tests {
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
flagSet.StringToString("stringtostring", testValue.Expected, "test")
for _, changed := range []bool{true, false} {
flagSet.VisitAll(func(f *pflag.Flag) {
f.Value.Set(testValue.Value)
f.Changed = changed
})
err := v.BindPFlags(flagSet)
require.NoError(t, err, "error binding flag set")
type TestMap struct {
StringToString map[string]string
}
val := &TestMap{}
err = v.Unmarshal(val)
require.NoError(t, err, "cannot unmarshal")
if changed {
assert.Equal(t, testValue.Expected, val.StringToString)
} else {
assert.Equal(t, defaultVal, val.StringToString)
}
}
}
}
func TestBindPFlagStringToInt(t *testing.T) {
tests := []struct {
Expected map[string]int
Value string
}{
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | true |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/viper_yaml_test.go | viper_yaml_test.go | package viper
var yamlExample = []byte(`Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
jacket: leather
trousers: denim
pants:
size: large
age: 35
eyes : brown
beard: true
`)
var yamlWriteExpected = []byte(`age: 35
beard: true
clothing:
jacket: leather
pants:
size: large
trousers: denim
eyes: brown
hacker: true
hobbies:
- skateboarding
- snowboarding
- go
name: steve
`)
var yamlExampleWithDot = []byte(`Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
jacket: leather
trousers: denim
pants:
size: large
age: 35
eyes : brown
beard: true
emails:
steve@hacker.com:
created: 01/02/03
active: true
`)
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/errors.go | errors.go | package viper
import (
"fmt"
)
// FileLookupError is returned when Viper cannot resolve a configuration file.
//
// This is meant to be a common interface for all file look-up errors, occurring either because a
// file does not exist or because it cannot find any file matching finder criteria.
type FileLookupError interface {
error
fileLookup()
}
// ConfigFileNotFoundError denotes failing to find a configuration file from a search.
//
// Deprecated: This is error wraps [FileNotFoundFromSearchError], which should be used instead.
type ConfigFileNotFoundError struct {
locations []string
name string
}
// Error returns the formatted error.
func (e ConfigFileNotFoundError) Error() string {
return e.Unwrap().Error()
}
// Unwraps to FileNotFoundFromSearchError.
func (e ConfigFileNotFoundError) Unwrap() error {
return FileNotFoundFromSearchError(e)
}
// FileNotFoundFromSearchError denotes failing to find a configuration file from a search.
// Wraps ConfigFileNotFoundError.
type FileNotFoundFromSearchError struct {
locations []string
name string
}
func (e FileNotFoundFromSearchError) fileLookup() {}
// Error returns the formatted error.
func (e FileNotFoundFromSearchError) Error() string {
message := fmt.Sprintf("File %q not found", e.name)
if len(e.locations) > 0 {
message += fmt.Sprintf(" in %v", e.locations)
}
return message
}
// FileNotFoundError denotes failing to find a specific configuration file.
type FileNotFoundError struct {
err error
path string
}
func (e FileNotFoundError) fileLookup() {}
// Error returns the formatted error.
func (e FileNotFoundError) Error() string {
return fmt.Sprintf("file not found: %s", e.path)
}
// ConfigFileAlreadyExistsError denotes failure to write new configuration file.
type ConfigFileAlreadyExistsError string
// Error returns the formatted error when configuration already exists.
func (e ConfigFileAlreadyExistsError) Error() string {
return fmt.Sprintf("Config File %q Already Exists", string(e))
}
// ConfigMarshalError happens when failing to marshal the configuration.
type ConfigMarshalError struct {
err error
}
// Error returns the formatted configuration error.
func (e ConfigMarshalError) Error() string {
return fmt.Sprintf("While marshaling config: %s", e.err.Error())
}
// UnsupportedConfigError denotes encountering an unsupported
// configuration filetype.
type UnsupportedConfigError string
// Error returns the formatted configuration error.
func (str UnsupportedConfigError) Error() string {
return fmt.Sprintf("Unsupported Config Type %q", string(str))
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/util.go | util.go | // Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Viper is a application configuration system.
// It believes that applications can be configured a variety of ways
// via flags, ENVIRONMENT variables, configuration files retrieved
// from the file system, or a remote key/value store.
package viper
import (
"fmt"
"log/slog"
"os"
"path/filepath"
"runtime"
"strings"
"unicode"
"github.com/spf13/cast"
)
// ConfigParseError denotes failing to parse configuration file.
type ConfigParseError struct {
err error
}
// Error returns the formatted configuration error.
func (pe ConfigParseError) Error() string {
return fmt.Sprintf("While parsing config: %s", pe.err.Error())
}
// Unwrap returns the wrapped error.
func (pe ConfigParseError) Unwrap() error {
return pe.err
}
// toCaseInsensitiveValue checks if the value is a map;
// if so, create a copy and lower-case the keys recursively.
func toCaseInsensitiveValue(value any) any {
switch v := value.(type) {
case map[any]any:
value = copyAndInsensitiviseMap(cast.ToStringMap(v))
case map[string]any:
value = copyAndInsensitiviseMap(v)
}
return value
}
// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
// any map it makes case insensitive.
func copyAndInsensitiviseMap(m map[string]any) map[string]any {
nm := make(map[string]any)
for key, val := range m {
lkey := strings.ToLower(key)
switch v := val.(type) {
case map[any]any:
nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
case map[string]any:
nm[lkey] = copyAndInsensitiviseMap(v)
default:
nm[lkey] = v
}
}
return nm
}
func insensitiviseVal(val any) any {
switch v := val.(type) {
case map[any]any:
// nested map: cast and recursively insensitivise
val = cast.ToStringMap(val)
insensitiviseMap(val.(map[string]any))
case map[string]any:
// nested map: recursively insensitivise
insensitiviseMap(v)
case []any:
// nested array: recursively insensitivise
insensitiveArray(v)
}
return val
}
func insensitiviseMap(m map[string]any) {
for key, val := range m {
val = insensitiviseVal(val)
lower := strings.ToLower(key)
if key != lower {
// remove old key (not lower-cased)
delete(m, key)
}
// update map
m[lower] = val
}
}
func insensitiveArray(a []any) {
for i, val := range a {
a[i] = insensitiviseVal(val)
}
}
func absPathify(logger *slog.Logger, inPath string) string {
logger.Info("trying to resolve absolute path", "path", inPath)
if inPath == "$HOME" || strings.HasPrefix(inPath, "$HOME"+string(os.PathSeparator)) {
inPath = userHomeDir() + inPath[5:]
}
inPath = os.ExpandEnv(inPath)
if filepath.IsAbs(inPath) {
return filepath.Clean(inPath)
}
p, err := filepath.Abs(inPath)
if err == nil {
return filepath.Clean(p)
}
logger.Error(fmt.Errorf("could not discover absolute path: %w", err).Error())
return ""
}
func userHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func safeMul(a, b uint) uint {
c := a * b
if a > 1 && b > 1 && c/b != a {
return 0
}
return c
}
// parseSizeInBytes converts strings like 1GB or 12 mb into an unsigned integer number of bytes.
func parseSizeInBytes(sizeStr string) uint {
sizeStr = strings.TrimSpace(sizeStr)
lastChar := len(sizeStr) - 1
multiplier := uint(1)
if lastChar > 0 {
if sizeStr[lastChar] == 'b' || sizeStr[lastChar] == 'B' {
if lastChar > 1 {
switch unicode.ToLower(rune(sizeStr[lastChar-1])) {
case 'k':
multiplier = 1 << 10
sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
case 'm':
multiplier = 1 << 20
sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
case 'g':
multiplier = 1 << 30
sizeStr = strings.TrimSpace(sizeStr[:lastChar-1])
default:
multiplier = 1
sizeStr = strings.TrimSpace(sizeStr[:lastChar])
}
}
}
}
size := max(cast.ToInt(sizeStr), 0)
return safeMul(uint(size), multiplier)
}
// deepSearch scans deep maps, following the key indexes listed in the
// sequence "path".
// The last value is expected to be another map, and is returned.
//
// In case intermediate keys do not exist, or map to a non-map value,
// a new map is created and inserted, and the search continues from there:
// the initial map "m" may be modified!
func deepSearch(m map[string]any, path []string) map[string]any {
for _, k := range path {
m2, ok := m[k]
if !ok {
// intermediate key does not exist
// => create it and continue from there
m3 := make(map[string]any)
m[k] = m3
m = m3
continue
}
m3, ok := m2.(map[string]any)
if !ok {
// intermediate key is a value
// => replace with a new map
m3 = make(map[string]any)
m[k] = m3
}
// continue search from here
m = m3
}
return m
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/overrides_test.go | overrides_test.go | package viper
import (
"strings"
"testing"
"github.com/spf13/cast"
"github.com/stretchr/testify/assert"
)
type layer int
const (
defaultLayer layer = iota + 1
overrideLayer
)
func TestNestedOverrides(t *testing.T) {
assert := assert.New(t)
var v *Viper
// Case 0: value overridden by a value
overrideDefault(assert, "tom", 10, "tom", 20) // "tom" is first given 10 as default value, then overridden by 20
override(assert, "tom", 10, "tom", 20) // "tom" is first given value 10, then overridden by 20
overrideDefault(assert, "tom.age", 10, "tom.age", 20)
override(assert, "tom.age", 10, "tom.age", 20)
overrideDefault(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
override(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
// Case 1: key:value overridden by a value
v = overrideDefault(assert, "tom.age", 10, "tom", "boy") // "tom.age" is first given 10 as default value, then "tom" is overridden by "boy"
assert.Nil(v.Get("tom.age")) // "tom.age" should not exist anymore
v = override(assert, "tom.age", 10, "tom", "boy")
assert.Nil(v.Get("tom.age"))
// Case 2: value overridden by a key:value
overrideDefault(assert, "tom", "boy", "tom.age", 10) // "tom" is first given "boy" as default value, then "tom" is overridden by map{"age":10}
override(assert, "tom.age", 10, "tom", "boy")
// Case 3: key:value overridden by a key:value
v = overrideDefault(assert, "tom.size", 4, "tom.age", 10)
assert.Equal(4, v.Get("tom.size")) // value should still be reachable
v = override(assert, "tom.size", 4, "tom.age", 10)
assert.Equal(4, v.Get("tom.size"))
deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
// Case 4: key:value overridden by a map
v = overrideDefault(assert, "tom.size", 4, "tom", map[string]any{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
assert.Equal(10, v.Get("tom.age")) // new value should be there
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
v = override(assert, "tom.size", 4, "tom", map[string]any{"age": 10})
assert.Nil(v.Get("tom.size"))
assert.Equal(10, v.Get("tom.age"))
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
// Case 5: array overridden by a value
overrideDefault(assert, "tom", []int{10, 20}, "tom", 30)
override(assert, "tom", []int{10, 20}, "tom", 30)
overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", 30)
override(assert, "tom.age", []int{10, 20}, "tom.age", 30)
// Case 6: array overridden by an array
overrideDefault(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
override(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
v = override(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
// explicit array merge:
s, ok := v.Get("tom.age").([]int)
if assert.True(ok, "tom[\"age\"] is not a slice") {
v.Set("tom.age", append(s, []int{50, 60}...))
assert.Equal([]int{30, 40, 50, 60}, v.Get("tom.age"))
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, []int{30, 40, 50, 60})
}
}
func overrideDefault(assert *assert.Assertions, firstPath string, firstValue any, secondPath string, secondValue any) *Viper {
return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
}
func override(assert *assert.Assertions, firstPath string, firstValue any, secondPath string, secondValue any) *Viper {
return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
}
// overrideFromLayer performs the sequential override and low-level checks.
//
// First assignment is made on layer l for path firstPath with value firstValue,
// the second one on the override layer (i.e., with the Set() function)
// for path secondPath with value secondValue.
//
// firstPath and secondPath can include an arbitrary number of dots to indicate
// a nested element.
//
// After each assignment, the value is checked, retrieved both by its full path
// and by its key sequence (successive maps).
func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue any, secondPath string, secondValue any) *Viper {
v := New()
firstKeys := strings.Split(firstPath, v.keyDelim)
if assert == nil ||
len(firstKeys) == 0 || firstKeys[0] == "" {
return v
}
// Set and check first value
switch l {
case defaultLayer:
v.SetDefault(firstPath, firstValue)
case overrideLayer:
v.Set(firstPath, firstValue)
default:
return v
}
assert.Equal(firstValue, v.Get(firstPath))
deepCheckValue(assert, v, l, firstKeys, firstValue)
// Override and check new value
secondKeys := strings.Split(secondPath, v.keyDelim)
if len(secondKeys) == 0 || secondKeys[0] == "" {
return v
}
v.Set(secondPath, secondValue)
assert.Equal(secondValue, v.Get(secondPath))
deepCheckValue(assert, v, overrideLayer, secondKeys, secondValue)
return v
}
// deepCheckValue checks that all given keys correspond to a valid path in the
// configuration map of the given layer, and that the final value equals the one given.
func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value any) {
if assert == nil || v == nil ||
len(keys) == 0 || keys[0] == "" {
return
}
// init
var val any
var ms string
switch l {
case defaultLayer:
val = v.defaults
ms = "v.defaults"
case overrideLayer:
val = v.override
ms = "v.override"
}
// loop through map
var m map[string]any
for _, k := range keys {
if val == nil {
assert.Failf("%s is not a map[string]any", ms)
return
}
// deep scan of the map to get the final value
switch val := val.(type) {
case map[any]any:
m = cast.ToStringMap(val)
case map[string]any:
m = val
default:
assert.Failf("%s is not a map[string]any", ms)
return
}
ms = ms + "[\"" + k + "\"]"
val = m[k]
}
assert.Equal(value, val)
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/encoding_test.go | encoding_test.go | package viper
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type codec struct{}
func (codec) Encode(_ map[string]any) ([]byte, error) {
return nil, nil
}
func (codec) Decode(_ []byte, _ map[string]any) error {
return nil
}
func TestDefaultCodecRegistry(t *testing.T) {
t.Run("OK", func(t *testing.T) {
registry := NewCodecRegistry()
c := codec{}
err := registry.RegisterCodec("myformat", c)
require.NoError(t, err)
encoder, err := registry.Encoder("myformat")
require.NoError(t, err)
assert.Equal(t, c, encoder)
decoder, err := registry.Decoder("myformat")
require.NoError(t, err)
assert.Equal(t, c, decoder)
})
t.Run("CodecNotFound", func(t *testing.T) {
registry := NewCodecRegistry()
_, err := registry.Encoder("myformat")
require.Error(t, err)
_, err = registry.Decoder("myformat")
require.Error(t, err)
})
t.Run("FormatIsCaseInsensitive", func(t *testing.T) {
registry := NewCodecRegistry()
c := codec{}
err := registry.RegisterCodec("MYFORMAT", c)
require.NoError(t, err)
{
encoder, err := registry.Encoder("myformat")
require.NoError(t, err)
assert.Equal(t, c, encoder)
}
{
encoder, err := registry.Encoder("MYFORMAT")
require.NoError(t, err)
assert.Equal(t, c, encoder)
}
{
decoder, err := registry.Decoder("myformat")
require.NoError(t, err)
assert.Equal(t, c, decoder)
}
{
decoder, err := registry.Decoder("MYFORMAT")
require.NoError(t, err)
assert.Equal(t, c, decoder)
}
})
t.Run("OverrideDefault", func(t *testing.T) {
registry := NewCodecRegistry()
c := codec{}
err := registry.RegisterCodec("yaml", c)
require.NoError(t, err)
encoder, err := registry.Encoder("yaml")
require.NoError(t, err)
assert.Equal(t, c, encoder)
decoder, err := registry.Decoder("yaml")
require.NoError(t, err)
assert.Equal(t, c, decoder)
})
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/finder_example_test.go | finder_example_test.go | package viper_test
import (
"fmt"
"github.com/sagikazarmark/locafero"
"github.com/spf13/afero"
"github.com/spf13/viper"
)
func ExampleFinder() {
fs := afero.NewMemMapFs()
fs.Mkdir("/home/user", 0o777)
f, _ := fs.Create("/home/user/myapp.yaml")
f.WriteString("foo: bar")
f.Close()
// HCL will have a "lower" priority in the search order
fs.Create("/home/user/myapp.hcl")
finder := locafero.Finder{
Paths: []string{"/home/user"},
Names: locafero.NameWithExtensions("myapp", viper.SupportedExts...),
Type: locafero.FileTypeFile, // This is important!
}
v := viper.NewWithOptions(viper.WithFinder(finder))
v.SetFs(fs)
v.ReadInConfig()
fmt.Println(v.GetString("foo"))
// Output:
// bar
}
func ExampleFinders() {
fs := afero.NewMemMapFs()
fs.Mkdir("/home/user", 0o777)
f, _ := fs.Create("/home/user/myapp.yaml")
f.WriteString("foo: bar")
f.Close()
fs.Mkdir("/etc/myapp", 0o777)
fs.Create("/etc/myapp/config.yaml")
// Combine multiple finders to search for files in multiple locations with different criteria
finder := viper.Finders(
locafero.Finder{
Paths: []string{"/home/user"},
Names: locafero.NameWithExtensions("myapp", viper.SupportedExts...),
Type: locafero.FileTypeFile, // This is important!
},
locafero.Finder{
Paths: []string{"/etc/myapp"},
Names: []string{"config.yaml"}, // Only accept YAML files in the system config directory
Type: locafero.FileTypeFile, // This is important!
},
)
v := viper.NewWithOptions(viper.WithFinder(finder))
v.SetFs(fs)
v.ReadInConfig()
fmt.Println(v.GetString("foo"))
// Output:
// bar
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/encoding.go | encoding.go | package viper
import (
"errors"
"strings"
"sync"
"github.com/spf13/viper/internal/encoding/dotenv"
"github.com/spf13/viper/internal/encoding/json"
"github.com/spf13/viper/internal/encoding/toml"
"github.com/spf13/viper/internal/encoding/yaml"
)
// Encoder encodes Viper's internal data structures into a byte representation.
// It's primarily used for encoding a map[string]any into a file format.
type Encoder interface {
Encode(v map[string]any) ([]byte, error)
}
// Decoder decodes the contents of a byte slice into Viper's internal data structures.
// It's primarily used for decoding contents of a file into a map[string]any.
type Decoder interface {
Decode(b []byte, v map[string]any) error
}
// Codec combines [Encoder] and [Decoder] interfaces.
type Codec interface {
Encoder
Decoder
}
// TODO: consider adding specific errors for not found scenarios
// EncoderRegistry returns an [Encoder] for a given format.
//
// Format is case-insensitive.
//
// [EncoderRegistry] returns an error if no [Encoder] is registered for the format.
type EncoderRegistry interface {
Encoder(format string) (Encoder, error)
}
// DecoderRegistry returns an [Decoder] for a given format.
//
// Format is case-insensitive.
//
// [DecoderRegistry] returns an error if no [Decoder] is registered for the format.
type DecoderRegistry interface {
Decoder(format string) (Decoder, error)
}
// CodecRegistry combines [EncoderRegistry] and [DecoderRegistry] interfaces.
type CodecRegistry interface {
EncoderRegistry
DecoderRegistry
}
// WithEncoderRegistry sets a custom [EncoderRegistry].
func WithEncoderRegistry(r EncoderRegistry) Option {
return optionFunc(func(v *Viper) {
if r == nil {
return
}
v.encoderRegistry = r
})
}
// WithDecoderRegistry sets a custom [DecoderRegistry].
func WithDecoderRegistry(r DecoderRegistry) Option {
return optionFunc(func(v *Viper) {
if r == nil {
return
}
v.decoderRegistry = r
})
}
// WithCodecRegistry sets a custom [EncoderRegistry] and [DecoderRegistry].
func WithCodecRegistry(r CodecRegistry) Option {
return optionFunc(func(v *Viper) {
if r == nil {
return
}
v.encoderRegistry = r
v.decoderRegistry = r
})
}
// DefaultCodecRegistry is a simple implementation of [CodecRegistry] that allows registering custom [Codec]s.
type DefaultCodecRegistry struct {
codecs map[string]Codec
mu sync.RWMutex
once sync.Once
}
// NewCodecRegistry returns a new [CodecRegistry], ready to accept custom [Codec]s.
func NewCodecRegistry() *DefaultCodecRegistry {
r := &DefaultCodecRegistry{}
r.init()
return r
}
func (r *DefaultCodecRegistry) init() {
r.once.Do(func() {
r.codecs = map[string]Codec{}
})
}
// RegisterCodec registers a custom [Codec].
//
// Format is case-insensitive.
func (r *DefaultCodecRegistry) RegisterCodec(format string, codec Codec) error {
r.init()
r.mu.Lock()
defer r.mu.Unlock()
r.codecs[strings.ToLower(format)] = codec
return nil
}
// Encoder implements the [EncoderRegistry] interface.
//
// Format is case-insensitive.
func (r *DefaultCodecRegistry) Encoder(format string) (Encoder, error) {
encoder, ok := r.codec(format)
if !ok {
return nil, errors.New("encoder not found for this format")
}
return encoder, nil
}
// Decoder implements the [DecoderRegistry] interface.
//
// Format is case-insensitive.
func (r *DefaultCodecRegistry) Decoder(format string) (Decoder, error) {
decoder, ok := r.codec(format)
if !ok {
return nil, errors.New("decoder not found for this format")
}
return decoder, nil
}
func (r *DefaultCodecRegistry) codec(format string) (Codec, bool) {
r.mu.Lock()
defer r.mu.Unlock()
format = strings.ToLower(format)
if r.codecs != nil {
codec, ok := r.codecs[format]
if ok {
return codec, true
}
}
switch format {
case "yaml", "yml":
return yaml.Codec{}, true
case "json":
return json.Codec{}, true
case "toml":
return toml.Codec{}, true
case "dotenv", "env":
return &dotenv.Codec{}, true
}
return nil, false
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/logger.go | logger.go | package viper
import (
"context"
"log/slog"
)
// WithLogger sets a custom logger.
func WithLogger(l *slog.Logger) Option {
return optionFunc(func(v *Viper) {
v.logger = l
})
}
type discardHandler struct{}
func (n *discardHandler) Enabled(_ context.Context, _ slog.Level) bool {
return false
}
func (n *discardHandler) Handle(_ context.Context, _ slog.Record) error {
return nil
}
func (n *discardHandler) WithAttrs(_ []slog.Attr) slog.Handler {
return n
}
func (n *discardHandler) WithGroup(_ string) slog.Handler {
return n
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/flags_test.go | flags_test.go | package viper
import (
"testing"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBindFlagValueSet(t *testing.T) {
Reset()
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
testValues := map[string]*string{
"host": nil,
"port": nil,
"endpoint": nil,
}
mutatedTestValues := map[string]string{
"host": "localhost",
"port": "6060",
"endpoint": "/public",
}
for name := range testValues {
testValues[name] = flagSet.String(name, "", "test")
}
flagValueSet := pflagValueSet{flagSet}
err := BindFlagValues(flagValueSet)
require.NoError(t, err, "error binding flag set")
flagSet.VisitAll(func(flag *pflag.Flag) {
flag.Value.Set(mutatedTestValues[flag.Name])
flag.Changed = true
})
for name, expected := range mutatedTestValues {
assert.Equal(t, expected, Get(name))
}
}
func TestBindFlagValue(t *testing.T) {
testString := "testing"
testValue := newStringValue(testString, &testString)
flag := &pflag.Flag{
Name: "testflag",
Value: testValue,
Changed: false,
}
flagValue := pflagValue{flag}
BindFlagValue("testvalue", flagValue)
assert.Equal(t, testString, Get("testvalue"))
flag.Value.Set("testing_mutate")
flag.Changed = true // hack for pflag usage
assert.Equal(t, "testing_mutate", Get("testvalue"))
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/util_test.go | util_test.go | // Copyright © 2016 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Viper is a application configuration system.
// It believes that applications can be configured a variety of ways
// via flags, ENVIRONMENT variables, configuration files retrieved
// from the file system, or a remote key/value store.
package viper
import (
"log/slog"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCopyAndInsensitiviseMap(t *testing.T) {
var (
given = map[string]any{
"Foo": 32,
"Bar": map[any]any{
"ABc": "A",
"cDE": "B",
},
}
expected = map[string]any{
"foo": 32,
"bar": map[string]any{
"abc": "A",
"cde": "B",
},
}
)
got := copyAndInsensitiviseMap(given)
assert.Equal(t, expected, got)
_, ok := given["foo"]
assert.False(t, ok)
_, ok = given["bar"]
assert.False(t, ok)
m := given["Bar"].(map[any]any)
_, ok = m["ABc"]
assert.True(t, ok)
}
func TestAbsPathify(t *testing.T) {
skipWindows(t)
home := userHomeDir()
homer := filepath.Join(home, "homer")
wd, _ := os.Getwd()
t.Setenv("HOMER_ABSOLUTE_PATH", homer)
t.Setenv("VAR_WITH_RELATIVE_PATH", "relative")
tests := []struct {
input string
output string
}{
{"", wd},
{"sub", filepath.Join(wd, "sub")},
{"./", wd},
{"./sub", filepath.Join(wd, "sub")},
{"$HOME", home},
{"$HOME/", home},
{"$HOME/sub", filepath.Join(home, "sub")},
{"$HOMER_ABSOLUTE_PATH", homer},
{"$HOMER_ABSOLUTE_PATH/", homer},
{"$HOMER_ABSOLUTE_PATH/sub", filepath.Join(homer, "sub")},
{"$VAR_WITH_RELATIVE_PATH", filepath.Join(wd, "relative")},
{"$VAR_WITH_RELATIVE_PATH/", filepath.Join(wd, "relative")},
{"$VAR_WITH_RELATIVE_PATH/sub", filepath.Join(wd, "relative", "sub")},
}
for _, test := range tests {
got := absPathify(slog.Default(), test.input)
assert.Equal(t, test.output, got)
}
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/remote/remote.go | remote/remote.go | // Copyright © 2015 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package remote integrates the remote features of Viper.
package remote
import (
"bytes"
"io"
"os"
"strings"
crypt "github.com/sagikazarmark/crypt/config"
"github.com/spf13/viper"
)
type remoteConfigProvider struct{}
func (rc remoteConfigProvider) Get(rp viper.RemoteProvider) (io.Reader, error) {
cm, err := getConfigManager(rp)
if err != nil {
return nil, err
}
b, err := cm.Get(rp.Path())
if err != nil {
return nil, err
}
return bytes.NewReader(b), nil
}
func (rc remoteConfigProvider) Watch(rp viper.RemoteProvider) (io.Reader, error) {
cm, err := getConfigManager(rp)
if err != nil {
return nil, err
}
resp, err := cm.Get(rp.Path())
if err != nil {
return nil, err
}
return bytes.NewReader(resp), nil
}
func (rc remoteConfigProvider) WatchChannel(rp viper.RemoteProvider) (<-chan *viper.RemoteResponse, chan bool) {
cm, err := getConfigManager(rp)
if err != nil {
return nil, nil
}
quit := make(chan bool)
quitwc := make(chan bool)
viperResponsCh := make(chan *viper.RemoteResponse)
cryptoResponseCh := cm.Watch(rp.Path(), quit)
// need this function to convert the Channel response form crypt.Response to viper.Response
go func(cr <-chan *crypt.Response, vr chan<- *viper.RemoteResponse, quitwc <-chan bool, quit chan<- bool) {
for {
select {
case <-quitwc:
quit <- true
return
case resp := <-cr:
vr <- &viper.RemoteResponse{
Error: resp.Error,
Value: resp.Value,
}
}
}
}(cryptoResponseCh, viperResponsCh, quitwc, quit)
return viperResponsCh, quitwc
}
func getConfigManager(rp viper.RemoteProvider) (crypt.ConfigManager, error) {
var cm crypt.ConfigManager
var err error
endpoints := strings.Split(rp.Endpoint(), ";")
if rp.SecretKeyring() != "" {
var kr *os.File
kr, err = os.Open(rp.SecretKeyring())
if err != nil {
return nil, err
}
defer kr.Close()
switch rp.Provider() {
case "etcd":
cm, err = crypt.NewEtcdConfigManager(endpoints, kr)
case "etcd3":
cm, err = crypt.NewEtcdV3ConfigManager(endpoints, kr)
case "firestore":
cm, err = crypt.NewFirestoreConfigManager(endpoints, kr)
case "nats":
cm, err = crypt.NewNatsConfigManager(endpoints, kr)
default:
cm, err = crypt.NewConsulConfigManager(endpoints, kr)
}
} else {
switch rp.Provider() {
case "etcd":
cm, err = crypt.NewStandardEtcdConfigManager(endpoints)
case "etcd3":
cm, err = crypt.NewStandardEtcdV3ConfigManager(endpoints)
case "firestore":
cm, err = crypt.NewStandardFirestoreConfigManager(endpoints)
case "nats":
cm, err = crypt.NewStandardNatsConfigManager(endpoints)
default:
cm, err = crypt.NewStandardConsulConfigManager(endpoints)
}
}
if err != nil {
return nil, err
}
return cm, nil
}
func init() {
viper.RemoteConfig = &remoteConfigProvider{}
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/json/codec_test.go | internal/encoding/json/codec_test.go | package json
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// encoded form of the data.
const encoded = `{
"key": "value",
"list": [
"item1",
"item2",
"item3"
],
"map": {
"key": "value"
},
"nested_map": {
"map": {
"key": "value",
"list": [
"item1",
"item2",
"item3"
]
}
}
}`
// data is Viper's internal representation.
var data = map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
"map": map[string]any{
"key": "value",
},
"nested_map": map[string]any{
"map": map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
},
},
}
func TestCodec_Encode(t *testing.T) {
codec := Codec{}
b, err := codec.Encode(data)
require.NoError(t, err)
assert.JSONEq(t, encoded, string(b))
}
func TestCodec_Decode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(encoded), v)
require.NoError(t, err)
assert.Equal(t, data, v)
})
t.Run("InvalidData", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(`invalid data`), v)
require.Error(t, err)
t.Logf("decoding failed as expected: %s", err)
})
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/json/codec.go | internal/encoding/json/codec.go | package json
import (
"encoding/json"
)
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for JSON encoding.
type Codec struct{}
// Encode encodes a map[string]any into a JSON byte slice.
func (Codec) Encode(v map[string]any) ([]byte, error) {
// TODO: expose prefix and indent in the Codec as setting?
return json.MarshalIndent(v, "", " ")
}
// Decode decodes a JSON byte slice into a map[string]any.
func (Codec) Decode(b []byte, v map[string]any) error {
return json.Unmarshal(b, &v)
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/dotenv/map_utils.go | internal/encoding/dotenv/map_utils.go | package dotenv
import (
"strings"
"github.com/spf13/cast"
)
// flattenAndMergeMap recursively flattens the given map into a new map
// Code is based on the function with the same name in the main package.
// TODO: move it to a common place.
func flattenAndMergeMap(shadow, m map[string]any, prefix, delimiter string) map[string]any {
if shadow != nil && prefix != "" && shadow[prefix] != nil {
// prefix is shadowed => nothing more to flatten
return shadow
}
if shadow == nil {
shadow = make(map[string]any)
}
var m2 map[string]any
if prefix != "" {
prefix += delimiter
}
for k, val := range m {
fullKey := prefix + k
switch val := val.(type) {
case map[string]any:
m2 = val
case map[any]any:
m2 = cast.ToStringMap(val)
default:
// immediate value
shadow[strings.ToLower(fullKey)] = val
continue
}
// recursively merge to shadow map
shadow = flattenAndMergeMap(shadow, m2, fullKey, delimiter)
}
return shadow
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/dotenv/codec_test.go | internal/encoding/dotenv/codec_test.go | package dotenv
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// original form of the data.
const original = `# key-value pair
KEY=value
`
// encoded form of the data.
const encoded = `KEY=value
`
// data is Viper's internal representation.
var data = map[string]any{
"KEY": "value",
}
func TestCodec_Encode(t *testing.T) {
codec := Codec{}
b, err := codec.Encode(data)
require.NoError(t, err)
assert.Equal(t, encoded, string(b))
}
func TestCodec_Decode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(original), v)
require.NoError(t, err)
assert.Equal(t, data, v)
})
t.Run("InvalidData", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(`invalid data`), v)
require.Error(t, err)
t.Logf("decoding failed as expected: %s", err)
})
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/dotenv/codec.go | internal/encoding/dotenv/codec.go | package dotenv
import (
"bytes"
"fmt"
"sort"
"strings"
"github.com/subosito/gotenv"
)
const keyDelimiter = "_"
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for encoding data containing environment variables
// (commonly called as dotenv format).
type Codec struct{}
// Encode encodes a map[string]any into a dotenv byte slice.
func (Codec) Encode(v map[string]any) ([]byte, error) {
flattened := map[string]any{}
flattened = flattenAndMergeMap(flattened, v, "", keyDelimiter)
keys := make([]string, 0, len(flattened))
for key := range flattened {
keys = append(keys, key)
}
sort.Strings(keys)
var buf bytes.Buffer
for _, key := range keys {
_, err := buf.WriteString(fmt.Sprintf("%v=%v\n", strings.ToUpper(key), flattened[key]))
if err != nil {
return nil, err
}
}
return buf.Bytes(), nil
}
// Decode decodes a dotenv byte slice into a map[string]any.
func (Codec) Decode(b []byte, v map[string]any) error {
var buf bytes.Buffer
_, err := buf.Write(b)
if err != nil {
return err
}
env, err := gotenv.StrictParse(&buf)
if err != nil {
return err
}
for key, value := range env {
v[key] = value
}
return nil
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/toml/codec_test.go | internal/encoding/toml/codec_test.go | package toml
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// original form of the data.
const original = `# key-value pair
key = "value"
list = ["item1", "item2", "item3"]
[map]
key = "value"
# nested
# map
[nested_map]
[nested_map.map]
key = "value"
list = [
"item1",
"item2",
"item3",
]
`
// encoded form of the data.
const encoded = `key = 'value'
list = ['item1', 'item2', 'item3']
[map]
key = 'value'
[nested_map]
[nested_map.map]
key = 'value'
list = ['item1', 'item2', 'item3']
`
// data is Viper's internal representation.
var data = map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
"map": map[string]any{
"key": "value",
},
"nested_map": map[string]any{
"map": map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
},
},
}
func TestCodec_Encode(t *testing.T) {
codec := Codec{}
b, err := codec.Encode(data)
require.NoError(t, err)
assert.Equal(t, encoded, string(b))
}
func TestCodec_Decode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(original), v)
require.NoError(t, err)
assert.Equal(t, data, v)
})
t.Run("InvalidData", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(`invalid data`), v)
require.Error(t, err)
t.Logf("decoding failed as expected: %s", err)
})
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/toml/codec.go | internal/encoding/toml/codec.go | package toml
import (
"github.com/pelletier/go-toml/v2"
)
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for TOML encoding.
type Codec struct{}
// Encode encodes a map[string]any into a TOML byte slice.
func (Codec) Encode(v map[string]any) ([]byte, error) {
return toml.Marshal(v)
}
// Decode decodes a TOML byte slice into a map[string]any.
func (Codec) Decode(b []byte, v map[string]any) error {
return toml.Unmarshal(b, &v)
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/yaml/codec_test.go | internal/encoding/yaml/codec_test.go | package yaml
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// original form of the data.
const original = `# key-value pair
key: value
list:
- item1
- item2
- item3
map:
key: value
# nested
# map
nested_map:
map:
key: value
list:
- item1
- item2
- item3
`
// encoded form of the data.
const encoded = `key: value
list:
- item1
- item2
- item3
map:
key: value
nested_map:
map:
key: value
list:
- item1
- item2
- item3
`
// decoded form of the data.
//
// In case of YAML it's slightly different from Viper's internal representation
// (e.g. map is decoded into a map with interface key).
var decoded = map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
"map": map[string]any{
"key": "value",
},
"nested_map": map[string]any{
"map": map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
},
},
}
// data is Viper's internal representation.
var data = map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
"map": map[string]any{
"key": "value",
},
"nested_map": map[string]any{
"map": map[string]any{
"key": "value",
"list": []any{
"item1",
"item2",
"item3",
},
},
},
}
func TestCodec_Encode(t *testing.T) {
codec := Codec{}
b, err := codec.Encode(data)
require.NoError(t, err)
assert.Equal(t, encoded, string(b))
}
func TestCodec_Decode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(original), v)
require.NoError(t, err)
assert.Equal(t, decoded, v)
})
t.Run("InvalidData", func(t *testing.T) {
codec := Codec{}
v := map[string]any{}
err := codec.Decode([]byte(`invalid data`), v)
require.Error(t, err)
t.Logf("decoding failed as expected: %s", err)
})
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/encoding/yaml/codec.go | internal/encoding/yaml/codec.go | package yaml
import "go.yaml.in/yaml/v3"
// Codec implements the encoding.Encoder and encoding.Decoder interfaces for YAML encoding.
type Codec struct{}
// Encode encodes a map[string]any into a YAML byte slice.
func (Codec) Encode(v map[string]any) ([]byte, error) {
return yaml.Marshal(v)
}
// Decode decodes a YAML byte slice into a map[string]any.
func (Codec) Decode(b []byte, v map[string]any) error {
return yaml.Unmarshal(b, &v)
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/features/finder.go | internal/features/finder.go | //go:build viper_finder
package features
// Finder is a feature flag for enabling/disabling the config finder.
const Finder = true
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/features/bind_struct.go | internal/features/bind_struct.go | //go:build viper_bind_struct
package features
// BindStruct is a feature flag for enabling/disabling the config binding to structs.
const BindStruct = true
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/features/finder_default.go | internal/features/finder_default.go | //go:build !viper_finder
package features
// Finder is a feature flag for enabling/disabling the config finder.
const Finder = false
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/features/bind_struct_default.go | internal/features/bind_struct_default.go | //go:build !viper_bind_struct
package features
// BindStruct is a feature flag for enabling/disabling the config binding to structs.
const BindStruct = false
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
spf13/viper | https://github.com/spf13/viper/blob/528f7416c4b56a4948673984b190bf8713f0c3c4/internal/testutil/filepath.go | internal/testutil/filepath.go | package testutil
import (
"path/filepath"
"testing"
)
// AbsFilePath calls filepath.Abs on path.
func AbsFilePath(t *testing.T, path string) string {
t.Helper()
s, err := filepath.Abs(path)
if err != nil {
t.Fatal(err)
}
return s
}
| go | MIT | 528f7416c4b56a4948673984b190bf8713f0c3c4 | 2026-01-07T08:36:47.476836Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/mockgen.go | mockgen.go | // 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 main
//go:generate go install golang.org/x/tools/cmd/goimports@v0.17.0
//go:generate go run github.com/unknwon/go-mockgen/cmd/go-mockgen@v0.0.0-20251002032800-a9a94b119e3b
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/gogs.go | gogs.go | //go:build go1.18
// Copyright 2014 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.
// Gogs is a painless self-hosted Git Service.
package main
import (
"os"
"github.com/urfave/cli"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/cmd"
"gogs.io/gogs/internal/conf"
)
func init() {
conf.App.Version = "0.14.0+dev"
}
func main() {
app := cli.NewApp()
app.Name = "Gogs"
app.Usage = "A painless self-hosted Git service"
app.Version = conf.App.Version
app.Commands = []cli.Command{
cmd.Web,
cmd.Serv,
cmd.Hook,
cmd.Cert,
cmd.Admin,
cmd.Import,
cmd.Backup,
cmd.Restore,
}
if err := app.Run(os.Args); err != nil {
log.Fatal("Failed to start application: %v", err)
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/public/embed.go | public/embed.go | // 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 public
import (
"embed"
)
//go:embed assets/* css/* img/* js/* plugins/*
var Files embed.FS
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/process/manager.go | internal/process/manager.go | // Copyright 2014 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 process
import (
"bytes"
"errors"
"fmt"
"os/exec"
"sync"
"time"
log "unknwon.dev/clog/v2"
)
var ErrExecTimeout = errors.New("process execution timeout")
const defaultTimeout = 60 * time.Second
// Process represents a running process calls shell command.
type Process struct {
PID int64
Description string
Start time.Time
Cmd *exec.Cmd
}
type pidCounter struct {
sync.Mutex
// The current number of pid, initial is 0, and increase 1 every time it's been used.
pid int64
}
func (c *pidCounter) PID() int64 {
c.pid++
return c.pid
}
var (
counter = new(pidCounter)
Processes []*Process
)
// Add adds a process to global list and returns its PID.
func Add(desc string, cmd *exec.Cmd) int64 {
counter.Lock()
defer counter.Unlock()
pid := counter.PID()
Processes = append(Processes, &Process{
PID: pid,
Description: desc,
Start: time.Now(),
Cmd: cmd,
})
return pid
}
// Remove removes a process from global list.
// It returns true if the process is found and removed by given pid.
func Remove(pid int64) bool {
counter.Lock()
defer counter.Unlock()
for i := range Processes {
if Processes[i].PID == pid {
Processes = append(Processes[:i], Processes[i+1:]...)
return true
}
}
return false
}
// Exec starts executing a shell command in given path, it tracks corresponding process and timeout.
func ExecDir(timeout time.Duration, dir, desc, cmdName string, args ...string) (string, string, error) {
if timeout == -1 {
timeout = defaultTimeout
}
bufOut := new(bytes.Buffer)
bufErr := new(bytes.Buffer)
cmd := exec.Command(cmdName, args...)
cmd.Dir = dir
cmd.Stdout = bufOut
cmd.Stderr = bufErr
if err := cmd.Start(); err != nil {
return "", err.Error(), err
}
pid := Add(desc, cmd)
done := make(chan error)
go func() {
done <- cmd.Wait()
}()
var err error
select {
case <-time.After(timeout):
if errKill := Kill(pid); errKill != nil {
log.Error("Failed to kill timeout process [pid: %d, desc: %s]: %v", pid, desc, errKill)
}
<-done
return "", ErrExecTimeout.Error(), ErrExecTimeout
case err = <-done:
}
Remove(pid)
return bufOut.String(), bufErr.String(), err
}
// Exec starts executing a shell command, it tracks corresponding process and timeout.
func ExecTimeout(timeout time.Duration, desc, cmdName string, args ...string) (string, string, error) {
return ExecDir(timeout, "", desc, cmdName, args...)
}
// Exec starts executing a shell command, it tracks corresponding its process and use default timeout.
func Exec(desc, cmdName string, args ...string) (string, string, error) {
return ExecDir(-1, "", desc, cmdName, args...)
}
// Kill kills and removes a process from global list.
func Kill(pid int64) error {
for _, proc := range Processes {
if proc.PID == pid {
if proc.Cmd != nil && proc.Cmd.Process != nil &&
proc.Cmd.ProcessState != nil && !proc.Cmd.ProcessState.Exited() {
if err := proc.Cmd.Process.Kill(); err != nil {
return fmt.Errorf("fail to kill process [pid: %d, desc: %s]: %v", proc.PID, proc.Description, err)
}
}
Remove(pid)
return nil
}
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/auth.go | internal/auth/auth.go | // Copyright 2014 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 auth
import (
"fmt"
"github.com/pkg/errors"
"gogs.io/gogs/internal/errutil"
)
type Type int
// Note: New type must append to the end of list to maintain backward compatibility.
const (
None Type = iota
Plain // 1
LDAP // 2
SMTP // 3
PAM // 4
DLDAP // 5
GitHub // 6
Mock Type = 999
)
// Name returns the human-readable name for given authentication type.
func Name(typ Type) string {
return map[Type]string{
LDAP: "LDAP (via BindDN)",
DLDAP: "LDAP (simple auth)", // Via direct bind
SMTP: "SMTP",
PAM: "PAM",
GitHub: "GitHub",
}[typ]
}
var _ errutil.NotFound = (*ErrBadCredentials)(nil)
type ErrBadCredentials struct {
Args errutil.Args
}
// IsErrBadCredentials returns true if the underlying error has the type
// ErrBadCredentials.
func IsErrBadCredentials(err error) bool {
return errors.As(err, &ErrBadCredentials{})
}
func (err ErrBadCredentials) Error() string {
return fmt.Sprintf("bad credentials: %v", err.Args)
}
func (ErrBadCredentials) NotFound() bool {
return true
}
// ExternalAccount contains queried information returned by an authenticate provider
// for an external account.
type ExternalAccount struct {
// REQUIRED: The login to be used for authenticating against the provider.
Login string
// REQUIRED: The username of the account.
Name string
// The full name of the account.
FullName string
// The email address of the account.
Email string
// The location of the account.
Location string
// The website of the account.
Website string
// Whether the user should be prompted as a site admin.
Admin bool
}
// Provider defines an authenticate provider which provides ability to authentication against
// an external identity provider and query external account information.
type Provider interface {
// Authenticate performs authentication against an external identity provider
// using given credentials and returns queried information of the external account.
Authenticate(login, password string) (*ExternalAccount, error)
// Config returns the underlying configuration of the authenticate provider.
Config() any
// HasTLS returns true if the authenticate provider supports TLS.
HasTLS() bool
// UseTLS returns true if the authenticate provider is configured to use TLS.
UseTLS() bool
// SkipTLSVerify returns true if the authenticate provider is configured to skip TLS verify.
SkipTLSVerify() bool
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/ldap/config.go | internal/auth/ldap/config.go | // Copyright 2014 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 ldap provide functions & structure to query a LDAP ldap directory.
// For now, it's mainly tested again an MS Active Directory service, see README.md for more information.
package ldap
import (
"crypto/tls"
"fmt"
"strings"
"github.com/go-ldap/ldap/v3"
log "unknwon.dev/clog/v2"
)
// SecurityProtocol is the security protocol when the authenticate provider talks to LDAP directory.
type SecurityProtocol int
// ⚠️ WARNING: new type must be added at the end of list to maintain compatibility.
const (
SecurityProtocolUnencrypted SecurityProtocol = iota
SecurityProtocolLDAPS
SecurityProtocolStartTLS
)
// SecurityProtocolName returns the human-readable name for given security protocol.
func SecurityProtocolName(protocol SecurityProtocol) string {
return map[SecurityProtocol]string{
SecurityProtocolUnencrypted: "Unencrypted",
SecurityProtocolLDAPS: "LDAPS",
SecurityProtocolStartTLS: "StartTLS",
}[protocol]
}
// Config contains configuration for LDAP authentication.
//
// ⚠️ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
type Config struct {
Host string // LDAP host
Port int // Port number
SecurityProtocol SecurityProtocol
SkipVerify bool
BindDN string `ini:"bind_dn,omitempty"` // DN to bind with
BindPassword string `ini:",omitempty"` // Bind DN password
UserBase string `ini:",omitempty"` // Base search path for users
UserDN string `ini:"user_dn,omitempty"` // Template for the DN of the user for simple auth
AttributeUsername string // Username attribute
AttributeName string // First name attribute
AttributeSurname string // Surname attribute
AttributeMail string // Email attribute
AttributesInBind bool // Fetch attributes in bind context (not user)
Filter string // Query filter to validate entry
AdminFilter string // Query filter to check if user is admin
GroupEnabled bool // Whether the group checking is enabled
GroupDN string `ini:"group_dn"` // Group search base
GroupFilter string // Group name filter
GroupMemberUID string `ini:"group_member_uid"` // Group Attribute containing array of UserUID
UserUID string `ini:"user_uid"` // User Attribute listed in group
}
func (c *Config) SecurityProtocolName() string {
return SecurityProtocolName(c.SecurityProtocol)
}
func (c *Config) sanitizedUserQuery(username string) (string, bool) {
// See http://tools.ietf.org/search/rfc4515
badCharacters := "\x00()*\\"
if strings.ContainsAny(username, badCharacters) {
log.Trace("LDAP: Username contains invalid query characters: %s", username)
return "", false
}
return strings.ReplaceAll(c.Filter, "%s", username), true
}
func (c *Config) sanitizedUserDN(username string) (string, bool) {
// See http://tools.ietf.org/search/rfc4514: "special characters"
badCharacters := "\x00()*\\,='\"#+;<>"
if strings.ContainsAny(username, badCharacters) || strings.HasPrefix(username, " ") || strings.HasSuffix(username, " ") {
log.Trace("LDAP: Username contains invalid query characters: %s", username)
return "", false
}
return strings.ReplaceAll(c.UserDN, "%s", username), true
}
func (*Config) sanitizedGroupFilter(group string) (string, bool) {
// See http://tools.ietf.org/search/rfc4515
badCharacters := "\x00*\\"
if strings.ContainsAny(group, badCharacters) {
log.Trace("LDAP: Group filter invalid query characters: %s", group)
return "", false
}
return group, true
}
func (*Config) sanitizedGroupDN(groupDn string) (string, bool) {
// See http://tools.ietf.org/search/rfc4514: "special characters"
badCharacters := "\x00()*\\'\"#+;<>"
if strings.ContainsAny(groupDn, badCharacters) || strings.HasPrefix(groupDn, " ") || strings.HasSuffix(groupDn, " ") {
log.Trace("LDAP: Group DN contains invalid query characters: %s", groupDn)
return "", false
}
return groupDn, true
}
func (c *Config) findUserDN(l *ldap.Conn, name string) (string, bool) {
log.Trace("Search for LDAP user: %s", name)
if len(c.BindDN) > 0 && len(c.BindPassword) > 0 {
// Replace placeholders with username
bindDN := strings.ReplaceAll(c.BindDN, "%s", name)
err := l.Bind(bindDN, c.BindPassword)
if err != nil {
log.Trace("LDAP: Failed to bind as BindDN '%s': %v", bindDN, err)
return "", false
}
log.Trace("LDAP: Bound as BindDN: %s", bindDN)
} else {
log.Trace("LDAP: Proceeding with anonymous LDAP search")
}
// A search for the user.
userFilter, ok := c.sanitizedUserQuery(name)
if !ok {
return "", false
}
log.Trace("LDAP: Searching for DN using filter %q and base %q", userFilter, c.UserBase)
search := ldap.NewSearchRequest(
c.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
false, userFilter, []string{}, nil)
// Ensure we found a user
sr, err := l.Search(search)
if err != nil || len(sr.Entries) < 1 {
log.Trace("LDAP: Failed to search using filter %q: %v", userFilter, err)
return "", false
} else if len(sr.Entries) > 1 {
log.Trace("LDAP: Filter %q returned more than one user", userFilter)
return "", false
}
userDN := sr.Entries[0].DN
if userDN == "" {
log.Error("LDAP: Search was successful, but found no DN!")
return "", false
}
return userDN, true
}
func dial(ls *Config) (*ldap.Conn, error) {
log.Trace("LDAP: Dialing with security protocol '%v' without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
tlsCfg := &tls.Config{
ServerName: ls.Host,
InsecureSkipVerify: ls.SkipVerify,
}
if ls.SecurityProtocol == SecurityProtocolLDAPS {
return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
}
conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
if err != nil {
return nil, fmt.Errorf("dial: %v", err)
}
if ls.SecurityProtocol == SecurityProtocolStartTLS {
if err = conn.StartTLS(tlsCfg); err != nil {
conn.Close()
return nil, fmt.Errorf("StartTLS: %v", err)
}
}
return conn, nil
}
func bindUser(l *ldap.Conn, userDN, passwd string) error {
log.Trace("Binding with userDN: %s", userDN)
err := l.Bind(userDN, passwd)
if err != nil {
log.Trace("LDAP authentication failed for '%s': %v", userDN, err)
return err
}
log.Trace("Bound successfully with userDN: %s", userDN)
return err
}
// searchEntry searches an LDAP source if an entry (name, passwd) is valid and in the specific filter.
func (c *Config) searchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
// See https://tools.ietf.org/search/rfc4513#section-5.1.2
if passwd == "" {
log.Trace("authentication failed for '%s' with empty password", name)
return "", "", "", "", false, false
}
l, err := dial(c)
if err != nil {
log.Error("LDAP connect failed for '%s': %v", c.Host, err)
return "", "", "", "", false, false
}
defer l.Close()
var userDN string
if directBind {
log.Trace("LDAP will bind directly via UserDN template: %s", c.UserDN)
var ok bool
userDN, ok = c.sanitizedUserDN(name)
if !ok {
return "", "", "", "", false, false
}
} else {
log.Trace("LDAP will use BindDN")
var found bool
userDN, found = c.findUserDN(l, name)
if !found {
return "", "", "", "", false, false
}
}
if directBind || !c.AttributesInBind {
// binds user (checking password) before looking-up attributes in user context
err = bindUser(l, userDN, passwd)
if err != nil {
return "", "", "", "", false, false
}
}
userFilter, ok := c.sanitizedUserQuery(name)
if !ok {
return "", "", "", "", false, false
}
log.Trace("Fetching attributes %q, %q, %q, %q, %q with user filter %q and user DN %q",
c.AttributeUsername, c.AttributeName, c.AttributeSurname, c.AttributeMail, c.UserUID, userFilter, userDN)
search := ldap.NewSearchRequest(
userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
[]string{c.AttributeUsername, c.AttributeName, c.AttributeSurname, c.AttributeMail, c.UserUID},
nil)
sr, err := l.Search(search)
if err != nil {
log.Error("LDAP: User search failed: %v", err)
return "", "", "", "", false, false
} else if len(sr.Entries) < 1 {
if directBind {
log.Trace("LDAP: User filter inhibited user login")
} else {
log.Trace("LDAP: User search failed: 0 entries")
}
return "", "", "", "", false, false
}
username := sr.Entries[0].GetAttributeValue(c.AttributeUsername)
firstname := sr.Entries[0].GetAttributeValue(c.AttributeName)
surname := sr.Entries[0].GetAttributeValue(c.AttributeSurname)
mail := sr.Entries[0].GetAttributeValue(c.AttributeMail)
uid := sr.Entries[0].GetAttributeValue(c.UserUID)
// Check group membership
if c.GroupEnabled {
groupFilter, ok := c.sanitizedGroupFilter(c.GroupFilter)
if !ok {
return "", "", "", "", false, false
}
groupDN, ok := c.sanitizedGroupDN(c.GroupDN)
if !ok {
return "", "", "", "", false, false
}
log.Trace("LDAP: Fetching groups '%v' with filter '%s' and base '%s'", c.GroupMemberUID, groupFilter, groupDN)
groupSearch := ldap.NewSearchRequest(
groupDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, groupFilter,
[]string{c.GroupMemberUID},
nil)
srg, err := l.Search(groupSearch)
if err != nil {
log.Error("LDAP: Group search failed: %v", err)
return "", "", "", "", false, false
} else if len(srg.Entries) < 1 {
log.Trace("LDAP: Group search returned no entries")
return "", "", "", "", false, false
}
isMember := false
if c.UserUID == "dn" {
for _, group := range srg.Entries {
for _, member := range group.GetAttributeValues(c.GroupMemberUID) {
if member == sr.Entries[0].DN {
isMember = true
}
}
}
} else {
for _, group := range srg.Entries {
for _, member := range group.GetAttributeValues(c.GroupMemberUID) {
if member == uid {
isMember = true
}
}
}
}
if !isMember {
log.Trace("LDAP: Group membership test failed [username: %s, group_member_uid: %s, user_uid: %s", username, c.GroupMemberUID, uid)
return "", "", "", "", false, false
}
}
isAdmin := false
if len(c.AdminFilter) > 0 {
log.Trace("Checking admin with filter '%s' and base '%s'", c.AdminFilter, userDN)
search = ldap.NewSearchRequest(
userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, c.AdminFilter,
[]string{c.AttributeName},
nil)
sr, err = l.Search(search)
if err != nil {
log.Error("LDAP: Admin search failed: %v", err)
} else if len(sr.Entries) < 1 {
log.Trace("LDAP: Admin search returned no entries")
} else {
isAdmin = true
}
}
if !directBind && c.AttributesInBind {
// binds user (checking password) after looking-up attributes in BindDN context
err = bindUser(l, userDN, passwd)
if err != nil {
return "", "", "", "", false, false
}
}
return username, firstname, surname, mail, isAdmin, true
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/ldap/provider.go | internal/auth/ldap/provider.go | // Copyright 2020 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 ldap
import (
"fmt"
"gogs.io/gogs/internal/auth"
)
// Provider contains configuration of an LDAP authentication provider.
type Provider struct {
directBind bool
config *Config
}
// NewProvider creates a new LDAP authentication provider.
func NewProvider(directBind bool, cfg *Config) auth.Provider {
return &Provider{
directBind: directBind,
config: cfg,
}
}
// Authenticate queries if login/password is valid against the LDAP directory pool,
// and returns queried information when succeeded.
func (p *Provider) Authenticate(login, password string) (*auth.ExternalAccount, error) {
username, fn, sn, email, isAdmin, succeed := p.config.searchEntry(login, password, p.directBind)
if !succeed {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
if username == "" {
username = login
}
if email == "" {
email = fmt.Sprintf("%s@localhost", username)
}
composeFullName := func(firstname, surname, username string) string {
switch {
case firstname == "" && surname == "":
return username
case firstname == "":
return surname
case surname == "":
return firstname
default:
return firstname + " " + surname
}
}
return &auth.ExternalAccount{
Login: login,
Name: username,
FullName: composeFullName(fn, sn, username),
Email: email,
Admin: isAdmin,
}, nil
}
func (p *Provider) Config() any {
return p.config
}
func (p *Provider) HasTLS() bool {
return p.config.SecurityProtocol > SecurityProtocolUnencrypted
}
func (p *Provider) UseTLS() bool {
return p.config.SecurityProtocol > SecurityProtocolUnencrypted
}
func (p *Provider) SkipTLSVerify() bool {
return p.config.SkipVerify
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/pam/config.go | internal/auth/pam/config.go | // Copyright 2014 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 pam
// Config contains configuration for PAM authentication.
//
// ⚠️ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
type Config struct {
// The name of the PAM service, e.g. system-auth.
ServiceName string
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/pam/pam.go | internal/auth/pam/pam.go | //go:build pam
// Copyright 2014 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 pam
import (
"github.com/msteinert/pam"
"github.com/pkg/errors"
)
func (c *Config) doAuth(login, password string) error {
t, err := pam.StartFunc(c.ServiceName, login, func(s pam.Style, msg string) (string, error) {
switch s {
case pam.PromptEchoOff:
return password, nil
case pam.PromptEchoOn, pam.ErrorMsg, pam.TextInfo:
return "", nil
}
return "", errors.Errorf("unrecognized PAM message style: %v - %s", s, msg)
})
if err != nil {
return err
}
err = t.Authenticate(0)
if err != nil {
return err
}
return t.AcctMgmt(0)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/pam/pam_stub.go | internal/auth/pam/pam_stub.go | //go:build !pam
// Copyright 2014 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 pam
import (
"github.com/pkg/errors"
)
func (*Config) doAuth(_, _ string) error {
return errors.New("PAM not supported")
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/pam/provider.go | internal/auth/pam/provider.go | // Copyright 2020 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 pam
import (
"strings"
"gogs.io/gogs/internal/auth"
)
// Provider contains configuration of a PAM authentication provider.
type Provider struct {
config *Config
}
// NewProvider creates a new PAM authentication provider.
func NewProvider(cfg *Config) auth.Provider {
return &Provider{
config: cfg,
}
}
func (p *Provider) Authenticate(login, password string) (*auth.ExternalAccount, error) {
err := p.config.doAuth(login, password)
if err != nil {
if strings.Contains(err.Error(), "Authentication failure") {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
return nil, err
}
return &auth.ExternalAccount{
Login: login,
Name: login,
}, nil
}
func (p *Provider) Config() any {
return p.config
}
func (*Provider) HasTLS() bool {
return false
}
func (*Provider) UseTLS() bool {
return false
}
func (*Provider) SkipTLSVerify() bool {
return false
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/github/config.go | internal/auth/github/config.go | // Copyright 2020 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 github
import (
"context"
"crypto/tls"
"net/http"
"strings"
"github.com/google/go-github/github"
"github.com/pkg/errors"
)
// Config contains configuration for GitHub authentication.
//
// ⚠️ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
type Config struct {
// the GitHub service endpoint, e.g. https://api.github.com/.
APIEndpoint string
SkipVerify bool
}
func (c *Config) doAuth(login, password string) (fullname, email, location, website string, err error) {
tp := github.BasicAuthTransport{
Username: strings.TrimSpace(login),
Password: strings.TrimSpace(password),
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: c.SkipVerify},
},
}
client, err := github.NewEnterpriseClient(c.APIEndpoint, c.APIEndpoint, tp.Client())
if err != nil {
return "", "", "", "", errors.Wrap(err, "create new client")
}
user, _, err := client.Users.Get(context.Background(), "")
if err != nil {
return "", "", "", "", errors.Wrap(err, "get user info")
}
if user.Name != nil {
fullname = *user.Name
}
if user.Email != nil {
email = *user.Email
} else {
email = login + "+github@local"
}
if user.Location != nil {
location = strings.ToUpper(*user.Location)
}
if user.HTMLURL != nil {
website = strings.ToLower(*user.HTMLURL)
}
return fullname, email, location, website, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/github/provider.go | internal/auth/github/provider.go | // Copyright 2020 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 github
import (
"strings"
"gogs.io/gogs/internal/auth"
)
// Provider contains configuration of a PAM authentication provider.
type Provider struct {
config *Config
}
// NewProvider creates a new PAM authentication provider.
func NewProvider(cfg *Config) auth.Provider {
return &Provider{
config: cfg,
}
}
func (p *Provider) Authenticate(login, password string) (*auth.ExternalAccount, error) {
fullname, email, website, location, err := p.config.doAuth(login, password)
if err != nil {
if strings.Contains(err.Error(), "401") {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
return nil, err
}
return &auth.ExternalAccount{
Login: login,
Name: login,
FullName: fullname,
Email: email,
Location: location,
Website: website,
}, nil
}
func (p *Provider) Config() any {
return p.config
}
func (*Provider) HasTLS() bool {
return true
}
func (*Provider) UseTLS() bool {
return true
}
func (p *Provider) SkipTLSVerify() bool {
return p.config.SkipVerify
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/smtp/config.go | internal/auth/smtp/config.go | // Copyright 2020 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 smtp
import (
"crypto/tls"
"fmt"
"net/smtp"
"github.com/pkg/errors"
)
// Config contains configuration for SMTP authentication.
//
// ⚠️ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
type Config struct {
Auth string
Host string
Port int
AllowedDomains string
TLS bool `ini:"tls"`
SkipVerify bool
}
func (c *Config) doAuth(auth smtp.Auth) error {
client, err := smtp.Dial(fmt.Sprintf("%s:%d", c.Host, c.Port))
if err != nil {
return err
}
defer client.Close()
if err = client.Hello("gogs"); err != nil {
return err
}
if c.TLS {
if ok, _ := client.Extension("STARTTLS"); ok {
if err = client.StartTLS(&tls.Config{
InsecureSkipVerify: c.SkipVerify,
ServerName: c.Host,
}); err != nil {
return err
}
} else {
return errors.New("SMTP server does not support TLS")
}
}
if ok, _ := client.Extension("AUTH"); ok {
if err = client.Auth(auth); err != nil {
return err
}
return nil
}
return errors.New("unsupported SMTP authentication method")
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/auth/smtp/provider.go | internal/auth/smtp/provider.go | // Copyright 2020 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 smtp
import (
"net/smtp"
"net/textproto"
"strings"
"github.com/pkg/errors"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/auth"
)
// Provider contains configuration of an SMTP authentication provider.
type Provider struct {
config *Config
}
// NewProvider creates a new SMTP authentication provider.
func NewProvider(cfg *Config) auth.Provider {
return &Provider{
config: cfg,
}
}
// Authenticate queries if login/password is valid against the SMTP server,
// and returns queried information when succeeded.
func (p *Provider) Authenticate(login, password string) (*auth.ExternalAccount, error) {
// Verify allowed domains
if p.config.AllowedDomains != "" {
fields := strings.SplitN(login, "@", 3)
if len(fields) != 2 {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
domain := fields[1]
isAllowed := false
for _, allowed := range strings.Split(p.config.AllowedDomains, ",") {
if domain == allowed {
isAllowed = true
break
}
}
if !isAllowed {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
}
var smtpAuth smtp.Auth
switch p.config.Auth {
case Plain:
smtpAuth = smtp.PlainAuth("", login, password, p.config.Host)
case Login:
smtpAuth = &smtpLoginAuth{login, password}
default:
return nil, errors.Errorf("unsupported SMTP authentication type %q", p.config.Auth)
}
if err := p.config.doAuth(smtpAuth); err != nil {
log.Trace("SMTP: Authentication failed: %v", err)
// Check standard error format first, then fallback to the worse case.
tperr, ok := err.(*textproto.Error)
if (ok && tperr.Code == 535) ||
strings.Contains(err.Error(), "Username and Password not accepted") {
return nil, auth.ErrBadCredentials{Args: map[string]any{"login": login}}
}
return nil, err
}
username := login
// NOTE: It is not required to have "@" in `login` for a successful SMTP authentication.
idx := strings.Index(login, "@")
if idx > -1 {
username = login[:idx]
}
return &auth.ExternalAccount{
Login: login,
Name: username,
Email: login,
}, nil
}
func (p *Provider) Config() any {
return p.config
}
func (*Provider) HasTLS() bool {
return true
}
func (p *Provider) UseTLS() bool {
return p.config.TLS
}
func (p *Provider) SkipTLSVerify() bool {
return p.config.SkipVerify
}
const (
Plain = "PLAIN"
Login = "LOGIN"
)
var AuthTypes = []string{Plain, Login}
type smtpLoginAuth struct {
username, password string
}
func (auth *smtpLoginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte(auth.username), nil
}
func (auth *smtpLoginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(auth.username), nil
case "Password:":
return []byte(auth.password), nil
}
}
return nil, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/hook.go | internal/cmd/hook.go | // Copyright 2014 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 cmd
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/unknwon/com"
"github.com/urfave/cli"
log "unknwon.dev/clog/v2"
"github.com/gogs/git-module"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/httplib"
)
var (
Hook = cli.Command{
Name: "hook",
Usage: "Delegate commands to corresponding Git hooks",
Description: "All sub-commands should only be called by Git",
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
Subcommands: []cli.Command{
subcmdHookPreReceive,
subcmdHookUpadte,
subcmdHookPostReceive,
},
}
subcmdHookPreReceive = cli.Command{
Name: "pre-receive",
Usage: "Delegate pre-receive Git hook",
Description: "This command should only be called by Git",
Action: runHookPreReceive,
}
subcmdHookUpadte = cli.Command{
Name: "update",
Usage: "Delegate update Git hook",
Description: "This command should only be called by Git",
Action: runHookUpdate,
}
subcmdHookPostReceive = cli.Command{
Name: "post-receive",
Usage: "Delegate post-receive Git hook",
Description: "This command should only be called by Git",
Action: runHookPostReceive,
}
)
func runHookPreReceive(c *cli.Context) error {
if os.Getenv("SSH_ORIGINAL_COMMAND") == "" {
return nil
}
setup(c, "pre-receive.log", true)
isWiki := strings.Contains(os.Getenv(database.EnvRepoCustomHooksPath), ".wiki.git/")
buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
buf.Write(scanner.Bytes())
buf.WriteByte('\n')
if isWiki {
continue
}
fields := bytes.Fields(scanner.Bytes())
if len(fields) != 3 {
continue
}
oldCommitID := string(fields[0])
newCommitID := string(fields[1])
branchName := git.RefShortName(string(fields[2]))
// Branch protection
repoID := com.StrTo(os.Getenv(database.EnvRepoID)).MustInt64()
protectBranch, err := database.GetProtectBranchOfRepoByName(repoID, branchName)
if err != nil {
if database.IsErrBranchNotExist(err) {
continue
}
fail("Internal error", "GetProtectBranchOfRepoByName [repo_id: %d, branch: %s]: %v", repoID, branchName, err)
}
if !protectBranch.Protected {
continue
}
// Whitelist users can bypass require pull request check
bypassRequirePullRequest := false
// Check if user is in whitelist when enabled
userID := com.StrTo(os.Getenv(database.EnvAuthUserID)).MustInt64()
if protectBranch.EnableWhitelist {
if !database.IsUserInProtectBranchWhitelist(repoID, userID, branchName) {
fail(fmt.Sprintf("Branch '%s' is protected and you are not in the push whitelist", branchName), "")
}
bypassRequirePullRequest = true
}
// Check if branch allows direct push
if !bypassRequirePullRequest && protectBranch.RequirePullRequest {
fail(fmt.Sprintf("Branch '%s' is protected and commits must be merged through pull request", branchName), "")
}
// check and deletion
if newCommitID == git.EmptyID {
fail(fmt.Sprintf("Branch '%s' is protected from deletion", branchName), "")
}
// Check force push
output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).
RunInDir(database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName)))
if err != nil {
fail("Internal error", "Failed to detect force push: %v", err)
} else if len(output) > 0 {
fail(fmt.Sprintf("Branch '%s' is protected from force push", branchName), "")
}
}
customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "pre-receive")
if !com.IsFile(customHooksPath) {
return nil
}
var hookCmd *exec.Cmd
if conf.IsWindowsRuntime() {
hookCmd = exec.Command("bash.exe", "custom_hooks/pre-receive")
} else {
hookCmd = exec.Command(customHooksPath)
}
hookCmd.Dir = database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName))
hookCmd.Stdout = os.Stdout
hookCmd.Stdin = buf
hookCmd.Stderr = os.Stderr
if err := hookCmd.Run(); err != nil {
fail("Internal error", "Failed to execute custom pre-receive hook: %v", err)
}
return nil
}
func runHookUpdate(c *cli.Context) error {
if os.Getenv("SSH_ORIGINAL_COMMAND") == "" {
return nil
}
setup(c, "update.log", false)
args := c.Args()
if len(args) != 3 {
fail("Arguments received are not equal to three", "Arguments received are not equal to three")
} else if args[0] == "" {
fail("First argument 'refName' is empty", "First argument 'refName' is empty")
}
customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "update")
if !com.IsFile(customHooksPath) {
return nil
}
var hookCmd *exec.Cmd
if conf.IsWindowsRuntime() {
hookCmd = exec.Command("bash.exe", append([]string{"custom_hooks/update"}, args...)...)
} else {
hookCmd = exec.Command(customHooksPath, args...)
}
hookCmd.Dir = database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName))
hookCmd.Stdout = os.Stdout
hookCmd.Stdin = os.Stdin
hookCmd.Stderr = os.Stderr
if err := hookCmd.Run(); err != nil {
fail("Internal error", "Failed to execute custom pre-receive hook: %v", err)
}
return nil
}
func runHookPostReceive(c *cli.Context) error {
if os.Getenv("SSH_ORIGINAL_COMMAND") == "" {
return nil
}
setup(c, "post-receive.log", true)
// Post-receive hook does more than just gather Git information,
// so we need to setup additional services for email notifications.
email.NewContext()
isWiki := strings.Contains(os.Getenv(database.EnvRepoCustomHooksPath), ".wiki.git/")
buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
buf.Write(scanner.Bytes())
buf.WriteByte('\n')
// TODO: support news feeds for wiki
if isWiki {
continue
}
fields := bytes.Fields(scanner.Bytes())
if len(fields) != 3 {
continue
}
options := database.PushUpdateOptions{
OldCommitID: string(fields[0]),
NewCommitID: string(fields[1]),
FullRefspec: string(fields[2]),
PusherID: com.StrTo(os.Getenv(database.EnvAuthUserID)).MustInt64(),
PusherName: os.Getenv(database.EnvAuthUserName),
RepoUserName: os.Getenv(database.EnvRepoOwnerName),
RepoName: os.Getenv(database.EnvRepoName),
}
if err := database.PushUpdate(options); err != nil {
log.Error("PushUpdate: %v", err)
}
// Ask for running deliver hook and test pull request tasks
q := make(url.Values)
q.Add("branch", git.RefShortName(options.FullRefspec))
q.Add("secret", os.Getenv(database.EnvRepoOwnerSaltMd5))
q.Add("pusher", os.Getenv(database.EnvAuthUserID))
reqURL := fmt.Sprintf("%s%s/%s/tasks/trigger?%s", conf.Server.LocalRootURL, options.RepoUserName, options.RepoName, q.Encode())
log.Trace("Trigger task: %s", reqURL)
resp, err := httplib.Get(reqURL).
SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
}).Response()
if err == nil {
_ = resp.Body.Close()
if resp.StatusCode/100 != 2 {
log.Error("Failed to trigger task: unsuccessful response code %d", resp.StatusCode)
}
} else {
log.Error("Failed to trigger task: %v", err)
}
}
customHooksPath := filepath.Join(os.Getenv(database.EnvRepoCustomHooksPath), "post-receive")
if !com.IsFile(customHooksPath) {
return nil
}
var hookCmd *exec.Cmd
if conf.IsWindowsRuntime() {
hookCmd = exec.Command("bash.exe", "custom_hooks/post-receive")
} else {
hookCmd = exec.Command(customHooksPath)
}
hookCmd.Dir = database.RepoPath(os.Getenv(database.EnvRepoOwnerName), os.Getenv(database.EnvRepoName))
hookCmd.Stdout = os.Stdout
hookCmd.Stdin = buf
hookCmd.Stderr = os.Stderr
if err := hookCmd.Run(); err != nil {
fail("Internal error", "Failed to execute custom post-receive hook: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/admin.go | internal/cmd/admin.go | // Copyright 2016 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 cmd
import (
"context"
"fmt"
"reflect"
"runtime"
"github.com/pkg/errors"
"github.com/urfave/cli"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
)
var (
Admin = cli.Command{
Name: "admin",
Usage: "Perform admin operations on command line",
Description: `Allow using internal logic of Gogs without hacking into the source code
to make automatic initialization process more smoothly`,
Subcommands: []cli.Command{
subcmdCreateUser,
subcmdDeleteInactivateUsers,
subcmdDeleteRepositoryArchives,
subcmdDeleteMissingRepositories,
subcmdGitGcRepos,
subcmdRewriteAuthorizedKeys,
subcmdSyncRepositoryHooks,
subcmdReinitMissingRepositories,
},
}
subcmdCreateUser = cli.Command{
Name: "create-user",
Usage: "Create a new user in database",
Action: runCreateUser,
Flags: []cli.Flag{
stringFlag("name", "", "Username"),
stringFlag("password", "", "User password"),
stringFlag("email", "", "User email address"),
boolFlag("admin", "User is an admin"),
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdDeleteInactivateUsers = cli.Command{
Name: "delete-inactive-users",
Usage: "Delete all inactive accounts",
Action: adminDashboardOperation(
func() error { return database.Handle.Users().DeleteInactivated() },
"All inactivated accounts have been deleted successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdDeleteRepositoryArchives = cli.Command{
Name: "delete-repository-archives",
Usage: "Delete all repositories archives",
Action: adminDashboardOperation(
database.DeleteRepositoryArchives,
"All repositories archives have been deleted successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdDeleteMissingRepositories = cli.Command{
Name: "delete-missing-repositories",
Usage: "Delete all repository records that lost Git files",
Action: adminDashboardOperation(
database.DeleteMissingRepositories,
"All repositories archives have been deleted successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdGitGcRepos = cli.Command{
Name: "collect-garbage",
Usage: "Do garbage collection on repositories",
Action: adminDashboardOperation(
database.GitGcRepos,
"All repositories have done garbage collection successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdRewriteAuthorizedKeys = cli.Command{
Name: "rewrite-authorized-keys",
Usage: "Rewrite '.ssh/authorized_keys' file (caution: non-Gogs keys will be lost)",
Action: adminDashboardOperation(
database.RewriteAuthorizedKeys,
"All public keys have been rewritten successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdSyncRepositoryHooks = cli.Command{
Name: "resync-hooks",
Usage: "Resync pre-receive, update and post-receive hooks",
Action: adminDashboardOperation(
database.SyncRepositoryHooks,
"All repositories' pre-receive, update and post-receive hooks have been resynced successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
subcmdReinitMissingRepositories = cli.Command{
Name: "reinit-missing-repositories",
Usage: "Reinitialize all repository records that lost Git files",
Action: adminDashboardOperation(
database.ReinitMissingRepositories,
"All repository records that lost Git files have been reinitialized successfully",
),
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
)
func runCreateUser(c *cli.Context) error {
if !c.IsSet("name") {
return errors.New("Username is not specified")
} else if !c.IsSet("password") {
return errors.New("Password is not specified")
} else if !c.IsSet("email") {
return errors.New("Email is not specified")
}
err := conf.Init(c.String("config"))
if err != nil {
return errors.Wrap(err, "init configuration")
}
conf.InitLogging(true)
if _, err = database.SetEngine(); err != nil {
return errors.Wrap(err, "set engine")
}
user, err := database.Handle.Users().Create(
context.Background(),
c.String("name"),
c.String("email"),
database.CreateUserOptions{
Password: c.String("password"),
Activated: true,
Admin: c.Bool("admin"),
},
)
if err != nil {
return errors.Wrap(err, "create user")
}
fmt.Printf("New user %q has been successfully created!\n", user.Name)
return nil
}
func adminDashboardOperation(operation func() error, successMessage string) func(*cli.Context) error {
return func(c *cli.Context) error {
err := conf.Init(c.String("config"))
if err != nil {
return errors.Wrap(err, "init configuration")
}
conf.InitLogging(true)
if _, err = database.SetEngine(); err != nil {
return errors.Wrap(err, "set engine")
}
if err := operation(); err != nil {
functionName := runtime.FuncForPC(reflect.ValueOf(operation).Pointer()).Name()
return fmt.Errorf("%s: %v", functionName, err)
}
fmt.Printf("%s\n", successMessage)
return nil
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/restore.go | internal/cmd/restore.go | // Copyright 2017 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 cmd
import (
"context"
"os"
"path"
"path/filepath"
"github.com/pkg/errors"
"github.com/unknwon/cae/zip"
"github.com/urfave/cli"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/semverutil"
)
var Restore = cli.Command{
Name: "restore",
Usage: "Restore files and database from backup",
Description: `Restore imports all related files and database from a backup archive.
The backup version must lower or equal to current Gogs version. You can also import
backup from other database engines, which is useful for database migrating.
If corresponding files or database tables are not presented in the archive, they will
be skipped and remain unchanged.`,
Action: runRestore,
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
boolFlag("verbose, v", "Show process details"),
stringFlag("tempdir, t", os.TempDir(), "Temporary directory path"),
stringFlag("from", "", "Path to backup archive"),
boolFlag("database-only", "Only import database"),
boolFlag("exclude-repos", "Exclude repositories"),
},
}
// lastSupportedVersionOfFormat returns the last supported version of the backup archive
// format that is able to import.
var lastSupportedVersionOfFormat = map[int]string{}
func runRestore(c *cli.Context) error {
zip.Verbose = c.Bool("verbose")
tmpDir := c.String("tempdir")
if !osutil.IsDir(tmpDir) {
log.Fatal("'--tempdir' does not exist: %s", tmpDir)
}
archivePath := path.Join(tmpDir, archiveRootDir)
// Make sure there was no leftover and also clean up afterwards
err := os.RemoveAll(archivePath)
if err != nil {
log.Fatal("Failed to clean up previous leftover in %q: %v", archivePath, err)
}
defer func() { _ = os.RemoveAll(archivePath) }()
log.Info("Restoring backup from: %s", c.String("from"))
err = zip.ExtractTo(c.String("from"), tmpDir)
if err != nil {
log.Fatal("Failed to extract backup archive: %v", err)
}
// Check backup version
metaFile := filepath.Join(archivePath, "metadata.ini")
if !osutil.IsFile(metaFile) {
log.Fatal("File 'metadata.ini' is missing")
}
metadata, err := ini.Load(metaFile)
if err != nil {
log.Fatal("Failed to load metadata '%s': %v", metaFile, err)
}
backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0")
if semverutil.Compare(conf.App.Version, "<", backupVersion) {
log.Fatal("Current Gogs version is lower than backup version: %s < %s", conf.App.Version, backupVersion)
}
formatVersion := metadata.Section("").Key("VERSION").MustInt()
if formatVersion == 0 {
log.Fatal("Failed to determine the backup format version from metadata '%s': %s", metaFile, "VERSION is not presented")
}
if formatVersion != currentBackupFormatVersion {
log.Fatal("Backup format version found is %d but this binary only supports %d\nThe last known version that is able to import your backup is %s",
formatVersion, currentBackupFormatVersion, lastSupportedVersionOfFormat[formatVersion])
}
// If config file is not present in backup, user must set this file via flag.
// Otherwise, it's optional to set config file flag.
configFile := filepath.Join(archivePath, "custom", "conf", "app.ini")
var customConf string
if c.IsSet("config") {
customConf = c.String("config")
} else if !osutil.IsFile(configFile) {
log.Fatal("'--config' is not specified and custom config file is not found in backup")
} else {
customConf = configFile
}
err = conf.Init(customConf)
if err != nil {
return errors.Wrap(err, "init configuration")
}
conf.InitLogging(true)
conn, err := database.SetEngine()
if err != nil {
return errors.Wrap(err, "set engine")
}
// Database
dbDir := path.Join(archivePath, "db")
if err = database.ImportDatabase(context.Background(), conn, dbDir, c.Bool("verbose")); err != nil {
log.Fatal("Failed to import database: %v", err)
}
if !c.Bool("database-only") {
// Custom files
if osutil.IsDir(conf.CustomDir()) {
if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil {
log.Fatal("Failed to backup current 'custom': %v", err)
}
}
if err = os.Rename(filepath.Join(archivePath, "custom"), conf.CustomDir()); err != nil {
log.Fatal("Failed to import 'custom': %v", err)
}
// Data files
_ = os.MkdirAll(conf.Server.AppDataPath, os.ModePerm)
for _, dir := range []string{"attachments", "avatars", "repo-avatars"} {
// Skip if backup archive does not have corresponding data
srcPath := filepath.Join(archivePath, "data", dir)
if !osutil.IsDir(srcPath) {
continue
}
dirPath := filepath.Join(conf.Server.AppDataPath, dir)
if osutil.IsDir(dirPath) {
if err = os.Rename(dirPath, dirPath+".bak"); err != nil {
log.Fatal("Failed to backup current 'data': %v", err)
}
}
if err = os.Rename(srcPath, dirPath); err != nil {
log.Fatal("Failed to import 'data': %v", err)
}
}
}
// Repositories
reposPath := filepath.Join(archivePath, "repositories.zip")
if !c.Bool("exclude-repos") && !c.Bool("database-only") && osutil.IsFile(reposPath) {
if err := zip.ExtractTo(reposPath, filepath.Dir(conf.Repository.Root)); err != nil {
log.Fatal("Failed to extract 'repositories.zip': %v", err)
}
}
log.Info("Restore succeed!")
log.Stop()
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/cmd.go | internal/cmd/cmd.go | // Copyright 2015 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 cmd
import (
"time"
"github.com/urfave/cli"
)
func stringFlag(name, value, usage string) cli.StringFlag {
return cli.StringFlag{
Name: name,
Value: value,
Usage: usage,
}
}
func boolFlag(name, usage string) cli.BoolFlag {
return cli.BoolFlag{
Name: name,
Usage: usage,
}
}
//nolint:deadcode,unused
func intFlag(name string, value int, usage string) cli.IntFlag {
return cli.IntFlag{
Name: name,
Value: value,
Usage: usage,
}
}
//nolint:deadcode,unused
func durationFlag(name string, value time.Duration, usage string) cli.DurationFlag {
return cli.DurationFlag{
Name: name,
Value: value,
Usage: usage,
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/web.go | internal/cmd/web.go | // Copyright 2014 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 cmd
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/fcgi"
"os"
"path/filepath"
"strings"
"github.com/go-macaron/binding"
"github.com/go-macaron/cache"
"github.com/go-macaron/captcha"
"github.com/go-macaron/csrf"
"github.com/go-macaron/gzip"
"github.com/go-macaron/i18n"
"github.com/go-macaron/session"
"github.com/go-macaron/toolbox"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/unknwon/com"
"github.com/urfave/cli"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
embedConf "gogs.io/gogs/conf"
"gogs.io/gogs/internal/app"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/route"
"gogs.io/gogs/internal/route/admin"
apiv1 "gogs.io/gogs/internal/route/api/v1"
"gogs.io/gogs/internal/route/dev"
"gogs.io/gogs/internal/route/lfs"
"gogs.io/gogs/internal/route/org"
"gogs.io/gogs/internal/route/repo"
"gogs.io/gogs/internal/route/user"
"gogs.io/gogs/internal/template"
"gogs.io/gogs/public"
"gogs.io/gogs/templates"
)
var Web = cli.Command{
Name: "web",
Usage: "Start web server",
Description: `Gogs web server is the only thing you need to run,
and it takes care of all the other things for you`,
Action: runWeb,
Flags: []cli.Flag{
stringFlag("port, p", "3000", "Temporary port number to prevent conflict"),
stringFlag("config, c", "", "Custom configuration file path"),
},
}
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
m := macaron.New()
if !conf.Server.DisableRouterLog {
m.Use(macaron.Logger())
}
m.Use(macaron.Recovery())
if conf.Server.EnableGzip {
m.Use(gzip.Gziper())
}
if conf.Server.Protocol == "fcgi" {
m.SetURLPrefix(conf.Server.Subpath)
}
// Register custom middleware first to make it possible to override files under "public".
m.Use(macaron.Static(
filepath.Join(conf.CustomDir(), "public"),
macaron.StaticOptions{
SkipLogging: conf.Server.DisableRouterLog,
},
))
var publicFs http.FileSystem
if !conf.Server.LoadAssetsFromDisk {
publicFs = http.FS(public.Files)
}
m.Use(macaron.Static(
filepath.Join(conf.WorkDir(), "public"),
macaron.StaticOptions{
ETag: true,
SkipLogging: conf.Server.DisableRouterLog,
FileSystem: publicFs,
},
))
m.Use(macaron.Static(
conf.Picture.AvatarUploadPath,
macaron.StaticOptions{
ETag: true,
Prefix: conf.UsersAvatarPathPrefix,
SkipLogging: conf.Server.DisableRouterLog,
},
))
m.Use(macaron.Static(
conf.Picture.RepositoryAvatarUploadPath,
macaron.StaticOptions{
ETag: true,
Prefix: database.RepoAvatarURLPrefix,
SkipLogging: conf.Server.DisableRouterLog,
},
))
customDir := filepath.Join(conf.CustomDir(), "templates")
renderOpt := macaron.RenderOptions{
Directory: filepath.Join(conf.WorkDir(), "templates"),
AppendDirectories: []string{customDir},
Funcs: template.FuncMap(),
IndentJSON: macaron.Env != macaron.PROD,
}
if !conf.Server.LoadAssetsFromDisk {
renderOpt.TemplateFileSystem = templates.NewTemplateFileSystem("", customDir)
}
m.Use(macaron.Renderer(renderOpt))
localeNames, err := embedConf.FileNames("locale")
if err != nil {
log.Fatal("Failed to list locale files: %v", err)
}
localeFiles := make(map[string][]byte)
for _, name := range localeNames {
localeFiles[name], err = embedConf.Files.ReadFile("locale/" + name)
if err != nil {
log.Fatal("Failed to read locale file %q: %v", name, err)
}
}
m.Use(i18n.I18n(i18n.Options{
SubURL: conf.Server.Subpath,
Files: localeFiles,
CustomDirectory: filepath.Join(conf.CustomDir(), "conf", "locale"),
Langs: conf.I18n.Langs,
Names: conf.I18n.Names,
DefaultLang: "en-US",
Redirect: true,
}))
m.Use(cache.Cacher(cache.Options{
Adapter: conf.Cache.Adapter,
AdapterConfig: conf.Cache.Host,
Interval: conf.Cache.Interval,
}))
m.Use(captcha.Captchaer(captcha.Options{
SubURL: conf.Server.Subpath,
}))
m.Use(toolbox.Toolboxer(m, toolbox.Options{
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
{
Desc: "Database connection",
Func: database.Ping,
},
},
}))
return m
}
func runWeb(c *cli.Context) error {
err := route.GlobalInit(c.String("config"))
if err != nil {
log.Fatal("Failed to initialize application: %v", err)
}
m := newMacaron()
reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: conf.Auth.RequireSigninView})
reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
bindIgnErr := binding.BindIgnErr
m.SetAutoHead(true)
m.Group("", func() {
m.Get("/", ignSignIn, route.Home)
m.Group("/explore", func() {
m.Get("", func(c *context.Context) {
c.Redirect(conf.Server.Subpath + "/explore/repos")
})
m.Get("/repos", route.ExploreRepos)
m.Get("/users", route.ExploreUsers)
m.Get("/organizations", route.ExploreOrganizations)
}, ignSignIn)
m.Combo("/install", route.InstallInit).Get(route.Install).
Post(bindIgnErr(form.Install{}), route.InstallPost)
m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
// ***** START: User *****
m.Group("/user", func() {
m.Group("/login", func() {
m.Combo("").Get(user.Login).
Post(bindIgnErr(form.SignIn{}), user.LoginPost)
m.Combo("/two_factor").Get(user.LoginTwoFactor).Post(user.LoginTwoFactorPost)
m.Combo("/two_factor_recovery_code").Get(user.LoginTwoFactorRecoveryCode).Post(user.LoginTwoFactorRecoveryCodePost)
})
m.Get("/sign_up", user.SignUp)
m.Post("/sign_up", bindIgnErr(form.Register{}), user.SignUpPost)
m.Get("/reset_password", user.ResetPasswd)
m.Post("/reset_password", user.ResetPasswdPost)
}, reqSignOut)
m.Group("/user/settings", func() {
m.Get("", user.Settings)
m.Post("", bindIgnErr(form.UpdateProfile{}), user.SettingsPost)
m.Combo("/avatar").Get(user.SettingsAvatar).
Post(binding.MultipartForm(form.Avatar{}), user.SettingsAvatarPost)
m.Post("/avatar/delete", user.SettingsDeleteAvatar)
m.Combo("/email").Get(user.SettingsEmails).
Post(bindIgnErr(form.AddEmail{}), user.SettingsEmailPost)
m.Post("/email/delete", user.DeleteEmail)
m.Get("/password", user.SettingsPassword)
m.Post("/password", bindIgnErr(form.ChangePassword{}), user.SettingsPasswordPost)
m.Combo("/ssh").Get(user.SettingsSSHKeys).
Post(bindIgnErr(form.AddSSHKey{}), user.SettingsSSHKeysPost)
m.Post("/ssh/delete", user.DeleteSSHKey)
m.Group("/security", func() {
m.Get("", user.SettingsSecurity)
m.Combo("/two_factor_enable").Get(user.SettingsTwoFactorEnable).
Post(user.SettingsTwoFactorEnablePost)
m.Combo("/two_factor_recovery_codes").Get(user.SettingsTwoFactorRecoveryCodes).
Post(user.SettingsTwoFactorRecoveryCodesPost)
m.Post("/two_factor_disable", user.SettingsTwoFactorDisable)
})
m.Group("/repositories", func() {
m.Get("", user.SettingsRepos)
m.Post("/leave", user.SettingsLeaveRepo)
})
m.Group("/organizations", func() {
m.Get("", user.SettingsOrganizations)
m.Post("/leave", user.SettingsLeaveOrganization)
})
settingsHandler := user.NewSettingsHandler(user.NewSettingsStore())
m.Combo("/applications").Get(settingsHandler.Applications()).
Post(bindIgnErr(form.NewAccessToken{}), settingsHandler.ApplicationsPost())
m.Post("/applications/delete", settingsHandler.DeleteApplication())
m.Route("/delete", "GET,POST", user.SettingsDelete)
}, reqSignIn, func(c *context.Context) {
c.Data["PageIsUserSettings"] = true
})
m.Group("/user", func() {
m.Any("/activate", user.Activate)
m.Any("/activate_email", user.ActivateEmail)
m.Get("/email2user", user.Email2User)
m.Get("/forget_password", user.ForgotPasswd)
m.Post("/forget_password", user.ForgotPasswdPost)
m.Post("/logout", user.SignOut)
})
// ***** END: User *****
reqAdmin := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
// ***** START: Admin *****
m.Group("/admin", func() {
m.Combo("").Get(admin.Dashboard).Post(admin.Operation) // "/admin"
m.Get("/config", admin.Config)
m.Post("/config/test_mail", admin.SendTestMail)
m.Get("/monitor", admin.Monitor)
m.Group("/users", func() {
m.Get("", admin.Users)
m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(form.AdminCrateUser{}), admin.NewUserPost)
m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(form.AdminEditUser{}), admin.EditUserPost)
m.Post("/:userid/delete", admin.DeleteUser)
})
m.Group("/orgs", func() {
m.Get("", admin.Organizations)
})
m.Group("/repos", func() {
m.Get("", admin.Repos)
m.Post("/delete", admin.DeleteRepo)
})
m.Group("/auths", func() {
m.Get("", admin.Authentications)
m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(form.Authentication{}), admin.NewAuthSourcePost)
m.Combo("/:authid").Get(admin.EditAuthSource).
Post(bindIgnErr(form.Authentication{}), admin.EditAuthSourcePost)
m.Post("/:authid/delete", admin.DeleteAuthSource)
})
m.Group("/notices", func() {
m.Get("", admin.Notices)
m.Post("/delete", admin.DeleteNotices)
m.Get("/empty", admin.EmptyNotices)
})
}, reqAdmin)
// ***** END: Admin *****
m.Group("", func() {
m.Group("/:username", func() {
m.Get("", user.Profile)
m.Get("/followers", user.Followers)
m.Get("/following", user.Following)
m.Get("/stars", user.Stars)
}, context.InjectParamsUser())
m.Get("/attachments/:uuid", func(c *context.Context) {
attach, err := database.GetAttachmentByUUID(c.Params(":uuid"))
if err != nil {
c.NotFoundOrError(err, "get attachment by UUID")
return
} else if !com.IsFile(attach.LocalPath()) {
c.NotFound()
return
}
fr, err := os.Open(attach.LocalPath())
if err != nil {
c.Error(err, "open attachment file")
return
}
defer fr.Close()
c.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox")
c.Header().Set("Cache-Control", "public,max-age=86400")
c.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, attach.Name))
if _, err = io.Copy(c.Resp, fr); err != nil {
c.Error(err, "copy from file to response")
return
}
})
m.Post("/issues/attachments", repo.UploadIssueAttachment)
m.Post("/releases/attachments", repo.UploadReleaseAttachment)
}, ignSignIn)
m.Group("/:username", func() {
m.Post("/action/:action", user.Action)
}, reqSignIn, context.InjectParamsUser())
if macaron.Env == macaron.DEV {
m.Get("/template/*", dev.TemplatePreview)
}
reqRepoAdmin := context.RequireRepoAdmin()
reqRepoWriter := context.RequireRepoWriter()
webhookRoutes := func() {
m.Group("", func() {
m.Get("", repo.Webhooks)
m.Post("/delete", repo.DeleteWebhook)
m.Get("/:type/new", repo.WebhooksNew)
m.Post("/gogs/new", bindIgnErr(form.NewWebhook{}), repo.WebhooksNewPost)
m.Post("/slack/new", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackNewPost)
m.Post("/discord/new", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordNewPost)
m.Post("/dingtalk/new", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkNewPost)
m.Get("/:id", repo.WebhooksEdit)
m.Post("/gogs/:id", bindIgnErr(form.NewWebhook{}), repo.WebhooksEditPost)
m.Post("/slack/:id", bindIgnErr(form.NewSlackHook{}), repo.WebhooksSlackEditPost)
m.Post("/discord/:id", bindIgnErr(form.NewDiscordHook{}), repo.WebhooksDiscordEditPost)
m.Post("/dingtalk/:id", bindIgnErr(form.NewDingtalkHook{}), repo.WebhooksDingtalkEditPost)
}, repo.InjectOrgRepoContext())
}
// ***** START: Organization *****
m.Group("/org", func() {
m.Group("", func() {
m.Get("/create", org.Create)
m.Post("/create", bindIgnErr(form.CreateOrg{}), org.CreatePost)
}, func(c *context.Context) {
if !c.User.CanCreateOrganization() {
c.NotFound()
}
})
m.Group("/:org", func() {
m.Get("/dashboard", user.Dashboard)
m.Get("/^:type(issues|pulls)$", user.Issues)
m.Get("/members", org.Members)
m.Get("/members/action/:action", org.MembersAction)
m.Get("/teams", org.Teams)
}, context.OrgAssignment(true))
m.Group("/:org", func() {
m.Get("/teams/:team", org.TeamMembers)
m.Get("/teams/:team/repositories", org.TeamRepositories)
m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
}, context.OrgAssignment(true, false, true))
m.Group("/:org", func() {
m.Get("/teams/new", org.NewTeam)
m.Post("/teams/new", bindIgnErr(form.CreateTeam{}), org.NewTeamPost)
m.Get("/teams/:team/edit", org.EditTeam)
m.Post("/teams/:team/edit", bindIgnErr(form.CreateTeam{}), org.EditTeamPost)
m.Post("/teams/:team/delete", org.DeleteTeam)
m.Group("/settings", func() {
m.Combo("").Get(org.Settings).
Post(bindIgnErr(form.UpdateOrgSetting{}), org.SettingsPost)
m.Post("/avatar", binding.MultipartForm(form.Avatar{}), org.SettingsAvatar)
m.Post("/avatar/delete", org.SettingsDeleteAvatar)
m.Group("/hooks", webhookRoutes)
m.Route("/delete", "GET,POST", org.SettingsDelete)
})
m.Route("/invitations/new", "GET,POST", org.Invitation)
}, context.OrgAssignment(true, true))
}, reqSignIn)
// ***** END: Organization *****
// ***** START: Repository *****
m.Group("/repo", func() {
m.Get("/create", repo.Create)
m.Post("/create", bindIgnErr(form.CreateRepo{}), repo.CreatePost)
m.Get("/migrate", repo.Migrate)
m.Post("/migrate", bindIgnErr(form.MigrateRepo{}), repo.MigratePost)
m.Combo("/fork/:repoid").Get(repo.Fork).
Post(bindIgnErr(form.CreateRepo{}), repo.ForkPost)
}, reqSignIn)
m.Group("/:username/:reponame", func() {
m.Group("/settings", func() {
m.Combo("").Get(repo.Settings).
Post(bindIgnErr(form.RepoSetting{}), repo.SettingsPost)
m.Combo("/avatar").Get(repo.SettingsAvatar).
Post(binding.MultipartForm(form.Avatar{}), repo.SettingsAvatarPost)
m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
m.Group("/collaboration", func() {
m.Combo("").Get(repo.SettingsCollaboration).Post(repo.SettingsCollaborationPost)
m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
m.Post("/delete", repo.DeleteCollaboration)
})
m.Group("/branches", func() {
m.Get("", repo.SettingsBranches)
m.Post("/default_branch", repo.UpdateDefaultBranch)
m.Combo("/*").Get(repo.SettingsProtectedBranch).
Post(bindIgnErr(form.ProtectBranch{}), repo.SettingsProtectedBranchPost)
}, func(c *context.Context) {
if c.Repo.Repository.IsMirror {
c.NotFound()
return
}
})
m.Group("/hooks", func() {
webhookRoutes()
m.Group("/:id", func() {
m.Post("/test", repo.TestWebhook)
m.Post("/redelivery", repo.RedeliveryWebhook)
})
m.Group("/git", func() {
m.Get("", repo.SettingsGitHooks)
m.Combo("/:name").Get(repo.SettingsGitHooksEdit).
Post(repo.SettingsGitHooksEditPost)
}, context.GitHookService())
})
m.Group("/keys", func() {
m.Combo("").Get(repo.SettingsDeployKeys).
Post(bindIgnErr(form.AddSSHKey{}), repo.SettingsDeployKeysPost)
m.Post("/delete", repo.DeleteDeployKey)
})
}, func(c *context.Context) {
c.Data["PageIsSettings"] = true
})
}, reqSignIn, context.RepoAssignment(), reqRepoAdmin, context.RepoRef())
m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), repo.Action)
m.Group("/:username/:reponame", func() {
m.Get("/issues", repo.RetrieveLabels, repo.Issues)
m.Get("/issues/:index", repo.ViewIssue)
m.Get("/labels/", repo.RetrieveLabels, repo.Labels)
m.Get("/milestones", repo.Milestones)
}, ignSignIn, context.RepoAssignment(true))
m.Group("/:username/:reponame", func() {
// FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
// So they can apply their own enable/disable logic on routers.
m.Group("/issues", func() {
m.Combo("/new", repo.MustEnableIssues).Get(context.RepoRef(), repo.NewIssue).
Post(bindIgnErr(form.NewIssue{}), repo.NewIssuePost)
m.Group("/:index", func() {
m.Post("/title", repo.UpdateIssueTitle)
m.Post("/content", repo.UpdateIssueContent)
m.Combo("/comments").Post(bindIgnErr(form.CreateComment{}), repo.NewComment)
})
})
m.Group("/comments/:id", func() {
m.Post("", repo.UpdateCommentContent)
m.Post("/delete", repo.DeleteComment)
})
}, reqSignIn, context.RepoAssignment(true))
m.Group("/:username/:reponame", func() {
m.Group("/wiki", func() {
m.Get("/?:page", repo.Wiki)
m.Get("/_pages", repo.WikiPages)
}, repo.MustEnableWiki, context.RepoRef())
}, ignSignIn, context.RepoAssignment(false, true))
m.Group("/:username/:reponame", func() {
// FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
// So they can apply their own enable/disable logic on routers.
m.Group("/issues", func() {
m.Group("/:index", func() {
m.Post("/label", repo.UpdateIssueLabel)
m.Post("/milestone", repo.UpdateIssueMilestone)
m.Post("/assignee", repo.UpdateIssueAssignee)
}, reqRepoWriter)
})
m.Group("/labels", func() {
m.Post("/new", bindIgnErr(form.CreateLabel{}), repo.NewLabel)
m.Post("/edit", bindIgnErr(form.CreateLabel{}), repo.UpdateLabel)
m.Post("/delete", repo.DeleteLabel)
m.Post("/initialize", bindIgnErr(form.InitializeLabels{}), repo.InitializeLabels)
}, reqRepoWriter, context.RepoRef())
m.Group("/milestones", func() {
m.Combo("/new").Get(repo.NewMilestone).
Post(bindIgnErr(form.CreateMilestone{}), repo.NewMilestonePost)
m.Get("/:id/edit", repo.EditMilestone)
m.Post("/:id/edit", bindIgnErr(form.CreateMilestone{}), repo.EditMilestonePost)
m.Get("/:id/:action", repo.ChangeMilestonStatus)
m.Post("/delete", repo.DeleteMilestone)
}, reqRepoWriter, context.RepoRef())
m.Group("/releases", func() {
m.Get("/new", repo.NewRelease)
m.Post("/new", bindIgnErr(form.NewRelease{}), repo.NewReleasePost)
m.Post("/delete", repo.DeleteRelease)
m.Get("/edit/*", repo.EditRelease)
m.Post("/edit/*", bindIgnErr(form.EditRelease{}), repo.EditReleasePost)
}, repo.MustBeNotBare, reqRepoWriter, func(c *context.Context) {
c.Data["PageIsViewFiles"] = true
})
// FIXME: Should use c.Repo.PullRequest to unify template, currently we have inconsistent URL
// for PR in same repository. After select branch on the page, the URL contains redundant head user name.
// e.g. /org1/test-repo/compare/master...org1:develop
// which should be /org1/test-repo/compare/master...develop
m.Combo("/compare/*", repo.MustAllowPulls).Get(repo.CompareAndPullRequest).
Post(bindIgnErr(form.NewIssue{}), repo.CompareAndPullRequestPost)
m.Group("", func() {
m.Combo("/_edit/*").Get(repo.EditFile).
Post(bindIgnErr(form.EditRepoFile{}), repo.EditFilePost)
m.Combo("/_new/*").Get(repo.NewFile).
Post(bindIgnErr(form.EditRepoFile{}), repo.NewFilePost)
m.Post("/_preview/*", bindIgnErr(form.EditPreviewDiff{}), repo.DiffPreviewPost)
m.Combo("/_delete/*").Get(repo.DeleteFile).
Post(bindIgnErr(form.DeleteRepoFile{}), repo.DeleteFilePost)
m.Group("", func() {
m.Combo("/_upload/*").Get(repo.UploadFile).
Post(bindIgnErr(form.UploadRepoFile{}), repo.UploadFilePost)
m.Post("/upload-file", repo.UploadFileToServer)
m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
}, func(c *context.Context) {
if !conf.Repository.Upload.Enabled {
c.NotFound()
return
}
})
}, repo.MustBeNotBare, reqRepoWriter, context.RepoRef(), func(c *context.Context) {
if !c.Repo.CanEnableEditor() {
c.NotFound()
return
}
c.Data["PageIsViewFiles"] = true
})
}, reqSignIn, context.RepoAssignment())
m.Group("/:username/:reponame", func() {
m.Group("", func() {
m.Get("/releases", repo.MustBeNotBare, repo.Releases)
m.Get("/pulls", repo.RetrieveLabels, repo.Pulls)
m.Get("/pulls/:index", repo.ViewPull)
}, context.RepoRef())
m.Group("/branches", func() {
m.Get("", repo.Branches)
m.Get("/all", repo.AllBranches)
m.Post("/delete/*", reqSignIn, reqRepoWriter, repo.DeleteBranchPost)
}, repo.MustBeNotBare, func(c *context.Context) {
c.Data["PageIsViewFiles"] = true
})
m.Group("/wiki", func() {
m.Group("", func() {
m.Combo("/_new").Get(repo.NewWiki).
Post(bindIgnErr(form.NewWiki{}), repo.NewWikiPost)
m.Combo("/:page/_edit").Get(repo.EditWiki).
Post(bindIgnErr(form.NewWiki{}), repo.EditWikiPost)
m.Post("/:page/delete", repo.DeleteWikiPagePost)
}, reqSignIn, reqRepoWriter)
}, repo.MustEnableWiki, context.RepoRef())
m.Get("/archive/*", repo.MustBeNotBare, repo.Download)
m.Group("/pulls/:index", func() {
m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
m.Get("/files", context.RepoRef(), repo.ViewPullFiles)
m.Post("/merge", reqRepoWriter, repo.MergePullRequest)
}, repo.MustAllowPulls)
m.Group("", func() {
m.Get("/src/*", repo.Home)
m.Get("/raw/*", repo.SingleDownload)
m.Get("/commits/*", repo.RefCommits)
m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.Diff)
m.Get("/forks", repo.Forks)
}, repo.MustBeNotBare, context.RepoRef())
m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)", repo.MustBeNotBare, repo.RawDiff)
m.Get("/compare/:before([a-z0-9]{40})\\.\\.\\.:after([a-z0-9]{40})", repo.MustBeNotBare, context.RepoRef(), repo.CompareDiff)
}, ignSignIn, context.RepoAssignment())
m.Group("/:username/:reponame", func() {
m.Get("", repo.Home)
m.Get("/stars", repo.Stars)
m.Get("/watchers", repo.Watchers)
}, context.ServeGoGet(), ignSignIn, context.RepoAssignment(), context.RepoRef())
// ***** END: Repository *****
// **********************
// ----- API routes -----
// **********************
// TODO: Without session and CSRF
m.Group("/api", func() {
apiv1.RegisterRoutes(m)
}, ignSignIn)
},
session.Sessioner(session.Options{
Provider: conf.Session.Provider,
ProviderConfig: conf.Session.ProviderConfig,
CookieName: conf.Session.CookieName,
CookiePath: conf.Server.Subpath,
Gclifetime: conf.Session.GCInterval,
Maxlifetime: conf.Session.MaxLifeTime,
Secure: conf.Session.CookieSecure,
}),
csrf.Csrfer(csrf.Options{
Secret: conf.Security.SecretKey,
Header: "X-CSRF-Token",
Cookie: conf.Session.CSRFCookieName,
CookieDomain: conf.Server.URL.Hostname(),
CookiePath: conf.Server.Subpath,
CookieHttpOnly: true,
SetCookie: true,
Secure: conf.Server.URL.Scheme == "https",
}),
context.Contexter(context.NewStore()),
)
// ***************************
// ----- HTTP Git routes -----
// ***************************
m.Group("/:username/:reponame", func() {
m.Get("/tasks/trigger", repo.TriggerTask)
m.Group("/info/lfs", func() {
lfs.RegisterRoutes(m.Router)
})
m.Route("/*", "GET,POST,OPTIONS", context.ServeGoGet(), repo.HTTPContexter(repo.NewStore()), repo.HTTP)
})
// ***************************
// ----- Internal routes -----
// ***************************
m.Group("/-", func() {
m.Get("/metrics", app.MetricsFilter(), promhttp.Handler()) // "/-/metrics"
m.Group("/api", func() {
m.Post("/sanitize_ipynb", app.SanitizeIpynb()) // "/-/api/sanitize_ipynb"
})
})
// **********************
// ----- robots.txt -----
// **********************
m.Get("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
if conf.HasRobotsTxt {
http.ServeFile(w, r, filepath.Join(conf.CustomDir(), "robots.txt"))
} else {
w.WriteHeader(http.StatusNotFound)
}
})
m.NotFound(route.NotFound)
// Flag for port number in case first time run conflict.
if c.IsSet("port") {
conf.Server.URL.Host = strings.Replace(conf.Server.URL.Host, ":"+conf.Server.URL.Port(), ":"+c.String("port"), 1)
conf.Server.ExternalURL = conf.Server.URL.String()
conf.Server.HTTPPort = c.String("port")
}
var listenAddr string
if conf.Server.Protocol == "unix" {
listenAddr = conf.Server.HTTPAddr
} else {
listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort)
}
log.Info("Available on %s", conf.Server.ExternalURL)
switch conf.Server.Protocol {
case "http":
err = http.ListenAndServe(listenAddr, m)
case "https":
tlsMinVersion := tls.VersionTLS12
switch conf.Server.TLSMinVersion {
case "TLS13":
tlsMinVersion = tls.VersionTLS13
case "TLS12":
tlsMinVersion = tls.VersionTLS12
case "TLS11":
tlsMinVersion = tls.VersionTLS11
case "TLS10":
tlsMinVersion = tls.VersionTLS10
}
server := &http.Server{
Addr: listenAddr,
TLSConfig: &tls.Config{
MinVersion: uint16(tlsMinVersion),
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
},
}, Handler: m,
}
err = server.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
case "fcgi":
err = fcgi.Serve(nil, m)
case "unix":
if osutil.IsExist(listenAddr) {
err = os.Remove(listenAddr)
if err != nil {
log.Fatal("Failed to remove existing Unix domain socket: %v", err)
}
}
var listener *net.UnixListener
listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
if err != nil {
log.Fatal("Failed to listen on Unix networks: %v", err)
}
// FIXME: add proper implementation of signal capture on all protocols
// execute this on SIGTERM or SIGINT: listener.Close()
if err = os.Chmod(listenAddr, conf.Server.UnixSocketMode); err != nil {
log.Fatal("Failed to change permission of Unix domain socket: %v", err)
}
err = http.Serve(listener, m)
default:
log.Fatal("Unexpected server protocol: %s", conf.Server.Protocol)
}
if err != nil {
log.Fatal("Failed to start server: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/backup.go | internal/cmd/backup.go | // Copyright 2017 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 cmd
import (
"context"
"fmt"
"os"
"path"
"path/filepath"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/unknwon/cae/zip"
"github.com/urfave/cli"
"gopkg.in/ini.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osutil"
)
var Backup = cli.Command{
Name: "backup",
Usage: "Backup files and database",
Description: `Backup dumps and compresses all related files and database into zip file,
which can be used for migrating Gogs to another server. The output format is meant to be
portable among all supported database engines.`,
Action: runBackup,
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
boolFlag("verbose, v", "Show process details"),
stringFlag("tempdir, t", os.TempDir(), "Temporary directory path"),
stringFlag("target", "./", "Target directory path to save backup archive"),
stringFlag("archive-name", fmt.Sprintf("gogs-backup-%s.zip", time.Now().Format("20060102150405")), "Name of backup archive"),
boolFlag("database-only", "Only dump database"),
boolFlag("exclude-mirror-repos", "Exclude mirror repositories"),
boolFlag("exclude-repos", "Exclude repositories"),
},
}
const (
currentBackupFormatVersion = 1
archiveRootDir = "gogs-backup"
)
func runBackup(c *cli.Context) error {
zip.Verbose = c.Bool("verbose")
err := conf.Init(c.String("config"))
if err != nil {
return errors.Wrap(err, "init configuration")
}
conf.InitLogging(true)
conn, err := database.SetEngine()
if err != nil {
return errors.Wrap(err, "set engine")
}
tmpDir := c.String("tempdir")
if !osutil.IsExist(tmpDir) {
log.Fatal("'--tempdir' does not exist: %s", tmpDir)
}
rootDir, err := os.MkdirTemp(tmpDir, "gogs-backup-")
if err != nil {
log.Fatal("Failed to create backup root directory '%s': %v", rootDir, err)
}
log.Info("Backup root directory: %s", rootDir)
// Metadata
metaFile := path.Join(rootDir, "metadata.ini")
metadata := ini.Empty()
metadata.Section("").Key("VERSION").SetValue(strconv.Itoa(currentBackupFormatVersion))
metadata.Section("").Key("DATE_TIME").SetValue(time.Now().String())
metadata.Section("").Key("GOGS_VERSION").SetValue(conf.App.Version)
if err = metadata.SaveTo(metaFile); err != nil {
log.Fatal("Failed to save metadata '%s': %v", metaFile, err)
}
archiveName := filepath.Join(c.String("target"), c.String("archive-name"))
log.Info("Packing backup files to: %s", archiveName)
z, err := zip.Create(archiveName)
if err != nil {
log.Fatal("Failed to create backup archive '%s': %v", archiveName, err)
}
if err = z.AddFile(archiveRootDir+"/metadata.ini", metaFile); err != nil {
log.Fatal("Failed to include 'metadata.ini': %v", err)
}
// Database
dbDir := filepath.Join(rootDir, "db")
if err = database.DumpDatabase(context.Background(), conn, dbDir, c.Bool("verbose")); err != nil {
log.Fatal("Failed to dump database: %v", err)
}
if err = z.AddDir(archiveRootDir+"/db", dbDir); err != nil {
log.Fatal("Failed to include 'db': %v", err)
}
if !c.Bool("database-only") {
// Custom files
err = addCustomDirToBackup(z)
if err != nil {
log.Fatal("Failed to add custom directory to backup: %v", err)
}
// Data files
for _, dir := range []string{"ssh", "attachments", "avatars", "repo-avatars"} {
dirPath := filepath.Join(conf.Server.AppDataPath, dir)
if !osutil.IsDir(dirPath) {
continue
}
if err = z.AddDir(path.Join(archiveRootDir+"/data", dir), dirPath); err != nil {
log.Fatal("Failed to include 'data': %v", err)
}
}
}
// Repositories
if !c.Bool("exclude-repos") && !c.Bool("database-only") {
reposDump := filepath.Join(rootDir, "repositories.zip")
log.Info("Dumping repositories in %q", conf.Repository.Root)
if c.Bool("exclude-mirror-repos") {
repos, err := database.GetNonMirrorRepositories()
if err != nil {
log.Fatal("Failed to get non-mirror repositories: %v", err)
}
reposZip, err := zip.Create(reposDump)
if err != nil {
log.Fatal("Failed to create %q: %v", reposDump, err)
}
baseDir := filepath.Base(conf.Repository.Root)
for _, r := range repos {
name := r.FullName() + ".git"
if err := reposZip.AddDir(filepath.Join(baseDir, name), filepath.Join(conf.Repository.Root, name)); err != nil {
log.Fatal("Failed to add %q: %v", name, err)
}
}
if err = reposZip.Close(); err != nil {
log.Fatal("Failed to save %q: %v", reposDump, err)
}
} else {
if err = zip.PackTo(conf.Repository.Root, reposDump, true); err != nil {
log.Fatal("Failed to dump repositories: %v", err)
}
}
log.Info("Repositories dumped to: %s", reposDump)
if err = z.AddFile(archiveRootDir+"/repositories.zip", reposDump); err != nil {
log.Fatal("Failed to include %q: %v", reposDump, err)
}
}
if err = z.Close(); err != nil {
log.Fatal("Failed to save backup archive '%s': %v", archiveName, err)
}
_ = os.RemoveAll(rootDir)
log.Info("Backup succeed! Archive is located at: %s", archiveName)
log.Stop()
return nil
}
func addCustomDirToBackup(z *zip.ZipArchive) error {
customDir := conf.CustomDir()
entries, err := os.ReadDir(customDir)
if err != nil {
return errors.Wrap(err, "list custom directory entries")
}
for _, e := range entries {
if e.Name() == "data" {
// Skip the "data" directory because it lives under the "custom" directory in
// the Docker setup and will be backed up separately.
log.Trace(`Skipping "data" directory in custom directory`)
continue
}
add := z.AddFile
if e.IsDir() {
add = z.AddDir
}
err = add(
fmt.Sprintf("%s/custom/%s", archiveRootDir, e.Name()),
filepath.Join(customDir, e.Name()),
)
if err != nil {
return errors.Wrapf(err, "add %q", e.Name())
}
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/serv.go | internal/cmd/serv.go | // Copyright 2014 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 cmd
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/unknwon/com"
"github.com/urfave/cli"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
)
const (
accessDeniedMessage = "Repository does not exist or you do not have access"
)
var Serv = cli.Command{
Name: "serv",
Usage: "This command should only be called by SSH shell",
Description: `Serv provide access auth for repositories`,
Action: runServ,
Flags: []cli.Flag{
stringFlag("config, c", "", "Custom configuration file path"),
},
}
// fail prints user message to the Git client (i.e. os.Stderr) and
// logs error message on the server side. When not in "prod" mode,
// error message is also printed to the client for easier debugging.
func fail(userMessage, errMessage string, args ...any) {
_, _ = fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
if len(errMessage) > 0 {
if !conf.IsProdMode() {
fmt.Fprintf(os.Stderr, errMessage+"\n", args...)
}
log.Error(errMessage, args...)
}
log.Stop()
os.Exit(1)
}
func setup(c *cli.Context, logFile string, connectDB bool) {
conf.HookMode = true
var customConf string
if c.IsSet("config") {
customConf = c.String("config")
} else if c.GlobalIsSet("config") {
customConf = c.GlobalString("config")
}
err := conf.Init(customConf)
if err != nil {
fail("Internal error", "Failed to init configuration: %v", err)
}
conf.InitLogging(true)
level := log.LevelTrace
if conf.IsProdMode() {
level = log.LevelError
}
err = log.NewFile(log.FileConfig{
Level: level,
Filename: filepath.Join(conf.Log.RootPath, "hooks", logFile),
FileRotationConfig: log.FileRotationConfig{
Rotate: true,
Daily: true,
MaxDays: 3,
},
})
if err != nil {
fail("Internal error", "Failed to init file logger: %v", err)
}
log.Remove(log.DefaultConsoleName) // Remove the primary logger
if !connectDB {
return
}
if conf.UseSQLite3 {
_ = os.Chdir(conf.WorkDir())
}
if _, err := database.SetEngine(); err != nil {
fail("Internal error", "Failed to set database engine: %v", err)
}
}
func parseSSHCmd(cmd string) (string, string) {
ss := strings.SplitN(cmd, " ", 2)
if len(ss) != 2 {
return "", ""
}
return ss[0], strings.Replace(ss[1], "'/", "'", 1)
}
func checkDeployKey(key *database.PublicKey, repo *database.Repository) {
// Check if this deploy key belongs to current repository.
if !database.HasDeployKey(key.ID, repo.ID) {
fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
}
// Update deploy key activity.
deployKey, err := database.GetDeployKeyByRepo(key.ID, repo.ID)
if err != nil {
fail("Internal error", "GetDeployKey: %v", err)
}
deployKey.Updated = time.Now()
if err = database.UpdateDeployKey(deployKey); err != nil {
fail("Internal error", "UpdateDeployKey: %v", err)
}
}
var allowedCommands = map[string]database.AccessMode{
"git-upload-pack": database.AccessModeRead,
"git-upload-archive": database.AccessModeRead,
"git-receive-pack": database.AccessModeWrite,
}
func runServ(c *cli.Context) error {
ctx := context.Background()
setup(c, "serv.log", true)
if conf.SSH.Disabled {
println("Gogs: SSH has been disabled")
return nil
}
if len(c.Args()) < 1 {
fail("Not enough arguments", "Not enough arguments")
}
sshCmd := os.Getenv("SSH_ORIGINAL_COMMAND")
if sshCmd == "" {
println("Hi there, You've successfully authenticated, but Gogs does not provide shell access.")
println("If this is unexpected, please log in with password and setup Gogs under another user.")
return nil
}
verb, args := parseSSHCmd(sshCmd)
repoFullName := strings.ToLower(strings.Trim(args, "'"))
repoFields := strings.SplitN(repoFullName, "/", 2)
if len(repoFields) != 2 {
fail("Invalid repository path", "Invalid repository path: %v", args)
}
ownerName := strings.ToLower(repoFields[0])
repoName := strings.TrimSuffix(strings.ToLower(repoFields[1]), ".git")
repoName = strings.TrimSuffix(repoName, ".wiki")
owner, err := database.Handle.Users().GetByUsername(ctx, ownerName)
if err != nil {
if database.IsErrUserNotExist(err) {
fail("Repository owner does not exist", "Unregistered owner: %s", ownerName)
}
fail("Internal error", "Failed to get repository owner '%s': %v", ownerName, err)
}
repo, err := database.GetRepositoryByName(owner.ID, repoName)
if err != nil {
if database.IsErrRepoNotExist(err) {
fail(accessDeniedMessage, "Repository does not exist: %s/%s", owner.Name, repoName)
}
fail("Internal error", "Failed to get repository: %v", err)
}
repo.Owner = owner
requestMode, ok := allowedCommands[verb]
if !ok {
fail("Unknown git command", "Unknown git command '%s'", verb)
}
// Prohibit push to mirror repositories.
if requestMode > database.AccessModeRead && repo.IsMirror {
fail("Mirror repository is read-only", "")
}
// Allow anonymous (user is nil) clone for public repositories.
var user *database.User
key, err := database.GetPublicKeyByID(com.StrTo(strings.TrimPrefix(c.Args()[0], "key-")).MustInt64())
if err != nil {
fail("Invalid key ID", "Invalid key ID '%s': %v", c.Args()[0], err)
}
if requestMode == database.AccessModeWrite || repo.IsPrivate {
// Check deploy key or user key.
if key.IsDeployKey() {
if key.Mode < requestMode {
fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
}
checkDeployKey(key, repo)
} else {
user, err = database.Handle.Users().GetByKeyID(ctx, key.ID)
if err != nil {
fail("Internal error", "Failed to get user by key ID '%d': %v", key.ID, err)
}
mode := database.Handle.Permissions().AccessMode(ctx, user.ID, repo.ID,
database.AccessModeOptions{
OwnerID: repo.OwnerID,
Private: repo.IsPrivate,
},
)
if mode < requestMode {
clientMessage := accessDeniedMessage
if mode >= database.AccessModeRead {
clientMessage = "You do not have sufficient authorization for this action"
}
fail(clientMessage,
"User '%s' does not have level '%v' access to repository '%s'",
user.Name, requestMode, repoFullName)
}
}
} else {
// Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
// A deploy key doesn't represent a signed in user, so in a site with Auth.RequireSignInView enabled,
// we should give read access only in repositories where this deploy key is in use. In other cases,
// a server or system using an active deploy key can get read access to all repositories on a Gogs instance.
if key.IsDeployKey() && conf.Auth.RequireSigninView {
checkDeployKey(key, repo)
}
}
// Update user key activity.
if key.ID > 0 {
key, err := database.GetPublicKeyByID(key.ID)
if err != nil {
fail("Internal error", "GetPublicKeyByID: %v", err)
}
key.Updated = time.Now()
if err = database.UpdatePublicKey(key); err != nil {
fail("Internal error", "UpdatePublicKey: %v", err)
}
}
// Special handle for Windows.
if conf.IsWindowsRuntime() {
verb = strings.Replace(verb, "-", " ", 1)
}
var gitCmd *exec.Cmd
verbs := strings.Split(verb, " ")
if len(verbs) == 2 {
gitCmd = exec.Command(verbs[0], verbs[1], repoFullName)
} else {
gitCmd = exec.Command(verb, repoFullName)
}
if requestMode == database.AccessModeWrite {
gitCmd.Env = append(os.Environ(), database.ComposeHookEnvs(database.ComposeHookEnvsOptions{
AuthUser: user,
OwnerName: owner.Name,
OwnerSalt: owner.Salt,
RepoID: repo.ID,
RepoName: repo.Name,
RepoPath: repo.RepoPath(),
})...)
}
gitCmd.Dir = conf.Repository.Root
gitCmd.Stdout = os.Stdout
gitCmd.Stdin = os.Stdin
gitCmd.Stderr = os.Stderr
if err = gitCmd.Run(); err != nil {
fail("Internal error", "Failed to execute git command: %v", err)
}
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/cert.go | internal/cmd/cert.go | // Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2014 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 cmd
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"log"
"math/big"
"net"
"os"
"strings"
"time"
"github.com/urfave/cli"
)
var Cert = cli.Command{
Name: "cert",
Usage: "Generate self-signed certificate",
Description: `Generate a self-signed X.509 certificate for a TLS server.
Outputs to 'cert.pem' and 'key.pem' and will overwrite existing files.`,
Action: runCert,
Flags: []cli.Flag{
stringFlag("host", "", "Comma-separated hostnames and IPs to generate a certificate for"),
stringFlag("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521"),
intFlag("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set"),
stringFlag("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011"),
durationFlag("duration", 365*24*time.Hour, "Duration that certificate is valid for"),
boolFlag("ca", "whether this cert should be its own Certificate Authority"),
},
}
func publicKey(priv any) any {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
func pemBlockForKey(priv any) *pem.Block {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
case *ecdsa.PrivateKey:
b, err := x509.MarshalECPrivateKey(k)
if err != nil {
log.Fatalf("Unable to marshal ECDSA private key: %v\n", err)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
default:
return nil
}
}
func runCert(ctx *cli.Context) error {
if len(ctx.String("host")) == 0 {
log.Fatal("Missing required --host parameter")
}
var priv any
var err error
switch ctx.String("ecdsa-curve") {
case "":
priv, err = rsa.GenerateKey(rand.Reader, ctx.Int("rsa-bits"))
case "P224":
priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
case "P256":
priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
case "P384":
priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
case "P521":
priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
default:
log.Fatalf("Unrecognized elliptic curve: %q", ctx.String("ecdsa-curve"))
}
if err != nil {
log.Fatalf("Failed to generate private key: %s", err)
}
var notBefore time.Time
if len(ctx.String("start-date")) == 0 {
notBefore = time.Now()
} else {
notBefore, err = time.Parse("Jan 2 15:04:05 2006", ctx.String("start-date"))
if err != nil {
log.Fatalf("Failed to parse creation date: %s", err)
}
}
notAfter := notBefore.Add(ctx.Duration("duration"))
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
log.Fatalf("Failed to generate serial number: %s", err)
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"Acme Co"},
CommonName: "Gogs",
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
}
hosts := strings.Split(ctx.String("host"), ",")
for _, h := range hosts {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
if ctx.Bool("ca") {
template.IsCA = true
template.KeyUsage |= x509.KeyUsageCertSign
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
if err != nil {
log.Fatalf("Failed to create certificate: %s", err)
}
certOut, err := os.Create("cert.pem")
if err != nil {
log.Fatalf("Failed to open cert.pem for writing: %s", err)
}
err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
if err != nil {
log.Fatalf("Failed to encode data to cert.pem: %s", err)
}
err = certOut.Close()
if err != nil {
log.Fatalf("Failed to close writing to cert.pem: %s", err)
}
log.Println("Written cert.pem")
keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Failed to open key.pem for writing: %v\n", err)
}
err = pem.Encode(keyOut, pemBlockForKey(priv))
if err != nil {
log.Fatalf("Failed to encode data to key.pem: %s", err)
}
err = keyOut.Close()
if err != nil {
log.Fatalf("Failed to close writing to key.pem: %s", err)
}
log.Println("Written key.pem")
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cmd/import.go | internal/cmd/import.go | // Copyright 2016 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 cmd
import (
"bufio"
"bytes"
"fmt"
"os"
"path/filepath"
"time"
"github.com/pkg/errors"
"github.com/unknwon/com"
"github.com/urfave/cli"
"gogs.io/gogs/internal/conf"
)
var (
Import = cli.Command{
Name: "import",
Usage: "Import portable data as local Gogs data",
Description: `Allow user import data from other Gogs installations to local instance
without manually hacking the data files`,
Subcommands: []cli.Command{
subcmdImportLocale,
},
}
subcmdImportLocale = cli.Command{
Name: "locale",
Usage: "Import locale files to local repository",
Action: runImportLocale,
Flags: []cli.Flag{
stringFlag("source", "", "Source directory that stores new locale files"),
stringFlag("target", "", "Target directory that stores old locale files"),
stringFlag("config, c", "", "Custom configuration file path"),
},
}
)
func runImportLocale(c *cli.Context) error {
if !c.IsSet("source") {
return errors.New("source directory is not specified")
} else if !c.IsSet("target") {
return errors.New("target directory is not specified")
}
if !com.IsDir(c.String("source")) {
return fmt.Errorf("source directory %q does not exist or is not a directory", c.String("source"))
} else if !com.IsDir(c.String("target")) {
return fmt.Errorf("target directory %q does not exist or is not a directory", c.String("target"))
}
err := conf.Init(c.String("config"))
if err != nil {
return errors.Wrap(err, "init configuration")
}
now := time.Now()
var line []byte
badChars := []byte(`="`)
escapedQuotes := []byte(`\"`)
regularQuotes := []byte(`"`)
// Cut out en-US.
for _, lang := range conf.I18n.Langs[1:] {
name := fmt.Sprintf("locale_%s.ini", lang)
source := filepath.Join(c.String("source"), name)
target := filepath.Join(c.String("target"), name)
if !com.IsFile(source) {
continue
}
// Crowdin surrounds double quotes for strings contain quotes inside,
// this breaks INI parser, we need to fix that.
sr, err := os.Open(source)
if err != nil {
return fmt.Errorf("open: %v", err)
}
tw, err := os.Create(target)
if err != nil {
return fmt.Errorf("create: %v", err)
}
scanner := bufio.NewScanner(sr)
for scanner.Scan() {
line = scanner.Bytes()
idx := bytes.Index(line, badChars)
if idx > -1 && line[len(line)-1] == '"' {
// We still want the "=" sign
line = append(line[:idx+1], line[idx+2:len(line)-1]...)
line = bytes.ReplaceAll(line, escapedQuotes, regularQuotes)
}
_, _ = tw.Write(line)
_, _ = tw.WriteString("\n")
}
_ = sr.Close()
_ = tw.Close()
// Modification time of files from Crowdin often ahead of current,
// so we need to set back to current.
_ = os.Chtimes(target, now, now)
}
fmt.Println("Locale files has been successfully imported!")
return nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/mocks/locale.go | internal/mocks/locale.go | // Copyright 2020 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 mocks
import (
"gopkg.in/macaron.v1"
)
var _ macaron.Locale = (*Locale)(nil)
type Locale struct {
MockLang string
MockTr func(string, ...any) string
}
func (l *Locale) Language() string {
return l.MockLang
}
func (l *Locale) Tr(format string, args ...any) string {
return l.MockTr(format, args...)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/app/metrics.go | internal/app/metrics.go | // Copyright 2020 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 app
import (
"net/http"
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/authutil"
"gogs.io/gogs/internal/conf"
)
func MetricsFilter() macaron.Handler {
return func(w http.ResponseWriter, r *http.Request) {
if !conf.Prometheus.Enabled {
w.WriteHeader(http.StatusNotFound)
return
}
if !conf.Prometheus.EnableBasicAuth {
return
}
username, password := authutil.DecodeBasic(r.Header)
if username != conf.Prometheus.BasicAuthUsername || password != conf.Prometheus.BasicAuthPassword {
w.WriteHeader(http.StatusForbidden)
return
}
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/app/api.go | internal/app/api.go | // Copyright 2020 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 app
import (
"net/http"
"github.com/microcosm-cc/bluemonday"
"gopkg.in/macaron.v1"
)
func ipynbSanitizer() *bluemonday.Policy {
p := bluemonday.UGCPolicy()
p.AllowAttrs("class", "data-prompt-number").OnElements("div")
p.AllowAttrs("class").OnElements("img")
p.AllowURLSchemes("data")
return p
}
func SanitizeIpynb() macaron.Handler {
p := ipynbSanitizer()
return func(c *macaron.Context) {
html, err := c.Req.Body().String()
if err != nil {
c.Error(http.StatusInternalServerError, "read body")
return
}
c.PlainText(http.StatusOK, []byte(p.Sanitize(html)))
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/app/api_test.go | internal/app/api_test.go | // Copyright 2020 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 app
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_ipynbSanitizer(t *testing.T) {
p := ipynbSanitizer()
tests := []struct {
name string
input string
want string
}{
{
name: "allow 'class' and 'data-prompt-number' attributes",
input: `
<div class="nb-notebook">
<div class="nb-worksheet">
<div class="nb-cell nb-markdown-cell">Hello world</div>
<div class="nb-cell nb-code-cell">
<div class="nb-input" data-prompt-number="4">
</div>
</div>
</div>
</div>
`,
want: `
<div class="nb-notebook">
<div class="nb-worksheet">
<div class="nb-cell nb-markdown-cell">Hello world</div>
<div class="nb-cell nb-code-cell">
<div class="nb-input" data-prompt-number="4">
</div>
</div>
</div>
</div>
`,
},
{
name: "allow base64 encoded images",
input: `
<div class="nb-output" data-prompt-number="4">
<img class="nb-image-output" src="data:image/png;base64,iVBORw0KGgoA"/>
</div>
`,
want: `
<div class="nb-output" data-prompt-number="4">
<img class="nb-image-output" src="data:image/png;base64,iVBORw0KGgoA"/>
</div>
`,
},
{
name: "prevent XSS",
input: `
<div class="nb-output" data-prompt-number="10">
<div class="nb-html-output">
<style>
.output {
align-items: center;
background: #00ff00;
}
</style>
<script>
function test() {
alert("test");
}
$(document).ready(test);
</script>
</div>
</div>
`,
want: `
<div class="nb-output" data-prompt-number="10">
<div class="nb-html-output">
</div>
</div>
`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, p.Sanitize(test.input))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/avatar/avatar_test.go | internal/avatar/avatar_test.go | // Copyright 2016 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 avatar
import (
"testing"
"github.com/stretchr/testify/assert"
)
func Test_RandomImage(t *testing.T) {
_, err := RandomImage([]byte("gogs@local"))
assert.NoError(t, err)
_, err = RandomImageWithSize(0, []byte("gogs@local"))
assert.Error(t, err)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/avatar/avatar.go | internal/avatar/avatar.go | // Copyright 2014 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 avatar
import (
"fmt"
"image"
"image/color/palette"
"math/rand"
"time"
"github.com/issue9/identicon"
)
const DefaultSize = 290
// RandomImageWithSize generates and returns a random avatar image unique to
// input data in custom size (height and width).
func RandomImageWithSize(size int, data []byte) (image.Image, error) {
randExtent := len(palette.WebSafe) - 32
rand.Seed(time.Now().UnixNano())
colorIndex := rand.Intn(randExtent)
backColorIndex := colorIndex - 1
if backColorIndex < 0 {
backColorIndex = randExtent - 1
}
// Define size, background, and forecolor
imgMaker, err := identicon.New(size,
palette.WebSafe[backColorIndex], palette.WebSafe[colorIndex:colorIndex+32]...)
if err != nil {
return nil, fmt.Errorf("identicon.New: %v", err)
}
return imgMaker.Make(data), nil
}
// RandomImage generates and returns a random avatar image unique to input data
// in DefaultSize (height and width).
func RandomImage(data []byte) (image.Image, error) {
return RandomImageWithSize(DefaultSize, data)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/osutil/osutil.go | internal/osutil/osutil.go | // Copyright 2020 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 osutil
import (
"os"
"os/user"
)
// IsFile returns true if given path exists as a file (i.e. not a directory).
func IsFile(path string) bool {
f, e := os.Stat(path)
if e != nil {
return false
}
return !f.IsDir()
}
// IsDir returns true if given path is a directory, and returns false when it's
// a file or does not exist.
func IsDir(dir string) bool {
f, e := os.Stat(dir)
if e != nil {
return false
}
return f.IsDir()
}
// IsExist returns true if a file or directory exists.
func IsExist(path string) bool {
_, err := os.Stat(path)
return err == nil || os.IsExist(err)
}
// IsSymlink returns true if given path is a symbolic link.
func IsSymlink(path string) bool {
if !IsExist(path) {
return false
}
fileInfo, err := os.Lstat(path)
if err != nil {
return false
}
return fileInfo.Mode()&os.ModeSymlink != 0
}
// CurrentUsername returns the username of the current user.
func CurrentUsername() string {
username := os.Getenv("USER")
if len(username) > 0 {
return username
}
username = os.Getenv("USERNAME")
if len(username) > 0 {
return username
}
if user, err := user.Current(); err == nil {
username = user.Username
}
return username
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/osutil/error.go | internal/osutil/error.go | // Copyright 2020 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 osutil
import (
"os"
"gogs.io/gogs/internal/errutil"
)
var _ errutil.NotFound = (*Error)(nil)
// Error is a wrapper of an OS error, which handles not found.
type Error struct {
error
}
func (e Error) NotFound() bool {
return e.error == os.ErrNotExist
}
// NewError wraps given error.
func NewError(err error) error {
return Error{error: err}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/osutil/error_test.go | internal/osutil/error_test.go | // Copyright 2020 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 osutil
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/errutil"
)
func TestError_NotFound(t *testing.T) {
tests := []struct {
err error
expVal bool
}{
{err: os.ErrNotExist, expVal: true},
{err: os.ErrClosed, expVal: false},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.expVal, errutil.IsNotFound(NewError(test.err)))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/osutil/osutil_test.go | internal/osutil/osutil_test.go | // Copyright 2020 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 osutil
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestIsFile(t *testing.T) {
tests := []struct {
path string
want bool
}{
{
path: "osutil.go",
want: true,
}, {
path: "../osutil",
want: false,
}, {
path: "not_found",
want: false,
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.want, IsFile(test.path))
})
}
}
func TestIsDir(t *testing.T) {
tests := []struct {
path string
want bool
}{
{
path: "osutil.go",
want: false,
}, {
path: "../osutil",
want: true,
}, {
path: "not_found",
want: false,
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.want, IsDir(test.path))
})
}
}
func TestIsExist(t *testing.T) {
tests := []struct {
path string
expVal bool
}{
{
path: "osutil.go",
expVal: true,
}, {
path: "../osutil",
expVal: true,
}, {
path: "not_found",
expVal: false,
},
}
for _, test := range tests {
t.Run("", func(t *testing.T) {
assert.Equal(t, test.expVal, IsExist(test.path))
})
}
}
func TestCurrentUsername(t *testing.T) {
if oldUser, ok := os.LookupEnv("USER"); ok {
defer func() { t.Setenv("USER", oldUser) }()
} else {
defer func() { _ = os.Unsetenv("USER") }()
}
t.Setenv("USER", "__TESTING::USERNAME")
assert.Equal(t, "__TESTING::USERNAME", CurrentUsername())
}
func TestIsSymlink(t *testing.T) {
// Create a temporary file
tempFile, err := os.CreateTemp("", "symlink-test-*")
require.NoError(t, err, "create temporary file")
tempFilePath := tempFile.Name()
_ = tempFile.Close()
defer func() { _ = os.Remove(tempFilePath) }()
// Create a temporary symlink
tempSymlinkPath := tempFilePath + "-symlink"
err = os.Symlink(tempFilePath, tempSymlinkPath)
require.NoError(t, err, "create temporary symlink")
defer func() { _ = os.Remove(tempSymlinkPath) }()
tests := []struct {
name string
path string
want bool
}{
{
name: "non-existent path",
path: "not_found",
want: false,
},
{
name: "regular file",
path: tempFilePath,
want: false,
},
{
name: "symlink",
path: tempSymlinkPath,
want: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.want, IsSymlink(test.path))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/authutil/basic.go | internal/authutil/basic.go | // Copyright 2020 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 authutil
import (
"encoding/base64"
"net/http"
"strings"
)
// DecodeBasic extracts username and password from given header using HTTP Basic Auth.
// It returns empty strings if values are not presented or not valid.
func DecodeBasic(header http.Header) (username, password string) {
if len(header) == 0 {
return "", ""
}
fields := strings.Fields(header.Get("Authorization"))
if len(fields) != 2 || fields[0] != "Basic" {
return "", ""
}
p, err := base64.StdEncoding.DecodeString(fields[1])
if err != nil {
return "", ""
}
creds := strings.SplitN(string(p), ":", 2)
if len(creds) == 1 {
return creds[0], ""
}
return creds[0], creds[1]
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/authutil/basic_test.go | internal/authutil/basic_test.go | // Copyright 2020 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 authutil
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestDecodeBasic(t *testing.T) {
tests := []struct {
name string
header http.Header
expUsername string
expPassword string
}{
{
name: "no header",
},
{
name: "no authorization",
header: http.Header{
"Content-Type": []string{"text/plain"},
},
},
{
name: "malformed value",
header: http.Header{
"Authorization": []string{"Basic"},
},
},
{
name: "not basic",
header: http.Header{
"Authorization": []string{"Digest dummy"},
},
},
{
name: "bad encoding",
header: http.Header{
"Authorization": []string{"Basic not_base64"},
},
},
{
name: "only has username",
header: http.Header{
"Authorization": []string{"Basic dXNlcm5hbWU="},
},
expUsername: "username",
},
{
name: "has username and password",
header: http.Header{
"Authorization": []string{"Basic dXNlcm5hbWU6cGFzc3dvcmQ="},
},
expUsername: "username",
expPassword: "password",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
username, password := DecodeBasic(test.header)
assert.Equal(t, test.expUsername, username)
assert.Equal(t, test.expPassword, password)
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/errutil/errutil_test.go | internal/errutil/errutil_test.go | // Copyright 2020 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 errutil
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
type notFoundError struct {
val bool
}
func (notFoundError) Error() string {
return "not found"
}
func (e notFoundError) NotFound() bool {
return e.val
}
func TestIsNotFound(t *testing.T) {
tests := []struct {
name string
err error
expVal bool
}{
{
name: "error does not implement NotFound",
err: errors.New("a simple error"),
expVal: false,
},
{
name: "error implements NotFound but not a not found",
err: notFoundError{val: false},
expVal: false,
},
{
name: "error implements NotFound",
err: notFoundError{val: true},
expVal: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
assert.Equal(t, test.expVal, IsNotFound(test.err))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/errutil/errutil.go | internal/errutil/errutil.go | // Copyright 2020 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 errutil
// NotFound represents a not found error.
type NotFound interface {
NotFound() bool
}
// IsNotFound returns true if the error is a not found error.
func IsNotFound(err error) bool {
e, ok := err.(NotFound)
return ok && e.NotFound()
}
// Args is a map of key-value pairs to provide additional context of an error.
type Args map[string]any
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/userutil/userutil_test.go | internal/userutil/userutil_test.go | // 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 (
"os"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/tool"
"gogs.io/gogs/public"
)
func TestDashboardURLPath(t *testing.T) {
t.Run("user", func(t *testing.T) {
got := DashboardURLPath("alice", false)
want := "/"
assert.Equal(t, want, got)
})
t.Run("organization", func(t *testing.T) {
got := DashboardURLPath("acme", true)
want := "/org/acme/dashboard/"
assert.Equal(t, want, got)
})
}
func TestGenerateActivateCode(t *testing.T) {
conf.SetMockAuth(t,
conf.AuthOpts{
ActivateCodeLives: 10,
},
)
code := GenerateActivateCode(1, "alice@example.com", "Alice", "123456", "rands")
got := tool.VerifyTimeLimitCode("1alice@example.comalice123456rands", conf.Auth.ActivateCodeLives, code[:tool.TimeLimitCodeLength])
assert.True(t, got)
}
func TestCustomAvatarPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockPicture(t,
conf.PictureOpts{
AvatarUploadPath: "data/avatars",
},
)
got := CustomAvatarPath(1)
want := "data/avatars/1"
assert.Equal(t, want, got)
}
func TestGenerateRandomAvatar(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockPicture(t,
conf.PictureOpts{
AvatarUploadPath: os.TempDir(),
},
)
avatarPath := CustomAvatarPath(1)
defer func() { _ = os.Remove(avatarPath) }()
err := GenerateRandomAvatar(1, "alice", "alice@example.com")
require.NoError(t, err)
got := osutil.IsFile(avatarPath)
assert.True(t, got)
}
func TestSaveAvatar(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockPicture(t,
conf.PictureOpts{
AvatarUploadPath: os.TempDir(),
},
)
avatar, err := public.Files.ReadFile("img/avatar_default.png")
require.NoError(t, err)
avatarPath := CustomAvatarPath(1)
defer func() { _ = os.Remove(avatarPath) }()
err = SaveAvatar(1, avatar)
require.NoError(t, err)
got := osutil.IsFile(avatarPath)
assert.True(t, got)
}
func TestEncodePassword(t *testing.T) {
want := EncodePassword("123456", "rands")
tests := []struct {
name string
password string
rands string
wantEqual bool
}{
{
name: "correct",
password: "123456",
rands: "rands",
wantEqual: true,
},
{
name: "wrong password",
password: "111333",
rands: "rands",
wantEqual: false,
},
{
name: "wrong salt",
password: "111333",
rands: "salt",
wantEqual: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := EncodePassword(test.password, test.rands)
if test.wantEqual {
assert.Equal(t, want, got)
} else {
assert.NotEqual(t, want, got)
}
})
}
}
func TestValidatePassword(t *testing.T) {
want := EncodePassword("123456", "rands")
tests := []struct {
name string
password string
rands string
wantEqual bool
}{
{
name: "correct",
password: "123456",
rands: "rands",
wantEqual: true,
},
{
name: "wrong password",
password: "111333",
rands: "rands",
wantEqual: false,
},
{
name: "wrong salt",
password: "111333",
rands: "salt",
wantEqual: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := ValidatePassword(want, test.rands, test.password)
assert.Equal(t, test.wantEqual, got)
})
}
}
func TestMailResendCacheKey(t *testing.T) {
got := MailResendCacheKey(1)
assert.Equal(t, "mailResend::1", got)
}
func TestTwoFactorCacheKey(t *testing.T) {
got := TwoFactorCacheKey(1, "113654")
assert.Equal(t, "twoFactor::1::113654", got)
}
func TestRandomSalt(t *testing.T) {
salt1, err := RandomSalt()
require.NoError(t, err)
salt2, err := RandomSalt()
require.NoError(t, err)
assert.NotEqual(t, salt1, salt2)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/userutil/userutil.go | internal/userutil/userutil.go | // 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 (
"bytes"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"image"
"image/png"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/nfnt/resize"
"github.com/pkg/errors"
"golang.org/x/crypto/pbkdf2"
"gogs.io/gogs/internal/avatar"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/strutil"
"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
}
// SaveAvatar saves the given avatar for the user.
func SaveAvatar(userID int64, data []byte) error {
img, _, err := image.Decode(bytes.NewReader(data))
if err != nil {
return errors.Wrap(err, "decode 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() }()
m := resize.Resize(avatar.DefaultSize, avatar.DefaultSize, img, resize.NearestNeighbor)
if err = png.Encode(f, m); 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
}
// MailResendCacheKey returns the key used for caching mail resend.
func MailResendCacheKey(userID int64) string {
return fmt.Sprintf("mailResend::%d", userID)
}
// TwoFactorCacheKey returns the key used for caching two factor passcode.
func TwoFactorCacheKey(userID int64, passcode string) string {
return fmt.Sprintf("twoFactor::%d::%s", userID, passcode)
}
// RandomSalt returns randomly generated 10-character string that can be used as
// the user salt.
func RandomSalt() (string, error) {
return strutil.RandomChars(10)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/cron/cron.go | internal/cron/cron.go | // Copyright 2014 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 cron
import (
"time"
log "unknwon.dev/clog/v2"
"github.com/gogs/cron"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
)
var c = cron.New()
func NewContext() {
var (
entry *cron.Entry
err error
)
if conf.Cron.UpdateMirror.Enabled {
entry, err = c.AddFunc("Update mirrors", conf.Cron.UpdateMirror.Schedule, database.MirrorUpdate)
if err != nil {
log.Fatal("Cron.(update mirrors): %v", err)
}
if conf.Cron.UpdateMirror.RunAtStart {
entry.Prev = time.Now()
entry.ExecTimes++
go database.MirrorUpdate()
}
}
if conf.Cron.RepoHealthCheck.Enabled {
entry, err = c.AddFunc("Repository health check", conf.Cron.RepoHealthCheck.Schedule, database.GitFsck)
if err != nil {
log.Fatal("Cron.(repository health check): %v", err)
}
if conf.Cron.RepoHealthCheck.RunAtStart {
entry.Prev = time.Now()
entry.ExecTimes++
go database.GitFsck()
}
}
if conf.Cron.CheckRepoStats.Enabled {
entry, err = c.AddFunc("Check repository statistics", conf.Cron.CheckRepoStats.Schedule, database.CheckRepoStats)
if err != nil {
log.Fatal("Cron.(check repository statistics): %v", err)
}
if conf.Cron.CheckRepoStats.RunAtStart {
entry.Prev = time.Now()
entry.ExecTimes++
go database.CheckRepoStats()
}
}
if conf.Cron.RepoArchiveCleanup.Enabled {
entry, err = c.AddFunc("Repository archive cleanup", conf.Cron.RepoArchiveCleanup.Schedule, database.DeleteOldRepositoryArchives)
if err != nil {
log.Fatal("Cron.(repository archive cleanup): %v", err)
}
if conf.Cron.RepoArchiveCleanup.RunAtStart {
entry.Prev = time.Now()
entry.ExecTimes++
go database.DeleteOldRepositoryArchives()
}
}
c.Start()
}
// ListTasks returns all running cron tasks.
func ListTasks() []*cron.Entry {
return c.Entries()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/ssh/ssh.go | internal/ssh/ssh.go | // Copyright 2014 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 ssh
import (
"context"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"github.com/pkg/errors"
"github.com/sourcegraph/run"
"github.com/unknwon/com"
"golang.org/x/crypto/ssh"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/osutil"
)
func cleanCommand(cmd string) string {
i := strings.Index(cmd, "git")
if i == -1 {
return cmd
}
return cmd[i:]
}
func handleServerConn(keyID string, chans <-chan ssh.NewChannel) {
for newChan := range chans {
if newChan.ChannelType() != "session" {
_ = newChan.Reject(ssh.UnknownChannelType, "unknown channel type")
continue
}
ch, reqs, err := newChan.Accept()
if err != nil {
log.Error("Error accepting channel: %v", err)
continue
}
go func(in <-chan *ssh.Request) {
defer func() {
_ = ch.Close()
}()
for req := range in {
payload := cleanCommand(string(req.Payload))
switch req.Type {
case "env":
// We only need to accept the request and do nothing since whatever environment
// variables being set here won't be used in subsequent commands anyway.
case "exec":
cmdName := strings.TrimLeft(payload, "'()")
log.Trace("SSH: Payload: %v", cmdName)
args := []string{"serv", "key-" + keyID, "--config=" + conf.CustomConf}
log.Trace("SSH: Arguments: %v", args)
cmd := exec.Command(conf.AppPath(), args...)
cmd.Env = append(os.Environ(), "SSH_ORIGINAL_COMMAND="+cmdName)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Error("SSH: StdoutPipe: %v", err)
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Error("SSH: StderrPipe: %v", err)
return
}
input, err := cmd.StdinPipe()
if err != nil {
log.Error("SSH: StdinPipe: %v", err)
return
}
// FIXME: check timeout
if err = cmd.Start(); err != nil {
log.Error("SSH: Start: %v", err)
return
}
_ = req.Reply(true, nil)
go func() {
_, _ = io.Copy(input, ch)
}()
_, _ = io.Copy(ch, stdout)
_, _ = io.Copy(ch.Stderr(), stderr)
if err = cmd.Wait(); err != nil {
log.Error("SSH: Wait: %v", err)
return
}
_, _ = ch.SendRequest("exit-status", false, []byte{0, 0, 0, 0})
return
default:
}
}
}(reqs)
}
}
func listen(config *ssh.ServerConfig, host string, port int) {
listener, err := net.Listen("tcp", host+":"+com.ToStr(port))
if err != nil {
log.Fatal("Failed to start SSH server: %v", err)
}
for {
// Once a ServerConfig has been configured, connections can be accepted.
conn, err := listener.Accept()
if err != nil {
log.Error("SSH: Error accepting incoming connection: %v", err)
continue
}
// Before use, a handshake must be performed on the incoming net.Conn.
// It must be handled in a separate goroutine,
// otherwise one user could easily block entire loop.
// For example, user could be asked to trust server key fingerprint and hangs.
go func() {
log.Trace("SSH: Handshaking for %s", conn.RemoteAddr())
sConn, chans, reqs, err := ssh.NewServerConn(conn, config)
if err != nil {
if err == io.EOF || errors.Is(err, syscall.ECONNRESET) {
log.Trace("SSH: Handshaking was terminated: %v", err)
} else {
log.Error("SSH: Error on handshaking: %v", err)
}
return
}
log.Trace("SSH: Connection from %s (%s)", sConn.RemoteAddr(), sConn.ClientVersion())
// The incoming Request channel must be serviced.
go ssh.DiscardRequests(reqs)
go handleServerConn(sConn.Permissions.Extensions["key-id"], chans)
}()
}
}
// Listen starts a SSH server listens on given port.
func Listen(opts conf.SSHOpts, appDataPath string) {
config := &ssh.ServerConfig{
Config: ssh.Config{
Ciphers: opts.ServerCiphers,
MACs: opts.ServerMACs,
},
PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
pkey, err := database.SearchPublicKeyByContent(strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))))
if err != nil {
if !database.IsErrKeyNotExist(err) {
log.Error("SearchPublicKeyByContent: %v", err)
}
return nil, err
}
return &ssh.Permissions{Extensions: map[string]string{"key-id": com.ToStr(pkey.ID)}}, nil
},
}
keys, err := setupHostKeys(appDataPath, opts.ServerAlgorithms)
if err != nil {
log.Fatal("SSH: Failed to setup host keys: %v", err)
}
for _, key := range keys {
config.AddHostKey(key)
}
go listen(config, opts.ListenHost, opts.ListenPort)
}
func setupHostKeys(appDataPath string, algorithms []string) ([]ssh.Signer, error) {
dir := filepath.Join(appDataPath, "ssh")
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return nil, errors.Wrapf(err, "create host key directory")
}
var hostKeys []ssh.Signer
for _, algo := range algorithms {
keyPath := filepath.Join(dir, "gogs."+algo)
if !osutil.IsExist(keyPath) {
args := []string{
conf.SSH.KeygenPath,
"-t", algo,
"-f", keyPath,
"-m", "PEM",
"-N", run.Arg(""),
}
err = run.Cmd(context.Background(), args...).Run().Wait()
if err != nil {
return nil, errors.Wrapf(err, "generate host key with args %v", args)
}
log.Trace("SSH: New private key is generated: %s", keyPath)
}
keyData, err := os.ReadFile(keyPath)
if err != nil {
return nil, errors.Wrapf(err, "read host key %q", keyPath)
}
signer, err := ssh.ParsePrivateKey(keyData)
if err != nil {
return nil, errors.Wrapf(err, "parse host key %q", keyPath)
}
hostKeys = append(hostKeys, signer)
}
return hostKeys, nil
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/semverutil/semverutil_test.go | internal/semverutil/semverutil_test.go | // Copyright 2020 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 semverutil
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCheck(t *testing.T) {
tests := []struct {
version1 string
comparison string
version2 string
expVal bool
}{
{version1: "1.0.c", comparison: ">", version2: "0.9", expVal: false},
{version1: "1.0.1", comparison: ">", version2: "0.9.a", expVal: false},
{version1: "7.2", comparison: ">=", version2: "5.1", expVal: true},
{version1: "1.8.3.1", comparison: ">=", version2: "1.8.3", expVal: true},
{version1: "0.12.0+dev", comparison: ">=", version2: "0.11.68.1023", expVal: true},
}
for _, test := range tests {
t.Run(test.version1+" "+test.comparison+" "+test.version2, func(t *testing.T) {
assert.Equal(t, test.expVal, Compare(test.version1, test.comparison, test.version2))
})
}
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/semverutil/semverutil.go | internal/semverutil/semverutil.go | // Copyright 2020 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 semverutil
import (
"strings"
"github.com/Masterminds/semver/v3"
)
// Compare returns true if the comparison is true for given versions. It returns false if
// comparison is false, or failed to parse one or both versions as Semantic Versions.
//
// See https://github.com/Masterminds/semver#basic-comparisons for supported comparisons.
func Compare(version1, comparison, version2 string) bool {
clean := func(v string) string {
if strings.Count(v, ".") > 2 {
fields := strings.SplitN(v, ".", 4)
v = strings.Join(fields[:3], ".")
}
return v
}
v, err := semver.NewVersion(clean(version1))
if err != nil {
return false
}
c, err := semver.NewConstraint(comparison + " " + clean(version2))
if err != nil {
return false
}
return c.Check(v)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/dbtest/dbtest.go | internal/dbtest/dbtest.go | // Copyright 2020 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 dbtest
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/dbutil"
)
// NewDB creates a new test database and initializes the given list of tables
// for the suite. The test database is dropped after testing is completed unless
// failed.
func NewDB(t *testing.T, suite string, tables ...any) *gorm.DB {
dbType := os.Getenv("GOGS_DATABASE_TYPE")
var dbName string
var dbOpts conf.DatabaseOpts
var cleanup func(db *gorm.DB)
switch dbType {
case "mysql":
dbOpts = conf.DatabaseOpts{
Type: "mysql",
Host: os.ExpandEnv("$MYSQL_HOST:$MYSQL_PORT"),
Name: dbName,
User: os.Getenv("MYSQL_USER"),
Password: os.Getenv("MYSQL_PASSWORD"),
}
dsn, err := dbutil.NewDSN(dbOpts)
require.NoError(t, err)
sqlDB, err := sql.Open("mysql", dsn)
require.NoError(t, err)
// Set up test database
dbName = fmt.Sprintf("gogs-%s-%d", suite, time.Now().Unix())
_, err = sqlDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName))
require.NoError(t, err)
_, err = sqlDB.Exec(fmt.Sprintf("CREATE DATABASE `%s`", dbName))
require.NoError(t, err)
dbOpts.Name = dbName
cleanup = func(db *gorm.DB) {
testDB, err := db.DB()
if err == nil {
_ = testDB.Close()
}
_, _ = sqlDB.Exec(fmt.Sprintf("DROP DATABASE `%s`", dbName))
_ = sqlDB.Close()
}
case "postgres":
dbOpts = conf.DatabaseOpts{
Type: "postgres",
Host: os.ExpandEnv("$PGHOST:$PGPORT"),
Name: dbName,
Schema: "public",
User: os.Getenv("PGUSER"),
Password: os.Getenv("PGPASSWORD"),
SSLMode: os.Getenv("PGSSLMODE"),
}
dsn, err := dbutil.NewDSN(dbOpts)
require.NoError(t, err)
sqlDB, err := sql.Open("pgx", dsn)
require.NoError(t, err)
// Set up test database
dbName = fmt.Sprintf("gogs-%s-%d", suite, time.Now().Unix())
_, err = sqlDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %q", dbName))
require.NoError(t, err)
_, err = sqlDB.Exec(fmt.Sprintf("CREATE DATABASE %q", dbName))
require.NoError(t, err)
dbOpts.Name = dbName
cleanup = func(db *gorm.DB) {
testDB, err := db.DB()
if err == nil {
_ = testDB.Close()
}
_, _ = sqlDB.Exec(fmt.Sprintf(`DROP DATABASE %q`, dbName))
_ = sqlDB.Close()
}
case "sqlite":
dbName = filepath.Join(os.TempDir(), fmt.Sprintf("gogs-%s-%d.db", suite, time.Now().Unix()))
dbOpts = conf.DatabaseOpts{
Type: "sqlite",
Path: dbName,
}
cleanup = func(db *gorm.DB) {
sqlDB, err := db.DB()
if err == nil {
_ = sqlDB.Close()
}
_ = os.Remove(dbName)
}
default:
dbName = filepath.Join(os.TempDir(), fmt.Sprintf("gogs-%s-%d.db", suite, time.Now().Unix()))
dbOpts = conf.DatabaseOpts{
Type: "sqlite3",
Path: dbName,
}
cleanup = func(db *gorm.DB) {
sqlDB, err := db.DB()
if err == nil {
_ = sqlDB.Close()
}
_ = os.Remove(dbName)
}
}
now := time.Now().UTC().Truncate(time.Second)
db, err := dbutil.OpenDB(
dbOpts,
&gorm.Config{
SkipDefaultTransaction: true,
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
NowFunc: func() time.Time {
return now
},
},
)
require.NoError(t, err)
t.Cleanup(func() {
if t.Failed() {
t.Logf("Database %q left intact for inspection", dbName)
return
}
cleanup(db)
})
err = db.Migrator().AutoMigrate(tables...)
require.NoError(t, err)
return db
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/repoutil/repoutil_test.go | internal/repoutil/repoutil_test.go | // 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 repoutil
import (
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"gogs.io/gogs/internal/conf"
)
func TestNewCloneLink(t *testing.T) {
conf.SetMockApp(t,
conf.AppOpts{
RunUser: "git",
},
)
conf.SetMockServer(t,
conf.ServerOpts{
ExternalURL: "https://example.com/",
},
)
t.Run("regular SSH port", func(t *testing.T) {
conf.SetMockSSH(t,
conf.SSHOpts{
Domain: "example.com",
Port: 22,
},
)
got := NewCloneLink("alice", "example", false)
want := &CloneLink{
SSH: "git@example.com:alice/example.git",
HTTPS: "https://example.com/alice/example.git",
}
assert.Equal(t, want, got)
})
t.Run("irregular SSH port", func(t *testing.T) {
conf.SetMockSSH(t,
conf.SSHOpts{
Domain: "example.com",
Port: 2222,
},
)
got := NewCloneLink("alice", "example", false)
want := &CloneLink{
SSH: "ssh://git@example.com:2222/alice/example.git",
HTTPS: "https://example.com/alice/example.git",
}
assert.Equal(t, want, got)
})
t.Run("wiki", func(t *testing.T) {
conf.SetMockSSH(t,
conf.SSHOpts{
Domain: "example.com",
Port: 22,
},
)
got := NewCloneLink("alice", "example", true)
want := &CloneLink{
SSH: "git@example.com:alice/example.wiki.git",
HTTPS: "https://example.com/alice/example.wiki.git",
}
assert.Equal(t, want, got)
})
}
func TestHTMLURL(t *testing.T) {
conf.SetMockServer(t,
conf.ServerOpts{
ExternalURL: "https://example.com/",
},
)
got := HTMLURL("alice", "example")
want := "https://example.com/alice/example"
assert.Equal(t, want, got)
}
func TestCompareCommitsPath(t *testing.T) {
got := CompareCommitsPath("alice", "example", "old", "new")
want := "alice/example/compare/old...new"
assert.Equal(t, want, got)
}
func TestUserPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockRepository(t,
conf.RepositoryOpts{
Root: "/home/git/gogs-repositories",
},
)
got := UserPath("alice")
want := "/home/git/gogs-repositories/alice"
assert.Equal(t, want, got)
}
func TestRepositoryPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockRepository(t,
conf.RepositoryOpts{
Root: "/home/git/gogs-repositories",
},
)
got := RepositoryPath("alice", "example")
want := "/home/git/gogs-repositories/alice/example.git"
assert.Equal(t, want, got)
}
func TestRepositoryLocalPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockServer(
t,
conf.ServerOpts{
AppDataPath: "data",
},
)
got := RepositoryLocalPath(1)
want := "data/tmp/local-repo/1"
assert.Equal(t, want, got)
}
func TestRepositoryLocalWikiPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Skipping testing on Windows")
return
}
conf.SetMockServer(
t,
conf.ServerOpts{
AppDataPath: "data",
},
)
got := RepositoryLocalWikiPath(1)
want := "data/tmp/local-wiki/1"
assert.Equal(t, want, got)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/repoutil/repoutil.go | internal/repoutil/repoutil.go | // 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 repoutil
import (
"fmt"
"path/filepath"
"strconv"
"strings"
"gogs.io/gogs/internal/conf"
)
// CloneLink represents different types of clone URLs of repository.
type CloneLink struct {
SSH string
HTTPS string
}
// NewCloneLink returns clone URLs using given owner and repository name.
func NewCloneLink(owner, repo string, isWiki bool) *CloneLink {
if isWiki {
repo += ".wiki"
}
cl := new(CloneLink)
if conf.SSH.Port != 22 {
cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", conf.App.RunUser, conf.SSH.Domain, conf.SSH.Port, owner, repo)
} else {
cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", conf.App.RunUser, conf.SSH.Domain, owner, repo)
}
cl.HTTPS = HTTPSCloneURL(owner, repo)
return cl
}
// HTTPSCloneURL returns HTTPS clone URL using given owner and repository name.
func HTTPSCloneURL(owner, repo string) string {
return fmt.Sprintf("%s%s/%s.git", conf.Server.ExternalURL, owner, repo)
}
// HTMLURL returns HTML URL using given owner and repository name.
func HTMLURL(owner, repo string) string {
return conf.Server.ExternalURL + owner + "/" + repo
}
// CompareCommitsPath returns the comparison path using given owner, repository,
// and commit IDs.
func CompareCommitsPath(owner, repo, oldCommitID, newCommitID string) string {
return fmt.Sprintf("%s/%s/compare/%s...%s", owner, repo, oldCommitID, newCommitID)
}
// UserPath returns the absolute path for storing user repositories.
func UserPath(user string) string {
return filepath.Join(conf.Repository.Root, strings.ToLower(user))
}
// RepositoryPath returns the absolute path using given user and repository
// name.
func RepositoryPath(owner, repo string) string {
return filepath.Join(UserPath(owner), strings.ToLower(repo)+".git")
}
// RepositoryLocalPath returns the absolute path of the repository local copy
// with the given ID.
func RepositoryLocalPath(repoID int64) string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-repo", strconv.FormatInt(repoID, 10))
}
// RepositoryLocalWikiPath returns the absolute path of the repository local
// wiki copy with the given ID.
func RepositoryLocalWikiPath(repoID int64) string {
return filepath.Join(conf.Server.AppDataPath, "tmp", "local-wiki", strconv.FormatInt(repoID, 10))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/email/email.go | internal/email/email.go | // Copyright 2016 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 email
import (
"fmt"
"html/template"
"path/filepath"
"sync"
"time"
"gopkg.in/gomail.v2"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/templates"
)
const (
tmplAuthActivate = "auth/activate"
tmplAuthActivateEmail = "auth/activate_email"
tmplAuthResetPassword = "auth/reset_passwd"
tmplAuthRegisterNotify = "auth/register_notify"
tmplIssueComment = "issue/comment"
tmplIssueMention = "issue/mention"
tmplNotifyCollaborator = "notify/collaborator"
)
var (
tplRender *macaron.TplRender
tplRenderOnce sync.Once
)
// render renders a mail template with given data.
func render(tpl string, data map[string]any) (string, error) {
tplRenderOnce.Do(func() {
customDir := filepath.Join(conf.CustomDir(), "templates")
opt := &macaron.RenderOptions{
Directory: filepath.Join(conf.WorkDir(), "templates", "mail"),
AppendDirectories: []string{filepath.Join(customDir, "mail")},
Extensions: []string{".tmpl", ".html"},
Funcs: []template.FuncMap{map[string]any{
"AppName": func() string {
return conf.App.BrandName
},
"AppURL": func() string {
return conf.Server.ExternalURL
},
"Year": func() int {
return time.Now().Year()
},
"Str2HTML": func(raw string) template.HTML {
return template.HTML(markup.Sanitize(raw))
},
}},
}
if !conf.Server.LoadAssetsFromDisk {
opt.TemplateFileSystem = templates.NewTemplateFileSystem("mail", customDir)
}
ts := macaron.NewTemplateSet()
ts.Set(macaron.DEFAULT_TPL_SET_NAME, opt)
tplRender = &macaron.TplRender{
TemplateSet: ts,
Opt: opt,
}
})
return tplRender.HTMLString(tpl, data)
}
func SendTestMail(email string) error {
return gomail.Send(&Sender{}, NewMessage([]string{email}, "Gogs Test Email", "Hello 👋, greeting from Gogs!").Message)
}
/*
Setup interfaces of used methods in mail to avoid cycle import.
*/
type User interface {
ID() int64
DisplayName() string
Email() string
GenerateEmailActivateCode(string) string
}
type Repository interface {
FullName() string
HTMLURL() string
ComposeMetas() map[string]string
}
type Issue interface {
MailSubject() string
Content() string
HTMLURL() string
}
func SendUserMail(_ *macaron.Context, u User, tpl, code, subject, info string) {
data := map[string]any{
"Username": u.DisplayName(),
"ActiveCodeLives": conf.Auth.ActivateCodeLives / 60,
"ResetPwdCodeLives": conf.Auth.ResetPasswordCodeLives / 60,
"Code": code,
}
body, err := render(tpl, data)
if err != nil {
log.Error("render: %v", err)
return
}
msg := NewMessage([]string{u.Email()}, subject, body)
msg.Info = fmt.Sprintf("UID: %d, %s", u.ID(), info)
Send(msg)
}
func SendActivateAccountMail(c *macaron.Context, u User) {
SendUserMail(c, u, tmplAuthActivate, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.activate_account"), "activate account")
}
func SendResetPasswordMail(c *macaron.Context, u User) {
SendUserMail(c, u, tmplAuthResetPassword, u.GenerateEmailActivateCode(u.Email()), c.Tr("mail.reset_password"), "reset password")
}
// SendActivateAccountMail sends confirmation email.
func SendActivateEmailMail(c *macaron.Context, u User, email string) {
data := map[string]any{
"Username": u.DisplayName(),
"ActiveCodeLives": conf.Auth.ActivateCodeLives / 60,
"Code": u.GenerateEmailActivateCode(email),
"Email": email,
}
body, err := render(tmplAuthActivateEmail, data)
if err != nil {
log.Error("HTMLString: %v", err)
return
}
msg := NewMessage([]string{email}, c.Tr("mail.activate_email"), body)
msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID())
Send(msg)
}
// SendRegisterNotifyMail triggers a notify e-mail by admin created a account.
func SendRegisterNotifyMail(c *macaron.Context, u User) {
data := map[string]any{
"Username": u.DisplayName(),
}
body, err := render(tmplAuthRegisterNotify, data)
if err != nil {
log.Error("HTMLString: %v", err)
return
}
msg := NewMessage([]string{u.Email()}, c.Tr("mail.register_notify"), body)
msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID())
Send(msg)
}
// SendCollaboratorMail sends mail notification to new collaborator.
func SendCollaboratorMail(u, doer User, repo Repository) {
subject := fmt.Sprintf("%s added you to %s", doer.DisplayName(), repo.FullName())
data := map[string]any{
"Subject": subject,
"RepoName": repo.FullName(),
"Link": repo.HTMLURL(),
}
body, err := render(tmplNotifyCollaborator, data)
if err != nil {
log.Error("HTMLString: %v", err)
return
}
msg := NewMessage([]string{u.Email()}, subject, body)
msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID())
Send(msg)
}
func composeTplData(subject, body, link string) map[string]any {
data := make(map[string]any, 10)
data["Subject"] = subject
data["Body"] = body
data["Link"] = link
return data
}
func composeIssueMessage(issue Issue, repo Repository, doer User, tplName string, tos []string, info string) *Message {
subject := issue.MailSubject()
body := string(markup.Markdown([]byte(issue.Content()), repo.HTMLURL(), repo.ComposeMetas()))
data := composeTplData(subject, body, issue.HTMLURL())
data["Doer"] = doer
content, err := render(tplName, data)
if err != nil {
log.Error("HTMLString (%s): %v", tplName, err)
}
from := gomail.NewMessage().FormatAddress(conf.Email.FromEmail, doer.DisplayName())
msg := NewMessageFrom(tos, from, subject, content)
msg.Info = fmt.Sprintf("Subject: %s, %s", subject, info)
return msg
}
// SendIssueCommentMail composes and sends issue comment emails to target receivers.
func SendIssueCommentMail(issue Issue, repo Repository, doer User, tos []string) {
if len(tos) == 0 {
return
}
Send(composeIssueMessage(issue, repo, doer, tmplIssueComment, tos, "issue comment"))
}
// SendIssueMentionMail composes and sends issue mention emails to target receivers.
func SendIssueMentionMail(issue Issue, repo Repository, doer User, tos []string) {
if len(tos) == 0 {
return
}
Send(composeIssueMessage(issue, repo, doer, tmplIssueMention, tos, "issue mention"))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/email/message.go | internal/email/message.go | // Copyright 2014 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 email
import (
"crypto/tls"
"fmt"
"io"
"net"
"net/smtp"
"os"
"strings"
"time"
"github.com/jaytaylor/html2text"
"gopkg.in/gomail.v2"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
)
type Message struct {
Info string // Message information for log purpose.
*gomail.Message
confirmChan chan struct{}
}
// NewMessageFrom creates new mail message object with custom From header.
func NewMessageFrom(to []string, from, subject, htmlBody string) *Message {
log.Trace("NewMessageFrom (htmlBody):\n%s", htmlBody)
msg := gomail.NewMessage()
msg.SetHeader("From", from)
msg.SetHeader("To", to...)
msg.SetHeader("Subject", conf.Email.SubjectPrefix+subject)
msg.SetDateHeader("Date", time.Now())
contentType := "text/html"
body := htmlBody
switchedToPlaintext := false
if conf.Email.UsePlainText || conf.Email.AddPlainTextAlt {
plainBody, err := html2text.FromString(htmlBody)
if err != nil {
log.Error("html2text.FromString: %v", err)
} else {
contentType = "text/plain"
body = plainBody
switchedToPlaintext = true
}
}
msg.SetBody(contentType, body)
if switchedToPlaintext && conf.Email.AddPlainTextAlt && !conf.Email.UsePlainText {
// The AddAlternative method name is confusing - adding html as an "alternative" will actually cause mail
// clients to show it as first priority, and the text "main body" is the 2nd priority fallback.
// See: https://godoc.org/gopkg.in/gomail.v2#Message.AddAlternative
msg.AddAlternative("text/html", htmlBody)
}
return &Message{
Message: msg,
confirmChan: make(chan struct{}),
}
}
// NewMessage creates new mail message object with default From header.
func NewMessage(to []string, subject, body string) *Message {
return NewMessageFrom(to, conf.Email.From, subject, body)
}
type loginAuth struct {
username, password string
}
// SMTP AUTH LOGIN Auth Handler
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
func (*loginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, fmt.Errorf("unknwon fromServer: %s", string(fromServer))
}
}
return nil, nil
}
type Sender struct{}
func (*Sender) Send(from string, to []string, msg io.WriterTo) error {
opts := conf.Email
host, port, err := net.SplitHostPort(opts.Host)
if err != nil {
return err
}
tlsconfig := &tls.Config{
InsecureSkipVerify: opts.SkipVerify,
ServerName: host,
}
if opts.UseCertificate {
cert, err := tls.LoadX509KeyPair(opts.CertFile, opts.KeyFile)
if err != nil {
return err
}
tlsconfig.Certificates = []tls.Certificate{cert}
}
conn, err := net.Dial("tcp", net.JoinHostPort(host, port))
if err != nil {
return err
}
defer conn.Close()
isSecureConn := false
// Start TLS directly if the port ends with 465 (SMTPS protocol)
if strings.HasSuffix(port, "465") {
conn = tls.Client(conn, tlsconfig)
isSecureConn = true
}
client, err := smtp.NewClient(conn, host)
if err != nil {
return fmt.Errorf("NewClient: %v", err)
}
if !opts.DisableHELO {
hostname := opts.HELOHostname
if hostname == "" {
hostname, err = os.Hostname()
if err != nil {
return err
}
}
if err = client.Hello(hostname); err != nil {
return fmt.Errorf("hello: %v", err)
}
}
// If not using SMTPS, always use STARTTLS if available
hasStartTLS, _ := client.Extension("STARTTLS")
if !isSecureConn && hasStartTLS {
if err = client.StartTLS(tlsconfig); err != nil {
return fmt.Errorf("StartTLS: %v", err)
}
}
canAuth, options := client.Extension("AUTH")
if canAuth && len(opts.User) > 0 {
var auth smtp.Auth
if strings.Contains(options, "CRAM-MD5") {
auth = smtp.CRAMMD5Auth(opts.User, opts.Password)
} else if strings.Contains(options, "PLAIN") {
auth = smtp.PlainAuth("", opts.User, opts.Password, host)
} else if strings.Contains(options, "LOGIN") {
// Patch for AUTH LOGIN
auth = LoginAuth(opts.User, opts.Password)
}
if auth != nil {
if err = client.Auth(auth); err != nil {
return fmt.Errorf("auth: %v", err)
}
}
}
if err = client.Mail(from); err != nil {
return fmt.Errorf("mail: %v", err)
}
for _, rec := range to {
if err = client.Rcpt(rec); err != nil {
return fmt.Errorf("rcpt: %v", err)
}
}
w, err := client.Data()
if err != nil {
return fmt.Errorf("data: %v", err)
} else if _, err = msg.WriteTo(w); err != nil {
return fmt.Errorf("write to: %v", err)
} else if err = w.Close(); err != nil {
return fmt.Errorf("close: %v", err)
}
return client.Quit()
}
func processMailQueue() {
sender := &Sender{}
for msg := range mailQueue {
log.Trace("New e-mail sending request %s: %s", msg.GetHeader("To"), msg.Info)
if err := gomail.Send(sender, msg.Message); err != nil {
log.Error("Failed to send emails %s: %s - %v", msg.GetHeader("To"), msg.Info, err)
} else {
log.Trace("E-mails sent %s: %s", msg.GetHeader("To"), msg.Info)
}
msg.confirmChan <- struct{}{}
}
}
var mailQueue chan *Message
// NewContext initializes settings for mailer.
func NewContext() {
// Need to check if mailQueue is nil because in during reinstall (user had installed
// before but switched install lock off), this function will be called again
// while mail queue is already processing tasks, and produces a race condition.
if !conf.Email.Enabled || mailQueue != nil {
return
}
mailQueue = make(chan *Message, 1000)
go processMailQueue()
}
// Send puts new message object into mail queue.
// It returns without confirmation (mail processed asynchronously) in normal cases,
// but waits/blocks under hook mode to make sure mail has been sent.
func Send(msg *Message) {
if !conf.Email.Enabled {
return
}
mailQueue <- msg
if conf.HookMode {
<-msg.confirmChan
return
}
go func() {
<-msg.confirmChan
}()
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/install.go | internal/route/install.go | // Copyright 2014 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 route
import (
"net/mail"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/gogs/git-module"
"github.com/pkg/errors"
"github.com/unknwon/com"
"gopkg.in/ini.v1"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/cron"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/markup"
"gogs.io/gogs/internal/osutil"
"gogs.io/gogs/internal/ssh"
"gogs.io/gogs/internal/strutil"
"gogs.io/gogs/internal/template/highlight"
)
const (
INSTALL = "install"
)
func checkRunMode() {
if conf.IsProdMode() {
macaron.Env = macaron.PROD
macaron.ColorLog = false
git.SetOutput(nil)
} else {
git.SetOutput(os.Stdout)
}
log.Info("Run mode: %s", strings.Title(macaron.Env))
}
// GlobalInit is for global configuration reload-able.
func GlobalInit(customConf string) error {
err := conf.Init(customConf)
if err != nil {
return errors.Wrap(err, "init configuration")
}
conf.InitLogging(false)
log.Info("%s %s", conf.App.BrandName, conf.App.Version)
log.Trace("Work directory: %s", conf.WorkDir())
log.Trace("Custom path: %s", conf.CustomDir())
log.Trace("Custom config: %s", conf.CustomConf)
log.Trace("Log path: %s", conf.Log.RootPath)
log.Trace("Build time: %s", conf.BuildTime)
log.Trace("Build commit: %s", conf.BuildCommit)
if conf.Email.Enabled {
log.Trace("Email service is enabled")
}
email.NewContext()
if conf.Security.InstallLock {
highlight.NewContext()
markup.NewSanitizer()
err := database.NewEngine()
if err != nil {
log.Fatal("Failed to initialize ORM engine: %v", err)
}
database.HasEngine = true
database.LoadRepoConfig()
database.NewRepoContext()
// Booting long running goroutines.
cron.NewContext()
database.InitSyncMirrors()
database.InitDeliverHooks()
database.InitTestPullRequests()
}
if conf.HasMinWinSvc {
log.Info("Builtin Windows Service is supported")
}
if conf.Server.LoadAssetsFromDisk {
log.Trace("Assets are loaded from disk")
}
checkRunMode()
if !conf.Security.InstallLock {
return nil
}
if conf.SSH.StartBuiltinServer {
ssh.Listen(conf.SSH, conf.Server.AppDataPath)
log.Info("SSH server started on %s:%v", conf.SSH.ListenHost, conf.SSH.ListenPort)
log.Trace("SSH server cipher list: %v", conf.SSH.ServerCiphers)
log.Trace("SSH server MAC list: %v", conf.SSH.ServerMACs)
log.Trace("SSH server algorithms: %v", conf.SSH.ServerAlgorithms)
}
if conf.SSH.RewriteAuthorizedKeysAtStart {
if err := database.RewriteAuthorizedKeys(); err != nil {
log.Warn("Failed to rewrite authorized_keys file: %v", err)
}
}
return nil
}
func InstallInit(c *context.Context) {
if conf.Security.InstallLock {
c.NotFound()
return
}
c.Title("install.install")
c.PageIs("Install")
c.Data["DbOptions"] = []string{"MySQL", "PostgreSQL", "SQLite3"}
}
func Install(c *context.Context) {
f := form.Install{}
// Database settings
f.DbHost = conf.Database.Host
f.DbUser = conf.Database.User
f.DbName = conf.Database.Name
f.DbSchema = conf.Database.Schema
f.DbPath = conf.Database.Path
c.Data["CurDbOption"] = "PostgreSQL"
switch conf.Database.Type {
case "mysql":
c.Data["CurDbOption"] = "MySQL"
case "sqlite3":
c.Data["CurDbOption"] = "SQLite3"
}
// Application general settings
f.AppName = conf.App.BrandName
f.RepoRootPath = conf.Repository.Root
// Note(unknwon): it's hard for Windows users change a running user,
// so just use current one if config says default.
if conf.IsWindowsRuntime() && conf.App.RunUser == "git" {
f.RunUser = osutil.CurrentUsername()
} else {
f.RunUser = conf.App.RunUser
}
f.Domain = conf.Server.Domain
f.SSHPort = conf.SSH.Port
f.UseBuiltinSSHServer = conf.SSH.StartBuiltinServer
f.HTTPPort = conf.Server.HTTPPort
f.AppUrl = conf.Server.ExternalURL
f.LogRootPath = conf.Log.RootPath
f.DefaultBranch = conf.Repository.DefaultBranch
// E-mail service settings
if conf.Email.Enabled {
f.SMTPHost = conf.Email.Host
f.SMTPFrom = conf.Email.From
f.SMTPUser = conf.Email.User
}
f.RegisterConfirm = conf.Auth.RequireEmailConfirmation
f.MailNotify = conf.User.EnableEmailNotification
// Server and other services settings
f.OfflineMode = conf.Server.OfflineMode
f.DisableGravatar = conf.Picture.DisableGravatar
f.EnableFederatedAvatar = conf.Picture.EnableFederatedAvatar
f.DisableRegistration = conf.Auth.DisableRegistration
f.EnableCaptcha = conf.Auth.EnableRegistrationCaptcha
f.RequireSignInView = conf.Auth.RequireSigninView
form.Assign(f, c.Data)
c.Success(INSTALL)
}
func InstallPost(c *context.Context, f form.Install) {
c.Data["CurDbOption"] = f.DbType
if c.HasError() {
if c.HasValue("Err_SMTPEmail") {
c.FormErr("SMTP")
}
if c.HasValue("Err_AdminName") ||
c.HasValue("Err_AdminPasswd") ||
c.HasValue("Err_AdminEmail") {
c.FormErr("Admin")
}
c.Success(INSTALL)
return
}
if _, err := exec.LookPath("git"); err != nil {
c.RenderWithErr(c.Tr("install.test_git_failed", err), INSTALL, &f)
return
}
// Pass basic check, now test configuration.
// Test database setting.
dbTypes := map[string]string{
"PostgreSQL": "postgres",
"MySQL": "mysql",
"SQLite3": "sqlite3",
}
conf.Database.Type = dbTypes[f.DbType]
conf.Database.Host = f.DbHost
conf.Database.User = f.DbUser
conf.Database.Password = f.DbPasswd
conf.Database.Name = f.DbName
conf.Database.Schema = f.DbSchema
conf.Database.SSLMode = f.SSLMode
conf.Database.Path = f.DbPath
if conf.Database.Type == "sqlite3" && conf.Database.Path == "" {
c.FormErr("DbPath")
c.RenderWithErr(c.Tr("install.err_empty_db_path"), INSTALL, &f)
return
}
// Set test engine.
if err := database.NewTestEngine(); err != nil {
if strings.Contains(err.Error(), `Unknown database type: sqlite3`) {
c.FormErr("DbType")
c.RenderWithErr(c.Tr("install.sqlite3_not_available", "https://gogs.io/docs/installation/install_from_binary.html"), INSTALL, &f)
} else {
c.FormErr("DbSetting")
c.RenderWithErr(c.Tr("install.invalid_db_setting", err), INSTALL, &f)
}
return
}
// Test repository root path.
f.RepoRootPath = strings.ReplaceAll(f.RepoRootPath, "\\", "/")
if err := os.MkdirAll(f.RepoRootPath, os.ModePerm); err != nil {
c.FormErr("RepoRootPath")
c.RenderWithErr(c.Tr("install.invalid_repo_path", err), INSTALL, &f)
return
}
// Test log root path.
f.LogRootPath = strings.ReplaceAll(f.LogRootPath, "\\", "/")
if err := os.MkdirAll(f.LogRootPath, os.ModePerm); err != nil {
c.FormErr("LogRootPath")
c.RenderWithErr(c.Tr("install.invalid_log_root_path", err), INSTALL, &f)
return
}
currentUser, match := conf.CheckRunUser(f.RunUser)
if !match {
c.FormErr("RunUser")
c.RenderWithErr(c.Tr("install.run_user_not_match", f.RunUser, currentUser), INSTALL, &f)
return
}
// Check host address and port
if len(f.SMTPHost) > 0 && !strings.Contains(f.SMTPHost, ":") {
c.FormErr("SMTP", "SMTPHost")
c.RenderWithErr(c.Tr("install.smtp_host_missing_port"), INSTALL, &f)
return
}
// Make sure FROM field is valid
if len(f.SMTPFrom) > 0 {
_, err := mail.ParseAddress(f.SMTPFrom)
if err != nil {
c.FormErr("SMTP", "SMTPFrom")
c.RenderWithErr(c.Tr("install.invalid_smtp_from", err), INSTALL, &f)
return
}
}
// Check logic loophole between disable self-registration and no admin account.
if f.DisableRegistration && f.AdminName == "" {
c.FormErr("Services", "Admin")
c.RenderWithErr(c.Tr("install.no_admin_and_disable_registration"), INSTALL, f)
return
}
// Check admin password.
if len(f.AdminName) > 0 && f.AdminPasswd == "" {
c.FormErr("Admin", "AdminPasswd")
c.RenderWithErr(c.Tr("install.err_empty_admin_password"), INSTALL, f)
return
}
if f.AdminPasswd != f.AdminConfirmPasswd {
c.FormErr("Admin", "AdminPasswd")
c.RenderWithErr(c.Tr("form.password_not_match"), INSTALL, f)
return
}
if f.AppUrl[len(f.AppUrl)-1] != '/' {
f.AppUrl += "/"
}
// Save settings.
cfg := ini.Empty()
if osutil.IsFile(conf.CustomConf) {
// Keeps custom settings if there is already something.
if err := cfg.Append(conf.CustomConf); err != nil {
log.Error("Failed to load custom conf %q: %v", conf.CustomConf, err)
}
}
cfg.Section("database").Key("TYPE").SetValue(conf.Database.Type)
cfg.Section("database").Key("HOST").SetValue(conf.Database.Host)
cfg.Section("database").Key("NAME").SetValue(conf.Database.Name)
cfg.Section("database").Key("SCHEMA").SetValue(conf.Database.Schema)
cfg.Section("database").Key("USER").SetValue(conf.Database.User)
cfg.Section("database").Key("PASSWORD").SetValue(conf.Database.Password)
cfg.Section("database").Key("SSL_MODE").SetValue(conf.Database.SSLMode)
cfg.Section("database").Key("PATH").SetValue(conf.Database.Path)
cfg.Section("").Key("BRAND_NAME").SetValue(f.AppName)
cfg.Section("repository").Key("ROOT").SetValue(f.RepoRootPath)
cfg.Section("repository").Key("DEFAULT_BRANCH").SetValue(f.DefaultBranch)
cfg.Section("").Key("RUN_USER").SetValue(f.RunUser)
cfg.Section("server").Key("DOMAIN").SetValue(f.Domain)
cfg.Section("server").Key("HTTP_PORT").SetValue(f.HTTPPort)
cfg.Section("server").Key("EXTERNAL_URL").SetValue(f.AppUrl)
if f.SSHPort == 0 {
cfg.Section("server").Key("DISABLE_SSH").SetValue("true")
} else {
cfg.Section("server").Key("DISABLE_SSH").SetValue("false")
cfg.Section("server").Key("SSH_PORT").SetValue(com.ToStr(f.SSHPort))
cfg.Section("server").Key("START_SSH_SERVER").SetValue(com.ToStr(f.UseBuiltinSSHServer))
}
if len(strings.TrimSpace(f.SMTPHost)) > 0 {
cfg.Section("email").Key("ENABLED").SetValue("true")
cfg.Section("email").Key("HOST").SetValue(f.SMTPHost)
cfg.Section("email").Key("FROM").SetValue(f.SMTPFrom)
cfg.Section("email").Key("USER").SetValue(f.SMTPUser)
cfg.Section("email").Key("PASSWORD").SetValue(f.SMTPPasswd)
} else {
cfg.Section("email").Key("ENABLED").SetValue("false")
}
cfg.Section("server").Key("OFFLINE_MODE").SetValue(com.ToStr(f.OfflineMode))
cfg.Section("auth").Key("REQUIRE_EMAIL_CONFIRMATION").SetValue(com.ToStr(f.RegisterConfirm))
cfg.Section("auth").Key("DISABLE_REGISTRATION").SetValue(com.ToStr(f.DisableRegistration))
cfg.Section("auth").Key("ENABLE_REGISTRATION_CAPTCHA").SetValue(com.ToStr(f.EnableCaptcha))
cfg.Section("auth").Key("REQUIRE_SIGNIN_VIEW").SetValue(com.ToStr(f.RequireSignInView))
cfg.Section("user").Key("ENABLE_EMAIL_NOTIFICATION").SetValue(com.ToStr(f.MailNotify))
cfg.Section("picture").Key("DISABLE_GRAVATAR").SetValue(com.ToStr(f.DisableGravatar))
cfg.Section("picture").Key("ENABLE_FEDERATED_AVATAR").SetValue(com.ToStr(f.EnableFederatedAvatar))
cfg.Section("").Key("RUN_MODE").SetValue("prod")
cfg.Section("session").Key("PROVIDER").SetValue("file")
mode := "file"
if f.EnableConsoleMode {
mode = "console, file"
}
cfg.Section("log").Key("MODE").SetValue(mode)
cfg.Section("log").Key("LEVEL").SetValue("Info")
cfg.Section("log").Key("ROOT_PATH").SetValue(f.LogRootPath)
cfg.Section("security").Key("INSTALL_LOCK").SetValue("true")
secretKey, err := strutil.RandomChars(15)
if err != nil {
c.RenderWithErr(c.Tr("install.secret_key_failed", err), INSTALL, &f)
return
}
cfg.Section("security").Key("SECRET_KEY").SetValue(secretKey)
_ = os.MkdirAll(filepath.Dir(conf.CustomConf), os.ModePerm)
if err := cfg.SaveTo(conf.CustomConf); err != nil {
c.RenderWithErr(c.Tr("install.save_config_failed", err), INSTALL, &f)
return
}
// NOTE: We reuse the current value because this handler does not have access to CLI flags.
err = GlobalInit(conf.CustomConf)
if err != nil {
c.RenderWithErr(c.Tr("install.init_failed", err), INSTALL, &f)
return
}
// Create admin account
if len(f.AdminName) > 0 {
user, err := database.Handle.Users().Create(
c.Req.Context(),
f.AdminName,
f.AdminEmail,
database.CreateUserOptions{
Password: f.AdminPasswd,
Activated: true,
Admin: true,
},
)
if err != nil {
if !database.IsErrUserAlreadyExist(err) {
conf.Security.InstallLock = false
c.FormErr("AdminName", "AdminEmail")
c.RenderWithErr(c.Tr("install.invalid_admin_setting", err), INSTALL, &f)
return
}
log.Info("Admin account already exist")
user, err = database.Handle.Users().GetByUsername(c.Req.Context(), f.AdminName)
if err != nil {
c.Error(err, "get user by name")
return
}
}
// Auto-login for admin
_ = c.Session.Set("uid", user.ID)
_ = c.Session.Set("uname", user.Name)
}
log.Info("First-time run install finished!")
c.Flash.Success(c.Tr("install.install_success"))
c.Redirect(f.AppUrl + "user/login")
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/home.go | internal/route/home.go | // Copyright 2014 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 route
import (
gocontext "context"
"fmt"
"net/http"
"github.com/go-macaron/i18n"
"github.com/unknwon/paginater"
"gopkg.in/macaron.v1"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/route/user"
)
const (
tmplHome = "home"
tmplExploreRepos = "explore/repos"
tmplExploreUsers = "explore/users"
tmplExploreOrganizations = "explore/organizations"
)
func Home(c *context.Context) {
if c.IsLogged {
if !c.User.IsActive && conf.Auth.RequireEmailConfirmation {
c.Data["Title"] = c.Tr("auth.active_your_account")
c.Success(user.TmplUserAuthActivate)
} else {
user.Dashboard(c)
}
return
}
// Check auto-login.
uname := c.GetCookie(conf.Security.CookieUsername)
if uname != "" {
c.Redirect(conf.Server.Subpath + "/user/login")
return
}
c.Data["PageIsHome"] = true
c.Success(tmplHome)
}
func ExploreRepos(c *context.Context) {
c.Data["Title"] = c.Tr("explore")
c.Data["PageIsExplore"] = true
c.Data["PageIsExploreRepositories"] = true
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
keyword := c.Query("q")
repos, count, err := database.SearchRepositoryByName(&database.SearchRepoOptions{
Keyword: keyword,
UserID: c.UserID(),
OrderBy: "updated_unix DESC",
Page: page,
PageSize: conf.UI.ExplorePagingNum,
})
if err != nil {
c.Error(err, "search repository by name")
return
}
c.Data["Keyword"] = keyword
c.Data["Total"] = count
c.Data["Page"] = paginater.New(int(count), conf.UI.ExplorePagingNum, page, 5)
if err = database.RepositoryList(repos).LoadAttributes(); err != nil {
c.Error(err, "load attributes")
return
}
c.Data["Repos"] = repos
c.Success(tmplExploreRepos)
}
type UserSearchOptions struct {
Type database.UserType
Counter func(ctx gocontext.Context) int64
Ranger func(ctx gocontext.Context, page, pageSize int) ([]*database.User, error)
PageSize int
OrderBy string
TplName string
}
func RenderUserSearch(c *context.Context, opts *UserSearchOptions) {
page := c.QueryInt("page")
if page <= 1 {
page = 1
}
var (
users []*database.User
count int64
err error
)
keyword := c.Query("q")
if keyword == "" {
users, err = opts.Ranger(c.Req.Context(), page, opts.PageSize)
if err != nil {
c.Error(err, "ranger")
return
}
count = opts.Counter(c.Req.Context())
} else {
search := database.Handle.Users().SearchByName
if opts.Type == database.UserTypeOrganization {
search = database.Handle.Organizations().SearchByName
}
users, count, err = search(c.Req.Context(), keyword, page, opts.PageSize, opts.OrderBy)
if err != nil {
c.Error(err, "search by name")
return
}
}
c.Data["Keyword"] = keyword
c.Data["Total"] = count
c.Data["Page"] = paginater.New(int(count), opts.PageSize, page, 5)
c.Data["Users"] = users
c.Success(opts.TplName)
}
func ExploreUsers(c *context.Context) {
c.Data["Title"] = c.Tr("explore")
c.Data["PageIsExplore"] = true
c.Data["PageIsExploreUsers"] = true
RenderUserSearch(c, &UserSearchOptions{
Type: database.UserTypeIndividual,
Counter: database.Handle.Users().Count,
Ranger: database.Handle.Users().List,
PageSize: conf.UI.ExplorePagingNum,
OrderBy: "updated_unix DESC",
TplName: tmplExploreUsers,
})
}
func ExploreOrganizations(c *context.Context) {
c.Data["Title"] = c.Tr("explore")
c.Data["PageIsExplore"] = true
c.Data["PageIsExploreOrganizations"] = true
RenderUserSearch(c, &UserSearchOptions{
Type: database.UserTypeOrganization,
Counter: func(gocontext.Context) int64 {
return database.CountOrganizations()
},
Ranger: func(_ gocontext.Context, page, pageSize int) ([]*database.User, error) {
return database.Organizations(page, pageSize)
},
PageSize: conf.UI.ExplorePagingNum,
OrderBy: "updated_unix DESC",
TplName: tmplExploreOrganizations,
})
}
func NotFound(c *macaron.Context, l i18n.Locale) {
c.Data["Title"] = l.Tr("status.page_not_found")
c.HTML(http.StatusNotFound, fmt.Sprintf("status/%d", http.StatusNotFound))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/dev/template.go | internal/route/dev/template.go | // Copyright 2014 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 dev
import (
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
)
func TemplatePreview(c *context.Context) {
c.Data["User"] = database.User{Name: "Unknown"}
c.Data["AppName"] = conf.App.BrandName
c.Data["AppVersion"] = conf.App.Version
c.Data["AppURL"] = conf.Server.ExternalURL
c.Data["Code"] = "2014031910370000009fff6782aadb2162b4a997acb69d4400888e0b9274657374"
c.Data["ActiveCodeLives"] = conf.Auth.ActivateCodeLives / 60
c.Data["ResetPwdCodeLives"] = conf.Auth.ResetPasswordCodeLives / 60
c.Data["CurDbValue"] = ""
c.Success(c.Params("*"))
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/user/profile.go | internal/route/user/profile.go | // Copyright 2015 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 user
import (
"strings"
"github.com/unknwon/paginater"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/route/repo"
"gogs.io/gogs/internal/tool"
)
const (
FOLLOWERS = "user/meta/followers"
STARS = "user/meta/stars"
)
func Profile(c *context.Context, puser *context.ParamsUser) {
// Show SSH keys.
if strings.HasSuffix(c.Params(":username"), ".keys") {
ShowSSHKeys(c, puser.ID)
return
}
if puser.IsOrganization() {
showOrgProfile(c)
return
}
c.Title(puser.DisplayName())
c.PageIs("UserProfile")
c.Data["Owner"] = puser
orgs, err := database.GetOrgsByUserID(puser.ID, c.IsLogged && (c.User.IsAdmin || c.User.ID == puser.ID))
if err != nil {
c.Error(err, "get organizations by user ID")
return
}
c.Data["Orgs"] = orgs
tab := c.Query("tab")
c.Data["TabName"] = tab
switch tab {
case "activity":
retrieveFeeds(c, puser.User, c.UserID(), true)
if c.Written() {
return
}
default:
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
showPrivate := c.IsLogged && (puser.ID == c.User.ID || c.User.IsAdmin)
c.Data["Repos"], err = database.GetUserRepositories(&database.UserRepoOptions{
UserID: puser.ID,
Private: showPrivate,
Page: page,
PageSize: conf.UI.User.RepoPagingNum,
})
if err != nil {
c.Error(err, "get user repositories")
return
}
count := database.CountUserRepositories(puser.ID, showPrivate)
c.Data["Page"] = paginater.New(int(count), conf.UI.User.RepoPagingNum, page, 5)
}
c.Success(tmplUserProfile)
}
func Followers(c *context.Context, puser *context.ParamsUser) {
c.Title(puser.DisplayName())
c.PageIs("Followers")
c.Data["CardsTitle"] = c.Tr("user.followers")
c.Data["Owner"] = puser
repo.RenderUserCards(
c,
puser.NumFollowers,
func(page int) ([]*database.User, error) {
return database.Handle.Users().ListFollowers(c.Req.Context(), puser.ID, page, database.ItemsPerPage)
},
FOLLOWERS,
)
}
func Following(c *context.Context, puser *context.ParamsUser) {
c.Title(puser.DisplayName())
c.PageIs("Following")
c.Data["CardsTitle"] = c.Tr("user.following")
c.Data["Owner"] = puser
repo.RenderUserCards(
c,
puser.NumFollowing,
func(page int) ([]*database.User, error) {
return database.Handle.Users().ListFollowings(c.Req.Context(), puser.ID, page, database.ItemsPerPage)
},
FOLLOWERS,
)
}
func Stars(_ *context.Context) {
}
func Action(c *context.Context, puser *context.ParamsUser) {
var err error
switch c.Params(":action") {
case "follow":
err = database.Handle.Users().Follow(c.Req.Context(), c.UserID(), puser.ID)
case "unfollow":
err = database.Handle.Users().Unfollow(c.Req.Context(), c.UserID(), puser.ID)
}
if err != nil {
c.Errorf(err, "action %q", c.Params(":action"))
return
}
redirectTo := c.Query("redirect_to")
if !tool.IsSameSiteURLPath(redirectTo) {
redirectTo = puser.HomeURLPath()
}
c.Redirect(redirectTo)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/user/home.go | internal/route/user/home.go | // Copyright 2014 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 user
import (
"bytes"
"fmt"
"net/http"
"github.com/unknwon/com"
"github.com/unknwon/paginater"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
)
const (
tmplUserDashboard = "user/dashboard/dashboard"
tmplUserDashboardFeeds = "user/dashboard/feeds"
tmplUserDashboardIssues = "user/dashboard/issues"
tmplUserProfile = "user/profile"
tmplOrgHome = "org/home"
)
// getDashboardContextUser finds out dashboard is viewing as which context user.
func getDashboardContextUser(c *context.Context) *database.User {
ctxUser := c.User
orgName := c.Params(":org")
if len(orgName) > 0 {
// Organization.
org, err := database.Handle.Users().GetByUsername(c.Req.Context(), orgName)
if err != nil {
c.NotFoundOrError(err, "get user by name")
return nil
}
ctxUser = org
}
c.Data["ContextUser"] = ctxUser
orgs, err := database.Handle.Organizations().List(
c.Req.Context(),
database.ListOrgsOptions{
MemberID: c.User.ID,
IncludePrivateMembers: true,
},
)
if err != nil {
c.Error(err, "list organizations")
return nil
}
c.Data["Orgs"] = orgs
return ctxUser
}
// retrieveFeeds loads feeds from database by given context user.
// The user could be organization so it is not always the logged in user,
// which is why we have to explicitly pass the context user ID.
func retrieveFeeds(c *context.Context, ctxUser *database.User, userID int64, isProfile bool) {
afterID := c.QueryInt64("after_id")
var err error
var actions []*database.Action
if ctxUser.IsOrganization() {
actions, err = database.Handle.Actions().ListByOrganization(c.Req.Context(), ctxUser.ID, userID, afterID)
} else {
actions, err = database.Handle.Actions().ListByUser(c.Req.Context(), ctxUser.ID, userID, afterID, isProfile)
}
if err != nil {
c.Error(err, "list actions")
return
}
// Check access of private repositories.
feeds := make([]*database.Action, 0, len(actions))
unameAvatars := make(map[string]string)
for _, act := range actions {
// Cache results to reduce queries.
_, ok := unameAvatars[act.ActUserName]
if !ok {
u, err := database.Handle.Users().GetByUsername(c.Req.Context(), act.ActUserName)
if err != nil {
if database.IsErrUserNotExist(err) {
continue
}
c.Error(err, "get user by name")
return
}
unameAvatars[act.ActUserName] = u.AvatarURLPath()
}
act.ActAvatar = unameAvatars[act.ActUserName]
feeds = append(feeds, act)
}
c.Data["Feeds"] = feeds
if len(feeds) > 0 {
afterID := feeds[len(feeds)-1].ID
c.Data["AfterID"] = afterID
c.Header().Set("X-AJAX-URL", fmt.Sprintf("%s?after_id=%d", c.Data["Link"], afterID))
}
}
func Dashboard(c *context.Context) {
ctxUser := getDashboardContextUser(c)
if c.Written() {
return
}
retrieveFeeds(c, ctxUser, c.User.ID, false)
if c.Written() {
return
}
if c.Req.Header.Get("X-AJAX") == "true" {
c.Success(tmplUserDashboardFeeds)
return
}
c.Data["Title"] = ctxUser.DisplayName() + " - " + c.Tr("dashboard")
c.Data["PageIsDashboard"] = true
c.Data["PageIsNews"] = true
// Only user can have collaborative repositories.
if !ctxUser.IsOrganization() {
collaborateRepos, err := database.Handle.Repositories().GetByCollaboratorID(c.Req.Context(), c.User.ID, conf.UI.User.RepoPagingNum, "updated_unix DESC")
if err != nil {
c.Error(err, "get accessible repositories by collaborator")
return
} else if err = database.RepositoryList(collaborateRepos).LoadAttributes(); err != nil {
c.Error(err, "load attributes")
return
}
c.Data["CollaborativeRepos"] = collaborateRepos
}
var err error
var repos, mirrors []*database.Repository
var repoCount int64
if ctxUser.IsOrganization() {
repos, repoCount, err = ctxUser.GetUserRepositories(c.User.ID, 1, conf.UI.User.RepoPagingNum)
if err != nil {
c.Error(err, "get user repositories")
return
}
mirrors, err = ctxUser.GetUserMirrorRepositories(c.User.ID)
if err != nil {
c.Error(err, "get user mirror repositories")
return
}
} else {
repos, err = database.GetUserRepositories(
&database.UserRepoOptions{
UserID: ctxUser.ID,
Private: true,
Page: 1,
PageSize: conf.UI.User.RepoPagingNum,
},
)
if err != nil {
c.Error(err, "get repositories")
return
}
repoCount = int64(ctxUser.NumRepos)
mirrors, err = database.GetUserMirrorRepositories(ctxUser.ID)
if err != nil {
c.Error(err, "get mirror repositories")
return
}
}
c.Data["Repos"] = repos
c.Data["RepoCount"] = repoCount
c.Data["MaxShowRepoNum"] = conf.UI.User.RepoPagingNum
if err := database.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil {
c.Error(err, "load attributes")
return
}
c.Data["MirrorCount"] = len(mirrors)
c.Data["Mirrors"] = mirrors
c.Success(tmplUserDashboard)
}
func Issues(c *context.Context) {
isPullList := c.Params(":type") == "pulls"
if isPullList {
c.Data["Title"] = c.Tr("pull_requests")
c.Data["PageIsPulls"] = true
} else {
c.Data["Title"] = c.Tr("issues")
c.Data["PageIsIssues"] = true
}
ctxUser := getDashboardContextUser(c)
if c.Written() {
return
}
var (
sortType = c.Query("sort")
filterMode = database.FilterModeYourRepos
)
// Note: Organization does not have view type and filter mode.
if !ctxUser.IsOrganization() {
viewType := c.Query("type")
types := []string{
string(database.FilterModeYourRepos),
string(database.FilterModeAssign),
string(database.FilterModeCreate),
}
if !com.IsSliceContainsStr(types, viewType) {
viewType = string(database.FilterModeYourRepos)
}
filterMode = database.FilterMode(viewType)
}
page := c.QueryInt("page")
if page <= 1 {
page = 1
}
repoID := c.QueryInt64("repo")
isShowClosed := c.Query("state") == "closed"
// Get repositories.
var (
err error
repos []*database.Repository
userRepoIDs []int64
showRepos = make([]*database.Repository, 0, 10)
)
if ctxUser.IsOrganization() {
repos, _, err = ctxUser.GetUserRepositories(c.User.ID, 1, ctxUser.NumRepos)
if err != nil {
c.Error(err, "get repositories")
return
}
} else {
repos, err = database.GetUserRepositories(
&database.UserRepoOptions{
UserID: ctxUser.ID,
Private: true,
Page: 1,
PageSize: ctxUser.NumRepos,
},
)
if err != nil {
c.Error(err, "get repositories")
return
}
}
userRepoIDs = make([]int64, 0, len(repos))
for _, repo := range repos {
userRepoIDs = append(userRepoIDs, repo.ID)
if filterMode != database.FilterModeYourRepos {
continue
}
if isPullList {
if isShowClosed && repo.NumClosedPulls == 0 ||
!isShowClosed && repo.NumOpenPulls == 0 {
continue
}
} else {
if !repo.EnableIssues || repo.EnableExternalTracker ||
isShowClosed && repo.NumClosedIssues == 0 ||
!isShowClosed && repo.NumOpenIssues == 0 {
continue
}
}
showRepos = append(showRepos, repo)
}
// Filter repositories if the page shows issues.
if !isPullList {
userRepoIDs, err = database.FilterRepositoryWithIssues(userRepoIDs)
if err != nil {
c.Error(err, "filter repositories with issues")
return
}
}
issueOptions := &database.IssuesOptions{
RepoID: repoID,
Page: page,
IsClosed: isShowClosed,
IsPull: isPullList,
SortType: sortType,
}
switch filterMode {
case database.FilterModeYourRepos:
// Get all issues from repositories from this user.
if userRepoIDs == nil {
issueOptions.RepoIDs = []int64{-1}
} else {
issueOptions.RepoIDs = userRepoIDs
}
case database.FilterModeAssign:
// Get all issues assigned to this user.
issueOptions.AssigneeID = ctxUser.ID
case database.FilterModeCreate:
// Get all issues created by this user.
issueOptions.PosterID = ctxUser.ID
}
issues, err := database.Issues(issueOptions)
if err != nil {
c.Error(err, "list issues")
return
}
if repoID > 0 {
repo, err := database.GetRepositoryByID(repoID)
if err != nil {
c.Error(err, "get repository by ID")
return
}
if err = repo.GetOwner(); err != nil {
c.Error(err, "get owner")
return
}
// Check if user has access to given repository.
if !repo.IsOwnedBy(ctxUser.ID) && !repo.HasAccess(ctxUser.ID) {
c.NotFound()
return
}
}
for _, issue := range issues {
if err = issue.Repo.GetOwner(); err != nil {
c.Error(err, "get owner")
return
}
}
issueStats := database.GetUserIssueStats(repoID, ctxUser.ID, userRepoIDs, filterMode, isPullList)
var total int
if !isShowClosed {
total = int(issueStats.OpenCount)
} else {
total = int(issueStats.ClosedCount)
}
c.Data["Issues"] = issues
c.Data["Repos"] = showRepos
c.Data["Page"] = paginater.New(total, conf.UI.IssuePagingNum, page, 5)
c.Data["IssueStats"] = issueStats
c.Data["ViewType"] = string(filterMode)
c.Data["SortType"] = sortType
c.Data["RepoID"] = repoID
c.Data["IsShowClosed"] = isShowClosed
if isShowClosed {
c.Data["State"] = "closed"
} else {
c.Data["State"] = "open"
}
c.Success(tmplUserDashboardIssues)
}
func ShowSSHKeys(c *context.Context, uid int64) {
keys, err := database.ListPublicKeys(uid)
if err != nil {
c.Error(err, "list public keys")
return
}
var buf bytes.Buffer
for i := range keys {
buf.WriteString(keys[i].OmitEmail())
buf.WriteString("\n")
}
c.PlainText(http.StatusOK, buf.String())
}
func showOrgProfile(c *context.Context) {
c.SetParams(":org", c.Params(":username"))
context.HandleOrgAssignment(c)
if c.Written() {
return
}
org := c.Org.Organization
c.Data["Title"] = org.FullName
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
var (
repos []*database.Repository
count int64
err error
)
if c.IsLogged && !c.User.IsAdmin {
repos, count, err = org.GetUserRepositories(c.User.ID, page, conf.UI.User.RepoPagingNum)
if err != nil {
c.Error(err, "get user repositories")
return
}
c.Data["Repos"] = repos
} else {
showPrivate := c.IsLogged && c.User.IsAdmin
repos, err = database.GetUserRepositories(&database.UserRepoOptions{
UserID: org.ID,
Private: showPrivate,
Page: page,
PageSize: conf.UI.User.RepoPagingNum,
})
if err != nil {
c.Error(err, "get user repositories")
return
}
c.Data["Repos"] = repos
count = database.CountUserRepositories(org.ID, showPrivate)
}
c.Data["Page"] = paginater.New(int(count), conf.UI.User.RepoPagingNum, page, 5)
if err := org.GetMembers(12); err != nil {
c.Error(err, "get members")
return
}
c.Data["Members"] = org.Members
c.Data["Teams"] = org.Teams
c.Success(tmplOrgHome)
}
func Email2User(c *context.Context) {
u, err := database.Handle.Users().GetByEmail(c.Req.Context(), c.Query("email"))
if err != nil {
c.NotFoundOrError(err, "get user by email")
return
}
c.Redirect(conf.Server.Subpath + "/user/" + u.Name)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/user/setting.go | internal/route/user/setting.go | // Copyright 2014 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 user
import (
"bytes"
gocontext "context"
"encoding/base64"
"fmt"
"html/template"
"image/png"
"io"
"github.com/pkg/errors"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"gopkg.in/macaron.v1"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/tool"
"gogs.io/gogs/internal/userutil"
)
// SettingsHandler is the handler for users settings endpoints.
type SettingsHandler struct {
store SettingsStore
}
// NewSettingsHandler returns a new SettingsHandler for users settings endpoints.
func NewSettingsHandler(s SettingsStore) *SettingsHandler {
return &SettingsHandler{
store: s,
}
}
const (
tmplUserSettingsProfile = "user/settings/profile"
tmplUserSettingsAvatar = "user/settings/avatar"
tmplUserSettingsPassword = "user/settings/password"
tmplUserSettingsEmail = "user/settings/email"
tmplUserSettingsSSHKeys = "user/settings/sshkeys"
tmplUserSettingsSecurity = "user/settings/security"
tmplUserSettingsTwoFactorEnable = "user/settings/two_factor_enable"
tmplUserSettingsTwoFactorRecoveryCodes = "user/settings/two_factor_recovery_codes"
tmplUserSettingsRepositories = "user/settings/repositories"
tmplUserSettingsOrganizations = "user/settings/organizations"
tmplUserSettingsApplications = "user/settings/applications"
tmplUserSettingsDelete = "user/settings/delete"
tmplUserNotification = "user/notification"
)
func Settings(c *context.Context) {
c.Title("settings.profile")
c.PageIs("SettingsProfile")
c.Data["origin_name"] = c.User.Name
c.Data["name"] = c.User.Name
c.Data["full_name"] = c.User.FullName
c.Data["email"] = c.User.Email
c.Data["website"] = c.User.Website
c.Data["location"] = c.User.Location
c.Success(tmplUserSettingsProfile)
}
func SettingsPost(c *context.Context, f form.UpdateProfile) {
c.Title("settings.profile")
c.PageIs("SettingsProfile")
c.Data["origin_name"] = c.User.Name
if c.HasError() {
c.Success(tmplUserSettingsProfile)
return
}
// Non-local users are not allowed to change their username
if c.User.IsLocal() {
// Check if the username (including cases) had been changed
if c.User.Name != f.Name {
err := database.Handle.Users().ChangeUsername(c.Req.Context(), c.User.ID, f.Name)
if err != nil {
c.FormErr("Name")
var msg string
switch {
case database.IsErrUserAlreadyExist(errors.Cause(err)):
msg = c.Tr("form.username_been_taken")
case database.IsErrNameNotAllowed(errors.Cause(err)):
msg = c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value())
default:
c.Error(err, "change user name")
return
}
c.RenderWithErr(msg, tmplUserSettingsProfile, &f)
return
}
log.Trace("Username changed: %s -> %s", c.User.Name, f.Name)
}
}
err := database.Handle.Users().Update(
c.Req.Context(),
c.User.ID,
database.UpdateUserOptions{
FullName: &f.FullName,
Website: &f.Website,
Location: &f.Location,
},
)
if err != nil {
c.Error(err, "update user")
return
}
c.Flash.Success(c.Tr("settings.update_profile_success"))
c.RedirectSubpath("/user/settings")
}
// FIXME: limit upload size
func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *database.User) error {
if f.Source == form.AvatarLookup && f.Gravatar != "" {
avatar := cryptoutil.MD5(f.Gravatar)
err := database.Handle.Users().Update(
c.Req.Context(),
ctxUser.ID,
database.UpdateUserOptions{
Avatar: &avatar,
AvatarEmail: &f.Gravatar,
},
)
if err != nil {
return errors.Wrap(err, "update user")
}
err = database.Handle.Users().DeleteCustomAvatar(c.Req.Context(), c.User.ID)
if err != nil {
return errors.Wrap(err, "delete custom avatar")
}
return nil
}
if f.Avatar != nil && f.Avatar.Filename != "" {
r, err := f.Avatar.Open()
if err != nil {
return fmt.Errorf("open avatar reader: %v", err)
}
defer func() { _ = r.Close() }()
data, err := io.ReadAll(r)
if err != nil {
return fmt.Errorf("read avatar content: %v", err)
}
if !tool.IsImageFile(data) {
return errors.New(c.Tr("settings.uploaded_avatar_not_a_image"))
}
err = database.Handle.Users().UseCustomAvatar(c.Req.Context(), ctxUser.ID, data)
if err != nil {
return errors.Wrap(err, "save avatar")
}
return nil
}
return nil
}
func SettingsAvatar(c *context.Context) {
c.Title("settings.avatar")
c.PageIs("SettingsAvatar")
c.Success(tmplUserSettingsAvatar)
}
func SettingsAvatarPost(c *context.Context, f form.Avatar) {
if err := UpdateAvatarSetting(c, f, c.User); err != nil {
c.Flash.Error(err.Error())
} else {
c.Flash.Success(c.Tr("settings.update_avatar_success"))
}
c.RedirectSubpath("/user/settings/avatar")
}
func SettingsDeleteAvatar(c *context.Context) {
err := database.Handle.Users().DeleteCustomAvatar(c.Req.Context(), c.User.ID)
if err != nil {
c.Flash.Error(fmt.Sprintf("Failed to delete avatar: %v", err))
}
c.RedirectSubpath("/user/settings/avatar")
}
func SettingsPassword(c *context.Context) {
c.Title("settings.password")
c.PageIs("SettingsPassword")
c.Success(tmplUserSettingsPassword)
}
func SettingsPasswordPost(c *context.Context, f form.ChangePassword) {
c.Title("settings.password")
c.PageIs("SettingsPassword")
if c.HasError() {
c.Success(tmplUserSettingsPassword)
return
}
if !userutil.ValidatePassword(c.User.Password, c.User.Salt, f.OldPassword) {
c.Flash.Error(c.Tr("settings.password_incorrect"))
} else if f.Password != f.Retype {
c.Flash.Error(c.Tr("form.password_not_match"))
} else {
err := database.Handle.Users().Update(
c.Req.Context(),
c.User.ID,
database.UpdateUserOptions{
Password: &f.Password,
},
)
if err != nil {
c.Errorf(err, "update user")
return
}
c.Flash.Success(c.Tr("settings.change_password_success"))
}
c.RedirectSubpath("/user/settings/password")
}
func SettingsEmails(c *context.Context) {
c.Title("settings.emails")
c.PageIs("SettingsEmails")
emails, err := database.Handle.Users().ListEmails(c.Req.Context(), c.User.ID)
if err != nil {
c.Errorf(err, "get email addresses")
return
}
c.Data["Emails"] = emails
c.Success(tmplUserSettingsEmail)
}
func SettingsEmailPost(c *context.Context, f form.AddEmail) {
c.Title("settings.emails")
c.PageIs("SettingsEmails")
if c.Query("_method") == "PRIMARY" {
err := database.Handle.Users().MarkEmailPrimary(c.Req.Context(), c.User.ID, c.Query("email"))
if err != nil {
c.Errorf(err, "make email primary")
return
}
c.RedirectSubpath("/user/settings/email")
return
}
// Add Email address.
emails, err := database.Handle.Users().ListEmails(c.Req.Context(), c.User.ID)
if err != nil {
c.Errorf(err, "get email addresses")
return
}
c.Data["Emails"] = emails
if c.HasError() {
c.Success(tmplUserSettingsEmail)
return
}
err = database.Handle.Users().AddEmail(c.Req.Context(), c.User.ID, f.Email, !conf.Auth.RequireEmailConfirmation)
if err != nil {
if database.IsErrEmailAlreadyUsed(err) {
c.RenderWithErr(c.Tr("form.email_been_used"), tmplUserSettingsEmail, &f)
} else {
c.Errorf(err, "add email address")
}
return
}
// Send confirmation email
if conf.Auth.RequireEmailConfirmation {
email.SendActivateEmailMail(c.Context, database.NewMailerUser(c.User), f.Email)
if err := c.Cache.Put("MailResendLimit_"+c.User.LowerName, c.User.LowerName, 180); err != nil {
log.Error("Set cache 'MailResendLimit' failed: %v", err)
}
c.Flash.Info(c.Tr("settings.add_email_confirmation_sent", f.Email, conf.Auth.ActivateCodeLives/60))
} else {
c.Flash.Success(c.Tr("settings.add_email_success"))
}
c.RedirectSubpath("/user/settings/email")
}
func DeleteEmail(c *context.Context) {
email := c.Query("id") // The "id" here is the actual email address
if c.User.Email == email {
c.Flash.Error(c.Tr("settings.email_deletion_primary"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/email",
})
return
}
err := database.Handle.Users().DeleteEmail(c.Req.Context(), c.User.ID, email)
if err != nil {
c.Error(err, "delete email address")
return
}
c.Flash.Success(c.Tr("settings.email_deletion_success"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/email",
})
}
func SettingsSSHKeys(c *context.Context) {
c.Title("settings.ssh_keys")
c.PageIs("SettingsSSHKeys")
keys, err := database.ListPublicKeys(c.User.ID)
if err != nil {
c.Errorf(err, "list public keys")
return
}
c.Data["Keys"] = keys
c.Success(tmplUserSettingsSSHKeys)
}
func SettingsSSHKeysPost(c *context.Context, f form.AddSSHKey) {
c.Title("settings.ssh_keys")
c.PageIs("SettingsSSHKeys")
keys, err := database.ListPublicKeys(c.User.ID)
if err != nil {
c.Errorf(err, "list public keys")
return
}
c.Data["Keys"] = keys
if c.HasError() {
c.Success(tmplUserSettingsSSHKeys)
return
}
content, err := database.CheckPublicKeyString(f.Content)
if err != nil {
if database.IsErrKeyUnableVerify(err) {
c.Flash.Info(c.Tr("form.unable_verify_ssh_key"))
} else {
c.Flash.Error(c.Tr("form.invalid_ssh_key", err.Error()))
c.RedirectSubpath("/user/settings/ssh")
return
}
}
if _, err = database.AddPublicKey(c.User.ID, f.Title, content); err != nil {
c.Data["HasError"] = true
switch {
case database.IsErrKeyAlreadyExist(err):
c.FormErr("Content")
c.RenderWithErr(c.Tr("settings.ssh_key_been_used"), tmplUserSettingsSSHKeys, &f)
case database.IsErrKeyNameAlreadyUsed(err):
c.FormErr("Title")
c.RenderWithErr(c.Tr("settings.ssh_key_name_used"), tmplUserSettingsSSHKeys, &f)
default:
c.Errorf(err, "add public key")
}
return
}
c.Flash.Success(c.Tr("settings.add_key_success", f.Title))
c.RedirectSubpath("/user/settings/ssh")
}
func DeleteSSHKey(c *context.Context) {
if err := database.DeletePublicKey(c.User, c.QueryInt64("id")); err != nil {
c.Flash.Error("DeletePublicKey: " + err.Error())
} else {
c.Flash.Success(c.Tr("settings.ssh_key_deletion_success"))
}
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/ssh",
})
}
func SettingsSecurity(c *context.Context) {
c.Title("settings.security")
c.PageIs("SettingsSecurity")
t, err := database.Handle.TwoFactors().GetByUserID(c.Req.Context(), c.UserID())
if err != nil && !database.IsErrTwoFactorNotFound(err) {
c.Errorf(err, "get two factor by user ID")
return
}
c.Data["TwoFactor"] = t
c.Success(tmplUserSettingsSecurity)
}
func SettingsTwoFactorEnable(c *context.Context) {
if database.Handle.TwoFactors().IsEnabled(c.Req.Context(), c.User.ID) {
c.NotFound()
return
}
c.Title("settings.two_factor_enable_title")
c.PageIs("SettingsSecurity")
var key *otp.Key
var err error
keyURL := c.Session.Get("twoFactorURL")
if keyURL != nil {
key, _ = otp.NewKeyFromURL(keyURL.(string))
}
if key == nil {
key, err = totp.Generate(totp.GenerateOpts{
Issuer: conf.App.BrandName,
AccountName: c.User.Email,
})
if err != nil {
c.Errorf(err, "generate TOTP")
return
}
}
c.Data["TwoFactorSecret"] = key.Secret()
img, err := key.Image(240, 240)
if err != nil {
c.Errorf(err, "generate image")
return
}
var buf bytes.Buffer
if err = png.Encode(&buf, img); err != nil {
c.Errorf(err, "encode image")
return
}
c.Data["QRCode"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()))
_ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"])
_ = c.Session.Set("twoFactorURL", key.String())
c.Success(tmplUserSettingsTwoFactorEnable)
}
func SettingsTwoFactorEnablePost(c *context.Context) {
secret, ok := c.Session.Get("twoFactorSecret").(string)
if !ok {
c.NotFound()
return
}
if !totp.Validate(c.Query("passcode"), secret) {
c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
c.RedirectSubpath("/user/settings/security/two_factor_enable")
return
}
if err := database.Handle.TwoFactors().Create(c.Req.Context(), c.UserID(), conf.Security.SecretKey, secret); err != nil {
c.Flash.Error(c.Tr("settings.two_factor_enable_error", err))
c.RedirectSubpath("/user/settings/security/two_factor_enable")
return
}
_ = c.Session.Delete("twoFactorSecret")
_ = c.Session.Delete("twoFactorURL")
c.Flash.Success(c.Tr("settings.two_factor_enable_success"))
c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes")
}
func SettingsTwoFactorRecoveryCodes(c *context.Context) {
if !database.Handle.TwoFactors().IsEnabled(c.Req.Context(), c.User.ID) {
c.NotFound()
return
}
c.Title("settings.two_factor_recovery_codes_title")
c.PageIs("SettingsSecurity")
recoveryCodes, err := database.GetRecoveryCodesByUserID(c.UserID())
if err != nil {
c.Errorf(err, "get recovery codes by user ID")
return
}
c.Data["RecoveryCodes"] = recoveryCodes
c.Success(tmplUserSettingsTwoFactorRecoveryCodes)
}
func SettingsTwoFactorRecoveryCodesPost(c *context.Context) {
if !database.Handle.TwoFactors().IsEnabled(c.Req.Context(), c.User.ID) {
c.NotFound()
return
}
if err := database.RegenerateRecoveryCodes(c.UserID()); err != nil {
c.Flash.Error(c.Tr("settings.two_factor_regenerate_recovery_codes_error", err))
} else {
c.Flash.Success(c.Tr("settings.two_factor_regenerate_recovery_codes_success"))
}
c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes")
}
func SettingsTwoFactorDisable(c *context.Context) {
if !database.Handle.TwoFactors().IsEnabled(c.Req.Context(), c.User.ID) {
c.NotFound()
return
}
if err := database.DeleteTwoFactor(c.UserID()); err != nil {
c.Errorf(err, "delete two factor")
return
}
c.Flash.Success(c.Tr("settings.two_factor_disable_success"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/security",
})
}
func SettingsRepos(c *context.Context) {
c.Title("settings.repos")
c.PageIs("SettingsRepositories")
repos, err := database.GetUserAndCollaborativeRepositories(c.User.ID)
if err != nil {
c.Errorf(err, "get user and collaborative repositories")
return
}
if err = database.RepositoryList(repos).LoadAttributes(); err != nil {
c.Errorf(err, "load attributes")
return
}
c.Data["Repos"] = repos
c.Success(tmplUserSettingsRepositories)
}
func SettingsLeaveRepo(c *context.Context) {
repo, err := database.GetRepositoryByID(c.QueryInt64("id"))
if err != nil {
c.NotFoundOrError(err, "get repository by ID")
return
}
if err = repo.DeleteCollaboration(c.User.ID); err != nil {
c.Errorf(err, "delete collaboration")
return
}
c.Flash.Success(c.Tr("settings.repos.leave_success", repo.FullName()))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/repositories",
})
}
func SettingsOrganizations(c *context.Context) {
c.Title("settings.orgs")
c.PageIs("SettingsOrganizations")
orgs, err := database.GetOrgsByUserID(c.User.ID, true)
if err != nil {
c.Errorf(err, "get organizations by user ID")
return
}
c.Data["Orgs"] = orgs
c.Success(tmplUserSettingsOrganizations)
}
func SettingsLeaveOrganization(c *context.Context) {
if err := database.RemoveOrgUser(c.QueryInt64("id"), c.User.ID); err != nil {
if database.IsErrLastOrgOwner(err) {
c.Flash.Error(c.Tr("form.last_org_owner"))
} else {
c.Errorf(err, "remove organization user")
return
}
}
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/organizations",
})
}
func (h *SettingsHandler) Applications() macaron.Handler {
return func(c *context.Context) {
c.Title("settings.applications")
c.PageIs("SettingsApplications")
tokens, err := h.store.ListAccessTokens(c.Req.Context(), c.User.ID)
if err != nil {
c.Errorf(err, "list access tokens")
return
}
c.Data["Tokens"] = tokens
c.Success(tmplUserSettingsApplications)
}
}
func (h *SettingsHandler) ApplicationsPost() macaron.Handler {
return func(c *context.Context, f form.NewAccessToken) {
c.Title("settings.applications")
c.PageIs("SettingsApplications")
if c.HasError() {
tokens, err := h.store.ListAccessTokens(c.Req.Context(), c.User.ID)
if err != nil {
c.Errorf(err, "list access tokens")
return
}
c.Data["Tokens"] = tokens
c.Success(tmplUserSettingsApplications)
return
}
t, err := h.store.CreateAccessToken(c.Req.Context(), c.User.ID, f.Name)
if err != nil {
if database.IsErrAccessTokenAlreadyExist(err) {
c.Flash.Error(c.Tr("settings.token_name_exists"))
c.RedirectSubpath("/user/settings/applications")
} else {
c.Errorf(err, "new access token")
}
return
}
c.Flash.Success(c.Tr("settings.generate_token_succees"))
c.Flash.Info(t.Sha1)
c.RedirectSubpath("/user/settings/applications")
}
}
func (h *SettingsHandler) DeleteApplication() macaron.Handler {
return func(c *context.Context) {
if err := h.store.DeleteAccessTokenByID(c.Req.Context(), c.User.ID, c.QueryInt64("id")); err != nil {
c.Flash.Error("DeleteAccessTokenByID: " + err.Error())
} else {
c.Flash.Success(c.Tr("settings.delete_token_success"))
}
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/user/settings/applications",
})
}
}
func SettingsDelete(c *context.Context) {
c.Title("settings.delete")
c.PageIs("SettingsDelete")
if c.Req.Method == "POST" {
if _, err := database.Handle.Users().Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil {
if auth.IsErrBadCredentials(err) {
c.RenderWithErr(c.Tr("form.enterred_invalid_password"), tmplUserSettingsDelete, nil)
} else {
c.Errorf(err, "authenticate user")
}
return
}
if err := database.Handle.Users().DeleteByID(c.Req.Context(), c.User.ID, false); err != nil {
switch {
case database.IsErrUserOwnRepos(err):
c.Flash.Error(c.Tr("form.still_own_repo"))
c.Redirect(conf.Server.Subpath + "/user/settings/delete")
case database.IsErrUserHasOrgs(err):
c.Flash.Error(c.Tr("form.still_has_org"))
c.Redirect(conf.Server.Subpath + "/user/settings/delete")
default:
c.Errorf(err, "delete user")
}
} else {
log.Trace("Account deleted: %s", c.User.Name)
c.Redirect(conf.Server.Subpath + "/")
}
return
}
c.Success(tmplUserSettingsDelete)
}
// SettingsStore is the data layer carrier for user settings endpoints. This
// interface is meant to abstract away and limit the exposure of the underlying
// data layer to the handler through a thin-wrapper.
type SettingsStore interface {
// CreateAccessToken creates a new access token and persist to database. It
// returns database.ErrAccessTokenAlreadyExist when an access token with same
// name already exists for the user.
CreateAccessToken(ctx gocontext.Context, userID int64, name string) (*database.AccessToken, error)
// GetAccessTokenBySHA1 returns the access token with given SHA1. It returns
// database.ErrAccessTokenNotExist when not found.
GetAccessTokenBySHA1(ctx gocontext.Context, sha1 string) (*database.AccessToken, error)
// TouchAccessTokenByID updates the updated time of the given access token to
// the current time.
TouchAccessTokenByID(ctx gocontext.Context, id int64) error
// ListAccessTokens returns all access tokens belongs to given user.
ListAccessTokens(ctx gocontext.Context, userID int64) ([]*database.AccessToken, error)
// DeleteAccessTokenByID deletes the access token by given ID.
DeleteAccessTokenByID(ctx gocontext.Context, userID, id int64) error
}
type settingsStore struct{}
// NewSettingsStore returns a new SettingsStore using the global database
// handle.
func NewSettingsStore() SettingsStore {
return &settingsStore{}
}
func (*settingsStore) CreateAccessToken(ctx gocontext.Context, userID int64, name string) (*database.AccessToken, error) {
return database.Handle.AccessTokens().Create(ctx, userID, name)
}
func (*settingsStore) GetAccessTokenBySHA1(ctx gocontext.Context, sha1 string) (*database.AccessToken, error) {
return database.Handle.AccessTokens().GetBySHA1(ctx, sha1)
}
func (*settingsStore) TouchAccessTokenByID(ctx gocontext.Context, id int64) error {
return database.Handle.AccessTokens().Touch(ctx, id)
}
func (*settingsStore) ListAccessTokens(ctx gocontext.Context, userID int64) ([]*database.AccessToken, error) {
return database.Handle.AccessTokens().List(ctx, userID)
}
func (*settingsStore) DeleteAccessTokenByID(ctx gocontext.Context, userID, id int64) error {
return database.Handle.AccessTokens().DeleteByID(ctx, userID, id)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/user/auth.go | internal/route/user/auth.go | // Copyright 2014 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 user
import (
gocontext "context"
"encoding/hex"
"fmt"
"net/http"
"net/url"
"github.com/go-macaron/captcha"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/tool"
"gogs.io/gogs/internal/userutil"
)
const (
tmplUserAuthLogin = "user/auth/login"
tmplUserAuthTwoFactor = "user/auth/two_factor"
tmplUserAuthTwoFactorRecoveryCode = "user/auth/two_factor_recovery_code"
tmplUserAuthSignup = "user/auth/signup"
TmplUserAuthActivate = "user/auth/activate"
tmplUserAuthForgotPassword = "user/auth/forgot_passwd"
tmplUserAuthResetPassword = "user/auth/reset_passwd"
)
// AutoLogin reads cookie and try to auto-login.
func AutoLogin(c *context.Context) (bool, error) {
if !database.HasEngine {
return false, nil
}
uname := c.GetCookie(conf.Security.CookieUsername)
if uname == "" {
return false, nil
}
isSucceed := false
defer func() {
if !isSucceed {
log.Trace("auto-login cookie cleared: %s", uname)
c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath)
c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath)
c.SetCookie(conf.Security.LoginStatusCookieName, "", -1, conf.Server.Subpath)
}
}()
u, err := database.Handle.Users().GetByUsername(c.Req.Context(), uname)
if err != nil {
if !database.IsErrUserNotExist(err) {
return false, fmt.Errorf("get user by name: %v", err)
}
return false, nil
}
if val, ok := c.GetSuperSecureCookie(u.Rands+u.Password, conf.Security.CookieRememberName); !ok || val != u.Name {
return false, nil
}
isSucceed = true
_ = c.Session.Set("uid", u.ID)
_ = c.Session.Set("uname", u.Name)
c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
if conf.Security.EnableLoginStatusCookie {
c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath)
}
return true, nil
}
func Login(c *context.Context) {
c.Title("sign_in")
// Check auto-login
isSucceed, err := AutoLogin(c)
if err != nil {
c.Error(err, "auto login")
return
}
redirectTo := c.Query("redirect_to")
if len(redirectTo) > 0 {
c.SetCookie("redirect_to", redirectTo, 0, conf.Server.Subpath)
} else {
redirectTo, _ = url.QueryUnescape(c.GetCookie("redirect_to"))
}
if isSucceed {
if tool.IsSameSiteURLPath(redirectTo) {
c.Redirect(redirectTo)
} else {
c.RedirectSubpath("/")
}
c.SetCookie("redirect_to", "", -1, conf.Server.Subpath)
return
}
// Display normal login page
loginSources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{OnlyActivated: true})
if err != nil {
c.Error(err, "list activated login sources")
return
}
c.Data["LoginSources"] = loginSources
for i := range loginSources {
if loginSources[i].IsDefault {
c.Data["DefaultLoginSource"] = loginSources[i]
c.Data["login_source"] = loginSources[i].ID
break
}
}
c.Success(tmplUserAuthLogin)
}
func afterLogin(c *context.Context, u *database.User, remember bool) {
if remember {
days := 86400 * conf.Security.LoginRememberDays
c.SetCookie(conf.Security.CookieUsername, u.Name, days, conf.Server.Subpath, "", conf.Security.CookieSecure, true)
c.SetSuperSecureCookie(u.Rands+u.Password, conf.Security.CookieRememberName, u.Name, days, conf.Server.Subpath, "", conf.Security.CookieSecure, true)
}
_ = c.Session.Set("uid", u.ID)
_ = c.Session.Set("uname", u.Name)
_ = c.Session.Delete("twoFactorRemember")
_ = c.Session.Delete("twoFactorUserID")
// Clear whatever CSRF has right now, force to generate a new one
c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
if conf.Security.EnableLoginStatusCookie {
c.SetCookie(conf.Security.LoginStatusCookieName, "true", 0, conf.Server.Subpath)
}
redirectTo, _ := url.QueryUnescape(c.GetCookie("redirect_to"))
c.SetCookie("redirect_to", "", -1, conf.Server.Subpath)
if tool.IsSameSiteURLPath(redirectTo) {
c.Redirect(redirectTo)
return
}
c.RedirectSubpath("/")
}
func LoginPost(c *context.Context, f form.SignIn) {
c.Title("sign_in")
loginSources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{OnlyActivated: true})
if err != nil {
c.Error(err, "list activated login sources")
return
}
c.Data["LoginSources"] = loginSources
if c.HasError() {
c.Success(tmplUserAuthLogin)
return
}
u, err := database.Handle.Users().Authenticate(c.Req.Context(), f.UserName, f.Password, f.LoginSource)
if err != nil {
switch {
case auth.IsErrBadCredentials(err):
c.FormErr("UserName", "Password")
c.RenderWithErr(c.Tr("form.username_password_incorrect"), tmplUserAuthLogin, &f)
case database.IsErrLoginSourceMismatch(err):
c.FormErr("LoginSource")
c.RenderWithErr(c.Tr("form.auth_source_mismatch"), tmplUserAuthLogin, &f)
default:
c.Error(err, "authenticate user")
}
for i := range loginSources {
if loginSources[i].IsDefault {
c.Data["DefaultLoginSource"] = loginSources[i]
break
}
}
return
}
if !database.Handle.TwoFactors().IsEnabled(c.Req.Context(), u.ID) {
afterLogin(c, u, f.Remember)
return
}
_ = c.Session.Set("twoFactorRemember", f.Remember)
_ = c.Session.Set("twoFactorUserID", u.ID)
c.RedirectSubpath("/user/login/two_factor")
}
func LoginTwoFactor(c *context.Context) {
_, ok := c.Session.Get("twoFactorUserID").(int64)
if !ok {
c.NotFound()
return
}
c.Success(tmplUserAuthTwoFactor)
}
func LoginTwoFactorPost(c *context.Context) {
userID, ok := c.Session.Get("twoFactorUserID").(int64)
if !ok {
c.NotFound()
return
}
t, err := database.Handle.TwoFactors().GetByUserID(c.Req.Context(), userID)
if err != nil {
c.Error(err, "get two factor by user ID")
return
}
passcode := c.Query("passcode")
valid, err := t.ValidateTOTP(passcode)
if err != nil {
c.Error(err, "validate TOTP")
return
} else if !valid {
c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
c.RedirectSubpath("/user/login/two_factor")
return
}
u, err := database.Handle.Users().GetByID(c.Req.Context(), userID)
if err != nil {
c.Error(err, "get user by ID")
return
}
// Prevent same passcode from being reused
if c.Cache.IsExist(userutil.TwoFactorCacheKey(u.ID, passcode)) {
c.Flash.Error(c.Tr("settings.two_factor_reused_passcode"))
c.RedirectSubpath("/user/login/two_factor")
return
}
if err = c.Cache.Put(userutil.TwoFactorCacheKey(u.ID, passcode), 1, 60); err != nil {
log.Error("Failed to put cache 'two factor passcode': %v", err)
}
afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
}
func LoginTwoFactorRecoveryCode(c *context.Context) {
_, ok := c.Session.Get("twoFactorUserID").(int64)
if !ok {
c.NotFound()
return
}
c.Success(tmplUserAuthTwoFactorRecoveryCode)
}
func LoginTwoFactorRecoveryCodePost(c *context.Context) {
userID, ok := c.Session.Get("twoFactorUserID").(int64)
if !ok {
c.NotFound()
return
}
if err := database.UseRecoveryCode(userID, c.Query("recovery_code")); err != nil {
if database.IsTwoFactorRecoveryCodeNotFound(err) {
c.Flash.Error(c.Tr("auth.login_two_factor_invalid_recovery_code"))
c.RedirectSubpath("/user/login/two_factor_recovery_code")
} else {
c.Error(err, "use recovery code")
}
return
}
u, err := database.Handle.Users().GetByID(c.Req.Context(), userID)
if err != nil {
c.Error(err, "get user by ID")
return
}
afterLogin(c, u, c.Session.Get("twoFactorRemember").(bool))
}
func SignOut(c *context.Context) {
_ = c.Session.Flush()
_ = c.Session.Destory(c.Context)
c.SetCookie(conf.Security.CookieUsername, "", -1, conf.Server.Subpath)
c.SetCookie(conf.Security.CookieRememberName, "", -1, conf.Server.Subpath)
c.SetCookie(conf.Session.CSRFCookieName, "", -1, conf.Server.Subpath)
c.RedirectSubpath("/")
}
func SignUp(c *context.Context) {
c.Title("sign_up")
c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
if conf.Auth.DisableRegistration {
c.Data["DisableRegistration"] = true
c.Success(tmplUserAuthSignup)
return
}
c.Success(tmplUserAuthSignup)
}
func SignUpPost(c *context.Context, cpt *captcha.Captcha, f form.Register) {
c.Title("sign_up")
c.Data["EnableCaptcha"] = conf.Auth.EnableRegistrationCaptcha
if conf.Auth.DisableRegistration {
c.Status(http.StatusForbidden)
return
}
if c.HasError() {
c.Success(tmplUserAuthSignup)
return
}
if conf.Auth.EnableRegistrationCaptcha && !cpt.VerifyReq(c.Req) {
c.FormErr("Captcha")
c.RenderWithErr(c.Tr("form.captcha_incorrect"), tmplUserAuthSignup, &f)
return
}
if f.Password != f.Retype {
c.FormErr("Password")
c.RenderWithErr(c.Tr("form.password_not_match"), tmplUserAuthSignup, &f)
return
}
user, err := database.Handle.Users().Create(
c.Req.Context(),
f.UserName,
f.Email,
database.CreateUserOptions{
Password: f.Password,
Activated: !conf.Auth.RequireEmailConfirmation,
},
)
if err != nil {
switch {
case database.IsErrUserAlreadyExist(err):
c.FormErr("UserName")
c.RenderWithErr(c.Tr("form.username_been_taken"), tmplUserAuthSignup, &f)
case database.IsErrEmailAlreadyUsed(err):
c.FormErr("Email")
c.RenderWithErr(c.Tr("form.email_been_used"), tmplUserAuthSignup, &f)
case database.IsErrNameNotAllowed(err):
c.FormErr("UserName")
c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplUserAuthSignup, &f)
default:
c.Error(err, "create user")
}
return
}
log.Trace("Account created: %s", user.Name)
// FIXME: Count has pretty bad performance implication in large instances, we
// should have a dedicate method to check whether the "user" table is empty.
//
// Auto-set admin for the only user.
if database.Handle.Users().Count(c.Req.Context()) == 1 {
v := true
err := database.Handle.Users().Update(
c.Req.Context(),
user.ID,
database.UpdateUserOptions{
IsActivated: &v,
IsAdmin: &v,
},
)
if err != nil {
c.Error(err, "update user")
return
}
}
// Send confirmation email.
if conf.Auth.RequireEmailConfirmation && user.ID > 1 {
email.SendActivateAccountMail(c.Context, database.NewMailerUser(user))
c.Data["IsSendRegisterMail"] = true
c.Data["Email"] = user.Email
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
c.Success(TmplUserAuthActivate)
if err := c.Cache.Put(userutil.MailResendCacheKey(user.ID), 1, 180); err != nil {
log.Error("Failed to put cache key 'mail resend': %v", err)
}
return
}
c.RedirectSubpath("/user/login")
}
// parseUserFromCode returns user by username encoded in code.
// It returns nil if code or username is invalid.
func parseUserFromCode(code string) (user *database.User) {
if len(code) <= tool.TimeLimitCodeLength {
return nil
}
// Use tail hex username to query user
hexStr := code[tool.TimeLimitCodeLength:]
if b, err := hex.DecodeString(hexStr); err == nil {
if user, err = database.Handle.Users().GetByUsername(gocontext.TODO(), string(b)); user != nil {
return user
} else if !database.IsErrUserNotExist(err) {
log.Error("Failed to get user by name %q: %v", string(b), err)
}
}
return nil
}
// verify active code when active account
func verifyUserActiveCode(code string) (user *database.User) {
minutes := conf.Auth.ActivateCodeLives
if user = parseUserFromCode(code); user != nil {
// time limit code
prefix := code[:tool.TimeLimitCodeLength]
data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Password + user.Rands
if tool.VerifyTimeLimitCode(data, minutes, prefix) {
return user
}
}
return nil
}
// verify active code when active account
func verifyActiveEmailCode(code, email string) *database.EmailAddress {
minutes := conf.Auth.ActivateCodeLives
if user := parseUserFromCode(code); user != nil {
// time limit code
prefix := code[:tool.TimeLimitCodeLength]
data := com.ToStr(user.ID) + email + user.LowerName + user.Password + user.Rands
if tool.VerifyTimeLimitCode(data, minutes, prefix) {
emailAddress, err := database.Handle.Users().GetEmail(gocontext.TODO(), user.ID, email, false)
if err == nil {
return emailAddress
}
}
}
return nil
}
func Activate(c *context.Context) {
code := c.Query("code")
if code == "" {
c.Data["IsActivatePage"] = true
if c.User.IsActive {
c.NotFound()
return
}
// Resend confirmation email.
if conf.Auth.RequireEmailConfirmation {
if c.Cache.IsExist(userutil.MailResendCacheKey(c.User.ID)) {
c.Data["ResendLimited"] = true
} else {
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
email.SendActivateAccountMail(c.Context, database.NewMailerUser(c.User))
if err := c.Cache.Put(userutil.MailResendCacheKey(c.User.ID), 1, 180); err != nil {
log.Error("Failed to put cache key 'mail resend': %v", err)
}
}
} else {
c.Data["ServiceNotEnabled"] = true
}
c.Success(TmplUserAuthActivate)
return
}
// Verify code.
if user := verifyUserActiveCode(code); user != nil {
v := true
err := database.Handle.Users().Update(
c.Req.Context(),
user.ID,
database.UpdateUserOptions{
GenerateNewRands: true,
IsActivated: &v,
},
)
if err != nil {
c.Error(err, "update user")
return
}
log.Trace("User activated: %s", user.Name)
_ = c.Session.Set("uid", user.ID)
_ = c.Session.Set("uname", user.Name)
c.RedirectSubpath("/")
return
}
c.Data["IsActivateFailed"] = true
c.Success(TmplUserAuthActivate)
}
func ActivateEmail(c *context.Context) {
code := c.Query("code")
emailAddr := c.Query("email")
// Verify code.
if email := verifyActiveEmailCode(code, emailAddr); email != nil {
err := database.Handle.Users().MarkEmailActivated(c.Req.Context(), email.UserID, email.Email)
if err != nil {
c.Error(err, "activate email")
return
}
log.Trace("Email activated: %s", email.Email)
c.Flash.Success(c.Tr("settings.add_email_success"))
}
c.RedirectSubpath("/user/settings/email")
}
func ForgotPasswd(c *context.Context) {
c.Title("auth.forgot_password")
if !conf.Email.Enabled {
c.Data["IsResetDisable"] = true
c.Success(tmplUserAuthForgotPassword)
return
}
c.Data["IsResetRequest"] = true
c.Success(tmplUserAuthForgotPassword)
}
func ForgotPasswdPost(c *context.Context) {
c.Title("auth.forgot_password")
if !conf.Email.Enabled {
c.Status(403)
return
}
c.Data["IsResetRequest"] = true
emailAddr := c.Query("email")
c.Data["Email"] = emailAddr
u, err := database.Handle.Users().GetByEmail(c.Req.Context(), emailAddr)
if err != nil {
if database.IsErrUserNotExist(err) {
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
c.Data["IsResetSent"] = true
c.Success(tmplUserAuthForgotPassword)
return
}
c.Error(err, "get user by email")
return
}
if !u.IsLocal() {
c.FormErr("Email")
c.RenderWithErr(c.Tr("auth.non_local_account"), tmplUserAuthForgotPassword, nil)
return
}
if c.Cache.IsExist(userutil.MailResendCacheKey(u.ID)) {
c.Data["ResendLimited"] = true
c.Success(tmplUserAuthForgotPassword)
return
}
email.SendResetPasswordMail(c.Context, database.NewMailerUser(u))
if err = c.Cache.Put(userutil.MailResendCacheKey(u.ID), 1, 180); err != nil {
log.Error("Failed to put cache key 'mail resend': %v", err)
}
c.Data["Hours"] = conf.Auth.ActivateCodeLives / 60
c.Data["IsResetSent"] = true
c.Success(tmplUserAuthForgotPassword)
}
func ResetPasswd(c *context.Context) {
c.Title("auth.reset_password")
code := c.Query("code")
if code == "" {
c.NotFound()
return
}
c.Data["Code"] = code
c.Data["IsResetForm"] = true
c.Success(tmplUserAuthResetPassword)
}
func ResetPasswdPost(c *context.Context) {
c.Title("auth.reset_password")
code := c.Query("code")
if code == "" {
c.NotFound()
return
}
c.Data["Code"] = code
if u := verifyUserActiveCode(code); u != nil {
// Validate password length.
password := c.Query("password")
if len(password) < 6 {
c.Data["IsResetForm"] = true
c.Data["Err_Password"] = true
c.RenderWithErr(c.Tr("auth.password_too_short"), tmplUserAuthResetPassword, nil)
return
}
err := database.Handle.Users().Update(c.Req.Context(), u.ID, database.UpdateUserOptions{Password: &password})
if err != nil {
c.Error(err, "update user")
return
}
log.Trace("User password reset: %s", u.Name)
c.RedirectSubpath("/user/login")
return
}
c.Data["IsResetFailed"] = true
c.Success(tmplUserAuthResetPassword)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/admin/admin.go | internal/route/admin/admin.go | // Copyright 2014 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 admin
import (
"fmt"
"runtime"
"strings"
"time"
jsoniter "github.com/json-iterator/go"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/cron"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/process"
"gogs.io/gogs/internal/tool"
)
const (
tmplDashboard = "admin/dashboard"
tmplConfig = "admin/config"
tmplMonitor = "admin/monitor"
)
// initTime is the time when the application was initialized.
var initTime = time.Now()
var sysStatus struct {
Uptime string
NumGoroutine int
// General statistics.
MemAllocated string // bytes allocated and still in use
MemTotal string // bytes allocated (even if freed)
MemSys string // bytes obtained from system (sum of XxxSys below)
Lookups uint64 // number of pointer lookups
MemMallocs uint64 // number of mallocs
MemFrees uint64 // number of frees
// Main allocation heap statistics.
HeapAlloc string // bytes allocated and still in use
HeapSys string // bytes obtained from system
HeapIdle string // bytes in idle spans
HeapInuse string // bytes in non-idle span
HeapReleased string // bytes released to the OS
HeapObjects uint64 // total number of allocated objects
// Low-level fixed-size structure allocator statistics.
// Inuse is bytes used now.
// Sys is bytes obtained from system.
StackInuse string // bootstrap stacks
StackSys string
MSpanInuse string // mspan structures
MSpanSys string
MCacheInuse string // mcache structures
MCacheSys string
BuckHashSys string // profiling bucket hash table
GCSys string // GC metadata
OtherSys string // other system allocations
// Garbage collector statistics.
NextGC string // next run in HeapAlloc time (bytes)
LastGC string // last run in absolute time (ns)
PauseTotalNs string
PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256]
NumGC uint32
}
func updateSystemStatus() {
sysStatus.Uptime = tool.TimeSincePro(initTime)
m := new(runtime.MemStats)
runtime.ReadMemStats(m)
sysStatus.NumGoroutine = runtime.NumGoroutine()
sysStatus.MemAllocated = tool.FileSize(int64(m.Alloc))
sysStatus.MemTotal = tool.FileSize(int64(m.TotalAlloc))
sysStatus.MemSys = tool.FileSize(int64(m.Sys))
sysStatus.Lookups = m.Lookups
sysStatus.MemMallocs = m.Mallocs
sysStatus.MemFrees = m.Frees
sysStatus.HeapAlloc = tool.FileSize(int64(m.HeapAlloc))
sysStatus.HeapSys = tool.FileSize(int64(m.HeapSys))
sysStatus.HeapIdle = tool.FileSize(int64(m.HeapIdle))
sysStatus.HeapInuse = tool.FileSize(int64(m.HeapInuse))
sysStatus.HeapReleased = tool.FileSize(int64(m.HeapReleased))
sysStatus.HeapObjects = m.HeapObjects
sysStatus.StackInuse = tool.FileSize(int64(m.StackInuse))
sysStatus.StackSys = tool.FileSize(int64(m.StackSys))
sysStatus.MSpanInuse = tool.FileSize(int64(m.MSpanInuse))
sysStatus.MSpanSys = tool.FileSize(int64(m.MSpanSys))
sysStatus.MCacheInuse = tool.FileSize(int64(m.MCacheInuse))
sysStatus.MCacheSys = tool.FileSize(int64(m.MCacheSys))
sysStatus.BuckHashSys = tool.FileSize(int64(m.BuckHashSys))
sysStatus.GCSys = tool.FileSize(int64(m.GCSys))
sysStatus.OtherSys = tool.FileSize(int64(m.OtherSys))
sysStatus.NextGC = tool.FileSize(int64(m.NextGC))
sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000)
sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000)
sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000)
sysStatus.NumGC = m.NumGC
}
func Dashboard(c *context.Context) {
c.Title("admin.dashboard")
c.PageIs("Admin")
c.PageIs("AdminDashboard")
c.Data["GitVersion"] = conf.Git.Version
c.Data["GoVersion"] = runtime.Version()
c.Data["BuildTime"] = conf.BuildTime
c.Data["BuildCommit"] = conf.BuildCommit
c.Data["Stats"] = database.GetStatistic(c.Req.Context())
// FIXME: update periodically
updateSystemStatus()
c.Data["SysStatus"] = sysStatus
c.Success(tmplDashboard)
}
// Operation types.
type AdminOperation int
const (
CleanInactivateUser AdminOperation = iota + 1
CleanRepoArchives
CleanMissingRepos
GitGCRepos
SyncSSHAuthorizedKey
SyncRepositoryHooks
ReinitMissingRepository
)
func Operation(c *context.Context) {
var err error
var success string
switch AdminOperation(c.QueryInt("op")) {
case CleanInactivateUser:
success = c.Tr("admin.dashboard.delete_inactivate_accounts_success")
err = database.Handle.Users().DeleteInactivated()
case CleanRepoArchives:
success = c.Tr("admin.dashboard.delete_repo_archives_success")
err = database.DeleteRepositoryArchives()
case CleanMissingRepos:
success = c.Tr("admin.dashboard.delete_missing_repos_success")
err = database.DeleteMissingRepositories()
case GitGCRepos:
success = c.Tr("admin.dashboard.git_gc_repos_success")
err = database.GitGcRepos()
case SyncSSHAuthorizedKey:
success = c.Tr("admin.dashboard.resync_all_sshkeys_success")
err = database.RewriteAuthorizedKeys()
case SyncRepositoryHooks:
success = c.Tr("admin.dashboard.resync_all_hooks_success")
err = database.SyncRepositoryHooks()
case ReinitMissingRepository:
success = c.Tr("admin.dashboard.reinit_missing_repos_success")
err = database.ReinitMissingRepositories()
}
if err != nil {
c.Flash.Error(err.Error())
} else {
c.Flash.Success(success)
}
c.RedirectSubpath("/admin")
}
func SendTestMail(c *context.Context) {
emailAddr := c.Query("email")
// Send a test email to the user's email address and redirect back to Config
if err := email.SendTestMail(emailAddr); err != nil {
c.Flash.Error(c.Tr("admin.config.email.test_mail_failed", emailAddr, err))
} else {
c.Flash.Info(c.Tr("admin.config.email.test_mail_sent", emailAddr))
}
c.Redirect(conf.Server.Subpath + "/admin/config")
}
func Config(c *context.Context) {
c.Title("admin.config")
c.PageIs("Admin")
c.PageIs("AdminConfig")
c.Data["App"] = conf.App
c.Data["Server"] = conf.Server
c.Data["SSH"] = conf.SSH
c.Data["Repository"] = conf.Repository
c.Data["Database"] = conf.Database
c.Data["Security"] = conf.Security
c.Data["Email"] = conf.Email
c.Data["Auth"] = conf.Auth
c.Data["User"] = conf.User
c.Data["Session"] = conf.Session
c.Data["Cache"] = conf.Cache
c.Data["Attachment"] = conf.Attachment
c.Data["Release"] = conf.Release
c.Data["Picture"] = conf.Picture
c.Data["HTTP"] = conf.HTTP
c.Data["Mirror"] = conf.Mirror
c.Data["Webhook"] = conf.Webhook
c.Data["Git"] = conf.Git
c.Data["LFS"] = conf.LFS
c.Data["LogRootPath"] = conf.Log.RootPath
type logger struct {
Mode, Config string
}
loggers := make([]*logger, len(conf.Log.Modes))
for i := range conf.Log.Modes {
loggers[i] = &logger{
Mode: strings.Title(conf.Log.Modes[i]),
}
result, _ := jsoniter.MarshalIndent(conf.Log.Configs[i], "", " ")
loggers[i].Config = string(result)
}
c.Data["Loggers"] = loggers
c.Success(tmplConfig)
}
func Monitor(c *context.Context) {
c.Data["Title"] = c.Tr("admin.monitor")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminMonitor"] = true
c.Data["Processes"] = process.Processes
c.Data["Entries"] = cron.ListTasks()
c.Success(tmplMonitor)
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/admin/orgs.go | internal/route/admin/orgs.go | // Copyright 2014 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 admin
import (
gocontext "context"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/route"
)
const (
ORGS = "admin/org/list"
)
func Organizations(c *context.Context) {
c.Data["Title"] = c.Tr("admin.organizations")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminOrganizations"] = true
route.RenderUserSearch(c, &route.UserSearchOptions{
Type: database.UserTypeOrganization,
Counter: func(gocontext.Context) int64 {
return database.CountOrganizations()
},
Ranger: func(_ gocontext.Context, page, pageSize int) ([]*database.User, error) {
return database.Organizations(page, pageSize)
},
PageSize: conf.UI.Admin.OrgPagingNum,
OrderBy: "id ASC",
TplName: ORGS,
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/admin/auths.go | internal/route/admin/auths.go | // Copyright 2014 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 admin
import (
"fmt"
"net/http"
"strings"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/auth/github"
"gogs.io/gogs/internal/auth/ldap"
"gogs.io/gogs/internal/auth/pam"
"gogs.io/gogs/internal/auth/smtp"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/form"
)
const (
tmplAdminAuthList = "admin/auth/list"
tmplAdminAuthNew = "admin/auth/new"
tmplAdminAuthEdit = "admin/auth/edit"
)
func Authentications(c *context.Context) {
c.Title("admin.authentication")
c.PageIs("Admin")
c.PageIs("AdminAuthentications")
var err error
c.Data["Sources"], err = database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{})
if err != nil {
c.Error(err, "list login sources")
return
}
c.Data["Total"] = database.Handle.LoginSources().Count(c.Req.Context())
c.Success(tmplAdminAuthList)
}
type dropdownItem struct {
Name string
Type any
}
var (
authSources = []dropdownItem{
{auth.Name(auth.LDAP), auth.LDAP},
{auth.Name(auth.DLDAP), auth.DLDAP},
{auth.Name(auth.SMTP), auth.SMTP},
{auth.Name(auth.PAM), auth.PAM},
{auth.Name(auth.GitHub), auth.GitHub},
}
securityProtocols = []dropdownItem{
{ldap.SecurityProtocolName(ldap.SecurityProtocolUnencrypted), ldap.SecurityProtocolUnencrypted},
{ldap.SecurityProtocolName(ldap.SecurityProtocolLDAPS), ldap.SecurityProtocolLDAPS},
{ldap.SecurityProtocolName(ldap.SecurityProtocolStartTLS), ldap.SecurityProtocolStartTLS},
}
)
func NewAuthSource(c *context.Context) {
c.Title("admin.auths.new")
c.PageIs("Admin")
c.PageIs("AdminAuthentications")
c.Data["type"] = auth.LDAP
c.Data["CurrentTypeName"] = auth.Name(auth.LDAP)
c.Data["CurrentSecurityProtocol"] = ldap.SecurityProtocolName(ldap.SecurityProtocolUnencrypted)
c.Data["smtp_auth"] = "PLAIN"
c.Data["is_active"] = true
c.Data["is_default"] = true
c.Data["AuthSources"] = authSources
c.Data["SecurityProtocols"] = securityProtocols
c.Data["SMTPAuths"] = smtp.AuthTypes
c.Success(tmplAdminAuthNew)
}
func parseLDAPConfig(f form.Authentication) *ldap.Config {
return &ldap.Config{
Host: f.Host,
Port: f.Port,
SecurityProtocol: ldap.SecurityProtocol(f.SecurityProtocol),
SkipVerify: f.SkipVerify,
BindDN: f.BindDN,
UserDN: f.UserDN,
BindPassword: f.BindPassword,
UserBase: f.UserBase,
AttributeUsername: f.AttributeUsername,
AttributeName: f.AttributeName,
AttributeSurname: f.AttributeSurname,
AttributeMail: f.AttributeMail,
AttributesInBind: f.AttributesInBind,
Filter: f.Filter,
GroupEnabled: f.GroupEnabled,
GroupDN: f.GroupDN,
GroupFilter: f.GroupFilter,
GroupMemberUID: f.GroupMemberUID,
UserUID: f.UserUID,
AdminFilter: f.AdminFilter,
}
}
func parseSMTPConfig(f form.Authentication) *smtp.Config {
return &smtp.Config{
Auth: f.SMTPAuth,
Host: f.SMTPHost,
Port: f.SMTPPort,
AllowedDomains: f.AllowedDomains,
TLS: f.TLS,
SkipVerify: f.SkipVerify,
}
}
func NewAuthSourcePost(c *context.Context, f form.Authentication) {
c.Title("admin.auths.new")
c.PageIs("Admin")
c.PageIs("AdminAuthentications")
c.Data["CurrentTypeName"] = auth.Name(auth.Type(f.Type))
c.Data["CurrentSecurityProtocol"] = ldap.SecurityProtocolName(ldap.SecurityProtocol(f.SecurityProtocol))
c.Data["AuthSources"] = authSources
c.Data["SecurityProtocols"] = securityProtocols
c.Data["SMTPAuths"] = smtp.AuthTypes
hasTLS := false
var config any
switch auth.Type(f.Type) {
case auth.LDAP, auth.DLDAP:
config = parseLDAPConfig(f)
hasTLS = ldap.SecurityProtocol(f.SecurityProtocol) > ldap.SecurityProtocolUnencrypted
case auth.SMTP:
config = parseSMTPConfig(f)
hasTLS = true
case auth.PAM:
config = &pam.Config{
ServiceName: f.PAMServiceName,
}
case auth.GitHub:
config = &github.Config{
APIEndpoint: strings.TrimSuffix(f.GitHubAPIEndpoint, "/") + "/",
SkipVerify: f.SkipVerify,
}
hasTLS = true
default:
c.Status(http.StatusBadRequest)
return
}
c.Data["HasTLS"] = hasTLS
if c.HasError() {
c.Success(tmplAdminAuthNew)
return
}
source, err := database.Handle.LoginSources().Create(c.Req.Context(),
database.CreateLoginSourceOptions{
Type: auth.Type(f.Type),
Name: f.Name,
Activated: f.IsActive,
Default: f.IsDefault,
Config: config,
},
)
if err != nil {
if database.IsErrLoginSourceAlreadyExist(err) {
c.FormErr("Name")
c.RenderWithErr(c.Tr("admin.auths.login_source_exist", f.Name), tmplAdminAuthNew, f)
} else {
c.Error(err, "create login source")
}
return
}
if source.IsDefault {
err = database.Handle.LoginSources().ResetNonDefault(c.Req.Context(), source)
if err != nil {
c.Error(err, "reset non-default login sources")
return
}
}
log.Trace("Authentication created by admin(%s): %s", c.User.Name, f.Name)
c.Flash.Success(c.Tr("admin.auths.new_success", f.Name))
c.Redirect(conf.Server.Subpath + "/admin/auths")
}
func EditAuthSource(c *context.Context) {
c.Title("admin.auths.edit")
c.PageIs("Admin")
c.PageIs("AdminAuthentications")
c.Data["SecurityProtocols"] = securityProtocols
c.Data["SMTPAuths"] = smtp.AuthTypes
source, err := database.Handle.LoginSources().GetByID(c.Req.Context(), c.ParamsInt64(":authid"))
if err != nil {
c.Error(err, "get login source by ID")
return
}
c.Data["Source"] = source
c.Data["HasTLS"] = source.Provider.HasTLS()
c.Success(tmplAdminAuthEdit)
}
func EditAuthSourcePost(c *context.Context, f form.Authentication) {
c.Title("admin.auths.edit")
c.PageIs("Admin")
c.PageIs("AdminAuthentications")
c.Data["SMTPAuths"] = smtp.AuthTypes
source, err := database.Handle.LoginSources().GetByID(c.Req.Context(), c.ParamsInt64(":authid"))
if err != nil {
c.Error(err, "get login source by ID")
return
}
c.Data["Source"] = source
c.Data["HasTLS"] = source.Provider.HasTLS()
if c.HasError() {
c.Success(tmplAdminAuthEdit)
return
}
var provider auth.Provider
switch auth.Type(f.Type) {
case auth.LDAP:
provider = ldap.NewProvider(false, parseLDAPConfig(f))
case auth.DLDAP:
provider = ldap.NewProvider(true, parseLDAPConfig(f))
case auth.SMTP:
provider = smtp.NewProvider(parseSMTPConfig(f))
case auth.PAM:
provider = pam.NewProvider(&pam.Config{
ServiceName: f.PAMServiceName,
})
case auth.GitHub:
provider = github.NewProvider(&github.Config{
APIEndpoint: strings.TrimSuffix(f.GitHubAPIEndpoint, "/") + "/",
SkipVerify: f.SkipVerify,
})
default:
c.Status(http.StatusBadRequest)
return
}
source.Name = f.Name
source.IsActived = f.IsActive
source.IsDefault = f.IsDefault
source.Provider = provider
if err := database.Handle.LoginSources().Save(c.Req.Context(), source); err != nil {
c.Error(err, "update login source")
return
}
if source.IsDefault {
err = database.Handle.LoginSources().ResetNonDefault(c.Req.Context(), source)
if err != nil {
c.Error(err, "reset non-default login sources")
return
}
}
log.Trace("Authentication changed by admin '%s': %d", c.User.Name, source.ID)
c.Flash.Success(c.Tr("admin.auths.update_success"))
c.Redirect(conf.Server.Subpath + "/admin/auths/" + com.ToStr(f.ID))
}
func DeleteAuthSource(c *context.Context) {
id := c.ParamsInt64(":authid")
if err := database.Handle.LoginSources().DeleteByID(c.Req.Context(), id); err != nil {
if database.IsErrLoginSourceInUse(err) {
c.Flash.Error(c.Tr("admin.auths.still_in_used"))
} else {
c.Flash.Error(fmt.Sprintf("DeleteSource: %v", err))
}
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/admin/auths/" + c.Params(":authid"),
})
return
}
log.Trace("Authentication deleted by admin(%s): %d", c.User.Name, id)
c.Flash.Success(c.Tr("admin.auths.deletion_success"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/admin/auths",
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/admin/notice.go | internal/route/admin/notice.go | // Copyright 2014 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 admin
import (
"net/http"
"github.com/unknwon/com"
"github.com/unknwon/paginater"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
)
const (
NOTICES = "admin/notice"
)
func Notices(c *context.Context) {
c.Title("admin.notices")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminNotices"] = true
total := database.Handle.Notices().Count(c.Req.Context())
page := c.QueryInt("page")
if page <= 1 {
page = 1
}
c.Data["Page"] = paginater.New(int(total), conf.UI.Admin.NoticePagingNum, page, 5)
notices, err := database.Handle.Notices().List(c.Req.Context(), page, conf.UI.Admin.NoticePagingNum)
if err != nil {
c.Error(err, "list notices")
return
}
c.Data["Notices"] = notices
c.Data["Total"] = total
c.Success(NOTICES)
}
func DeleteNotices(c *context.Context) {
strs := c.QueryStrings("ids[]")
ids := make([]int64, 0, len(strs))
for i := range strs {
id := com.StrTo(strs[i]).MustInt64()
if id > 0 {
ids = append(ids, id)
}
}
if err := database.Handle.Notices().DeleteByIDs(c.Req.Context(), ids...); err != nil {
c.Flash.Error("DeleteNoticesByIDs: " + err.Error())
c.Status(http.StatusInternalServerError)
} else {
c.Flash.Success(c.Tr("admin.notices.delete_success"))
c.Status(http.StatusOK)
}
}
func EmptyNotices(c *context.Context) {
if err := database.Handle.Notices().DeleteAll(c.Req.Context()); err != nil {
c.Error(err, "delete notices")
return
}
log.Trace("System notices deleted by admin (%s): [start: %d]", c.User.Name, 0)
c.Flash.Success(c.Tr("admin.notices.delete_success"))
c.Redirect(conf.Server.Subpath + "/admin/notices")
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/admin/repos.go | internal/route/admin/repos.go | // Copyright 2014 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 admin
import (
"github.com/unknwon/paginater"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
)
const (
REPOS = "admin/repo/list"
)
func Repos(c *context.Context) {
c.Data["Title"] = c.Tr("admin.repositories")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminRepositories"] = true
page := c.QueryInt("page")
if page <= 0 {
page = 1
}
var (
repos []*database.Repository
count int64
err error
)
keyword := c.Query("q")
if keyword == "" {
repos, err = database.Repositories(page, conf.UI.Admin.RepoPagingNum)
if err != nil {
c.Error(err, "list repositories")
return
}
count = database.CountRepositories(true)
} else {
repos, count, err = database.SearchRepositoryByName(&database.SearchRepoOptions{
Keyword: keyword,
OrderBy: "id ASC",
Private: true,
Page: page,
PageSize: conf.UI.Admin.RepoPagingNum,
})
if err != nil {
c.Error(err, "search repository by name")
return
}
}
c.Data["Keyword"] = keyword
c.Data["Total"] = count
c.Data["Page"] = paginater.New(int(count), conf.UI.Admin.RepoPagingNum, page, 5)
if err = database.RepositoryList(repos).LoadAttributes(); err != nil {
c.Error(err, "load attributes")
return
}
c.Data["Repos"] = repos
c.Success(REPOS)
}
func DeleteRepo(c *context.Context) {
repo, err := database.GetRepositoryByID(c.QueryInt64("id"))
if err != nil {
c.Error(err, "get repository by ID")
return
}
if err := database.DeleteRepository(repo.MustOwner().ID, repo.ID); err != nil {
c.Error(err, "delete repository")
return
}
log.Trace("Repository deleted: %s/%s", repo.MustOwner().Name, repo.Name)
c.Flash.Success(c.Tr("repo.settings.deletion_success"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/admin/repos?page=" + c.Query("page"),
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
gogs/gogs | https://github.com/gogs/gogs/blob/e68949dd1307d1b72a2fe885976ea0be72ee31d5/internal/route/admin/users.go | internal/route/admin/users.go | // Copyright 2014 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 admin
import (
"strconv"
"strings"
log "unknwon.dev/clog/v2"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/database"
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/route"
)
const (
tmplAdminUserList = "admin/user/list"
tmplAdminUserNew = "admin/user/new"
tmplAdminUserEdit = "admin/user/edit"
)
func Users(c *context.Context) {
c.Data["Title"] = c.Tr("admin.users")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminUsers"] = true
route.RenderUserSearch(c, &route.UserSearchOptions{
Type: database.UserTypeIndividual,
Counter: database.Handle.Users().Count,
Ranger: database.Handle.Users().List,
PageSize: conf.UI.Admin.UserPagingNum,
OrderBy: "id ASC",
TplName: tmplAdminUserList,
})
}
func NewUser(c *context.Context) {
c.Data["Title"] = c.Tr("admin.users.new_account")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminUsers"] = true
c.Data["login_type"] = "0-0"
sources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{})
if err != nil {
c.Error(err, "list login sources")
return
}
c.Data["Sources"] = sources
c.Data["CanSendEmail"] = conf.Email.Enabled
c.Success(tmplAdminUserNew)
}
func NewUserPost(c *context.Context, f form.AdminCrateUser) {
c.Data["Title"] = c.Tr("admin.users.new_account")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminUsers"] = true
sources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{})
if err != nil {
c.Error(err, "list login sources")
return
}
c.Data["Sources"] = sources
c.Data["CanSendEmail"] = conf.Email.Enabled
if c.HasError() {
c.Success(tmplAdminUserNew)
return
}
createUserOpts := database.CreateUserOptions{
Password: f.Password,
Activated: true,
}
if len(f.LoginType) > 0 {
fields := strings.Split(f.LoginType, "-")
if len(fields) == 2 {
createUserOpts.LoginSource, _ = strconv.ParseInt(fields[1], 10, 64)
createUserOpts.LoginName = f.LoginName
}
}
user, err := database.Handle.Users().Create(c.Req.Context(), f.UserName, f.Email, createUserOpts)
if err != nil {
switch {
case database.IsErrUserAlreadyExist(err):
c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("form.username_been_taken"), tmplAdminUserNew, &f)
case database.IsErrEmailAlreadyUsed(err):
c.Data["Err_Email"] = true
c.RenderWithErr(c.Tr("form.email_been_used"), tmplAdminUserNew, &f)
case database.IsErrNameNotAllowed(err):
c.Data["Err_UserName"] = true
c.RenderWithErr(c.Tr("user.form.name_not_allowed", err.(database.ErrNameNotAllowed).Value()), tmplAdminUserNew, &f)
default:
c.Error(err, "create user")
}
return
}
log.Trace("Account %q created by admin %q", user.Name, c.User.Name)
// Send email notification.
if f.SendNotify && conf.Email.Enabled {
email.SendRegisterNotifyMail(c.Context, database.NewMailerUser(user))
}
c.Flash.Success(c.Tr("admin.users.new_success", user.Name))
c.Redirect(conf.Server.Subpath + "/admin/users/" + strconv.FormatInt(user.ID, 10))
}
func prepareUserInfo(c *context.Context) *database.User {
u, err := database.Handle.Users().GetByID(c.Req.Context(), c.ParamsInt64(":userid"))
if err != nil {
c.Error(err, "get user by ID")
return nil
}
c.Data["User"] = u
if u.LoginSource > 0 {
c.Data["LoginSource"], err = database.Handle.LoginSources().GetByID(c.Req.Context(), u.LoginSource)
if err != nil {
c.Error(err, "get login source by ID")
return nil
}
} else {
c.Data["LoginSource"] = &database.LoginSource{}
}
sources, err := database.Handle.LoginSources().List(c.Req.Context(), database.ListLoginSourceOptions{})
if err != nil {
c.Error(err, "list login sources")
return nil
}
c.Data["Sources"] = sources
return u
}
func EditUser(c *context.Context) {
c.Data["Title"] = c.Tr("admin.users.edit_account")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminUsers"] = true
c.Data["EnableLocalPathMigration"] = conf.Repository.EnableLocalPathMigration
prepareUserInfo(c)
if c.Written() {
return
}
c.Success(tmplAdminUserEdit)
}
func EditUserPost(c *context.Context, f form.AdminEditUser) {
c.Data["Title"] = c.Tr("admin.users.edit_account")
c.Data["PageIsAdmin"] = true
c.Data["PageIsAdminUsers"] = true
c.Data["EnableLocalPathMigration"] = conf.Repository.EnableLocalPathMigration
u := prepareUserInfo(c)
if c.Written() {
return
}
if c.HasError() {
c.Success(tmplAdminUserEdit)
return
}
opts := database.UpdateUserOptions{
LoginName: &f.LoginName,
FullName: &f.FullName,
Website: &f.Website,
Location: &f.Location,
MaxRepoCreation: &f.MaxRepoCreation,
IsActivated: &f.Active,
IsAdmin: &f.Admin,
AllowGitHook: &f.AllowGitHook,
AllowImportLocal: &f.AllowImportLocal,
ProhibitLogin: &f.ProhibitLogin,
}
fields := strings.Split(f.LoginType, "-")
if len(fields) == 2 {
loginSource, _ := strconv.ParseInt(fields[1], 10, 64)
if u.LoginSource != loginSource {
opts.LoginSource = &loginSource
}
}
if f.Password != "" {
opts.Password = &f.Password
}
if u.Email != f.Email {
opts.Email = &f.Email
}
err := database.Handle.Users().Update(c.Req.Context(), u.ID, opts)
if err != nil {
if database.IsErrEmailAlreadyUsed(err) {
c.Data["Err_Email"] = true
c.RenderWithErr(c.Tr("form.email_been_used"), tmplAdminUserEdit, &f)
} else {
c.Error(err, "update user")
}
return
}
log.Trace("Account updated by admin %q: %s", c.User.Name, u.Name)
c.Flash.Success(c.Tr("admin.users.update_profile_success"))
c.Redirect(conf.Server.Subpath + "/admin/users/" + c.Params(":userid"))
}
func DeleteUser(c *context.Context) {
u, err := database.Handle.Users().GetByID(c.Req.Context(), c.ParamsInt64(":userid"))
if err != nil {
c.Error(err, "get user by ID")
return
}
if err = database.Handle.Users().DeleteByID(c.Req.Context(), u.ID, false); err != nil {
switch {
case database.IsErrUserOwnRepos(err):
c.Flash.Error(c.Tr("admin.users.still_own_repo"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/admin/users/" + c.Params(":userid"),
})
case database.IsErrUserHasOrgs(err):
c.Flash.Error(c.Tr("admin.users.still_has_org"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/admin/users/" + c.Params(":userid"),
})
default:
c.Error(err, "delete user")
}
return
}
log.Trace("Account deleted by admin (%s): %s", c.User.Name, u.Name)
c.Flash.Success(c.Tr("admin.users.deletion_success"))
c.JSONSuccess(map[string]any{
"redirect": conf.Server.Subpath + "/admin/users",
})
}
| go | MIT | e68949dd1307d1b72a2fe885976ea0be72ee31d5 | 2026-01-07T08:35:43.578986Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.