Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Resolve Issue #9 [Authentication System] and #12 [CORS Error] #11

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions backend/controllers/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// ref https://github.com/jtblin/go-ldap-client

package controllers

import (
"encoding/json"
"log"
"net/http"

ldap "github.com/jtblin/go-ldap-client"
)

type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}

var client = &ldap.LDAPClient{
Base: "dc=example,dc=com",
Host: "ldap.forumsys.com", // test server ref https://www.forumsys.com/2022/05/10/online-ldap-test-server/
Port: 389,
UseSSL: false,
InsecureSkipVerify: false,
SkipTLS: true, // fix for tls handshake err [maybe Host doesnt support newer TLS]
BindDN: "cn=read-only-admin,dc=example,dc=com",
BindPassword: "password",
UserFilter: "(uid=%s)",
GroupFilter: "(memberUid=%s)",
Attributes: []string{"givenName", "sn", "mail", "uid"},
}

// handles LDAP auth req
func AuthenticateLDAP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}

var creds Credentials
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
http.Error(w, "Invalid JSON payload", http.StatusBadRequest)
return
}

defer client.Close()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see this problematic, I have checked it, this will be nice for single user system, but if concurrent req are made and all try to close the same client(here global client), so from 2nd req onwards they are processing this on closed client.

What you can do , create new client for each request inside that function and then defer closing it. Or something else.

Otherwise it is nice.


authenticated, user, err := client.Authenticate(creds.Username, creds.Password)
if err != nil {
log.Printf("LDAP Authentication Error: %v", err)
http.Error(w, "Authentication failed due to server error", http.StatusInternalServerError)
return
}

if !authenticated {
log.Printf("Invalid credentials for user %s", creds.Username)
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}

groups, err := client.GetGroupsOfUser(creds.Username)
if err != nil {
log.Printf("Error fetching groups for user %s: %v", creds.Username, err)
http.Error(w, "Authenticated but failed to retrieve groups", http.StatusInternalServerError)
return
}

response := map[string]interface{}{
"message": "Authenticated successfully",
"user": user,
"groups": groups,
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
4 changes: 4 additions & 0 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ go 1.19

require (
github.com/golang/snappy v0.0.1 // indirect
github.com/jtblin/go-ldap-client v0.0.0-20170223121919-b73f66626b33 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rs/cors v1.11.1 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.1 // indirect
github.com/xdg-go/stringprep v1.0.3 // indirect
Expand All @@ -15,4 +17,6 @@ require (
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
gopkg.in/ldap.v2 v2.5.1 // indirect
)
8 changes: 8 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/jtblin/go-ldap-client v0.0.0-20170223121919-b73f66626b33 h1:XDpFOMOZq0u0Ar4F0p/wklqQXp/AMV1pTF5T5bDoUfQ=
github.com/jtblin/go-ldap-client v0.0.0-20170223121919-b73f66626b33/go.mod h1:+0BcLY5d54TVv6irFzHoiFvwAHR6T0g9B+by/UaS9T0=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
Expand All @@ -13,6 +15,8 @@ github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJ
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
Expand Down Expand Up @@ -40,7 +44,11 @@ golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d h1:TxyelI5cVkbREznMhfzycHdkp5cLA7DpE+GKjSslYhM=
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d/go.mod h1:cuepJuh7vyXfUyUwEgHQXw849cJrilpS5NeIjOWESAw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ldap.v2 v2.5.1 h1:wiu0okdNfjlBzg6UWvd1Hn8Y+Ux17/u/4nlk4CQr6tU=
gopkg.in/ldap.v2 v2.5.1/go.mod h1:oI0cpe/D7HRtBQl8aTg+ZmzFUAvu4lsv3eLXMLGFxWk=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
2 changes: 1 addition & 1 deletion backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func main() {
return
}
routers.Router()
err = http.ListenAndServe(":8080", nil)
err = http.ListenAndServe(":8080", routers.Router())
if err != nil {
fmt.Println(err)
}
Expand Down
19 changes: 16 additions & 3 deletions backend/routers/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,27 @@ package routers
import (
"net/http"
"tokenSystem/controllers"

"github.com/rs/cors"
)

func Router() {
http.HandleFunc("/student", func(w http.ResponseWriter, r *http.Request) {
func Router() http.Handler {
mux := http.NewServeMux()

// Define routes
mux.HandleFunc("/student", func(w http.ResponseWriter, r *http.Request) {
controllers.CreateStudnet(w, r, controllers.Client)
})
http.HandleFunc("/students", func(w http.ResponseWriter, r *http.Request) {
mux.HandleFunc("/students", func(w http.ResponseWriter, r *http.Request) {
controllers.GetAllstudents(w, r, controllers.Client)
})
mux.HandleFunc("/login", controllers.AuthenticateLDAP)

// Apply CORS middleware
return cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowCredentials: true,
}).Handler(mux)
}
Loading