sum7/warehost
sum7
/
warehost
Archived
1
0
Fork 0

system login,logout

This commit is contained in:
Martin Geno 2016-08-14 13:33:53 +02:00
parent 9017881f05
commit 7fc74044d7
6 changed files with 41 additions and 74 deletions

2
.gitignore vendored
View File

@ -1,2 +1,2 @@
webroot
/webroot
config.yml

View File

@ -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

View File

@ -12,9 +12,11 @@ type Config struct {
API struct {
Address string `yaml:"address"`
Port string `yaml:"port"`
AllowedOrigins string `yaml:"allowedorigins"`
} `yaml:"api"`
Webroot string `yaml:"webroot"`
Database string `yaml:"database"`
DatabaseDebug bool `yaml:"databasedebug"`
Modules []struct {
Name string `yaml:"name"`
Database string `yaml:"database"`

View File

@ -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)
}
}

17
main.go
View File

@ -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))
}

View File

@ -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,13 +57,18 @@ 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 {
log.Println("[system]-login error fetch database")
libapi.JsonOutput(api.sessions, w, r, false)
return
}
result := false
if login.Active {
output, _ := libpassword.Validate(login.Password, requestlogin.Password)
@ -72,26 +77,6 @@ func (api *API) Login(w http.ResponseWriter, r *http.Request, _ httprouter.Param
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)
}
}
// 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
}
log.Println("[system]-login worked", result)
libapi.JsonOutput(api.sessions, w, r, result)
}