mirror of
https://github.com/netbirdio/netbird.git
synced 2024-11-30 20:13:33 +01:00
6ae27c9a9b
* feature: add User entity to Account * test: new file store creation test * test: add FileStore persist-restore tests * test: add GetOrCreateAccountByUser Accountmanager test * refactor: rename account manager users file * refactor: use userId instead of accountId when handling Management HTTP API * fix: new account creation for every request * fix: golint * chore: add account creator to Account Entity to identify who created the account. * chore: use xid ID generator for account IDs * fix: test failures * test: check that CreatedBy is stored when account is stored * chore: add account copy method * test: remove test for non existent GetOrCreateAccount func * chore: add accounts conversion function * fix: golint * refactor: simplify admin user creation * refactor: move migration script to a separate package
60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"github.com/golang-jwt/jwt"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// extractUserIdFromRequestContext extracts accountId from the request context previously filled by the JWT token (after auth)
|
|
func extractUserIdFromRequestContext(r *http.Request) string {
|
|
token := r.Context().Value("user").(*jwt.Token)
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
//actually a user id but for now we have a 1 to 1 mapping.
|
|
return claims["sub"].(string)
|
|
}
|
|
|
|
//writeJSONObject simply writes object to the HTTP reponse in JSON format
|
|
func writeJSONObject(w http.ResponseWriter, obj interface{}) {
|
|
w.WriteHeader(200)
|
|
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
|
|
err := json.NewEncoder(w).Encode(obj)
|
|
if err != nil {
|
|
http.Error(w, "failed handling request", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
|
|
//Duration is used strictly for JSON requests/responses due to duration marshalling issues
|
|
type Duration struct {
|
|
time.Duration
|
|
}
|
|
|
|
func (d Duration) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(d.String())
|
|
}
|
|
|
|
func (d *Duration) UnmarshalJSON(b []byte) error {
|
|
var v interface{}
|
|
if err := json.Unmarshal(b, &v); err != nil {
|
|
return err
|
|
}
|
|
switch value := v.(type) {
|
|
case float64:
|
|
d.Duration = time.Duration(value)
|
|
return nil
|
|
case string:
|
|
var err error
|
|
d.Duration, err = time.ParseDuration(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
default:
|
|
return errors.New("invalid duration")
|
|
}
|
|
}
|