mirror of
https://github.com/nestriness/nestri.git
synced 2025-12-12 16:55:37 +02:00
This adds a simple way to incorporate a centralized authentication flow. The idea is to have the user, API and SSH (for machine authentication) all in one place using `openauthjs` + `SST` We also have a database now :) > We are using InstantDB as it allows us to authenticate a use with just the email. Plus it is super simple simple to use _of course after the initial fumbles trying to design the db and relationships_
45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"nestrilabs/cli/internal/machine"
|
|
"nestrilabs/cli/internal/resource"
|
|
"net/http"
|
|
"net/url"
|
|
)
|
|
|
|
type UserCredentials struct {
|
|
AccessToken string `json:"access_token"`
|
|
RefreshToken string `json:"refresh_token"`
|
|
}
|
|
|
|
func FetchUserCredentials() (*UserCredentials, error) {
|
|
m := machine.NewMachine()
|
|
fingerprint := m.GetMachineID()
|
|
data := url.Values{}
|
|
data.Set("grant_type", "client_credentials")
|
|
data.Set("client_id", "device")
|
|
data.Set("client_secret", resource.Resource.AuthFingerprintKey.Value)
|
|
data.Set("hostname", m.Hostname)
|
|
data.Set("fingerprint", fingerprint)
|
|
data.Set("provider", "device")
|
|
resp, err := http.PostForm(resource.Resource.Auth.Url+"/token", data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != 200 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
fmt.Println(string(body))
|
|
return nil, fmt.Errorf("failed to auth: " + string(body))
|
|
}
|
|
credentials := UserCredentials{}
|
|
err = json.NewDecoder(resp.Body).Decode(&credentials)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &credentials, nil
|
|
}
|