sum7/warehost
sum7
/
warehost
Archived
1
0
Fork 0

sourcecode comments

This commit is contained in:
Martin Geno 2016-09-03 10:18:46 +02:00
parent 3a3af67885
commit cd8a5fbf89
10 changed files with 48 additions and 28 deletions

4
.gitignore vendored
View File

@ -1,5 +1,5 @@
!/webroot
!/web_webroot
/webroot
/web_webroot
cmd/warehost/warehost
cmd/warehost-web/warehost-web
test.log

View File

@ -90,7 +90,7 @@ func main() {
router.NotFound = gziphandler.GzipHandler(http.FileServer(http.Dir(config.Webroot)))
}
// Manage CORS (JsonOutput allow requested -> lib/api)
// Manage CORS (JSONOutput allow requested -> lib/api)
c := cors.New(cors.Options{
AllowedOrigins: []string{config.API.AllowedOrigins},
AllowCredentials: true,

View File

@ -8,13 +8,17 @@ import (
"github.com/julienschmidt/httprouter"
)
// Handle for session
type Handle func(w http.ResponseWriter, r *http.Request, ps httprouter.Params, sess session.Session) (interface{}, *ErrorResult)
// ErrorResult struct for api error answer
type ErrorResult struct {
Fields []string `json:"fields"`
Message string `json:"msg"`
}
type JsonResult struct {
// JSONResult struct for api answer
type JSONResult struct {
Data interface{} `json:"data"`
Error *ErrorResult `json:"error,omitempty"`
Session struct {
@ -23,8 +27,9 @@ type JsonResult struct {
} `json:"session,omitempty"`
}
func JsonOutput(w http.ResponseWriter, r *http.Request, sess session.Session, data interface{}, errorresult *ErrorResult) {
result := JsonResult{Data: data, Error: errorresult}
// JSONOutput generate default json answer
func JSONOutput(w http.ResponseWriter, r *http.Request, sess session.Session, data interface{}, errorresult *ErrorResult) {
result := JSONResult{Data: data, Error: errorresult}
result.Session.Login = sess.Get("login")
js, err := json.Marshal(result)
if err != nil {
@ -42,10 +47,11 @@ func JsonOutput(w http.ResponseWriter, r *http.Request, sess session.Session, da
w.Write(js)
}
// SessionHandler Handler to manage session of api request
func SessionHandler(h Handle, sessions *session.Manager) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
sess := sessions.SessionStart(w, r)
data, err := h(w, r, ps, sess)
JsonOutput(w, r, sess, data, err)
JSONOutput(w, r, sess, data, err)
}
}

View File

@ -7,17 +7,22 @@ import (
"github.com/rifflock/lfshook"
)
// Log current logger
var Log *log.Logger
// ModulLog with current Log
type ModulLog struct {
log *log.Entry
}
// NewSilenceLogger initial logger withou output
func NewSilenceLogger(path string) *log.Logger {
Log = NewLogger(path)
//Log.Out = nil
return Log
}
// NewLogger initial logger
func NewLogger(path string) *log.Logger {
if Log != nil {
return Log
@ -31,6 +36,7 @@ func NewLogger(path string) *log.Logger {
return Log
}
// NewModulLog with modul field
func NewModulLog(modul string) *ModulLog {
return &ModulLog{
log: Log.WithFields(log.Fields{
@ -39,6 +45,7 @@ func NewModulLog(modul string) *ModulLog {
}
}
// GetLog with api request ip in log
func (m *ModulLog) GetLog(r *http.Request, request string) *log.Entry {
ip := r.Header.Get("X-Real-IP")
if len(ip) <= 1 {

View File

@ -1,15 +1,15 @@
package libPassword
package password
import "fmt"
func main() {
password_str := "root"
x, err := Validate("pbkdf2_sha1$10000$a5viM+Paz3o=$orD4shu1Ss+1wPAhAt8hkZ/fH7Y=", password_str)
password := "root"
x, err := Validate("pbkdf2_sha1$10000$a5viM+Paz3o=$orD4shu1Ss+1wPAhAt8hkZ/fH7Y=", password)
if x {
fmt.Println("Valide")
if err {
fmt.Print("Deprecated,replace with: ")
fmt.Println(NewHash(password_str))
fmt.Println(NewHash(password))
}
}
}

View File

@ -1,4 +1,4 @@
package libPassword
package password
import "golang.org/x/crypto/pbkdf2"
import "hash"
@ -12,8 +12,8 @@ import "fmt"
import "strings"
const (
salt_length = 8
hash_length = 20
saltLength = 8
hashLength = 20
interations = 10000
hashfunc string = "sha256"
)
@ -24,23 +24,26 @@ var hashlib = map[string]func() hash.Hash{
"sha512": sha512.New,
}
// Validate a password and a hash
func Validate(hash, password string) (output, replace bool) {
parts := strings.Split(hash, "$")
if len(parts) == 3 {
return false, false
}
cur_iter, err := strconv.Atoi(parts[1])
curIter, err := strconv.Atoi(parts[1])
if err != nil {
return false, false
}
hashfunc_c := strings.Split(parts[0], "_")[1]
replace = (hashfunc_c != hashfunc)
hashfuncC := strings.Split(parts[0], "_")[1]
replace = (hashfuncC != hashfunc)
dk := pbkdf2.Key([]byte(password), []byte(parts[2]), cur_iter, len(parts[3])-8, hashlib[hashfunc_c])
x := fmt.Sprintf("pbkdf2_%s$%s$%s$%s", hashfunc_c, parts[1], parts[2], base64.StdEncoding.EncodeToString(dk))
dk := pbkdf2.Key([]byte(password), []byte(parts[2]), curIter, len(parts[3])-8, hashlib[hashfuncC])
x := fmt.Sprintf("pbkdf2_%s$%s$%s$%s", hashfuncC, parts[1], parts[2], base64.StdEncoding.EncodeToString(dk))
output = (x == hash)
return
}
// GenerateRandomString by length for key
func GenerateRandomString(n int) (string, error) {
b := make([]byte, n)
_, err := rand.Read(b)
@ -49,8 +52,10 @@ func GenerateRandomString(n int) (string, error) {
}
return base64.URLEncoding.EncodeToString(b), nil
}
// NewHash of given password
func NewHash(password string) string {
salt, _ := GenerateRandomString(salt_length)
dk := pbkdf2.Key([]byte(password), []byte(salt), interations, hash_length, hashlib[hashfunc])
salt, _ := GenerateRandomString(saltLength)
dk := pbkdf2.Key([]byte(password), []byte(salt), interations, hashLength, hashlib[hashfunc])
return fmt.Sprintf("pbkdf2_%s$%d$%s$%s", hashfunc, interations, salt, base64.StdEncoding.EncodeToString(dk))
}

View File

@ -47,7 +47,7 @@ func (api *API) Involve(w http.ResponseWriter, r *http.Request, _ httprouter.Par
return
}
// Add Website
// WebsiteAdd to add a new website
func (api *API) WebsiteAdd(w http.ResponseWriter, r *http.Request, _ httprouter.Params, sess session.Session, login *libsystem.Login) (returndata interface{}, returnerr *libapi.ErrorResult) {
returndata = false
logger := api.log.GetLog(r, "websiteadd")

View File

@ -298,7 +298,7 @@ func (api *API) Invitor(w http.ResponseWriter, r *http.Request, ps httprouter.Pa
return
}
// InvitorAdmin toggle admin of current login
// InvitorAdminToggle toggle admin of current login
func (api *API) InvitorAdminToggle(w http.ResponseWriter, r *http.Request, ps httprouter.Params, sess session.Session, login *Login) (returndata interface{}, returnerr *libapi.ErrorResult) {
returndata = false
logger := api.log.GetLog(r, "invitoradmintoggle")

View File

@ -9,6 +9,7 @@ import (
libapi "dev.sum7.de/sum7/warehost/lib/api"
)
// Handle to handle request with session and current logged in user
type Handle func(w http.ResponseWriter, r *http.Request, ps httprouter.Params, sess session.Session, login *Login) (interface{}, *libapi.ErrorResult)
//LoginHandler for api function to Verifie User ist loggedin
@ -24,6 +25,6 @@ func LoginHandler(h Handle, sessions *session.Manager) httprouter.Handle {
data, err = h(w, r, ps, sess, &loginObj)
}
}
libapi.JsonOutput(w, r, sess, data, err)
libapi.JSONOutput(w, r, sess, data, err)
}
}

View File

@ -37,23 +37,24 @@ type Login struct {
ID uint
Username string `gorm:"type:varchar(255);unique;column:mail" json:"username"`
Password string `gorm:"type:varchar(255);column:password" json:"-"`
Active bool `gorm:"default:'false';column:active" json:"active"`
Active bool `gorm:"default:false;column:active" json:"active"`
Code string `gorm:"type:varchar(255);column:code" json:"-"`
Superadmin bool `gorm:"default:'false';column:superadmin" json:"superadmin"`
Superadmin bool `gorm:"default:false;column:superadmin" json:"superadmin"`
CreateAt time.Time `sql:"default:current_timestamp" gorm:"column:createat" json:"createat"`
LastLoginAt time.Time `gorm:"column:lastloginat" json:"lastloginat"`
Invites []Invite `gorm:"foreignkey:Login" json:"invites"`
}
// Login found
// Invite struct
type Invite struct {
LoginID uint `sql:"type:bigint REFERENCES login(id) ON UPDATE CASCADE ON DELETE CASCADE;column:login;primary_key"`
Login Login `gorm:"column:login" json:"login"`
InvitedID uint `sql:"type:bigint REFERENCES login(id) ON UPDATE CASCADE ON DELETE CASCADE;column:invited;primary_key"`
Invited Login `gorm:"column:invited" json:"invited"`
Admin bool `sql:"default:'false'" json:"admin"`
Admin bool `sql:"default:false" json:"admin"`
}
// GetInvitedby of current login -> Invitor
func (l *Login) GetInvitedby(dbconnection *gorm.DB) (invited Invite) {
invited = Invite{InvitedID: l.ID}
dbconnection.Where("invited = ?", invited.InvitedID).First(&invited)