Skip to content

Commit

Permalink
Adding some new functions but nothing finalised by any means
Browse files Browse the repository at this point in the history
  • Loading branch information
COMTOP1 committed Jan 10, 2024
1 parent b324605 commit dfc7d9b
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 15 deletions.
20 changes: 20 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ func main() {

domainName := os.Getenv("WAUTH_DOMAIN_NAME")

adPort, err := strconv.Atoi(os.Getenv("WAUTH_AD_PORT"))
if err != nil {
log.Fatalf("failed to get ad port env: %+v", err)
}

adSecurity, err := strconv.Atoi(os.Getenv("WAUTH_AD_SECURITY"))
if err != nil {
log.Fatalf("failed to get ad security env: %+v", err)
}

// Generate config
conf := &views.Config{
Version: Version,
Expand All @@ -96,6 +106,16 @@ func main() {
AuthenticationKey: os.Getenv("WAUTH_AUTHENTICATION_KEY"),
SigningKey: signingKey,
},
AD: views.ADConfig{
Server: os.Getenv("WAUTH_AD_SERVER"),
Port: adPort,
BaseDN: os.Getenv("WAUTH_AD_BASE_DN"),
Security: adSecurity,
Bind: views.ADBind{
Username: os.Getenv("WAUTH_AD_BIND_USERNAME"),
Password: os.Getenv("WAUTH_AD_BIND_PASSWORD"),
},
},
}

v := views.New(conf, dbHost)
Expand Down
1 change: 1 addition & 0 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func (r *Router) middleware() {
"https://internal." + r.config.BaseDomainName,
"https://docs." + r.config.BaseDomainName,
"https://history." + r.config.BaseDomainName,
"http://localhost:*",
},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAccessControlAllowCredentials, echo.HeaderAccessControlAllowOrigin, echo.HeaderAuthorization},
AllowMethods: []string{http.MethodGet, http.MethodPost},
Expand Down
9 changes: 9 additions & 0 deletions utils/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"math/big"

whirl "github.com/balacode/zr-whirl"
"golang.org/x/crypto/scrypt"
)

type Type int
Expand Down Expand Up @@ -34,6 +35,14 @@ func HashPass(password string) string {
return next
}

func HashPassScrypt(password, salt []byte) (string, error) {
hash, err := scrypt.Key(password, salt, 32768, 16, 2, 64)
if err != nil {
return "", fmt.Errorf("failed to generate hash: %w", err)
}
return hex.EncodeToString(hash), nil
}

// GenerateRandom generates a random string for either password or salt
func GenerateRandom(t Type) (string, error) {
switch t {
Expand Down
48 changes: 37 additions & 11 deletions views/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
"time"

Expand Down Expand Up @@ -206,17 +207,42 @@ func (v *Views) SetTokenHandler(c echo.Context) error {
return c.JSON(http.StatusInternalServerError, data)
}

c.Response().Header().Set("Content-Type", "application/json")
c.Response().WriteHeader(http.StatusCreated)
_, err = c.Response().Write(tokenByte)
if err != nil {
log.Printf("failed to write token to http body: %+v", err)
data := struct {
Error error `json:"error"`
}{
Error: fmt.Errorf("failed to write token to http body: %w", err),
}
return c.JSON(http.StatusInternalServerError, data)
_ = tokenByte

callback := ""
callbackURL, err := url.Parse(c.QueryParam("callback"))
fmt.Println(callbackURL.String(), err)
if err == nil /*&& strings.HasSuffix(callbackURL.Host, v.conf.BaseDomainName)*/ && callbackURL.String() != "" {
callback = callbackURL.String()
}
//c.Response().Header().Set("Content-Type", "application/json")

Check failure on line 218 in views/api.go

View workflow job for this annotation

GitHub Actions / lint

commentFormatting: put a space between `//` and comment text (gocritic)
c.Response().Header().Set("Authorization", "Bearer "+tokenString)
cookie := new(http.Cookie)
cookie.Name = "token"
cookie.Expires = time.Now().Add(30 * time.Second)
cookie.Value = tokenString
cookie.Secure = false
cookie.HttpOnly = false
cookie.Domain = "localhost"
c.SetCookie(cookie)
http.SetCookie(c.Response().Writer, cookie)
c.Response().Committed = false
//c.Response().Write(tokenByte)

Check failure on line 230 in views/api.go

View workflow job for this annotation

GitHub Actions / lint

commentFormatting: put a space between `//` and comment text (gocritic)
//_, err = c.Response().Write(tokenByte)
//if err != nil {
// log.Printf("failed to write token to http body: %+v", err)
// data := struct {
// Error error `json:"error"`
// }{
// Error: fmt.Errorf("failed to write token to http body: %w", err),
// }
// return c.JSON(http.StatusInternalServerError, data)
//}
if len(callback) > 0 {
//c.Response().Header().Set("Location", callback)

Check failure on line 242 in views/api.go

View workflow job for this annotation

GitHub Actions / lint

commentFormatting: put a space between `//` and comment text (gocritic)
//c.Response().WriteHeader(http.StatusFound)
return c.Redirect(http.StatusFound, callback+"?token="+tokenString)
//c.Redirect()
}
return nil
}
Expand Down
89 changes: 85 additions & 4 deletions views/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import (
"log"
"net/http"
"net/url"
"strings"

"github.com/google/uuid"
"github.com/labstack/echo/v4"
emailParser "github.com/mcnijman/go-emailaddress"
"github.com/patrickmn/go-cache"
"github.com/ystv/web-auth/templates"
"gopkg.in/guregu/null.v4"

"github.com/ystv/web-auth/templates"
"github.com/ystv/web-auth/user"
)

Expand All @@ -30,7 +30,7 @@ func (v *Views) LoginFunc(c echo.Context) error {

// Check if there is a callback request
callbackURL, err := url.Parse(c.QueryParam("callback"))
if err == nil && strings.HasSuffix(callbackURL.Host, v.conf.BaseDomainName) && callbackURL.String() != "" {
if err == nil && /*strings.HasSuffix(callbackURL.Host, v.conf.BaseDomainName) &&*/ callbackURL.String() != "" {
context.Callback = callbackURL.String()
}
// Check if authenticated
Expand All @@ -54,12 +54,17 @@ func (v *Views) LoginFunc(c echo.Context) error {

callback := "/internal"
callbackURL, err := url.Parse(c.QueryParam("callback"))
if err == nil && strings.HasSuffix(callbackURL.Host, v.conf.BaseDomainName) && callbackURL.String() != "" {
if err == nil /*&& strings.HasSuffix(callbackURL.Host, v.conf.BaseDomainName)*/ && callbackURL.String() != "" {
callback = callbackURL.String()
}
// Authentication
u, resetPw, err := v.user.VerifyUser(c.Request().Context(), u)
if err != nil {
address, _ := emailParser.Parse(username)
if address != nil {
u.LDAPUsername = null.StringFrom(address.LocalPart)
_, err = v.user.GetUser(c.Request().Context(), u)
}
log.Printf("failed login for \"%s\": %v", u.Username, err)
err = session.Save(c.Request(), c.Response())
if err != nil {
Expand Down Expand Up @@ -110,6 +115,14 @@ func (v *Views) LoginFunc(c echo.Context) error {

session.Values["user"] = u

c.SetCookie(&http.Cookie{
Name: "test-pass",
Value: "hello",
MaxAge: 60,
Secure: false,
HttpOnly: false,
})

if c.FormValue("remember") != "on" {
session.Options.MaxAge = 86400 * 31
}
Expand All @@ -124,3 +137,71 @@ func (v *Views) LoginFunc(c echo.Context) error {
}
return fmt.Errorf("failed to parse method")
}

//func (v *Views) LDAPFunc(username, password string) (bool, error) {
// config := &auth.Config{
// Server: v.conf.AD.Server,
// Port: v.conf.AD.Port,
// BaseDN: v.conf.AD.BaseDN,
// Security: auth.SecurityType(v.conf.AD.Security),
// }
//
// conn, err := config.Connect()
// if err != nil {
// return false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("error connecting to server: %w", err))
// }
// defer func(Conn *ldap.Conn) {
// err = Conn.Close()
// if err != nil {
// log.Printf("failed to close to LDAP server: %+v", err)
// }
// }(conn.Conn)
//
// status, err := conn.Bind(v.conf.AD.Bind.Username, v.conf.AD.Bind.Password)
// if err != nil {
// return false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("error binding to server: %w", err))
// }
//
// if !status {
// return false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("error binding to server: invalid credentials"))
// }
//
// status1, err := auth.Authenticate(config, username, password)
// if err != nil {
// return false, echo.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("unable to authenticate %s with error: %w", username, err))
// }
//
// if status1 {
// var entry *ldap.Entry
// if _, err = mail.ParseAddress(username); err == nil {
// entry, err = conn.GetAttributes("userPrincipalName", username, []string{"memberOf"})
// } else {
// entry, err = conn.GetAttributes("samAccountName", username, []string{"memberOf"})
// }
// if err != nil {
// return false, echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("error getting user groups: %w", err))
// }
//
// dnGroups := entry.GetAttributeValues("memberOf")
//
// if len(dnGroups) == 0 {
// return false, echo.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("BIND_SAM user not member of any groups"))
// }
//
// //stv := false
//
// for _, group := range dnGroups {
// if group == "CN=STV Admin,CN=Users,DC=ystv,DC=local" {
// //stv = true
// return true, nil
// }
// }
//
// //if !stv {
// // return false, echo.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("STV not allowed for %s!\n", username))
// //}
// log.Printf("%s is authenticated", username)
// return true, nil
// }
// return false, echo.NewHTTPError(http.StatusUnauthorized, fmt.Errorf("user not authenticated: %s", username))
//}
14 changes: 14 additions & 0 deletions views/views.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,20 @@ type (
SessionCookieName string
Mail SMTPConfig
Security SecurityConfig
AD ADConfig
}

ADConfig struct {
Server string
Port int
BaseDN string
Security int
Bind ADBind
}

ADBind struct {
Username string
Password string
}

// SMTPConfig stores the SMTP Mailer configuration
Expand Down

0 comments on commit dfc7d9b

Please sign in to comment.