Browse Source

SHA шифровка пароле на mysql сервере

toomanysugar 3 years ago
parent
commit
e87c8844ea
2 changed files with 138 additions and 16 deletions
  1. 96 10
      cmd/web/connector.go
  2. 42 6
      cmd/web/main.go

+ 96 - 10
cmd/web/connector.go

@@ -18,31 +18,112 @@ type ConnectionProperties struct {
 
 type connection struct {
 	dBOpenStr string
+	connProperties ConnectionProperties
 }
 
 func (c *connection) Init(filepath string){
+	if (NOMYSQL) {
+		return
+	}
 	b, err := ioutil.ReadFile(filepath)
     if err != nil {
       fmt.Print(err)
     }
     propJson := string(b)
-	var connProperties ConnectionProperties
 
-	json.Unmarshal([]byte(propJson), &connProperties)
-	fmt.Printf("Connection data:\n%s\n%s\n%s\n%s\n", connProperties.User, connProperties.Pass,connProperties.Host,connProperties.Db)
-	c.dBOpenStr = connProperties.User + ":" + connProperties.Pass + "@tcp(" + connProperties.Host + ")/" + connProperties.Db
+	json.Unmarshal([]byte(propJson), &c.connProperties)
+	
+	//c.connProperties.Db = "nosite"
+	fmt.Printf("Connection data:\n%s\n%s\n%s\n%s\n", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
+	c.dBOpenStr = fmt.Sprintf ("%s:%s@tcp(%s)/%s", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host, c.connProperties.Db)
 	fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
 	db, err := sql.Open("mysql", c.dBOpenStr)
+	if err != nil {
+		panic(err)
+	}
+	if err = db.Ping(); err != nil {
+        db.Close()
+        logger.Print("Fatal : Error with connection to database!")
+    } else {
+    	fmt.Print("Connection succesfull!")
+    	return
+    }
+    
+
+    logger.Print("Trying to connect to DB-server...")
+    c.dBOpenStr = fmt.Sprintf ("%s:%s@tcp(%s)/", c.connProperties.User, c.connProperties.Pass, c.connProperties.Host)
+    fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
+	db, err = sql.Open("mysql", c.dBOpenStr)
+	if err != nil {
+		panic(err)
+	}
+	if err = db.Ping(); err != nil {
+        db.Close()
+        logger.Print("Fatal : Error with connection to database server!")
+        return
+    } else {
+    	
+    }
+    c.databaseInitialization();
+}
+
+/*  создает на сервере необходимую бд и таблицы  */
+func (c *connection) databaseInitialization() { 
+	db, err := sql.Open("mysql", c.dBOpenStr)
 
 	if err != nil {
 		panic(err)
 	}
 
 	defer db.Close()
+
+	var counter int
+	var act_query string
+	logger.Printf("Checking for existence of database '%s' on server...", c.connProperties.Db)
+	act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_SCHEMA = '" + c.connProperties.Db + "';"
+	db.QueryRow(act_query).Scan(&counter)
+	fmt.Print(counter)
+	if (counter != 0) {
+		logger.Print("Server already has the specified database")
+	} else {
+		logger.Print("The server does not have the specified database")
+		logger.Printf("Creating database '%s'...", c.connProperties.Db)
+		act_query = "CREATE SCHEMA " + c.connProperties.Db + " DEFAULT CHARACTER SET utf8 ;"
+		result, err := db.Exec(act_query)
+	    if err != nil{
+	        panic(err)
+	    }
+
+	    rowsCount, _ := result.RowsAffected()
+		fmt.Printf("Lines changed: %d\n", rowsCount)
+	    if (rowsCount == 1) {
+	    	logger.Print("Succesfull!")
+	    }
+	}
+
+	logger.Print("Checking for existence of table 'users' on server...")
+	act_query = "SELECT count(*) FROM information_schema.tables WHERE TABLE_NAME = 'users' AND TABLE_SCHEMA = '"+ c.connProperties.Db +"';"
+	db.QueryRow(act_query).Scan(&counter)
+	fmt.Print(counter)
+	if (counter != 0) {
+		logger.Print("Server already has the specified table!")
+	} else {
+		logger.Print("The server does not have the specified table")
+		logger.Printf("Creating table '%s'.'users'...",c.connProperties.Db)
+		act_query = "CREATE TABLE `" + c.connProperties.Db + "`.`users` ( `idusers` INT NOT NULL AUTO_INCREMENT,`username` VARCHAR(45) NOT NULL, `password` VARCHAR(45) NOT NULL, PRIMARY KEY(`idusers`), UNIQUE INDEX `idusers_UNIQUE` (`idusers` ASC), UNIQUE INDEX `username_UNIQUE` (`username` ASC)) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 ;"
+		fmt.Print(act_query)
+		_, err := db.Exec(act_query)
+	    if err != nil{
+	        panic(err)
+	    }
+    	logger.Print("Succesfull!")
+	}
+
+
 }
 
 func (c connection) LogIn(username string, password string) bool{
-	fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
+	fmt.Printf("\n\nLogIn\nConnecting with:\n%s\n", c.dBOpenStr)
 	db, err := sql.Open("mysql", c.dBOpenStr)
 
 	if err != nil {
@@ -52,8 +133,8 @@ func (c connection) LogIn(username string, password string) bool{
 	defer db.Close()
 
 	var counter int
-	fmt.Printf("%s\n%s\n", username, password)
-	act_query := "SELECT count(*) FROM gosite.users WHERE username='" + username + "' AND password='" + password + "';"
+	//fmt.Printf("%s\n%s\n", username, password)
+	act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s' AND password=SHA('%s');", c.connProperties.Db, username, password)
 	db.QueryRow(act_query).Scan(&counter)
 	fmt.Println("we have", counter, "rows")
     
@@ -62,6 +143,7 @@ func (c connection) LogIn(username string, password string) bool{
     }
 	return true
 
+
 }
 
 func (c connection) IsNameUsed(username string) bool {
@@ -73,7 +155,7 @@ func (c connection) IsNameUsed(username string) bool {
 	defer db.Close()
 
 	var counter int
-	act_query := "SELECT count(*) FROM gosite.users WHERE username='" + username + "';"
+	act_query := fmt.Sprintf("SELECT count(*) FROM %s.users WHERE username='%s';", c.connProperties.Db, username)
 	db.QueryRow(act_query).Scan(&counter)
     
 	if (counter == 0) {
@@ -90,8 +172,8 @@ func (c connection) SigInUser(username string, password string) bool {
         panic(err)
     } 
     defer db.Close()
-     
-    result, err := db.Exec("INSERT INTO gosite.users (username, password) values (?, ?)", username, password)
+    act_query := fmt.Sprintf("INSERT INTO %s.users (username, password) VALUES ('%s', SHA('%s'))", c.connProperties.Db, username, password)
+    result, err := db.Exec(act_query)
     if err != nil{
         panic(err)
     }
@@ -105,6 +187,10 @@ func (c connection) SigInUser(username string, password string) bool {
     }
 }
 
+func (c connection) SubmitScore(score int){
+	fmt.Printf("Submiting score %d", score)
+}
+
 /*
 func main() {
 

+ 42 - 6
cmd/web/main.go

@@ -6,7 +6,7 @@ import (
 	
 	"os"
 	"time"
-	//"fmt"
+	"fmt"
 	"net/http"
 	"html/template"
 	"github.com/gorilla/mux"
@@ -15,10 +15,18 @@ import (
 
 )
 
+const (
+	NOMYSQL = false;
+)
+
 var (
+
+
 	logger	*log.Logger
 	dBConnector connection
+
 	sessionsStore = sessions.NewCookieStore([]byte("mysecretcookie"))
+
 	indexTemplate = template.Must(template.ParseFiles("ui\\templates\\index.html"))
 	logInTemplate = template.Must(template.ParseFiles("ui\\templates\\login.html"))
 	signInTemplate = template.Must(template.ParseFiles("ui\\templates\\signin.html"))
@@ -31,14 +39,36 @@ func createLogger() {
 	startTime := time.Now()
 	logFileName := "logs/go-site_log_" + startTime.Format("2006-01-02_15-04-05") + ".txt"
 	file, err := os.OpenFile(logFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
-	logger = log.New(file, "logger: ", log.Lshortfile)
+	logger = log.New(file, "", log.Ldate|log.Ltime)
   	
   	if err != nil {
-        	log.Fatal(err)
-    	}
+    	log.Fatal(err)
+	}
 
 }
 
+
+type justFilesFilesystem struct {
+    fs http.FileSystem
+}
+
+func (fs justFilesFilesystem) Open(name string) (http.File, error) {
+    f, err := fs.fs.Open(name)
+    if err != nil {
+        return nil, err
+    }
+    return neuteredReaddirFile{f}, nil
+}
+
+type neuteredReaddirFile struct {
+    http.File
+}
+
+func (f neuteredReaddirFile) Readdir(count int) ([]os.FileInfo, error) {
+    return nil, nil
+}
+
+
 func main() {
 	
 	
@@ -54,14 +84,20 @@ func main() {
     
 
     requestRouter.HandleFunc("/", indexHandler).Methods("GET")
-    //requestRouter.HandleFunc("/", indexPostHandler).Methods("POST")		//Есть ли нужда в обработке POST для /
+    requestRouter.HandleFunc("/", indexPostHandler).Methods("POST")		//Есть ли нужда в обработке POST для /
     requestRouter.HandleFunc("/login/", logInGetHandler).Methods("GET")
     requestRouter.HandleFunc("/login/", logInPostHandler).Methods("POST")
     requestRouter.HandleFunc("/logout/", logOutGetHandler).Methods("GET")
     requestRouter.HandleFunc("/signin/", signInGetHandler).Methods("GET")
     requestRouter.HandleFunc("/signin/", signInPostHandler).Methods("POST")
     requestRouter.HandleFunc("/game/", gameGetHandler).Methods("GET")
-    requestRouter.HandleFunc("/", gamePostHandler).Methods("POST")
+    requestRouter.HandleFunc("/game/", gamePostHandler).Methods("POST")
+    
+    fs := justFilesFilesystem{http.Dir("resources/")}
+    http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(fs)))
+
     http.Handle("/", requestRouter)
+
+    fmt.Print("Starting web-listener")
     logger.Fatal(http.ListenAndServe(":8080", nil))
 }