ajout du state

This commit is contained in:
2021-01-27 21:40:26 +01:00
parent cfe68a5329
commit 29c7e70cc9
4 changed files with 44 additions and 25 deletions

View File

@@ -7,7 +7,7 @@ type Oauth struct {
AccessToken string `db:"access_token"` AccessToken string `db:"access_token"`
TokenType string `db:"token_type"` TokenType string `db:"token_type"`
ExpireIN int `db:"expire_in"` ExpireIN int `db:"expire_in"`
RefreshToken string `db:"refreh_token"` RefreshToken string `db:"refresh_token"`
} }
func (o Oauth) String() string { func (o Oauth) String() string {

View File

@@ -4,6 +4,7 @@ import "fmt"
type Param struct { type Param struct {
ID int64 `db:"id"` ID int64 `db:"id"`
State string `db:"state"`
Domaine string `db:"domaine"` Domaine string `db:"domaine"`
ClientID string `db:"client_id"` ClientID string `db:"client_id"`
ClientSecret string `db:"client_secret"` ClientSecret string `db:"client_secret"`
@@ -11,6 +12,6 @@ type Param struct {
} }
func (p Param) String() string { func (p Param) String() string {
return fmt.Sprintf("id=%v, title=%v, releaseDate=%v, duration=%v, trailerURL=%v", return fmt.Sprintf("id=%v, state=%v, domaine=%v, clientId=%v, clientSecret=%v, grantType=%v",
p.ID, p.Domaine, p.ClientID, p.ClientSecret, p.GrantType) p.ID, p.State, p.Domaine, p.ClientID, p.ClientSecret, p.GrantType)
} }

View File

@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"html/template" "html/template"
"log" "log"
"math/rand"
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
@@ -46,16 +47,6 @@ type Claims struct {
func (s *server) handleIndex() http.HandlerFunc { func (s *server) handleIndex() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) {
err := s.store.DeleteOauth(1)
if err != nil {
fmt.Printf("erreur à la récupération des paramètres %v", err)
}
err = s.store.DeleteParam("state")
if err != nil {
fmt.Printf("erreur à la récupération des paramètres %v", err)
}
rw.Header().Set("Content-Type", "text/html") rw.Header().Set("Content-Type", "text/html")
rw.WriteHeader(http.StatusOK) rw.WriteHeader(http.StatusOK)
@@ -116,14 +107,16 @@ func (s *server) handleLocal() http.HandlerFunc {
AccessToken: at, AccessToken: at,
TokenType: "bearer", TokenType: "bearer",
ExpireIN: -1, ExpireIN: -1,
RefreshToken: "", RefreshToken: "refresh",
} }
err = s.store.CreateOauth(o) err = s.store.CreateOauth(o)
if err != nil { if err != nil {
fmt.Printf("erreur suivante %v", err) fmt.Printf("erreur suivante %v", err)
} }
rj := "http://localhost:8080/jwt" monID := strconv.Itoa(int(o.ID))
// Puis redisrect vers page resultat
rj := "http://localhost:8080/jwt?model=" + monID
http.Redirect(rw, r, rj, http.StatusMovedPermanently) http.Redirect(rw, r, rj, http.StatusMovedPermanently)
} }
@@ -144,9 +137,15 @@ func (s *server) handleOAuth20() http.HandlerFunc {
cc = "true" cc = "true"
} }
// Création du nombre aléatoire pour la state
nr := rand.NewSource(time.Now().UnixNano())
rand := rand.New(nr)
st := strconv.Itoa(rand.Intn(10000000000))
// Insert en base de données // Insert en base de données
p := &model.Param{ p := &model.Param{
ID: 0, ID: 0,
State: st,
Domaine: d, Domaine: d,
ClientID: ci, ClientID: ci,
ClientSecret: cs, ClientSecret: cs,
@@ -158,10 +157,13 @@ func (s *server) handleOAuth20() http.HandlerFunc {
fmt.Printf("erreur suivante %v", err) fmt.Printf("erreur suivante %v", err)
} }
// on appelle les méthodes de l'instance de `rand.Rand` obtenue comme les autres méthodes du package.
//fmt.Print(r1.Intn(100), ",")
rhttp := "https://" + d + "/entreprise-partenaire/authorize?client_id=" + ci + rhttp := "https://" + d + "/entreprise-partenaire/authorize?client_id=" + ci +
"&scope=" + sc + "&scope=" + sc +
"&current_company=" + cc + "&current_company=" + cc +
"&redirect_uri=http://localhost:8080/oauth/redirect%3Fstate=ererer" + "&redirect_uri=http://localhost:8080/oauth/redirect%3Fstate=" + st +
"&abort_uri=http://localhost:8080/index" "&abort_uri=http://localhost:8080/index"
http.Redirect(rw, r, rhttp, http.StatusMovedPermanently) http.Redirect(rw, r, rhttp, http.StatusMovedPermanently)
@@ -181,9 +183,10 @@ func (s *server) handleRedirect() http.HandlerFunc {
fmt.Printf("erreur à la recupération des param (err=%v)", err) fmt.Printf("erreur à la recupération des param (err=%v)", err)
} }
jsonStr := constJSONToken(c, st, p) jsonStr := constJSONToken(c, st, p)
log.Printf("jsonStr %v", jsonStr)
apiURL := "https://api." + p.Domaine + "/auth/v1/oauth2.0/accessToken" apiURL := "https://api." + p.Domaine + "/auth/v1/oauth2.0/accessToken"
data := url.Values{} data := url.Values{}
log.Printf("data %v", data)
data.Set("client_id", jsonStr.ClientID) data.Set("client_id", jsonStr.ClientID)
data.Set("client_secret", jsonStr.ClientSecret) data.Set("client_secret", jsonStr.ClientSecret)
data.Set("grant_type", jsonStr.GrantType) data.Set("grant_type", jsonStr.GrantType)
@@ -192,15 +195,19 @@ func (s *server) handleRedirect() http.HandlerFunc {
client := &http.Client{} client := &http.Client{}
req, err := http.NewRequest("POST", apiURL, bytes.NewBufferString(data.Encode())) req, err := http.NewRequest("POST", apiURL, bytes.NewBufferString(data.Encode()))
if err != nil {
log.Printf("erreur sur le post (err=%v)", err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode()))) req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
req.Header.Add("Accept", "application/json") req.Header.Add("Accept", "application/json")
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
panic(err) log.Printf("client erreur %v", err)
} }
log.Printf("resp status %v", resp.StatusCode)
var t map[string]interface{} var t map[string]interface{}
// here's the trick // here's the trick
json.NewDecoder(resp.Body).Decode(&t) json.NewDecoder(resp.Body).Decode(&t)
@@ -224,7 +231,7 @@ func (s *server) handleRedirect() http.HandlerFunc {
AccessToken: t["access_token"].(string), AccessToken: t["access_token"].(string),
TokenType: t["type_token"].(string), TokenType: t["type_token"].(string),
ExpireIN: t["expire_in"].(int), ExpireIN: t["expire_in"].(int),
RefreshToken: t["refresh-token"].(string), RefreshToken: t["refresh_token"].(string),
} }
err = s.store.CreateOauth(o) err = s.store.CreateOauth(o)
if err != nil { if err != nil {
@@ -240,6 +247,9 @@ func (s *server) handleRedirect() http.HandlerFunc {
func (s *server) handleJSONWebToken() http.HandlerFunc { func (s *server) handleJSONWebToken() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) { return func(rw http.ResponseWriter, r *http.Request) {
c := r.URL.Query().Get("model")
rw.Header().Set("Content-Type", "text/html") rw.Header().Set("Content-Type", "text/html")
rw.WriteHeader(http.StatusOK) rw.WriteHeader(http.StatusOK)
@@ -248,7 +258,12 @@ func (s *server) handleJSONWebToken() http.HandlerFunc {
fmt.Printf("erreur suivante %v", err) fmt.Printf("erreur suivante %v", err)
} }
oauth, _ := s.store.GetOauth(1) oauthID, err := strconv.ParseInt(c, 10, 64)
oauth, err := s.store.GetOauth(oauthID)
if err != nil {
log.Printf("erreur a la récupération oauth (err=%v)", err)
}
tokenVal := oauth.AccessToken tokenVal := oauth.AccessToken
fmt.Println("============") fmt.Println("============")
@@ -290,7 +305,7 @@ func constJSONToken(code, state string, param *model.Param) JSONToken {
ClientID: param.ClientID, ClientID: param.ClientID,
ClientSecret: param.ClientSecret, ClientSecret: param.ClientSecret,
GrantType: param.GrantType, GrantType: param.GrantType,
RedirectURI: "http://localhost:8080/oauth/redirect?state=" + state, RedirectURI: "http://localhost:8080/oauth/redirect%3Fstate=" + state,
Code: code, Code: code,
} }
} }

View File

@@ -40,6 +40,7 @@ var schemaParam = `
CREATE TABLE IF NOT EXISTS param CREATE TABLE IF NOT EXISTS param
( (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
state TEXT,
domaine TEXT, domaine TEXT,
client_id TEXT, client_id TEXT,
client_secret TEXT, client_secret TEXT,
@@ -66,16 +67,18 @@ func (store *DbStore) Close() error {
func (store *DbStore) GetOauth(id int64) (*model.Oauth, error) { func (store *DbStore) GetOauth(id int64) (*model.Oauth, error) {
var oauth = &model.Oauth{} var oauth = &model.Oauth{}
log.Println("ME VOICI")
err := store.db.Get(oauth, "SELECT * FROM oauth where id=$1", id) err := store.db.Get(oauth, "SELECT * FROM oauth where id=$1", id)
if err != nil { if err != nil {
return oauth, err return oauth, err
} }
log.Printf("oauth=%v", oauth)
return oauth, nil return oauth, nil
} }
func (store *DbStore) CreateOauth(o *model.Oauth) error { func (store *DbStore) CreateOauth(o *model.Oauth) error {
res, err := store.db.Exec("INSERT INTO oauth (access_token, expire_in, refresh_token) VALUES (?, ?, ?)", res, err := store.db.Exec("INSERT INTO oauth (access_token, token_type, expire_in, refresh_token) VALUES (?, ?, ?, ?)",
o.AccessToken, o.ExpireIN, o.RefreshToken) o.AccessToken, o.TokenType, o.ExpireIN, o.RefreshToken)
if err != nil { if err != nil {
return err return err
@@ -105,8 +108,8 @@ func (store *DbStore) GetParam(state string) (*model.Param, error) {
} }
func (store *DbStore) CreateParam(p *model.Param) error { func (store *DbStore) CreateParam(p *model.Param) error {
res, err := store.db.Exec("INSERT INTO param (domaine, client_id, client_secret, grant_type) VALUES (?, ?, ?, ?)", res, err := store.db.Exec("INSERT INTO param (state, domaine, client_id, client_secret, grant_type) VALUES (?, ?, ?, ?, ?)",
p.Domaine, p.ClientID, p.ClientSecret, p.GrantType) p.State, p.Domaine, p.ClientID, p.ClientSecret, p.GrantType)
if err != nil { if err != nil {
return err return err
} }