aboutsummaryrefslogtreecommitdiff
path: root/internal/db/login_source_files.go
blob: 4c5cb3776ddabca970de0076dd1a75beb98ef254 (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
// 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"

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

	"gogs.io/gogs/internal/errutil"
	"gogs.io/gogs/internal/osutil"
)

// loginSourceFilesStore is the in-memory interface for login source files stored on file system.
//
// NOTE: All methods are sorted in alphabetical order.
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 ListLoginSourceOpts) []*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
}

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 ListLoginSourceOpts) []*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 = gorm.NowFunc()
	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) (loginSourceFilesStore, error) {
	if !osutil.IsDir(authdPath) {
		return &loginSourceFiles{}, nil
	}

	store := &loginSourceFiles{}
	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()
		switch authType {
		case "ldap_bind_dn":
			loginSource.Type = LoginLDAP
			loginSource.Config = &LDAPConfig{}
		case "ldap_simple_auth":
			loginSource.Type = LoginDLDAP
			loginSource.Config = &LDAPConfig{}
		case "smtp":
			loginSource.Type = LoginSMTP
			loginSource.Config = &SMTPConfig{}
		case "pam":
			loginSource.Type = LoginPAM
			loginSource.Config = &PAMConfig{}
		case "github":
			loginSource.Type = LoginGitHub
			loginSource.Config = &GitHubConfig{}
		default:
			return fmt.Errorf("unknown type %q", authType)
		}

		if err = authSource.Section("config").MapTo(loginSource.Config); err != nil {
			return errors.Wrap(err, `map "config" section`)
		}

		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 interface{}) 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 interface{}) error {
	return f.file.Section("config").ReflectFrom(cfg)
}

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