summaryrefslogtreecommitdiff
path: root/internal/authorization/regexp.go
blob: 9c3c0d73ba8be1b22741c7f270dfc2d38d0ee59f (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
package authorization

import (
	"regexp"
	"strings"

	"github.com/authelia/authelia/v4/internal/utils"
)

// RegexpGroupStringSubjectMatcher matches the input string against the pattern taking into account Subexp groups.
type RegexpGroupStringSubjectMatcher struct {
	Pattern         regexp.Regexp
	SubexpNameUser  int
	SubexpNameGroup int
}

// IsMatch returns true if the underlying pattern matches the input given the subject.
func (r RegexpGroupStringSubjectMatcher) IsMatch(input string, subject Subject) (match bool) {
	matches := r.Pattern.FindStringSubmatch(input)
	if matches == nil {
		return false
	}

	if subject.IsAnonymous() {
		return true
	}

	if r.SubexpNameUser != -1 && !strings.EqualFold(subject.Username, matches[r.SubexpNameUser]) {
		return false
	}

	if r.SubexpNameGroup != -1 && !utils.IsStringInSliceFold(matches[r.SubexpNameGroup], subject.Groups) {
		return false
	}

	return true
}

// String returns the pattern string.
func (r RegexpGroupStringSubjectMatcher) String() string {
	return r.Pattern.String()
}

// RegexpStringSubjectMatcher just matches the input string against the pattern.
type RegexpStringSubjectMatcher struct {
	Pattern regexp.Regexp
}

// IsMatch returns true if the underlying pattern matches the input.
func (r RegexpStringSubjectMatcher) IsMatch(input string, _ Subject) (match bool) {
	return r.Pattern.MatchString(input)
}

// String returns the pattern string.
func (r RegexpStringSubjectMatcher) String() string {
	return r.Pattern.String()
}