-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnginx-ldap-proxy.go
71 lines (59 loc) · 1.64 KB
/
nginx-ldap-proxy.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
package main
import (
"encoding/base64"
"fmt"
"nginx-auth-request-ldap/util"
"sort"
"strings"
"github.com/gin-gonic/gin"
)
func returnUnauthoried(c *gin.Context) {
c.Header("WWW-Authenticate", "Basic realm=\"Secure Area\"")
c.String(401, "")
}
func main() {
r := gin.Default()
r.OPTIONS("/*request", func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-type")
})
r.GET("/*request", func(c *gin.Context) {
// check for authen HTTP header
if value, exist := c.Request.Header["Authorization"]; exist {
checkAuthorizeGroup := "general" // default group
headerGroups := c.Request.Header["X-Group"]
if len(headerGroups) > 0 {
checkAuthorizeGroup = headerGroups[0]
}
auth, _ := base64.StdEncoding.DecodeString(strings.Replace(value[0], "Basic ", "", -1))
tmp := strings.Split(string(auth), ":")
// user/pass from HTTP header
username := tmp[0]
password := tmp[1]
conn := util.LdapConnect()
defer conn.Close()
util.LdapBind(conn)
// authenticate
isValid := util.LdapAuthen(conn, username, password)
if isValid {
groups := util.GetPersonGroup(conn, username)
sort.Strings(groups)
index := sort.SearchStrings(groups, checkAuthorizeGroup)
// authorize
if index < len(groups) && groups[index] == checkAuthorizeGroup {
c.String(200, "Ok")
} else {
fmt.Println("Authenticated but unauthorized")
returnUnauthoried(c)
}
} else {
fmt.Println("Authenticate error")
returnUnauthoried(c)
}
} else {
fmt.Println("No authenicate header")
returnUnauthoried(c)
}
})
r.Run("0.0.0.0:9009")
}