1
0
Fork 0
mirror of https://github.com/documize/community.git synced 2025-08-04 21:15:24 +02:00

major code repair from old to new API -- WIP

This commit is contained in:
Harvey Kandola 2017-07-24 16:24:21 +01:00
parent 25b576f861
commit 792c3e2ce8
46 changed files with 3403 additions and 171 deletions

207
domain/auth/endpoint.go Normal file
View file

@ -0,0 +1,207 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package auth
import (
"database/sql"
"errors"
"net/http"
"strings"
"github.com/documize/community/core/response"
"github.com/documize/community/core/secrets"
"github.com/documize/community/domain"
"github.com/documize/community/domain/organization"
"github.com/documize/community/domain/section/provider"
"github.com/documize/community/domain/user"
)
// Authenticate user based up HTTP Authorization header.
// An encrypted authentication token is issued with an expiry date.
func (h *Handler) Authenticate(w http.ResponseWriter, r *http.Request) {
method := "Authenticate"
s := domain.StoreContext{Runtime: h.Runtime, Context: domain.GetRequestContext(r)}
// check for http header
authHeader := r.Header.Get("Authorization")
if len(authHeader) == 0 {
response.WriteBadRequestError(w, method, "Missing Authorization header")
return
}
// decode what we received
data := strings.Replace(authHeader, "Basic ", "", 1)
decodedBytes, err := secrets.DecodeBase64([]byte(data))
if err != nil {
response.WriteBadRequestError(w, method, "Unable to decode authentication token")
return
}
decoded := string(decodedBytes)
// check that we have domain:email:password (but allow for : in password field!)
credentials := strings.SplitN(decoded, ":", 3)
if len(credentials) != 3 {
response.WriteBadRequestError(w, method, "Bad authentication token, expecting domain:email:password")
return
}
dom := strings.TrimSpace(strings.ToLower(credentials[0]))
dom = organization.CheckDomain(s, dom) // TODO optimize by removing this once js allows empty domains
email := strings.TrimSpace(strings.ToLower(credentials[1]))
password := credentials[2]
h.Runtime.Log.Info("logon attempt " + email + " @ " + dom)
u, err := user.GetByDomain(s, dom, email)
if err == sql.ErrNoRows {
response.WriteUnauthorizedError(w)
return
}
if err != nil {
response.WriteServerError(w, method, err)
return
}
if len(u.Reset) > 0 || len(u.Password) == 0 {
response.WriteUnauthorizedError(w)
return
}
// Password correct and active user
if email != strings.TrimSpace(strings.ToLower(u.Email)) || !secrets.MatchPassword(u.Password, password, u.Salt) {
response.WriteUnauthorizedError(w)
return
}
org, err := organization.GetOrganizationByDomain(s, dom)
if err != nil {
response.WriteUnauthorizedError(w)
return
}
// Attach user accounts and work out permissions
user.AttachUserAccounts(s, org.RefID, &u)
// active check
if len(u.Accounts) == 0 {
response.WriteUnauthorizedError(w)
return
}
authModel := AuthenticationModel{}
authModel.Token = GenerateJWT(h.Runtime, u.RefID, org.RefID, dom)
authModel.User = u
response.WriteJSON(w, authModel)
}
// ValidateAuthToken finds and validates authentication token.
func (h *Handler) ValidateAuthToken(w http.ResponseWriter, r *http.Request) {
// TODO should this go after token validation?
if s := r.URL.Query().Get("section"); s != "" {
if err := provider.Callback(s, w, r); err != nil {
h.Runtime.Log.Error("section validation failure", err)
w.WriteHeader(http.StatusUnauthorized)
}
return
}
s := domain.StoreContext{Runtime: h.Runtime, Context: domain.GetRequestContext(r)}
token := FindJWT(r)
rc, _, tokenErr := DecodeJWT(h.Runtime, token)
var org = organization.Organization{}
var err = errors.New("")
// We always grab the org record regardless of token status.
// Why? If bad token we might be OK to alow anonymous access
// depending upon the domain in question.
if len(rc.OrgID) == 0 {
org, err = organization.GetOrganizationByDomain(s, organization.GetRequestSubdomain(s, r))
} else {
org, err = organization.GetOrganization(s, rc.OrgID)
}
rc.Subdomain = org.Domain
// Inability to find org record spells the end of this request.
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
// If we have bad auth token and the domain does not allow anon access
if !org.AllowAnonymousAccess && tokenErr != nil {
return
}
dom := organization.GetSubdomainFromHost(s, r)
dom2 := organization.GetRequestSubdomain(s, r)
if org.Domain != dom && org.Domain != dom2 {
w.WriteHeader(http.StatusUnauthorized)
return
}
// If we have bad auth token and the domain allows anon access
// then we generate guest rc.
if org.AllowAnonymousAccess {
// So you have a bad token
if len(token) > 1 {
if tokenErr != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
} else {
// Just grant anon user guest access
rc.UserID = "0"
rc.OrgID = org.RefID
rc.Authenticated = false
rc.Guest = true
}
}
rc.AllowAnonymousAccess = org.AllowAnonymousAccess
rc.OrgName = org.Title
rc.Administrator = false
rc.Editor = false
rc.Global = false
rc.AppURL = r.Host
rc.Subdomain = organization.GetSubdomainFromHost(s, r)
rc.SSL = r.TLS != nil
// Fetch user permissions for this org
if !rc.Authenticated {
w.WriteHeader(http.StatusUnauthorized)
return
}
u, err := user.GetSecuredUser(s, org.RefID, rc.UserID)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
rc.Administrator = u.Admin
rc.Editor = u.Editor
rc.Global = u.Global
response.WriteJSON(w, u)
return
}

133
domain/auth/jwt.go Normal file
View file

@ -0,0 +1,133 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package auth
import (
"fmt"
"net/http"
"strings"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/documize/community/core/env"
"github.com/documize/community/domain"
)
// GenerateJWT generates JSON Web Token (http://jwt.io)
func GenerateJWT(rt env.Runtime, user, org, domain string) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iss": "Documize",
"sub": "webapp",
"exp": time.Now().Add(time.Hour * 168).Unix(),
"user": user,
"org": org,
"domain": domain,
})
tokenString, _ := token.SignedString([]byte(rt.Flags.Salt))
return tokenString
}
// FindJWT looks for 'Authorization' request header OR query string "?token=XXX".
func FindJWT(r *http.Request) (token string) {
header := r.Header.Get("Authorization")
if header != "" {
header = strings.Replace(header, "Bearer ", "", 1)
}
if len(header) > 1 {
token = header
} else {
query := r.URL.Query()
token = query.Get("token")
}
if token == "null" {
token = ""
}
return
}
// DecodeJWT decodes raw token.
func DecodeJWT(rt env.Runtime, tokenString string) (c domain.RequestContext, claims jwt.Claims, err error) {
// sensible defaults
c.UserID = ""
c.OrgID = ""
c.Authenticated = false
c.Guest = false
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(rt.Flags.Salt), nil
})
if err != nil {
err = fmt.Errorf("bad authorization token")
return
}
if !token.Valid {
if ve, ok := err.(*jwt.ValidationError); ok {
if ve.Errors&jwt.ValidationErrorMalformed != 0 {
err = fmt.Errorf("bad token")
return
} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
err = fmt.Errorf("expired token")
return
} else {
err = fmt.Errorf("bad token")
return
}
} else {
err = fmt.Errorf("bad token")
return
}
}
c = domain.RequestContext{}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
c.UserID = claims["user"].(string)
c.OrgID = claims["org"].(string)
} else {
fmt.Println(err)
}
if len(c.UserID) == 0 || len(c.OrgID) == 0 {
err = fmt.Errorf("unable parse token data")
return
}
c.Authenticated = true
c.Guest = false
return c, token.Claims, nil
}
// DecodeKeycloakJWT takes in Keycloak token string and decodes it.
func DecodeKeycloakJWT(t, pk string) (c jwt.MapClaims, err error) {
token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return jwt.ParseRSAPublicKeyFromPEM([]byte(pk))
})
if c, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return c, nil
}
return nil, err
}

28
domain/auth/model.go Normal file
View file

@ -0,0 +1,28 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package auth
import (
"github.com/documize/community/core/env"
"github.com/documize/community/domain/user"
)
// Handler contains the runtime information such as logging and database.
type Handler struct {
Runtime env.Runtime
}
// AuthenticationModel details authentication token and user details.
type AuthenticationModel struct {
Token string `json:"token"`
User user.User `json:"user"`
}