chore: archi package du projet
This commit is contained in:
171
routeserv/routes.auth.go
Normal file
171
routeserv/routes.auth.go
Normal file
@@ -0,0 +1,171 @@
|
||||
package routeserv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/ldrogou/goauth20/model"
|
||||
templateoauth "github.com/ldrogou/goauth20/templateOAuth"
|
||||
)
|
||||
|
||||
//Claim claims to export
|
||||
type Claims struct {
|
||||
Sub string `json:"sub"`
|
||||
IDEntreprise string `json:"idEntreprise,omitempty"`
|
||||
RcaPartnerID string `json:"rcaPartnerId"`
|
||||
Scopes []string `json:"scopes"`
|
||||
Roles []string `json:"roles"`
|
||||
jwt.StandardClaims
|
||||
}
|
||||
|
||||
func (s *Server) handleIndex() http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
rw.Header().Set("Content-Type", "text/html")
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
|
||||
t, err := template.New("test").Parse(templateoauth.TemplateIndex)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
|
||||
err = t.Execute(rw, nil)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
func (s *Server) handleLocal() http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
sub := r.FormValue("sub")
|
||||
idEntreprise := r.FormValue("id_entreprise")
|
||||
rcaPartnerID := r.FormValue("rcaPartnerId")
|
||||
jwtKey := r.FormValue("secret")
|
||||
scopes := r.FormValue("scopes")
|
||||
roles := r.FormValue("roles")
|
||||
|
||||
var sc []string
|
||||
sc = append(sc, scopes)
|
||||
|
||||
rs := strings.Fields(roles)
|
||||
|
||||
// Declare the expiration time of the token
|
||||
// here, we have kept it as 5 minutes
|
||||
expirationTime := time.Now().Add(5 * time.Hour)
|
||||
// Create the JWT claims, which includes the username and expiry time
|
||||
claims := &Claims{
|
||||
StandardClaims: jwt.StandardClaims{
|
||||
// In JWT, the expiry time is expressed as unix milliseconds
|
||||
ExpiresAt: expirationTime.Unix(),
|
||||
},
|
||||
}
|
||||
if idEntreprise != "0" {
|
||||
claims.IDEntreprise = idEntreprise
|
||||
}
|
||||
claims.Sub = sub
|
||||
claims.RcaPartnerID = rcaPartnerID
|
||||
claims.Roles = rs
|
||||
claims.Scopes = sc
|
||||
|
||||
secretBase64, err := jwt.DecodeSegment(jwtKey)
|
||||
// Declare the token with the algorithm used for signing, and the claims
|
||||
ts := jwt.NewWithClaims(jwt.SigningMethodHS512, claims)
|
||||
|
||||
at, err := ts.SignedString(secretBase64)
|
||||
// Create the JWT string
|
||||
if err != nil {
|
||||
log.Printf("erreur %v", err)
|
||||
// If there is an error in creating the JWT return an internal server error
|
||||
rw.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Puis redisrect vers page resultat
|
||||
o := &model.Oauth{
|
||||
ID: 0,
|
||||
AccessToken: at,
|
||||
TokenType: "bearer",
|
||||
ExpiresIN: -1,
|
||||
RefreshToken: "refresh",
|
||||
}
|
||||
err = s.Store.CreateOauth(o)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
|
||||
monID := strconv.Itoa(int(o.ID))
|
||||
// Puis redisrect vers page resultat
|
||||
rj := "http://localhost:8090/jwt/" + monID
|
||||
http.Redirect(rw, r, rj, http.StatusMovedPermanently)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) handleOAuth20() http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
d := r.FormValue("domain")
|
||||
ci := r.FormValue("clientId")
|
||||
cs := r.FormValue("clientSecret")
|
||||
sc := r.FormValue("clientScopes")
|
||||
cc := r.FormValue("currentCompany")
|
||||
|
||||
// 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
|
||||
p := &model.Param{
|
||||
ID: 0,
|
||||
State: st,
|
||||
Domaine: d,
|
||||
ClientID: ci,
|
||||
ClientSecret: cs,
|
||||
GrantType: "authorization_code",
|
||||
}
|
||||
|
||||
err := s.Store.CreateParam(p)
|
||||
if err != nil {
|
||||
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), ",")
|
||||
|
||||
var b bytes.Buffer
|
||||
if cc == "none" {
|
||||
b.WriteString("https://api.")
|
||||
b.WriteString(d)
|
||||
b.WriteString("/auth/v1/oauth2.0/authorize?response_type=code")
|
||||
} else {
|
||||
b.WriteString("https://")
|
||||
b.WriteString(d)
|
||||
b.WriteString("/entreprise-partenaire/authorize?")
|
||||
b.WriteString("current_company=")
|
||||
b.WriteString(cc)
|
||||
b.WriteString("&abort_uri=http://localhost:8090/index")
|
||||
}
|
||||
|
||||
b.WriteString("&client_id=")
|
||||
b.WriteString(ci)
|
||||
b.WriteString("&scope=")
|
||||
b.WriteString(sc)
|
||||
b.WriteString("&redirect_uri=http://localhost:8090/oauth/redirect%3Fstate=")
|
||||
b.WriteString(st)
|
||||
|
||||
http.Redirect(rw, r, b.String(), http.StatusMovedPermanently)
|
||||
}
|
||||
|
||||
}
|
||||
11
routeserv/routes.go
Normal file
11
routeserv/routes.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package routeserv
|
||||
|
||||
func (s *Server) routes() {
|
||||
s.Router.HandleFunc("/index", s.handleIndex()).Methods("GET")
|
||||
s.Router.HandleFunc("/oauth/redirect", s.handleRedirect()).Methods("GET")
|
||||
s.Router.HandleFunc("/local", s.handleLocal()).Methods("POST")
|
||||
s.Router.HandleFunc("/oauth20", s.handleOAuth20()).Methods("POST")
|
||||
s.Router.HandleFunc("/jwt/{id}", s.handleJSONWebToken()).Methods("GET")
|
||||
s.Router.HandleFunc("/jwt/refresh/{id}", s.handleRefreshToken()).Methods("POST")
|
||||
|
||||
}
|
||||
164
routeserv/routes.jwt.go
Normal file
164
routeserv/routes.jwt.go
Normal file
@@ -0,0 +1,164 @@
|
||||
package routeserv
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/ldrogou/goauth20/model"
|
||||
templateoauth "github.com/ldrogou/goauth20/templateOAuth"
|
||||
)
|
||||
|
||||
//"YNVZF88dD4vny59k")
|
||||
//JSONToken json token
|
||||
type JSONToken struct {
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
GrantType string `json:"grant_type"`
|
||||
RedirectURI string `json:"redirect_uri"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
func (s *Server) handleRedirect() http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
c := r.URL.Query().Get("code")
|
||||
st := r.URL.Query().Get("state")
|
||||
|
||||
// ici jouter la récupération du param
|
||||
p, err := s.Store.GetParam(st)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur à la recupération des param (err=%v)", err)
|
||||
}
|
||||
jsonStr := constJSONToken(c, st, p)
|
||||
//log.Printf("jsonStr %v", jsonStr)
|
||||
apiURL := "https://api." + p.Domaine + "/auth/v1/oauth2.0/accessToken"
|
||||
data := url.Values{}
|
||||
log.Printf("data %v", data)
|
||||
data.Set("client_id", jsonStr.ClientID)
|
||||
data.Set("client_secret", jsonStr.ClientSecret)
|
||||
data.Set("grant_type", jsonStr.GrantType)
|
||||
data.Set("redirect_uri", jsonStr.RedirectURI)
|
||||
data.Set("code", jsonStr.Code)
|
||||
|
||||
client := &http.Client{}
|
||||
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-Length", strconv.Itoa(len(data.Encode())))
|
||||
req.Header.Add("Accept", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
log.Printf("client erreur %v", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
log.Printf("Problème dans la requete retour http %v", resp.StatusCode)
|
||||
s.response(rw, r, nil, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
var t map[string]interface{}
|
||||
// here's the trick
|
||||
err = json.NewDecoder(resp.Body).Decode(&t)
|
||||
if err != nil {
|
||||
log.Printf("Cannot parse token body err=%v", err)
|
||||
s.response(rw, r, nil, http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Insert en base de données
|
||||
o := &model.Oauth{
|
||||
ID: 0,
|
||||
AccessToken: t["access_token"].(string),
|
||||
TokenType: t["token_type"].(string),
|
||||
ExpiresIN: t["expires_in"].(float64),
|
||||
RefreshToken: t["refresh_token"].(string),
|
||||
}
|
||||
err = s.Store.CreateOauth(o)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
|
||||
monID := strconv.Itoa(int(o.ID))
|
||||
// Puis redisrect vers page resultat
|
||||
rj := "http://localhost:8090/jwt/" + monID
|
||||
http.Redirect(rw, r, rj, http.StatusMovedPermanently)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleJSONWebToken() http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
vars, _ := mux.Vars(r)["id"]
|
||||
jwtID, err := strconv.ParseInt(vars, 10, 64)
|
||||
if err != nil {
|
||||
log.Printf("erreur a la récupération id jwt (err=%v)", err)
|
||||
}
|
||||
|
||||
rw.Header().Set("Content-Type", "text/html")
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
|
||||
t, err := template.New("test").Parse(templateoauth.TemplateIndex)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
|
||||
oauth, err := s.Store.GetOauth(jwtID)
|
||||
if err != nil {
|
||||
log.Printf("erreur a la récupération oauth (err=%v)", err)
|
||||
}
|
||||
tokenVal := oauth.AccessToken
|
||||
|
||||
tableau := strings.Split(tokenVal, ".")
|
||||
header, err := jwt.DecodeSegment(tableau[0])
|
||||
if err != nil {
|
||||
fmt.Printf("Impossible de décoder le header. (err=%v)", err)
|
||||
}
|
||||
payload, err := jwt.DecodeSegment(tableau[1])
|
||||
if err != nil {
|
||||
fmt.Printf("Impossible de décoder le payload. (err=%v)", err)
|
||||
}
|
||||
|
||||
//t := template.New("mon template")
|
||||
t, err = template.New("Resultat").Parse(templateoauth.Resultat)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
|
||||
f := File{
|
||||
JwtID: jwtID,
|
||||
JwtProduce: tokenVal,
|
||||
Header: string(header),
|
||||
Payload: string(payload),
|
||||
Sign: tableau[2],
|
||||
}
|
||||
|
||||
err = t.Execute(rw, f)
|
||||
if err != nil {
|
||||
fmt.Printf("erreur suivante %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func constJSONToken(code, state string, param *model.Param) JSONToken {
|
||||
return JSONToken{
|
||||
ClientID: param.ClientID,
|
||||
ClientSecret: param.ClientSecret,
|
||||
GrantType: param.GrantType,
|
||||
RedirectURI: "http://localhost:8090/oauth/redirect%3Fstate=" + state,
|
||||
Code: code,
|
||||
}
|
||||
}
|
||||
26
routeserv/routes.refresh.go
Normal file
26
routeserv/routes.refresh.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package routeserv
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func (s *Server) handleRefreshToken() http.HandlerFunc {
|
||||
return func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
vars, _ := mux.Vars(r)["id"]
|
||||
jwtID, err := strconv.ParseInt(vars, 10, 64)
|
||||
if err != nil {
|
||||
log.Printf("erreur a la récupération id jwt (err=%v)", err)
|
||||
}
|
||||
|
||||
fmt.Printf("le jwtID : %v", jwtID)
|
||||
|
||||
// Puis redisrect vers page resultat
|
||||
//s.response(rw, r, resp, http.StatusOK)
|
||||
}
|
||||
}
|
||||
57
routeserv/server.go
Normal file
57
routeserv/server.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package routeserv
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/ldrogou/goauth20/middleware"
|
||||
"github.com/ldrogou/goauth20/store"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
Router *mux.Router
|
||||
Store store.Store
|
||||
}
|
||||
|
||||
//File structure du fichier
|
||||
type File struct {
|
||||
JwtID int64
|
||||
JwtProduce string
|
||||
Header string
|
||||
Payload string
|
||||
Sign string
|
||||
}
|
||||
|
||||
func NewServer() *Server {
|
||||
s := &Server{
|
||||
Router: mux.NewRouter(),
|
||||
}
|
||||
s.routes()
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
|
||||
middleware.LogRequestMiddleware(s.Router.ServeHTTP).ServeHTTP(rw, r)
|
||||
}
|
||||
|
||||
func (s *Server) response(rw http.ResponseWriter, _ *http.Request, data interface{}, status int) {
|
||||
rw.Header().Add("Content-type", "application/json")
|
||||
rw.WriteHeader(status)
|
||||
|
||||
if data == nil {
|
||||
return
|
||||
}
|
||||
|
||||
err := json.NewEncoder(rw).Encode(data)
|
||||
if err != nil {
|
||||
log.Printf("Cannot encode to json (err=%v)\n", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) decode(rw http.ResponseWriter, r *http.Request, v interface{}) error {
|
||||
return json.NewDecoder(r.Body).Decode(v)
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user