forked from pydio/cells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authfront-login-middlewares.go
197 lines (167 loc) · 6.64 KB
/
authfront-login-middlewares.go
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
package modifiers
import (
"fmt"
"net/http"
"strconv"
json "github.com/pydio/cells/x/jsonx"
"github.com/emicklei/go-restful"
"github.com/gorilla/sessions"
"github.com/micro/go-micro/client"
"github.com/micro/go-micro/errors"
"go.uber.org/zap"
"github.com/pydio/cells/common"
"github.com/pydio/cells/common/log"
defaults "github.com/pydio/cells/common/micro"
"github.com/pydio/cells/common/proto/idm"
"github.com/pydio/cells/common/proto/rest"
"github.com/pydio/cells/common/service/frontend"
"github.com/pydio/cells/common/utils/permissions"
)
// LoginSuccessWrapper wraps functionalities after user was successfully logged in
func LoginSuccessWrapper(middleware frontend.AuthMiddleware) frontend.AuthMiddleware {
return func(req *restful.Request, rsp *restful.Response, in *rest.FrontSessionRequest, out *rest.FrontSessionResponse, session *sessions.Session) error {
if a, ok := in.AuthInfo["type"]; !ok || a != "credentials" && a != "authorization_code" { // Ignore this middleware
return middleware(req, rsp, in, out, session)
}
// BEFORE MIDDLEWARE
// MIDDLEWARE
err := middleware(req, rsp, in, out, session)
if err != nil {
return err
}
// AFTER MIDDLEWARE
// retrieving user
username, ok := in.AuthInfo["login"]
if !ok {
return errors.New("user.not_found", "User id not found", http.StatusNotFound)
}
ctx := req.Request.Context()
// Searching user for attributes
user, err := permissions.SearchUniqueUser(ctx, username, "")
if err != nil {
return err
}
// Checking user is locked
if permissions.IsUserLocked(user) {
log.Auditer(ctx).Error(
"Locked user ["+user.Login+"] tried to log in.",
log.GetAuditId(common.AUDIT_LOGIN_POLICY_DENIAL),
zap.String(common.KEY_USER_UUID, user.Uuid),
)
log.Logger(ctx).Error("lock denies login for "+user.Login, zap.Error(fmt.Errorf("blocked login")))
return errors.Unauthorized(common.ServiceUser, "User "+user.Login+" has been blocked. Contact your sysadmin.")
}
// Reset failed connections
if user.Attributes != nil {
if _, ok := user.Attributes["failedConnections"]; ok {
log.Logger(ctx).Info("[WrapWithUserLocks] Resetting user failedConnections", user.ZapLogin())
userClient := idm.NewUserServiceClient(common.ServiceGrpcNamespace_+common.ServiceUser, defaults.NewClient())
delete(user.Attributes, "failedConnections")
userClient.CreateUser(ctx, &idm.CreateUserRequest{User: user})
}
}
// Checking policies
cli := idm.NewPolicyEngineServiceClient(common.ServiceGrpcNamespace_+common.ServicePolicy, defaults.NewClient())
policyContext := make(map[string]string)
permissions.PolicyContextFromMetadata(policyContext, ctx)
subjects := permissions.PolicyRequestSubjectsFromUser(user)
// Check all subjects, if one has deny return false
policyRequest := &idm.PolicyEngineRequest{
Subjects: subjects,
Resource: "oidc",
Action: "login",
Context: policyContext,
}
if resp, err := cli.IsAllowed(ctx, policyRequest); err != nil || resp.Allowed == false {
log.Auditer(ctx).Error(
"Policy denied login to ["+user.Login+"]",
log.GetAuditId(common.AUDIT_LOGIN_POLICY_DENIAL),
zap.String(common.KEY_USER_UUID, user.Uuid),
zap.Any(common.KEY_POLICY_REQUEST, policyRequest),
zap.Error(err),
)
log.Logger(ctx).Error("policy denies login for request", zap.Any(common.KEY_POLICY_REQUEST, policyRequest), zap.Error(err))
return errors.Unauthorized(common.ServiceUser, "User "+user.Login+" is not authorized to log in")
}
client.Publish(ctx, client.NewPublication(common.TopicIdmEvent, &idm.ChangeEvent{
Type: idm.ChangeEventType_LOGIN,
User: user,
}))
return nil
}
}
// LoginFailedWrapper wraps functionalities after user failed to log in
func LoginFailedWrapper(middleware frontend.AuthMiddleware) frontend.AuthMiddleware {
return func(req *restful.Request, rsp *restful.Response, in *rest.FrontSessionRequest, out *rest.FrontSessionResponse, session *sessions.Session) error {
if a, ok := in.AuthInfo["type"]; !ok || a != "credentials" && a != "external" { // Ignore this middleware
return middleware(req, rsp, in, out, session)
}
// MIDDLEWARE
err := middleware(req, rsp, in, out, session)
if err == nil {
return nil
}
fmt.Println("Login failed with ", err)
ctx := req.Request.Context()
username := in.AuthInfo["login"]
const maxFailedLogins = 10
// Searching user for attributes
user, _ := permissions.SearchUniqueUser(ctx, username, "")
if user == nil {
return errors.New("login.failed", "Login failed", http.StatusUnauthorized)
}
// double check if user was already locked to reduce work load
if permissions.IsUserLocked(user) {
msg := fmt.Sprintf("locked user %s is still trying to connect", user.GetLogin())
log.Logger(ctx).Warn(msg, user.ZapLogin())
return errors.New("user.locked", "User is locked - Please contact your admin", http.StatusUnauthorized)
}
var failedInt int64
if user.Attributes == nil {
user.Attributes = make(map[string]string)
}
if failed, ok := user.Attributes["failedConnections"]; ok {
failedInt, _ = strconv.ParseInt(failed, 10, 32)
}
failedInt++
user.Attributes["failedConnections"] = fmt.Sprintf("%d", failedInt)
hardLock := false
if failedInt >= maxFailedLogins {
// Set lock via attributes
var locks []string
if l, ok := user.Attributes["locks"]; ok {
var existingLocks []string
if e := json.Unmarshal([]byte(l), &existingLocks); e == nil {
for _, lock := range existingLocks {
if lock != "logout" {
locks = append(locks, lock)
}
}
}
}
locks = append(locks, "logout")
data, _ := json.Marshal(locks)
user.Attributes["locks"] = string(data)
msg := fmt.Sprintf("Locked user [%s] after %d failed connections", user.GetLogin(), maxFailedLogins)
log.Logger(ctx).Error(msg, user.ZapLogin())
log.Auditer(ctx).Error(
msg,
log.GetAuditId(common.AUDIT_LOCK_USER),
user.ZapLogin(),
zap.String(common.KEY_USER_UUID, user.GetUuid()),
)
hardLock = true
}
log.Logger(ctx).Debug(fmt.Sprintf("[WrapWithUserLocks] Updating failed connection number for user [%s]", user.GetLogin()), user.ZapLogin())
userClient := idm.NewUserServiceClient(common.ServiceGrpcNamespace_+common.ServiceUser, defaults.NewClient())
if _, e := userClient.CreateUser(ctx, &idm.CreateUserRequest{User: user}); e != nil {
log.Logger(ctx).Error("could not store failedConnection for user", zap.Error(e))
}
// Replacing error not to give any hint
if hardLock {
return errors.New("user.locked", "User is locked - Please contact your admin", http.StatusUnauthorized)
} else {
return errors.New("login.failed", "Login failed", http.StatusUnauthorized)
}
}
}