From 7fc74044d747d6d043f0d14336e61a23cca71fa2 Mon Sep 17 00:00:00 2001 From: Martin Geno Date: Sun, 14 Aug 2016 13:33:53 +0200 Subject: [PATCH] system login,logout --- .gitignore | 2 +- config.yml.example | 4 +++- config/config.go | 12 +++++++----- lib/api/main.go | 37 ------------------------------------- main.go | 17 ++++++++++++++++- system/api.go | 43 ++++++++++++++----------------------------- 6 files changed, 41 insertions(+), 74 deletions(-) diff --git a/.gitignore b/.gitignore index 62e5008..8abdef3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -webroot +/webroot config.yml diff --git a/config.yml.example b/config.yml.example index 00e5821..17825eb 100644 --- a/config.yml.example +++ b/config.yml.example @@ -2,5 +2,7 @@ api: address: ::1 port: 8080 -webroot: ./webroot + allowedorigins: "*" +webroot: ./webroot/build database: "host=localhost user=warehost dbname=warehost password=hallo sslmode=disable" +databasedebug: false diff --git a/config/config.go b/config/config.go index bcbdca2..44e9bd6 100644 --- a/config/config.go +++ b/config/config.go @@ -10,12 +10,14 @@ import ( // Config is the struct of the api type Config struct { API struct { - Address string `yaml:"address"` - Port string `yaml:"port"` + Address string `yaml:"address"` + Port string `yaml:"port"` + AllowedOrigins string `yaml:"allowedorigins"` } `yaml:"api"` - Webroot string `yaml:"webroot"` - Database string `yaml:"database"` - Modules []struct { + Webroot string `yaml:"webroot"` + Database string `yaml:"database"` + DatabaseDebug bool `yaml:"databasedebug"` + Modules []struct { Name string `yaml:"name"` Database string `yaml:"database"` } `yaml:"modules"` diff --git a/lib/api/main.go b/lib/api/main.go index f8c8e95..b36ee05 100644 --- a/lib/api/main.go +++ b/lib/api/main.go @@ -1,14 +1,10 @@ package api import ( - "bytes" - "encoding/base64" "encoding/json" "net/http" - "strings" "github.com/astaxie/session" - "github.com/julienschmidt/httprouter" ) type JsonResult struct { @@ -38,36 +34,3 @@ func JsonOutput(sessions *session.Manager, w http.ResponseWriter, r *http.Reques w.Header().Set("Access-Control-Allow-Credentials", "true") w.Write(js) } -func BasicAuth(h httprouter.Handle, pass []byte) httprouter.Handle { - return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { - if origin := r.Header.Get("Origin"); origin != "" { - w.Header().Set("Access-Control-Allow-Origin", origin) - } - w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") - w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization") - w.Header().Set("Access-Control-Allow-Credentials", "true") - - const basicAuthPrefix string = "Basic " - - // Get the Basic Authentication credentials - auth := r.Header.Get("Authorization") - if strings.HasPrefix(auth, basicAuthPrefix) { - // Check credentials - payload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):]) - if err == nil { - pair := bytes.SplitN(payload, []byte(":"), 2) - if len(pair) == 2 && - bytes.Equal(pair[1], pass) { - - // Delegate request to the given handle - h(w, r, ps) - return - } - } - } - - // Request Basic Authentication otherwise - w.Header().Set("WWW-Authenticate", "Basic realm=Restricted") - http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) - } -} diff --git a/main.go b/main.go index f9673ff..dd08f1d 100644 --- a/main.go +++ b/main.go @@ -12,6 +12,7 @@ import ( "github.com/go-xorm/xorm" "github.com/julienschmidt/httprouter" _ "github.com/lib/pq" + "github.com/rs/cors" libconfig "dev.sum7.de/sum7/warehost/config" "dev.sum7.de/sum7/warehost/system" @@ -30,24 +31,38 @@ func main() { flag.Parse() config = libconfig.ReadConfigFile(configFile) + // Session mgmt sessions, _ = session.NewManager("memory", "session", 3600) go sessions.GC() + // Main Databaseconnection dbconnection, err = xorm.NewEngine("postgres", config.Database) if err != nil { log.Fatal("[system] Error database connection: ", err) } defer dbconnection.Close() + dbconnection.ShowSQL(config.DatabaseDebug) + //load system Models to database system.SyncModels(dbconnection) + // API routes router := httprouter.New() system.NewAPI(config, sessions, dbconnection, router, "") + // Fallback filesystem if config.Webroot != "" { router.NotFound = gziphandler.GzipHandler(http.FileServer(http.Dir(config.Webroot))) } + + // Manage CORS (JsonOutput allow requested -> lib/api) + c := cors.New(cors.Options{ + AllowedOrigins: []string{config.API.AllowedOrigins}, + AllowCredentials: true, + }) + handler := c.Handler(router) + // Start server address := net.JoinHostPort(config.API.Address, config.API.Port) log.Println("starting webserver on", address) // TODO bad - log.Fatal(http.ListenAndServe(address, router)) + log.Fatal(http.ListenAndServe(address, handler)) } diff --git a/system/api.go b/system/api.go index 2a1a47d..ec93b69 100644 --- a/system/api.go +++ b/system/api.go @@ -4,7 +4,6 @@ import ( "encoding/json" "log" "net/http" - "strconv" "github.com/astaxie/session" "github.com/go-xorm/xorm" @@ -26,9 +25,10 @@ type API struct { func NewAPI(config *libconfig.Config, sessions *session.Manager, dbconnection *xorm.Engine, router *httprouter.Router, prefix string) { api := &API{config: config, sessions: sessions, dbconnection: dbconnection} router.GET(prefix+"/status", api.Status) - router.GET(prefix+"/login", api.Login) - router.GET(prefix+"/login/:id", api.FakeLogin) router.GET(prefix+"/logout", api.Logout) + + router.POST(prefix+"/login", api.Login) + //router.OPTIONS(prefix+"/login", api.Login) } // Status to get Login and Server status @@ -57,41 +57,26 @@ func (api *API) Login(w http.ResponseWriter, r *http.Request, _ httprouter.Param var requestlogin RequestLogin err := json.NewDecoder(r.Body).Decode(&requestlogin) if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) log.Println("[system]-login error fetch request") + http.Error(w, err.Error(), http.StatusInternalServerError) + libapi.JsonOutput(api.sessions, w, r, false) return } var login = Login{Username: requestlogin.Username} _, err = api.dbconnection.Get(&login) if err != nil { - result := false - if login.Active { - output, _ := libpassword.Validate(login.Password, requestlogin.Password) - if output { - result = true - sess.Set("login", login) - } - } - libapi.JsonOutput(api.sessions, w, r, result) - } else { - http.Error(w, err.Error(), http.StatusInternalServerError) log.Println("[system]-login error fetch database") - libapi.JsonOutput(api.sessions, w, r, true) + libapi.JsonOutput(api.sessions, w, r, false) + return } -} - -// FakeLogin is a API test function -func (api *API) FakeLogin(w http.ResponseWriter, r *http.Request, params httprouter.Params) { - id, _ := strconv.ParseInt(params.ByName("id"), 10, 64) - sess := api.sessions.SessionStart(w, r) - var login = Login{} - _, err := api.dbconnection.Id(id).Get(&login) result := false - if err != nil { - log.Print("[system] Error get login count: ", err) - } else { - sess.Set("login", login) - result = true + if login.Active { + output, _ := libpassword.Validate(login.Password, requestlogin.Password) + if output { + result = true + sess.Set("login", login) + } } + log.Println("[system]-login worked", result) libapi.JsonOutput(api.sessions, w, r, result) }