Bladeren bron

Cleaned up inconsistent code

Thisnthat 1 jaar geleden
bovenliggende
commit
0df5707aec
4 gewijzigde bestanden met toevoegingen van 48 en 6 verwijderingen
  1. 27 0
      sso.go
  2. 1 1
      topics.go
  3. 9 0
      types.go
  4. 11 5
      users.go

+ 27 - 0
sso.go

@@ -7,6 +7,8 @@ import (
 	"encoding/hex"
 	"fmt"
 	"net/url"
+	"strconv"
+	"strings"
 
 	"github.com/google/uuid"
 )
@@ -80,3 +82,28 @@ func computeHmac256(message string, secret string) string {
 	h.Write([]byte(message))
 	return hex.EncodeToString(h.Sum(nil))
 }
+
+func ParseSSOResponse(ssoData string) (SSOResponse, error) {
+	decodedSsoData, err := base64.StdEncoding.DecodeString(ssoData)
+	if err != nil {
+		return SSOResponse{}, err
+	}
+
+	queryData, err := url.ParseQuery(string(decodedSsoData))
+	if err != nil {
+		return SSOResponse{}, err
+	}
+
+	id, _ := strconv.Atoi(queryData.Get("external_id"))
+
+	response := SSOResponse{
+		ID:        id,
+		Admin:     (queryData.Get("admin") == "true"),
+		Moderator: (queryData.Get("moderator") == "true"),
+		Groups:    strings.Split(queryData.Get("groups"), ","),
+		Username:  queryData.Get("username"),
+		Nonce:     queryData.Get("nonce"),
+	}
+
+	return response, nil
+}

+ 1 - 1
topics.go

@@ -19,7 +19,7 @@ type errorResponse struct {
 }
 
 type newPMResponse struct {
-	ID int `json:"id"`
+	ID int `json:"topic_id"`
 }
 
 const pmArchtype = "private_message"

+ 9 - 0
types.go

@@ -56,3 +56,12 @@ type Group struct {
 	CanAdminGroup             bool   `json:"can_admin_group"`
 	PublishReadState          bool   `json:"publish_read_state"`
 }
+
+type SSOResponse struct {
+	ID        int
+	Username  string
+	Groups    []string
+	Admin     bool
+	Moderator bool
+	Nonce     string
+}

+ 11 - 5
users.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"io/ioutil"
+	"net/http"
 	"strings"
 	"time"
 
@@ -112,14 +113,19 @@ func GetUserByID(config APIConfig, userID int) (User, error) {
 	client := getClient(rl)
 	response, _ := client.Do(req)
 
-	var result *UserResponse
-	json.NewDecoder(response.Body).Decode(&result)
+	if response.StatusCode != http.StatusOK {
+		var errorResult *UserResponse
+		json.NewDecoder(response.Body).Decode(&errorResult)
 
-	if result.ErrorType != "" {
-		return User{}, fmt.Errorf("Failed to get discourse user. Error: %s", strings.Join(result.Errors, "; "))
+		if errorResult.ErrorType != "" {
+			return User{}, fmt.Errorf("failed to get discourse user. Error: %s", strings.Join(errorResult.Errors, "; "))
+		}
 	}
 
-	return result.User, nil
+	var result *User
+	json.NewDecoder(response.Body).Decode(&result)
+
+	return *result, nil
 }
 
 func GetUsersByMinTrustLevel(config APIConfig, minTrustLevel int64) ([]User, error) {