chore: archi package du projet

This commit is contained in:
Laurent Drogou
2021-04-13 14:09:58 +02:00
parent 7544643cfb
commit 8cdf1ca15f
9 changed files with 126 additions and 97 deletions

11
main.go
View File

@@ -6,6 +6,7 @@ import (
"net/http"
"os"
"github.com/ldrogou/goauth20/routeserv"
"github.com/ldrogou/goauth20/store"
)
@@ -19,16 +20,16 @@ func main() {
}
func run() error {
srv := newServer()
srv.store = &store.DbStore{}
srv := routeserv.NewServer()
srv.Store = &store.DbStore{}
err := srv.store.Open()
err := srv.Store.Open()
if err != nil {
return err
}
defer srv.store.Close()
defer srv.Store.Close()
http.HandleFunc("/", srv.serveHTTP)
http.HandleFunc("/", srv.ServeHTTP)
port := 8090
log.Printf("servering http port %v", port)

View File

@@ -1,11 +1,11 @@
package main
package middleware
import (
"log"
"net/http"
)
func logRequestMiddleware(next http.HandlerFunc) http.HandlerFunc {
func LogRequestMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
log.Printf("[%v] %v", r.Method, r.RequestURI)

View File

@@ -1,11 +0,0 @@
package main
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")
}

View File

@@ -1,6 +1,7 @@
package main
package routeserv
import (
"bytes"
"fmt"
"html/template"
"log"
@@ -18,14 +19,14 @@ import (
//Claim claims to export
type Claims struct {
Sub string `json:"sub"`
IDEntreprise string `json:"idEntreprise"`
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 {
func (s *Server) handleIndex() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "text/html")
@@ -43,7 +44,7 @@ func (s *server) handleIndex() http.HandlerFunc {
}
}
func (s *server) handleLocal() http.HandlerFunc {
func (s *Server) handleLocal() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
sub := r.FormValue("sub")
@@ -63,16 +64,18 @@ func (s *server) handleLocal() http.HandlerFunc {
expirationTime := time.Now().Add(5 * time.Hour)
// Create the JWT claims, which includes the username and expiry time
claims := &Claims{
Sub: sub,
IDEntreprise: idEntreprise,
RcaPartnerID: rcaPartnerID,
Roles: rs,
Scopes: sc,
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
@@ -95,7 +98,7 @@ func (s *server) handleLocal() http.HandlerFunc {
ExpiresIN: -1,
RefreshToken: "refresh",
}
err = s.store.CreateOauth(o)
err = s.Store.CreateOauth(o)
if err != nil {
fmt.Printf("erreur suivante %v", err)
}
@@ -109,19 +112,14 @@ func (s *server) handleLocal() http.HandlerFunc {
}
func (s *server) handleOAuth20() http.HandlerFunc {
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("scopes")
sc := r.FormValue("clientScopes")
cc := r.FormValue("currentCompany")
if len(cc) == 0 {
cc = "false"
} else {
cc = "true"
}
// Création du nombre aléatoire pour la state
nr := rand.NewSource(time.Now().UnixNano())
@@ -138,7 +136,7 @@ func (s *server) handleOAuth20() http.HandlerFunc {
GrantType: "authorization_code",
}
err := s.store.CreateParam(p)
err := s.Store.CreateParam(p)
if err != nil {
fmt.Printf("erreur suivante %v", err)
}
@@ -146,13 +144,28 @@ func (s *server) handleOAuth20() http.HandlerFunc {
// 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 +
"&scope=" + sc +
"&current_company=" + cc +
"&redirect_uri=http://localhost:8090/oauth/redirect%3Fstate=" + st +
"&abort_uri=http://localhost:8090/index"
http.Redirect(rw, r, rhttp, http.StatusMovedPermanently)
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
View 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")
}

View File

@@ -1,4 +1,4 @@
package main
package routeserv
import (
"bytes"
@@ -17,6 +17,7 @@ import (
templateoauth "github.com/ldrogou/goauth20/templateOAuth"
)
//"YNVZF88dD4vny59k")
//JSONToken json token
type JSONToken struct {
ClientID string `json:"client_id"`
@@ -26,14 +27,14 @@ type JSONToken struct {
Code string `json:"code"`
}
func (s *server) handleRedirect() http.HandlerFunc {
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)
p, err := s.Store.GetParam(st)
if err != nil {
fmt.Printf("erreur à la recupération des param (err=%v)", err)
}
@@ -44,7 +45,6 @@ func (s *server) handleRedirect() http.HandlerFunc {
log.Printf("data %v", data)
data.Set("client_id", jsonStr.ClientID)
data.Set("client_secret", jsonStr.ClientSecret)
//"YNVZF88dD4vny59k")
data.Set("grant_type", jsonStr.GrantType)
data.Set("redirect_uri", jsonStr.RedirectURI)
data.Set("code", jsonStr.Code)
@@ -87,7 +87,7 @@ func (s *server) handleRedirect() http.HandlerFunc {
ExpiresIN: t["expires_in"].(float64),
RefreshToken: t["refresh_token"].(string),
}
err = s.store.CreateOauth(o)
err = s.Store.CreateOauth(o)
if err != nil {
fmt.Printf("erreur suivante %v", err)
}
@@ -99,7 +99,7 @@ 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) {
vars, _ := mux.Vars(r)["id"]
@@ -116,7 +116,7 @@ func (s *server) handleJSONWebToken() http.HandlerFunc {
fmt.Printf("erreur suivante %v", err)
}
oauth, err := s.store.GetOauth(jwtID)
oauth, err := s.Store.GetOauth(jwtID)
if err != nil {
log.Printf("erreur a la récupération oauth (err=%v)", err)
}

View File

@@ -1,4 +1,4 @@
package main
package routeserv
import (
"fmt"
@@ -9,7 +9,7 @@ import (
"github.com/gorilla/mux"
)
func (s *server) handleRefreshToken() http.HandlerFunc {
func (s *Server) handleRefreshToken() http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
vars, _ := mux.Vars(r)["id"]

View File

@@ -1,4 +1,4 @@
package main
package routeserv
import (
"encoding/json"
@@ -6,12 +6,13 @@ import (
"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
type Server struct {
Router *mux.Router
Store store.Store
}
//File structure du fichier
@@ -23,19 +24,19 @@ type File struct {
Sign string
}
func newServer() *server {
s := &server{
router: mux.NewRouter(),
func NewServer() *Server {
s := &Server{
Router: mux.NewRouter(),
}
s.routes()
return s
}
func (s *server) serveHTTP(rw http.ResponseWriter, r *http.Request) {
logRequestMiddleware(s.router.ServeHTTP).ServeHTTP(rw, r)
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) {
func (s *Server) response(rw http.ResponseWriter, _ *http.Request, data interface{}, status int) {
rw.Header().Add("Content-type", "application/json")
rw.WriteHeader(status)
@@ -50,7 +51,7 @@ func (s *server) response(rw http.ResponseWriter, _ *http.Request, data interfac
}
func (s *server) decode(rw http.ResponseWriter, r *http.Request, v interface{}) error {
func (s *Server) decode(rw http.ResponseWriter, r *http.Request, v interface{}) error {
return json.NewDecoder(r.Body).Decode(v)
}

View File

@@ -26,9 +26,13 @@ var TemplateIndex = `<!DOCTYPE html>
</head>
<body>
<div>
<h1 class="center-align">JWT</h1>
</div>
<div class="container">
<div class="row">
<div>
<h1 class="center-align">JWT</h1>
</div>
</div>
</div>
<div class="container">
<div class="row">
<form class="col s6 light-blue lighten-5" id="formLocal" method="post" action="/local">
@@ -39,27 +43,6 @@ var TemplateIndex = `<!DOCTYPE html>
<label for="name">Subject :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_balance</i>
<input type="text" id="id_entreprise" name="id_entreprise" value="1">
<label for="name">Id entreprise :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">fiber_pin</i>
<input type="text" id="scopes" name="scopes" value="purchase">
<label for="name">Scopes :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">fiber_pin</i>
<input type="text" id="roles" name="roles" value="RCA_CLOUD_EXPERT_COMPTABLE E_COLLECTE_BO_CREA E_CREATION_CREA E_QUESTIONNAIRE_CREA">
<label for="name">Roles :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_balance</i>
@@ -73,6 +56,27 @@ var TemplateIndex = `<!DOCTYPE html>
<input type="text" id="secret" name="secret" value="XXXXXXX">
<label for="name">Secret :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">fiber_pin</i>
<input type="text" id="scopes" name="scopes" value="purchase">
<label for="name">Scopes :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_balance</i>
<input type="text" id="id_entreprise" name="id_entreprise" value="1">
<label for="name">Id entreprise : (0 absent du token)</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">fiber_pin</i>
<input type="text" id="roles" name="roles" value="RCA_CLOUD_EXPERT_COMPTABLE E_COLLECTE_BO_CREA E_CREATION_CREA E_QUESTIONNAIRE_CREA">
<label for="name">Roles :</label>
</div>
</div>
<div class="row">
<a class="waves-effect waves-light btn" onclick="generateToken('formLocal');"><i
@@ -97,29 +101,31 @@ var TemplateIndex = `<!DOCTYPE html>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_balance</i>
<i class="material-icons prefix">fiber_pin</i>
<input type="text" id="clientSecret" name="clientSecret" value="xxxxxxxx">
<label for="name">Client Secret :</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_balance</i>
<input type="text" id="scopes" name="scopes" value="user">
<label for="name">Scopes</label>
<i class="material-icons prefix">fiber_pin</i>
<input type="text" id="clientScopes" name="clientScopes" value="user">
<label for="name">clientScopes</label>
</div>
</div>
<div class="row">
<div class="checkbox col s12">
<label>
<input type="checkbox" id="currentCompany" name="currentCompany" checked="checked" />
<span>Company courante</span>
</label>
<div class="input-field center-align col s12">
<select id="currentCompany" name="currentCompany">
<option value="true" selected>entreprise partenaire</option>
<option value="false" >Sans entreprise</option>
<option value="none" >CAS</option>
</select>
<label>Entreprise</label>
</div>
</div>
<div class="row">
<a class="waves-effect waves-light btn" onclick="generateToken('formOAtuh20');"><i
class="material-icons left">cloud</i>OAuth2.0</a>
<a class="waves-effect waves-light btn" onclick="generateToken('formOAtuh20');">
<i class="material-icons left">cloud</i>OAuth2.0</a>
</div>
</form>
</div>
@@ -128,4 +134,12 @@ var TemplateIndex = `<!DOCTYPE html>
</body>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
</script>
</html>`