From 90db15d2ed787e93475c1fcad846455f2b434d45 Mon Sep 17 00:00:00 2001 From: Pierre-Olivier Mercier Date: Sat, 20 May 2023 12:43:32 +0200 Subject: [PATCH] Enable detection and fix go vet issues --- .drone.yml | 14 ++-- api/domains.go | 2 +- api/providers.go | 12 +-- api/user_auth.go | 4 +- api/users.go | 6 +- api/zones.go | 6 +- generators/gen_database_migration.go | 5 +- generators/gen_icon.go | 11 +-- model/session.go | 1 - model/user.go | 2 +- services/analyzer.go | 38 +++++---- storage/leveldb/database.go | 2 +- storage/leveldb/provider.go | 8 +- storage/mysql/config.go | 77 ------------------ storage/mysql/database.go | 116 --------------------------- storage/mysql/domain.go | 112 -------------------------- storage/mysql/schemas.go | 72 ----------------- storage/mysql/schemas/001.sql | 30 ------- storage/mysql/schemas/002.sql | 14 ---- storage/mysql/schemas/003.sql | 12 --- storage/mysql/schemas/004.sql | 4 - storage/mysql/session.go | 71 ---------------- storage/mysql/user.go | 101 ----------------------- 23 files changed, 59 insertions(+), 661 deletions(-) delete mode 100644 storage/mysql/config.go delete mode 100644 storage/mysql/database.go delete mode 100644 storage/mysql/domain.go delete mode 100644 storage/mysql/schemas.go delete mode 100644 storage/mysql/schemas/001.sql delete mode 100644 storage/mysql/schemas/002.sql delete mode 100644 storage/mysql/schemas/003.sql delete mode 100644 storage/mysql/schemas/004.sql delete mode 100644 storage/mysql/session.go delete mode 100644 storage/mysql/user.go diff --git a/.drone.yml b/.drone.yml index 9ae3c5a..1501560 100644 --- a/.drone.yml +++ b/.drone.yml @@ -58,7 +58,7 @@ steps: commands: - apk add --no-cache git - sed -i '/yarn --offline build/d' ui/assets.go - - go generate -v + - go generate -v ./... - go build -v -tags netgo -ldflags '-w -X main.version="${DRONE_BRANCH}-${DRONE_COMMIT}" -X main.build=${DRONE_BUILD_NUMBER}' -o happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} - ln happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} happydomain environment: @@ -73,7 +73,7 @@ steps: commands: - apk add --no-cache git - sed -i '/yarn --offline build/d' ui/assets.go - - go generate -v + - go generate -v ./... - go build -v -tags netgo -ldflags '-w -X main.version=${DRONE_TAG##v} -X main.build=${DRONE_BUILD_NUMBER}' -o happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} - ln happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} happydomain environment: @@ -86,7 +86,7 @@ steps: image: golang:1-alpine commands: - apk --no-cache add build-base git - - go vet -v + - go vet -v ./... environment: CGO_ENABLED: 0 @@ -227,7 +227,7 @@ steps: commands: - apk add --no-cache git - sed -i '/yarn --offline build/d' ui/assets.go - - go generate -v + - go generate -v ./... - go build -v -tags netgo -ldflags '-w -X main.version="${DRONE_BRANCH}-${DRONE_COMMIT}" -X main.build=${DRONE_BUILD_NUMBER}' -o happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} - ln happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} happydomain environment: @@ -242,7 +242,7 @@ steps: commands: - apk add --no-cache git - sed -i '/yarn --offline build/d' ui/assets.go - - go generate -v + - go generate -v ./... - go build -v -tags netgo -ldflags '-w -X main.version=${DRONE_TAG##v} -X main.build=${DRONE_BUILD_NUMBER}' -o happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} - ln happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH} happydomain environment: @@ -388,7 +388,7 @@ steps: commands: - apk --no-cache add build-base git - sed -i '/yarn --offline build/d' ui/assets.go - - go generate -v + - go generate -v ./... - go build -v -tags netgo -ldflags '-w -X main.version="${DRONE_BRANCH}-${DRONE_COMMIT}" -X main.build=${DRONE_BUILD_NUMBER}' -o happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH}el environment: CGO_ENABLED: 0 @@ -406,7 +406,7 @@ steps: commands: - apk --no-cache add build-base git - sed -i '/yarn --offline build/d' ui/assets.go - - go generate -v + - go generate -v ./... - go build -v -tags netgo -ldflags '-w -X main.version="${DRONE_TAG##v}" -X main.build=${DRONE_BUILD_NUMBER}' -o happydomain-${DRONE_STAGE_OS}-${DRONE_STAGE_ARCH}el environment: CGO_ENABLED: 0 diff --git a/api/domains.go b/api/domains.go index 09467f1..d1e6bd7 100644 --- a/api/domains.go +++ b/api/domains.go @@ -181,7 +181,7 @@ func GetDomain(c *gin.Context) { zoneMeta, err := storage.MainStore.GetZoneMeta(zm) if err != nil { - log.Println("%s: An error occurs in getDomain, when retrieving a meta history: %s", c.ClientIP(), err.Error()) + log.Printf("%s: An error occurs in getDomain, when retrieving a meta history: %s", c.ClientIP(), err.Error()) } else { ret.ZoneHistory = append(ret.ZoneHistory, *zoneMeta) } diff --git a/api/providers.go b/api/providers.go index ee5af8a..312608c 100644 --- a/api/providers.go +++ b/api/providers.go @@ -97,8 +97,8 @@ func DecodeProvider(c *gin.Context) (*happydns.ProviderCombined, int, error) { } src := &happydns.ProviderCombined{ - us, - ust, + Provider: us, + ProviderMeta: ust, } err = json.Unmarshal(buf, &src) @@ -188,7 +188,7 @@ func addProvider(c *gin.Context) { s, err := storage.MainStore.CreateProvider(user, src.Provider, src.Comment) if err != nil { - log.Println("%s unable to CreateProvider: %s", c.ClientIP(), err.Error()) + log.Printf("%s unable to CreateProvider: %s", c.ClientIP(), err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are currently unable to create the given provider. Please try again later."}) return } @@ -209,7 +209,7 @@ func UpdateProvider(c *gin.Context) { src.OwnerId = provider.OwnerId if err := storage.MainStore.UpdateProvider(src); err != nil { - log.Println("%s unable to UpdateProvider: %s", c.ClientIP(), err.Error()) + log.Printf("%s unable to UpdateProvider: %s", c.ClientIP(), err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are currently unable to update the provider. Please try again later."}) return } @@ -224,7 +224,7 @@ func deleteProvider(c *gin.Context) { // Check if the provider has no more domain associated domains, err := storage.MainStore.GetDomains(user) if err != nil { - log.Println("%s unable to GetDomains for user id=%x email=%s: %s", c.ClientIP(), user.Id, user.Email, err.Error()) + log.Printf("%s unable to GetDomains for user id=%x email=%s: %s", c.ClientIP(), user.Id, user.Email, err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are currently unable to perform this action. Please try again later."}) return } @@ -237,7 +237,7 @@ func deleteProvider(c *gin.Context) { } if err := storage.MainStore.DeleteProvider(providermeta); err != nil { - log.Println("%s unable to DeleteProvider %x for user id=%x email=%s: %s", c.ClientIP(), providermeta.Id, user.Id, user.Email, err.Error()) + log.Printf("%s unable to DeleteProvider %x for user id=%x email=%s: %s", c.ClientIP(), providermeta.Id, user.Id, user.Email, err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are currently unable to delete your provider. Please try again later."}) return } diff --git a/api/user_auth.go b/api/user_auth.go index 0cd9d73..096b822 100644 --- a/api/user_auth.go +++ b/api/user_auth.go @@ -192,11 +192,11 @@ func completeAuth(opts *config.Options, c *gin.Context, userprofile UserProfile) return nil, fmt.Errorf("unable to read enough random bytes: %w", err) } - iat := jwt.NumericDate{time.Now()} + iat := jwt.NewNumericDate(time.Now()) claims := &UserClaims{ userprofile, jwt.RegisteredClaims{ - IssuedAt: &iat, + IssuedAt: iat, ID: base64.StdEncoding.EncodeToString(jti), }, } diff --git a/api/users.go b/api/users.go index 5ff0548..a75ab51 100644 --- a/api/users.go +++ b/api/users.go @@ -215,7 +215,7 @@ func SameUserHandler(c *gin.Context) { user := c.MustGet("user").(*happydns.User) if !bytes.Equal(user.Id, myuser.Id) { - log.Printf("%s: tries to do action as %s (logged %s)", c.ClientIP(), myuser, user) + log.Printf("%s: tries to do action as %s (logged %s)", c.ClientIP(), myuser.Id, user.Id) c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"errmsg": "Not authorized"}) return } @@ -307,7 +307,7 @@ func changePassword(opts *config.Options, c *gin.Context) { for _, session := range sessions { err = storage.MainStore.DeleteSession(session) if err != nil { - log.Println("%s: unable to delete session (password changed): %s", c.ClientIP(), err.Error()) + log.Printf("%s: unable to delete session (password changed): %s", c.ClientIP(), err.Error()) } } @@ -348,7 +348,7 @@ func deleteUser(opts *config.Options, c *gin.Context) { for _, session := range sessions { err = storage.MainStore.DeleteSession(session) if err != nil { - log.Println("%s: unable to delete session (drop account): %s", c.ClientIP(), err.Error()) + log.Printf("%s: unable to delete session (drop account): %s", c.ClientIP(), err.Error()) } } diff --git a/api/zones.go b/api/zones.go index 7279776..e16dab9 100644 --- a/api/zones.go +++ b/api/zones.go @@ -390,7 +390,7 @@ func applyZone(c *gin.Context) { //newZone.IdAuthor = //TODO get current user id err = storage.MainStore.CreateZone(newZone) if err != nil { - log.Printf("%s was unable to CreateZone", c.ClientIP(), err) + log.Printf("%s was unable to CreateZone: %s", c.ClientIP(), err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are unable to create the zone now."}) return } @@ -400,7 +400,7 @@ func applyZone(c *gin.Context) { err = storage.MainStore.UpdateDomain(domain) if err != nil { - log.Printf("%s was unable to UpdateDomain", c.ClientIP(), err) + log.Printf("%s was unable to UpdateDomain: %s", c.ClientIP(), err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are unable to create the zone now."}) return } @@ -414,7 +414,7 @@ func applyZone(c *gin.Context) { err = storage.MainStore.UpdateZone(zone) if err != nil { - log.Printf("%s was unable to UpdateZone", c.ClientIP(), err) + log.Printf("%s was unable to UpdateZone: %s", c.ClientIP(), err.Error()) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"errmsg": "Sorry, we are unable to create the zone now."}) return } diff --git a/generators/gen_database_migration.go b/generators/gen_database_migration.go index 3af29f3..8d6f82d 100644 --- a/generators/gen_database_migration.go +++ b/generators/gen_database_migration.go @@ -29,10 +29,11 @@ // The fact that you are presently reading this means that you have had // knowledge of the CeCILL license and that you accept its terms. -package main - +//go:build ignore // +build ignore +package main + import ( "io/ioutil" "os" diff --git a/generators/gen_icon.go b/generators/gen_icon.go index 76581e4..4d56cde 100644 --- a/generators/gen_icon.go +++ b/generators/gen_icon.go @@ -29,10 +29,11 @@ // The fact that you are presently reading this means that you have had // knowledge of the CeCILL license and that you accept its terms. -package main - +//go:build ignore // +build ignore +package main + import ( "io/ioutil" "os" @@ -41,7 +42,7 @@ import ( "text/template" ) -const tpl = `// Code generated by go generate. DO NOT EDIT. +const tplIcon = `// Code generated by go generate. DO NOT EDIT. // sources: {{ range $idx, $path := .Sources }}// {{ $path }} {{ end }} @@ -52,7 +53,7 @@ var Icons = map[string][]byte{ {{ end }}} ` -var bundleTpl = template.Must(template.New("").Parse(tpl)) +var bundleTplIcon = template.Must(template.New("").Parse(tplIcon)) type valTpl struct { Directory string @@ -99,5 +100,5 @@ func main() { } defer f.Close() - bundleTpl.Execute(f, d) + bundleTplIcon.Execute(f, d) } diff --git a/model/session.go b/model/session.go index 0e8fc12..d93ffbc 100644 --- a/model/session.go +++ b/model/session.go @@ -89,7 +89,6 @@ func (s *Session) FindNewKey(prefix string) (key string, id int64) { return } } - return } // SetValue defines, erase or delete a content to stores at the given diff --git a/model/user.go b/model/user.go index ef42722..9fabae1 100644 --- a/model/user.go +++ b/model/user.go @@ -50,7 +50,7 @@ type User struct { LastSeen time.Time // Settings holds the settings for an account. - Settings UserSettings `json:settings,omitempty` + Settings UserSettings `json:"settings,omitempty"` } // Users is a group of User. diff --git a/services/analyzer.go b/services/analyzer.go index b24ea33..efa9b8d 100644 --- a/services/analyzer.go +++ b/services/analyzer.go @@ -121,14 +121,17 @@ func (a *Analyzer) UseRR(rr dns.RR, domain string, svc happydns.Service) error { ttl = rr.Header().Ttl } - a.services[domain] = append(a.services[domain], &happydns.ServiceCombined{svc, happydns.ServiceMeta{ - Id: hash.Sum(nil), - Type: reflect.Indirect(reflect.ValueOf(svc)).Type().String(), - Domain: domain, - Ttl: ttl, - Comment: svc.GenComment(a.origin), - NbResources: svc.GetNbResources(), - }}) + a.services[domain] = append(a.services[domain], &happydns.ServiceCombined{ + Service: svc, + ServiceMeta: happydns.ServiceMeta{ + Id: hash.Sum(nil), + Type: reflect.Indirect(reflect.ValueOf(svc)).Type().String(), + Domain: domain, + Ttl: ttl, + Comment: svc.GenComment(a.origin), + NbResources: svc.GetNbResources(), + }, + }) return nil } @@ -188,14 +191,17 @@ func AnalyzeZone(origin string, zone []dns.RR) (svcs map[string][]*happydns.Serv io.WriteString(hash, record.String()) orphan := &Orphan{record.String()[strings.LastIndex(record.Header().String(), "\tIN\t")+4:]} - svcs[domain] = append(svcs[domain], &happydns.ServiceCombined{orphan, happydns.ServiceMeta{ - Id: hash.Sum(nil), - Type: reflect.Indirect(reflect.ValueOf(orphan)).Type().String(), - Domain: domain, - Ttl: record.Header().Ttl, - NbResources: 1, - Comment: orphan.GenComment(a.origin), - }}) + svcs[domain] = append(svcs[domain], &happydns.ServiceCombined{ + Service: orphan, + ServiceMeta: happydns.ServiceMeta{ + Id: hash.Sum(nil), + Type: reflect.Indirect(reflect.ValueOf(orphan)).Type().String(), + Domain: domain, + Ttl: record.Header().Ttl, + NbResources: 1, + Comment: orphan.GenComment(a.origin), + }, + }) } return diff --git a/storage/leveldb/database.go b/storage/leveldb/database.go index 1588efd..49e5536 100644 --- a/storage/leveldb/database.go +++ b/storage/leveldb/database.go @@ -55,7 +55,7 @@ func NewLevelDBStorage(path string) (s *LevelDBStorage, err error) { db, err = leveldb.OpenFile(path, nil) if err != nil { if _, ok := err.(*errors.ErrCorrupted); ok { - log.Println("LevelDB was corrupted; attempting recovery (%s)", err.Error()) + log.Printf("LevelDB was corrupted; attempting recovery (%s)", err.Error()) _, err = leveldb.RecoverFile(path, nil) if err != nil { return diff --git a/storage/leveldb/provider.go b/storage/leveldb/provider.go index 7d41d60..5472ca9 100644 --- a/storage/leveldb/provider.go +++ b/storage/leveldb/provider.go @@ -120,8 +120,8 @@ func (s *LevelDBStorage) GetProvider(u *happydns.User, id happydns.Identifier) ( tsrc, err = providers.FindProvider(srcMeta.Type) src = &happydns.ProviderCombined{ - tsrc, - srcMeta, + Provider: tsrc, + ProviderMeta: srcMeta, } err = decodeData(v, src) @@ -138,8 +138,8 @@ func (s *LevelDBStorage) CreateProvider(u *happydns.User, src happydns.Provider, sType := reflect.Indirect(reflect.ValueOf(src)).Type() st := &happydns.ProviderCombined{ - src, - happydns.ProviderMeta{ + Provider: src, + ProviderMeta: happydns.ProviderMeta{ Type: sType.Name(), Id: id, OwnerId: u.Id, diff --git a/storage/mysql/config.go b/storage/mysql/config.go deleted file mode 100644 index 05a9266..0000000 --- a/storage/mysql/config.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright or © or Copr. happyDNS (2020) -// -// contact@happydomain.org -// -// This software is a computer program whose purpose is to provide a modern -// interface to interact with DNS systems. -// -// This software is governed by the CeCILL license under French law and abiding -// by the rules of distribution of free software. You can use, modify and/or -// redistribute the software under the terms of the CeCILL license as -// circulated by CEA, CNRS and INRIA at the following URL -// "http://www.cecill.info". -// -// As a counterpart to the access to the source code and rights to copy, modify -// and redistribute granted by the license, users are provided only with a -// limited warranty and the software's author, the holder of the economic -// rights, and the successive licensors have only limited liability. -// -// In this respect, the user's attention is drawn to the risks associated with -// loading, using, modifying and/or developing or reproducing the software by -// the user in light of its specific status of free software, that may mean -// that it is complicated to manipulate, and that also therefore means that it -// is reserved for developers and experienced professionals having in-depth -// computer knowledge. Users are therefore encouraged to load and test the -// software's suitability as regards their requirements in conditions enabling -// the security of their systems and/or data to be ensured and, more generally, -// to use and operate it in the same conditions as regards security. -// -// The fact that you are presently reading this means that you have had -// knowledge of the CeCILL license and that you accept its terms. - -package database - -import ( - "flag" - "os" - - "git.happydns.org/happydomain/storage" -) - -var dsn string - -func init() { - storage.StorageEngines["mysql"] = Instantiate - - flag.StringVar(&dsn, "mysql-dsn", DSNGenerator(), "DSN to connect to the MySQL server") -} - -// DSNGenerator returns DSN filed with values from environment -func DSNGenerator() string { - db_user := "happydomain" - db_password := "happydomain" - db_host := "" - db_db := "happydomain" - - if v, exists := os.LookupEnv("MYSQL_HOST"); exists { - db_host = v - } - if v, exists := os.LookupEnv("MYSQL_PASSWORD"); exists { - db_password = v - } else if v, exists := os.LookupEnv("MYSQL_ROOT_PASSWORD"); exists { - db_user = "root" - db_password = v - } - if v, exists := os.LookupEnv("MYSQL_USER"); exists { - db_user = v - } - if v, exists := os.LookupEnv("MYSQL_DATABASE"); exists { - db_db = v - } - - return db_user + ":" + db_password + "@" + db_host + "/" + db_db -} - -func Instantiate() (storage.Storage, error) { - return NewMySQLStorage(dsn) -} diff --git a/storage/mysql/database.go b/storage/mysql/database.go deleted file mode 100644 index 0aec9ec..0000000 --- a/storage/mysql/database.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright or © or Copr. happyDNS (2020) -// -// contact@happydomain.org -// -// This software is a computer program whose purpose is to provide a modern -// interface to interact with DNS systems. -// -// This software is governed by the CeCILL license under French law and abiding -// by the rules of distribution of free software. You can use, modify and/or -// redistribute the software under the terms of the CeCILL license as -// circulated by CEA, CNRS and INRIA at the following URL -// "http://www.cecill.info". -// -// As a counterpart to the access to the source code and rights to copy, modify -// and redistribute granted by the license, users are provided only with a -// limited warranty and the software's author, the holder of the economic -// rights, and the successive licensors have only limited liability. -// -// In this respect, the user's attention is drawn to the risks associated with -// loading, using, modifying and/or developing or reproducing the software by -// the user in light of its specific status of free software, that may mean -// that it is complicated to manipulate, and that also therefore means that it -// is reserved for developers and experienced professionals having in-depth -// computer knowledge. Users are therefore encouraged to load and test the -// software's suitability as regards their requirements in conditions enabling -// the security of their systems and/or data to be ensured and, more generally, -// to use and operate it in the same conditions as regards security. -// -// The fact that you are presently reading this means that you have had -// knowledge of the CeCILL license and that you accept its terms. - -package database // import "happydns.org/database" - -import ( - "database/sql" - "log" - "strings" - "time" - - _ "github.com/go-sql-driver/mysql" -) - -type MySQLStorage struct { - db *sql.DB -} - -// NewMySQLStorage establishes the connection to the database -func NewMySQLStorage(dsn string) (*MySQLStorage, error) { - if db, err := sql.Open("mysql", dsn+"?parseTime=true&foreign_key_checks=1"); err != nil { - return nil, err - } else { - _, err := db.Exec(`SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO';`) - for i := 0; err != nil && i < 45; i += 1 { - if _, err = db.Exec(`SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO';`); err != nil && i <= 45 { - log.Println("An error occurs when trying to connect to DB, will retry in 2 seconds: ", err) - time.Sleep(2 * time.Second) - } - } - - if err != nil { - return nil, err - } - - return &MySQLStorage{db}, nil - } -} - -func (s *MySQLStorage) DoMigration() error { - var currentVersion uint16 - s.db.QueryRow(`SELECT version FROM schema_version`).Scan(¤tVersion) - - log.Println("Current schema version:", currentVersion) - log.Println("Latest schema version:", schemaVersion) - - for version := currentVersion + 1; version <= schemaVersion; version++ { - log.Println("Migrating to version:", version) - - tx, err := s.db.Begin() - if err != nil { - return err - } - - rawSQL := schemaRevisions[version] - for _, request := range strings.Split(rawSQL, ";") { - if len(strings.TrimSpace(request)) == 0 { - continue - } - _, err = tx.Exec(request) - if err != nil { - tx.Rollback() - return err - } - } - - if _, err := tx.Exec(`delete from schema_version`); err != nil { - tx.Rollback() - return err - } - - if _, err := tx.Exec(`INSERT INTO schema_version (version) VALUES (?)`, version); err != nil { - tx.Rollback() - return err - } - - if err := tx.Commit(); err != nil { - tx.Rollback() - return err - } - } - - return nil -} - -func (s *MySQLStorage) Close() error { - return s.db.Close() -} diff --git a/storage/mysql/domain.go b/storage/mysql/domain.go deleted file mode 100644 index 697ad76..0000000 --- a/storage/mysql/domain.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright or © or Copr. happyDNS (2020) -// -// contact@happydomain.org -// -// This software is a computer program whose purpose is to provide a modern -// interface to interact with DNS systems. -// -// This software is governed by the CeCILL license under French law and abiding -// by the rules of distribution of free software. You can use, modify and/or -// redistribute the software under the terms of the CeCILL license as -// circulated by CEA, CNRS and INRIA at the following URL -// "http://www.cecill.info". -// -// As a counterpart to the access to the source code and rights to copy, modify -// and redistribute granted by the license, users are provided only with a -// limited warranty and the software's author, the holder of the economic -// rights, and the successive licensors have only limited liability. -// -// In this respect, the user's attention is drawn to the risks associated with -// loading, using, modifying and/or developing or reproducing the software by -// the user in light of its specific status of free software, that may mean -// that it is complicated to manipulate, and that also therefore means that it -// is reserved for developers and experienced professionals having in-depth -// computer knowledge. Users are therefore encouraged to load and test the -// software's suitability as regards their requirements in conditions enabling -// the security of their systems and/or data to be ensured and, more generally, -// to use and operate it in the same conditions as regards security. -// -// The fact that you are presently reading this means that you have had -// knowledge of the CeCILL license and that you accept its terms. - -package database - -import ( - "git.happydns.org/happydomain/model" -) - -func (s *MySQLStorage) GetDomains(u *happydns.User) (domains happydns.Domains, err error) { - if rows, errr := s.db.Query("SELECT id_domain, id_user, id_source, domain FROM domains WHERE id_user = ?", u.Id); errr != nil { - return nil, errr - } else { - defer rows.Close() - - for rows.Next() { - var z happydns.Domain - if err = rows.Scan(&z.Id, &z.IdUser, &z.IdSource, &z.DomainName); err != nil { - return - } - domains = append(domains, &z) - } - if err = rows.Err(); err != nil { - return - } - - return - } -} - -func (s *MySQLStorage) GetDomain(u *happydns.User, id int64) (z *happydns.Domain, err error) { - z = &happydns.Domain{} - err = s.db.QueryRow("SELECT id_domain, id_user, id_source, domain FROM domains WHERE id_domain=? AND id_user=?", id, u.Id).Scan(&z.Id, &z.IdUser, &z.IdSource, &z.DomainName) - return -} - -func (s *MySQLStorage) GetDomainByDN(u *happydns.User, dn string) (z *happydns.Domain, err error) { - z = &happydns.Domain{} - err = s.db.QueryRow("SELECT id_domain, id_user, id_source, domain FROM domains WHERE domain=? AND id_user=?", dn, u.Id).Scan(&z.Id, &z.IdUser, &z.IdSource, &z.DomainName) - return -} - -func (s *MySQLStorage) DomainExists(dn string) bool { - var z int - err := s.db.QueryRow("SELECT 1 FROM domains WHERE domain=?", dn).Scan(&z) - return err == nil && z == 1 -} - -func (s *MySQLStorage) CreateDomain(u *happydns.User, src happydns.SourceMeta, z *happydns.Domain) error { - if res, err := s.db.Exec("INSERT INTO domains (id_user, id_source, domain) VALUES (?, ?, ?)", u.Id, src.Id, z.DomainName); err != nil { - return err - } else if z.Id, err = res.LastInsertId(); err != nil { - return err - } else { - return nil - } -} - -func (s *MySQLStorage) UpdateDomain(z *happydns.Domain) error { - if _, err := s.db.Exec("UPDATE domains SET id_source = ?, domain = ? WHERE id_domain = ?", z.IdSource, z.DomainName, z.Id); err != nil { - return err - } else { - return nil - } -} - -func (s *MySQLStorage) UpdateDomainOwner(z *happydns.Domain, newOwner *happydns.User) error { - if _, err := s.db.Exec("UPDATE domains SET id_user = ? WHERE id_domain = ?", newOwner.Id, z.Id); err != nil { - return err - } else { - z.IdUser = newOwner.Id - return nil - } -} - -func (s *MySQLStorage) DeleteDomain(z *happydns.Domain) error { - _, err := s.db.Exec("DELETE FROM domains WHERE id_domain = ?", z.Id) - return err -} - -func (s *MySQLStorage) ClearDomains() error { - _, err := s.db.Exec("DELETE FROM domains") - return err -} diff --git a/storage/mysql/schemas.go b/storage/mysql/schemas.go deleted file mode 100644 index bb82902..0000000 --- a/storage/mysql/schemas.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by go generate. DO NOT EDIT. - -package database // import "happydns.org/database" - -const schemaVersion = 4 - -var schemaRevisions = map[uint16]string{ - 1: `CREATE TABLE schema_version ( - version SMALLINT UNSIGNED NOT NULL -); - -CREATE TABLE users ( - id_user INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, - email VARCHAR(255) NOT NULL UNIQUE, - password BINARY(92) NOT NULL, - salt BINARY(64) NOT NULL, - registration_time TIMESTAMP NOT NULL -) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; - -CREATE TABLE user_sessions ( - id_session BLOB(255) NOT NULL, - id_user INTEGER NOT NULL, - time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY(id_user) REFERENCES users(id_user) -); - -CREATE TABLE zones ( - id_zone INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, - id_user INTEGER NOT NULL, - domain VARCHAR(255) NOT NULL, - server VARCHAR(255), - key_name VARCHAR(255) NOT NULL, - key_algo ENUM("hmac-md5.sig-alg.reg.int.", "hmac-sha1.", "hmac-sha224.", "hmac-sha256.", "hmac-sha384.", "hmac-sha512.") NOT NULL DEFAULT "hmac-sha256.", - key_blob BLOB NOT NULL, - storage_facility ENUM("live", "history") NOT NULL DEFAULT "live", - FOREIGN KEY(id_user) REFERENCES users(id_user) -) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; -`, - 2: `ALTER TABLE user_sessions - DROP FOREIGN KEY user_sessions_ibfk_1; - -ALTER TABLE zones - DROP FOREIGN KEY zones_ibfk_1; - -ALTER TABLE users - CHANGE id_user id_user BIGINT NOT NULL AUTO_INCREMENT; - -ALTER TABLE user_sessions - CHANGE id_user id_user BIGINT NOT NULL; - -ALTER TABLE zones - CHANGE id_user id_user BIGINT NOT NULL; -`, - 3: `ALTER TABLE zones - DROP COLUMN server; -ALTER TABLE zones - DROP COLUMN key_name; -ALTER TABLE zones - DROP COLUMN key_algo; -ALTER TABLE zones - DROP COLUMN key_blob; -ALTER TABLE zones - DROP COLUMN storage_facility; - -RENAME TABLE zones TO domains; -`, - 4: `ALTER TABLE users - DROP COLUMN salt; -ALTER TABLE users - MODIFY COLUMN password VARBINARY(255); -`, -} diff --git a/storage/mysql/schemas/001.sql b/storage/mysql/schemas/001.sql deleted file mode 100644 index 0004ed2..0000000 --- a/storage/mysql/schemas/001.sql +++ /dev/null @@ -1,30 +0,0 @@ -CREATE TABLE schema_version ( - version SMALLINT UNSIGNED NOT NULL -); - -CREATE TABLE users ( - id_user INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, - email VARCHAR(255) NOT NULL UNIQUE, - password BINARY(92) NOT NULL, - salt BINARY(64) NOT NULL, - registration_time TIMESTAMP NOT NULL -) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; - -CREATE TABLE user_sessions ( - id_session BLOB(255) NOT NULL, - id_user INTEGER NOT NULL, - time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY(id_user) REFERENCES users(id_user) -); - -CREATE TABLE zones ( - id_zone INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, - id_user INTEGER NOT NULL, - domain VARCHAR(255) NOT NULL, - server VARCHAR(255), - key_name VARCHAR(255) NOT NULL, - key_algo ENUM("hmac-md5.sig-alg.reg.int.", "hmac-sha1.", "hmac-sha224.", "hmac-sha256.", "hmac-sha384.", "hmac-sha512.") NOT NULL DEFAULT "hmac-sha256.", - key_blob BLOB NOT NULL, - storage_facility ENUM("live", "history") NOT NULL DEFAULT "live", - FOREIGN KEY(id_user) REFERENCES users(id_user) -) DEFAULT CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci; diff --git a/storage/mysql/schemas/002.sql b/storage/mysql/schemas/002.sql deleted file mode 100644 index 1a7cfd0..0000000 --- a/storage/mysql/schemas/002.sql +++ /dev/null @@ -1,14 +0,0 @@ -ALTER TABLE user_sessions - DROP FOREIGN KEY user_sessions_ibfk_1; - -ALTER TABLE zones - DROP FOREIGN KEY zones_ibfk_1; - -ALTER TABLE users - CHANGE id_user id_user BIGINT NOT NULL AUTO_INCREMENT; - -ALTER TABLE user_sessions - CHANGE id_user id_user BIGINT NOT NULL; - -ALTER TABLE zones - CHANGE id_user id_user BIGINT NOT NULL; diff --git a/storage/mysql/schemas/003.sql b/storage/mysql/schemas/003.sql deleted file mode 100644 index 70f7195..0000000 --- a/storage/mysql/schemas/003.sql +++ /dev/null @@ -1,12 +0,0 @@ -ALTER TABLE zones - DROP COLUMN server; -ALTER TABLE zones - DROP COLUMN key_name; -ALTER TABLE zones - DROP COLUMN key_algo; -ALTER TABLE zones - DROP COLUMN key_blob; -ALTER TABLE zones - DROP COLUMN storage_facility; - -RENAME TABLE zones TO domains; diff --git a/storage/mysql/schemas/004.sql b/storage/mysql/schemas/004.sql deleted file mode 100644 index 542ed9a..0000000 --- a/storage/mysql/schemas/004.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE users - DROP COLUMN salt; -ALTER TABLE users - MODIFY COLUMN password VARBINARY(255); diff --git a/storage/mysql/session.go b/storage/mysql/session.go deleted file mode 100644 index 784a58b..0000000 --- a/storage/mysql/session.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright or © or Copr. happyDNS (2020) -// -// contact@happydomain.org -// -// This software is a computer program whose purpose is to provide a modern -// interface to interact with DNS systems. -// -// This software is governed by the CeCILL license under French law and abiding -// by the rules of distribution of free software. You can use, modify and/or -// redistribute the software under the terms of the CeCILL license as -// circulated by CEA, CNRS and INRIA at the following URL -// "http://www.cecill.info". -// -// As a counterpart to the access to the source code and rights to copy, modify -// and redistribute granted by the license, users are provided only with a -// limited warranty and the software's author, the holder of the economic -// rights, and the successive licensors have only limited liability. -// -// In this respect, the user's attention is drawn to the risks associated with -// loading, using, modifying and/or developing or reproducing the software by -// the user in light of its specific status of free software, that may mean -// that it is complicated to manipulate, and that also therefore means that it -// is reserved for developers and experienced professionals having in-depth -// computer knowledge. Users are therefore encouraged to load and test the -// software's suitability as regards their requirements in conditions enabling -// the security of their systems and/or data to be ensured and, more generally, -// to use and operate it in the same conditions as regards security. -// -// The fact that you are presently reading this means that you have had -// knowledge of the CeCILL license and that you accept its terms. - -package database - -import ( - "crypto/rand" - - "git.happydns.org/happydomain/model" -) - -func (s *MySQLStorage) GetSession(id []byte) (session *happydns.Session, err error) { - session = &happydns.Session{} - err = s.db.QueryRow("SELECT id_session, id_user, time FROM user_sessions WHERE id_session=?", id).Scan(&session.Id, &session.IdUser, &session.Time) - return -} - -func (s *MySQLStorage) CreateSession(session *happydns.Session) error { - session_id := make([]byte, 255) - if _, err := rand.Read(session_id); err != nil { - return err - } else if _, err := s.db.Exec("INSERT INTO user_sessions (id_session, id_user, time) VALUES (?, ?, ?)", session_id, session.IdUser, session.Time); err != nil { - return err - } else { - session.Id = session_id - return nil - } -} - -func (s *MySQLStorage) UpdateSession(session *happydns.Session) error { - _, err := s.db.Exec(`UPDATE user_sessions SET id_user = ?, time = ? WHERE id_session = ?`, session.IdUser, session.Time, session.Id) - return err -} - -func (s *MySQLStorage) DeleteSession(session *happydns.Session) error { - _, err := s.db.Exec("DELETE FROM user_sessions WHERE id_session = ?", session.Id) - return err -} - -func (s *MySQLStorage) ClearSessions() error { - _, err := s.db.Exec("DELETE FROM user_sessions") - return err -} diff --git a/storage/mysql/user.go b/storage/mysql/user.go deleted file mode 100644 index 96f9bd1..0000000 --- a/storage/mysql/user.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright or © or Copr. happyDNS (2020) -// -// contact@happydomain.org -// -// This software is a computer program whose purpose is to provide a modern -// interface to interact with DNS systems. -// -// This software is governed by the CeCILL license under French law and abiding -// by the rules of distribution of free software. You can use, modify and/or -// redistribute the software under the terms of the CeCILL license as -// circulated by CEA, CNRS and INRIA at the following URL -// "http://www.cecill.info". -// -// As a counterpart to the access to the source code and rights to copy, modify -// and redistribute granted by the license, users are provided only with a -// limited warranty and the software's author, the holder of the economic -// rights, and the successive licensors have only limited liability. -// -// In this respect, the user's attention is drawn to the risks associated with -// loading, using, modifying and/or developing or reproducing the software by -// the user in light of its specific status of free software, that may mean -// that it is complicated to manipulate, and that also therefore means that it -// is reserved for developers and experienced professionals having in-depth -// computer knowledge. Users are therefore encouraged to load and test the -// software's suitability as regards their requirements in conditions enabling -// the security of their systems and/or data to be ensured and, more generally, -// to use and operate it in the same conditions as regards security. -// -// The fact that you are presently reading this means that you have had -// knowledge of the CeCILL license and that you accept its terms. - -package database - -import ( - "git.happydns.org/happydomain/model" -) - -func (s *MySQLStorage) GetUsers() (users happydns.Users, err error) { - if rows, errr := s.db.Query("SELECT id_user, email, password, registration_time FROM users"); errr != nil { - return nil, errr - } else { - defer rows.Close() - - for rows.Next() { - var u happydns.User - if err = rows.Scan(&u.Id, &u.Email, &u.Password, &u.RegistrationTime); err != nil { - return - } - users = append(users, &u) - } - if err = rows.Err(); err != nil { - return - } - - return - } -} - -func (s *MySQLStorage) GetUser(id int64) (u *happydns.User, err error) { - u = &happydns.User{} - err = s.db.QueryRow("SELECT id_user, email, password, registration_time FROM users WHERE id_user=?", id).Scan(&u.Id, &u.Email, &u.Password, &u.RegistrationTime) - return -} - -func (s *MySQLStorage) GetUserByEmail(email string) (u *happydns.User, err error) { - u = &happydns.User{} - err = s.db.QueryRow("SELECT id_user, email, password, registration_time FROM users WHERE email=?", email).Scan(&u.Id, &u.Email, &u.Password, &u.RegistrationTime) - return -} - -func (s *MySQLStorage) UserExists(email string) bool { - var z int - err := s.db.QueryRow("SELECT 1 FROM users WHERE email=?", email).Scan(&z) - return err == nil && z == 1 -} - -func (s *MySQLStorage) CreateUser(u *happydns.User) error { - if res, err := s.db.Exec("INSERT INTO users (email, password, registration_time) VALUES (?, ?, ?, ?)", u.Email, u.Password, u.RegistrationTime); err != nil { - return err - } else if sid, err := res.LastInsertId(); err != nil { - return err - } else { - u.Id = sid - return err - } -} - -func (s *MySQLStorage) UpdateUser(u *happydns.User) error { - _, err := s.db.Exec("UPDATE users SET email = ?, password = ?, registration_time = ? WHERE id_user = ?", u.Email, u.Password, u.RegistrationTime, u.Id) - return err -} - -func (s *MySQLStorage) DeleteUser(u *happydns.User) error { - _, err := s.db.Exec("DELETE FROM users WHERE id_user = ?", u.Id) - return err -} - -func (s *MySQLStorage) ClearUsers() error { - _, err := s.db.Exec("DELETE FROM users") - return err -}