aboutsummaryrefslogtreecommitdiff
path: root/internal/db/login_source_files.go
blob: 7c0967a57db91bd042a810aa195bf127d1f0168f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
// 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 db

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/pkg/errors"
	"gopkg.in/ini.v1"

	"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/errutil"
	"gogs.io/gogs/internal/osutil"
)

// loginSourceFilesStore is the in-memory interface for login source files stored on file system.
type loginSourceFilesStore interface {
	// GetByID returns a clone of login source by given ID.
	GetByID(id int64) (*LoginSource, error)
	// Len returns number of login sources.
	Len() int
	// List returns a list of login sources filtered by options.
	List(opts ListLoginSourceOptions) []*LoginSource
	// Update updates in-memory copy of the authentication source.
	Update(source *LoginSource)
}

var _ loginSourceFilesStore = (*loginSourceFiles)(nil)

// loginSourceFiles contains authentication sources configured and loaded from local files.
type loginSourceFiles struct {
	sync.RWMutex
	sources []*LoginSource
	clock   func() time.Time
}

var _ errutil.NotFound = (*ErrLoginSourceNotExist)(nil)

type ErrLoginSourceNotExist struct {
	args errutil.Args
}

func IsErrLoginSourceNotExist(err error) bool {
	_, ok := err.(ErrLoginSourceNotExist)
	return ok
}

func (err ErrLoginSourceNotExist) Error() string {
	return fmt.Sprintf("login source does not exist: %v", err.args)
}

func (ErrLoginSourceNotExist) NotFound() bool {
	return true
}

func (s *loginSourceFiles) GetByID(id int64) (*LoginSource, error) {
	s.RLock()
	defer s.RUnlock()

	for _, source := range s.sources {
		if source.ID == id {
			return source, nil
		}
	}

	return nil, ErrLoginSourceNotExist{args: errutil.Args{"id": id}}
}

func (s *loginSourceFiles) Len() int {
	s.RLock()
	defer s.RUnlock()
	return len(s.sources)
}

func (s *loginSourceFiles) List(opts ListLoginSourceOptions) []*LoginSource {
	s.RLock()
	defer s.RUnlock()

	list := make([]*LoginSource, 0, s.Len())
	for _, source := range s.sources {
		if opts.OnlyActivated && !source.IsActived {
			continue
		}

		list = append(list, source)
	}
	return list
}

func (s *loginSourceFiles) Update(source *LoginSource) {
	s.Lock()
	defer s.Unlock()

	source.Updated = s.clock()
	for _, old := range s.sources {
		if old.ID == source.ID {
			*old = *source
		} else if source.IsDefault {
			old.IsDefault = false
		}
	}
}

// loadLoginSourceFiles loads login sources from file system.
func loadLoginSourceFiles(authdPath string, clock func() time.Time) (loginSourceFilesStore, error) {
	if !osutil.IsDir(authdPath) {
		return &loginSourceFiles{clock: clock}, nil
	}

	store := &loginSourceFiles{clock: clock}
	return store, filepath.Walk(authdPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if path == authdPath || !strings.HasSuffix(path, ".conf") {
			return nil
		} else if info.IsDir() {
			return filepath.SkipDir
		}

		authSource, err := ini.Load(path)
		if err != nil {
			return errors.Wrap(err, "load file")
		}
		authSource.NameMapper = ini.TitleUnderscore

		// Set general attributes
		s := authSource.Section("")
		loginSource := &LoginSource{
			ID:        s.Key("id").MustInt64(),
			Name:      s.Key("name").String(),
			IsActived: s.Key("is_activated").MustBool(),
			IsDefault: s.Key("is_default").MustBool(),
			File: &loginSourceFile{
				path: path,
				file: authSource,
			},
		}

		fi, err := os.Stat(path)
		if err != nil {
			return errors.Wrap(err, "stat file")
		}
		loginSource.Updated = fi.ModTime()

		// Parse authentication source file
		authType := s.Key("type").String()
		cfgSection := authSource.Section("config")
		switch authType {
		case "ldap_bind_dn":
			var cfg ldap.Config
			err = cfgSection.MapTo(&cfg)
			if err != nil {
				return errors.Wrap(err, `map "config" section`)
			}
			loginSource.Type = auth.LDAP
			loginSource.Provider = ldap.NewProvider(false, &cfg)

		case "ldap_simple_auth":
			var cfg ldap.Config
			err = cfgSection.MapTo(&cfg)
			if err != nil {
				return errors.Wrap(err, `map "config" section`)
			}
			loginSource.Type = auth.DLDAP
			loginSource.Provider = ldap.NewProvider(true, &cfg)

		case "smtp":
			var cfg smtp.Config
			err = cfgSection.MapTo(&cfg)
			if err != nil {
				return errors.Wrap(err, `map "config" section`)
			}
			loginSource.Type = auth.SMTP
			loginSource.Provider = smtp.NewProvider(&cfg)

		case "pam":
			var cfg pam.Config
			err = cfgSection.MapTo(&cfg)
			if err != nil {
				return errors.Wrap(err, `map "config" section`)
			}
			loginSource.Type = auth.PAM
			loginSource.Provider = pam.NewProvider(&cfg)

		case "github":
			var cfg github.Config
			err = cfgSection.MapTo(&cfg)
			if err != nil {
				return errors.Wrap(err, `map "config" section`)
			}
			loginSource.Type = auth.GitHub
			loginSource.Provider = github.NewProvider(&cfg)

		default:
			return fmt.Errorf("unknown type %q", authType)
		}

		store.sources = append(store.sources, loginSource)
		return nil
	})
}

// loginSourceFileStore is the persistent interface for a login source file.
type loginSourceFileStore interface {
	// SetGeneral sets new value to the given key in the general (default) section.
	SetGeneral(name, value string)
	// SetConfig sets new values to the "config" section.
	SetConfig(cfg any) error
	// Save persists values to file system.
	Save() error
}

var _ loginSourceFileStore = (*loginSourceFile)(nil)

type loginSourceFile struct {
	path string
	file *ini.File
}

func (f *loginSourceFile) SetGeneral(name, value string) {
	f.file.Section("").Key(name).SetValue(value)
}

func (f *loginSourceFile) SetConfig(cfg any) error {
	return f.file.Section("config").ReflectFrom(cfg)
}

func (f *loginSourceFile) Save() error {
	return f.file.SaveTo(f.path)
}