/
basicauth.go
81 lines (72 loc) · 2.32 KB
/
basicauth.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
/*
* Copyright 2022-2023 Thorsten A. Knieling
*
* 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
*
*/
package auth
import (
"net/http"
"os"
errors "github.com/go-openapi/errors"
"github.com/tknie/log"
"github.com/tknie/services"
)
// PrincipalInterface principal independent to model
type PrincipalInterface interface {
UUID() string
Name() string
AddRoles([]string)
Remote() string
SetRemote(string)
Roles() []string
Session() interface{}
SetSession(interface{})
}
var principalRegister []func(PrincipalInterface) error
// PrincipalCreater creator of an principal instance
var PrincipalCreater func(session *SessionInfo, user, pass string) PrincipalInterface
// AuthenticationConfig authentication config base
var AuthenticationConfig *Authentication
// Register register principal hooks
func Register(r func(PrincipalInterface) error) {
principalRegister = append(principalRegister, r)
}
// BasicAuth basic authentication on REST
func BasicAuth(user string, pass string) (PrincipalInterface, error) {
var saveErr error
log.Log.Debugf("Basic authentication")
if AuthenticationConfig == nil || len(AuthenticationConfig.AuthenticationServer) == 0 {
services.ServerMessage("Fatal: No Authentication defined!!!!!")
os.Exit(201)
}
sessionUUID := NewSessionInfo(user)
principal := PrincipalCreater(sessionUUID, user, pass)
for _, s := range AuthenticationConfig.AuthenticationServer {
log.Log.Debugf("Check %s authentication (%p)", s.Type, s)
err := s.Authenticate(principal, user, pass)
if err == nil {
log.Log.Debugf("Validated by %s authentication", s.Type)
log.Log.Debugf("User authentication ok: %s", user)
err = uuidStore(principal, user, pass)
if err != nil {
return nil, err
}
evaluateRoles(principal)
if log.IsDebugLevel() {
log.Log.Debugf("Create principal: %p", principal.Name)
}
return principal, nil
}
log.Log.Debugf("Authorization(%s/%p) refused for user %s: %v", s.AuthMethod.Method(), s, user, err)
if saveErr == nil {
saveErr = err
}
}
services.ServerMessage("Authorization refused for user '%s': %v", user, saveErr)
return nil, errors.New(http.StatusUnauthorized, "Access denied: %v", saveErr)
}