diff --git a/auth_utility.go b/auth_utility.go index 93a7fdb..d4abaaf 100644 --- a/auth_utility.go +++ b/auth_utility.go @@ -15,12 +15,13 @@ import ( const OneDay = time.Hour * 24 const OneWeek = OneDay * 7 const saltSize = 32 -const appName = "korisnicki-centar" -const secret = "korisnicki-centar-api" + +var appName = "webutility" +var secret = "webutility" type Role struct { Name string `json:"name"` - ID int `json:"id"` + ID int32 `json:"id"` } // TokenClaims are JWT token claims. @@ -29,20 +30,26 @@ type TokenClaims struct { TokenType string `json:"token_type"` Username string `json:"username"` Role string `json:"role"` - RoleID int `json:"role_id"` + RoleID int32 `json:"role_id"` ExpiresIn int64 `json:"expires_in"` // extending a struct jwt.StandardClaims } +func InitJWT(appName, secret string) { + appName = appName + secret = secret +} + // ValidateCredentials hashes pass and salt and returns comparison result with resultHash -func ValidateCredentials(pass, salt, resultHash string) bool { +func ValidateCredentials(pass, salt, resultHash string) (bool, error) { hash, _, err := CreateHash(pass, salt) if err != nil { - return false + return false, err } - return hash == resultHash + res := hash == resultHash + return res, nil } // CreateHash hashes str using SHA256. diff --git a/http_utility.go b/http_utility.go index 16d7711..8ca7e55 100644 --- a/http_utility.go +++ b/http_utility.go @@ -16,10 +16,7 @@ func NotFoundHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "OPTIONS" { return } - ErrorResponse(w, req, http.StatusNotFound, []HttpErrorDesc{ - {"en", "Not found."}, - {"rs", "Traženi resurs ne postoji."}, - }) + NotFound(w, req, "Not found") } // SetDefaultHeaders set's default headers for an HTTP response. diff --git a/json_utility.go b/json_utility.go index bf150d9..71d848c 100644 --- a/json_utility.go +++ b/json_utility.go @@ -3,6 +3,7 @@ package webutility import ( "database/sql" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -21,6 +22,7 @@ var ( activeProject string inited bool + driver string ) var logger *gologger.Logger @@ -79,8 +81,12 @@ func DecodeJSON(r io.Reader, v interface{}) error { return json.NewDecoder(r).Decode(v) } -// LoadPayloadsdetaData loads all payloads' information into 'metadata' variable. -func LoadPayloadsMetadata(db *sql.DB, project string) error { +// InitPayloadsMetadata loads all payloads' information into 'metadata' variable. +func InitPayloadsMetadata(drv string, db *sql.DB, project string) error { + if drv != "ora" && drv != "mysql" { + return errors.New("driver not supported") + } + driver = drv metadataDB = db activeProject = project @@ -138,7 +144,7 @@ func initMetadata(project string) error { p := Payload{} err := json.Unmarshal([]byte(load), &p) if err != nil { - logger.Log("couldn't init: '%s' metadata: %s\n%s\n", name, err.Error(), load) + logger.Log("webutility: couldn't init: '%s' metadata: %s\n%s\n", name, err.Error(), load) } else { success++ metadata[name] = p @@ -146,7 +152,7 @@ func initMetadata(project string) error { count++ } perc := float32(success/count) * 100.0 - logger.Log("loaded %d/%d (%.1f%%) entities\n", success, count, perc) + logger.Log("webutility: loaded %d/%d (%.1f%%) entities\n", success, count, perc) return nil } @@ -161,7 +167,7 @@ func hotload(n int) { entity_type from entities where projekat = ` + fmt.Sprintf("'%s'", activeProject)) if err != nil { - logger.Log("hotload failed: %v\n", err) + logger.Log("webutility: hotload failed: %v\n", err) time.Sleep(time.Duration(n) * time.Second) continue } @@ -180,7 +186,7 @@ func hotload(n int) { rows.Close() if rows.Err() != nil { - logger.Log("hotload rset error: %v\n", rows.Err()) + logger.Log("webutility: hotload rset error: %v\n", rows.Err()) time.Sleep(time.Duration(n) * time.Second) continue } @@ -217,7 +223,7 @@ func refreshMetadata(entities []string) { p := Payload{} err := json.Unmarshal([]byte(load), &p) if err != nil { - logger.Log("couldn't refresh: '%s' metadata: %s\n%s\n", e, err.Error(), load) + logger.Log("webutility: couldn't refresh: '%s' metadata: %s\n%s\n", e, err.Error(), load) } else { metadata[e] = p } @@ -226,14 +232,13 @@ func refreshMetadata(entities []string) { } } -/* func UpdateEntityModels(command string) (total, upd, add int, err error) { if command != "force" && command != "missing" { - return total, 0, 0, errors.New("uknown command: " + command) + return total, 0, 0, errors.New("webutility: unknown command: " + command) } if !inited { - return 0, 0, 0, errors.New("webutil: metadata not initialized but update was tried.") + return 0, 0, 0, errors.New("webutility: metadata not initialized but update was tried.") } total = len(updateQue) @@ -251,44 +256,54 @@ func UpdateEntityModels(command string) (total, upd, add int, err error) { } } + var uStmt *sql.Stmt + if driver == "ora" { + uStmt, err = metadataDB.Prepare("update entities set entity_model = :1 where entity_type = :2") + if err != nil { + return + } + } else if driver == "mysql" { + uStmt, err = metadataDB.Prepare("update entities set entity_model = ? where entity_type = ?") + if err != nil { + return + } + } for _, k := range forUpdate { - _, err := metadataDB.PrepAndExe(`update entities set - entity_model = :1 - where entity_type = :2`, - string(updateQue[k]), - k) - + _, err = uStmt.Exec(string(updateQue[k]), k) if err != nil { - logger.Log("webutility: update metadata: prep and exe: %v\n", err) - continue + logger.Log("webutility: %v\n", err) + return } upd++ - logger.Log("webutility: updated %s payload model\n", k) } blankPayload, _ := json.Marshal(Payload{}) + var iStmt *sql.Stmt + if driver == "ora" { + iStmt, err = metadataDB.Prepare("INSERT INTO ENTITIES(PROJEKAT, METADATA, ENTITY_TYPE, ENTITY_MODEL) VALUES(:1, :2, :3, :4)") + if err != nil { + return + } + } else if driver == "mysql" { + iStmt, err = metadataDB.Prepare("INSERT INTO ENTITIES(PROJEKAT, METADATA, ENTITY_TYPE, ENTITY_MODEL) VALUES(?, ?, ?, ?)") + if err != nil { + return + } + } for _, k := range forAdd { - _, err := metadataDB.PrepAndExe(`insert into entities - (projekat, metadata, entity_type, entity_model) - values(:1, :2, :3, :4)`, - activeProject, - string(blankPayload), - k, - string(updateQue[k])) - + _, err = iStmt.Exec(activeProject, string(blankPayload), k, string(updateQue[k])) if err != nil { - logger.Log("webutility: add metadata: prep and exe: %v\n", err) - continue + logger.Log("webutility: %v\n", err) + return } metadata[k] = Payload{} add++ - logger.Log("webutility: added %s to the payload models\n", k) - } return total, upd, add, nil } +/* func ModifyMetadataForEntity(entityType string, p *Payload) error { md, err := json.Marshal(*p) if err != nil { diff --git a/locale_utility.go b/locale_utility.go index b08d530..2c0b64e 100644 --- a/locale_utility.go +++ b/locale_utility.go @@ -5,9 +5,17 @@ import ( "io/ioutil" ) -var locales = map[string]map[string]string{} +type Dictionary struct { + locales map[string]map[string]string +} + +func NewDictionary() Dictionary { + return Dictionary{ + locales: map[string]map[string]string{}, + } +} -func LoadLocale(loc, filePath string) error { +func (d *Dictionary) AddLocale(loc, filePath string) error { file, err := ioutil.ReadFile(filePath) if err != nil { return err @@ -23,11 +31,20 @@ func LoadLocale(loc, filePath string) error { for k, v := range data.(map[string]interface{}) { l[k] = v.(string) } - locales[loc] = l + d.locales[loc] = l return nil } -func Translate(loc, key string) string { - return locales[loc][key] +func (d *Dictionary) Translate(loc, key string) string { + return d.locales[loc][key] +} + +func (d *Dictionary) SupportsLocale(loc string) bool { + for k, _ := range d.locales { + if k == loc { + return true + } + } + return false }