harbor/src/ui/auth/authenticator.go

75 lines
2.1 KiB
Go
Raw Normal View History

2016-02-01 12:59:10 +01:00
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2016-02-26 11:54:14 +01:00
package auth
2016-02-01 12:59:10 +01:00
import (
"fmt"
2016-10-19 08:32:00 +02:00
"github.com/vmware/harbor/src/common/utils/log"
2016-10-18 08:39:02 +02:00
"os"
"time"
2016-02-01 12:59:10 +01:00
2016-10-19 08:32:00 +02:00
"github.com/vmware/harbor/src/common/models"
2016-02-01 12:59:10 +01:00
)
2016-10-18 08:39:02 +02:00
// 1.5 seconds
const frozenTime time.Duration = 1500 * time.Millisecond
var lock = NewUserLock(frozenTime)
2016-02-26 11:35:55 +01:00
// Authenticator provides interface to authenticate user credentials.
type Authenticator interface {
2016-02-26 11:35:55 +01:00
// Authenticate ...
Authenticate(m models.AuthModel) (*models.User, error)
2016-02-01 12:59:10 +01:00
}
var registry = make(map[string]Authenticator)
2016-02-01 12:59:10 +01:00
2016-02-26 11:35:55 +01:00
// Register add different authenticators to registry map.
func Register(name string, authenticator Authenticator) {
2016-02-01 12:59:10 +01:00
if _, dup := registry[name]; dup {
log.Infof("authenticator: %s has been registered", name)
2016-02-01 12:59:10 +01:00
return
}
registry[name] = authenticator
2016-02-01 12:59:10 +01:00
}
2016-02-26 11:35:55 +01:00
// Login authenticates user credentials based on setting.
func Login(m models.AuthModel) (*models.User, error) {
2016-02-01 12:59:10 +01:00
2016-02-26 04:26:54 +01:00
var authMode = os.Getenv("AUTH_MODE")
if authMode == "" || m.Principal == "admin" {
2016-02-01 12:59:10 +01:00
authMode = "db_auth"
}
log.Debug("Current AUTH_MODE is ", authMode)
2016-02-01 12:59:10 +01:00
authenticator, ok := registry[authMode]
if !ok {
2016-02-01 12:59:10 +01:00
return nil, fmt.Errorf("Unrecognized auth_mode: %s", authMode)
}
2016-10-18 08:39:02 +02:00
if lock.IsLocked(m.Principal) {
log.Debugf("%s is locked due to login failure, login failed", m.Principal)
return nil, nil
}
user, err := authenticator.Authenticate(m)
if user == nil && err == nil {
log.Debugf("Login failed, locking %s, and sleep for %v", m.Principal, frozenTime)
lock.Lock(m.Principal)
time.Sleep(frozenTime)
}
return user, err
2016-02-01 12:59:10 +01:00
}