Moved DB to root folder

Created db package to handle DB connection/queries
Removed Setup.go (now handled in db package)
Setup context in middleware
pull/24/head
Jordan 2014-01-09 17:18:49 -06:00
parent d4dbf30499
commit 7eb90b27ad
7 changed files with 71 additions and 67 deletions

View File

@ -2,15 +2,22 @@ package auth
import ( import (
"database/sql" "database/sql"
"encoding/gob"
"net/http" "net/http"
"code.google.com/p/go.crypto/bcrypt" "code.google.com/p/go.crypto/bcrypt"
ctx "github.com/gorilla/context" ctx "github.com/gorilla/context"
"github.com/gorilla/securecookie" "github.com/gorilla/securecookie"
"github.com/gorilla/sessions" "github.com/gorilla/sessions"
"github.com/jordan-wright/gophish/db"
"github.com/jordan-wright/gophish/models" "github.com/jordan-wright/gophish/models"
) )
//init registers the necessary models to be saved in the session later
func init() {
gob.Register(&models.User{})
}
var Store = sessions.NewCookieStore([]byte(securecookie.GenerateRandomKey(64))) var Store = sessions.NewCookieStore([]byte(securecookie.GenerateRandomKey(64)))
// CheckLogin attempts to request a SQL record with the given username. // CheckLogin attempts to request a SQL record with the given username.
@ -19,11 +26,7 @@ var Store = sessions.NewCookieStore([]byte(securecookie.GenerateRandomKey(64)))
func CheckLogin(r *http.Request) (bool, error) { func CheckLogin(r *http.Request) (bool, error) {
username, password := r.FormValue("username"), r.FormValue("password") username, password := r.FormValue("username"), r.FormValue("password")
session, _ := Store.Get(r, "gophish") session, _ := Store.Get(r, "gophish")
stmt, err := db.Prepare("SELECT * FROM Users WHERE username=?") stmt, err := db.Conn.Prepare("SELECT * FROM Users WHERE username=?")
if err != nil {
return false, err
}
hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil { if err != nil {
return false, err return false, err
} }
@ -34,20 +37,20 @@ func CheckLogin(r *http.Request) (bool, error) {
} }
//If we've made it here, we should have a valid user stored in u //If we've made it here, we should have a valid user stored in u
//Let's check the password //Let's check the password
err = bcrypt.CompareHashAndPassword(u.Hash, hash) err = bcrypt.CompareHashAndPassword([]byte(u.Hash), []byte(password))
if err != nil { if err != nil {
ctx.Set(r, User, nil) ctx.Set(r, "user", nil)
//Return false, but don't return an error //Return false, but don't return an error
return false, nil return false, nil
} }
ctx.Set(r, models.User, u) ctx.Set(r, "user", u)
session.Values["id"] = GetUser(r).Id session.Values["id"] = u.Id
return true, nil return true, nil
} }
func GetUser(r *http.Request) User { func GetUser(r *http.Request) models.User {
if rv := ctx.Get(r, models.User); rv != nil { if rv := ctx.Get(r, "user"); rv != nil {
return rv.(models.User) return rv.(models.User)
} }
return nil return models.User{}
} }

View File

@ -5,5 +5,5 @@
"user" : "username", "user" : "username",
"pass" : "password" "pass" : "password"
}, },
"dbpath" : "db/gophish.db" "dbpath" : "gophish.db"
} }

View File

@ -102,6 +102,7 @@ func Login(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", 302) http.Redirect(w, r, "/", 302)
} else { } else {
session.AddFlash("Invalid Username/Password") session.AddFlash("Invalid Username/Password")
renderTemplate(w, "login")
} }
} }
} }

44
db/db.go Normal file
View File

@ -0,0 +1,44 @@
package db
import (
"database/sql"
"fmt"
"os"
"github.com/jordan-wright/gophish/config"
_ "github.com/mattn/go-sqlite3"
)
var Conn *sql.DB
// Setup initializes the Conn object
// It also populates the Gophish Config object
func Setup() error {
//If the file already exists, delete it and recreate it
_, err := os.Stat(config.Conf.DBPath)
if err == nil {
os.Remove(config.Conf.DBPath)
}
fmt.Println("Creating db at " + config.Conf.DBPath)
Conn, err = sql.Open("sqlite3", config.Conf.DBPath)
if err != nil {
return err
}
//Create the tables needed
_, err = Conn.Exec(
`CREATE TABLE Users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, hash VARCHAR(60), apikey VARCHAR(32));`)
if err != nil {
return err
}
//Create the default user
stmt, err := Conn.Prepare(`INSERT INTO Users (username, hash, apikey) VALUES (?, ?, ?);`)
defer stmt.Close()
if err != nil {
return err
}
_, err = stmt.Exec("jordan", "$2a$10$d4OtT.RkEOQn.iruVWIQ5u8CeV/85ZYF41y8wKeUwsAPqPNFvTccW", "12345678901234567890123456789012")
if err != nil {
return err
}
return nil
}

View File

@ -30,7 +30,9 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"github.com/jordan-wright/gophish/config"
"github.com/jordan-wright/gophish/controllers" "github.com/jordan-wright/gophish/controllers"
"github.com/jordan-wright/gophish/db"
"github.com/jordan-wright/gophish/middleware" "github.com/jordan-wright/gophish/middleware"
) )
@ -38,11 +40,13 @@ var setupFlag = flag.Bool("setup", false, "Starts the initial setup process for
func main() { func main() {
//Setup the global variables and settings //Setup the global variables and settings
err = Setup() err := db.Setup()
//defer db.Conn.Close()
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
fmt.Printf("Gophish server started at http://%s\n", config.Conf.URL) fmt.Printf("Gophish server started at http://%s\n", config.Conf.URL)
http.Handle("/", middleware.Use(controllers.CreateRouter(), middleware.GetContext)) http.Handle("/", middleware.Use(controllers.CreateRouter(), middleware.GetContext))
http.ListenAndServe(config.URL, nil) http.ListenAndServe(config.Conf.URL, nil)
fmt.Println("Closed.")
} }

View File

@ -3,6 +3,8 @@ package middleware
import ( import (
"fmt" "fmt"
"net/http" "net/http"
ctx "github.com/gorilla/context"
) )
// Use allows us to stack middleware to process the request // Use allows us to stack middleware to process the request
@ -19,8 +21,9 @@ func Use(handler http.Handler, middleware ...func(http.Handler) http.Handler) ht
func GetContext(handler http.Handler) http.Handler { func GetContext(handler http.Handler) http.Handler {
// Set the context here // Set the context here
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Get context called!") // Set the context appropriately here.
handler.ServeHTTP(w, r) handler.ServeHTTP(w, r)
ctx.Clear(r)
}) })
} }

View File

@ -1,51 +0,0 @@
package main
import (
"database/sql"
"encoding/gob"
"fmt"
"os"
"github.com/jordan-wright/gophish/config"
"github.com/jordan-wright/gophish/models"
_ "github.com/mattn/go-sqlite3"
)
var Db sql.DB
//init registers the necessary models to be saved in the session later
func init() {
gob.Register(&models.User{})
}
// Setup creates and returns the database needed by Gophish.
// It also populates the Gophish Config object
func Setup() error {
//If the file already exists, delete it and recreate it
if _, err := os.Stat(config.Conf.DBPath); err == nil {
os.Remove(Conf.DBPath)
}
fmt.Println("Creating db at " + config.Conf.DBPath)
db, err := sql.Open("sqlite3", config.Conf.DBPath)
defer db.Close()
if err != nil {
return err
}
//Create the tables needed
_, err = db.Exec(
`CREATE TABLE Users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, hash VARCHAR(32), apikey VARCHAR(32));`)
if err != nil {
return err
}
//Create the default user
stmt, err := db.Prepare(`INSERT INTO Users (username, hash, apikey) VALUES (?, ?, ?);`)
defer stmt.Close()
if err != nil {
return err
}
_, err = stmt.Exec("jordan", "12345678901234567890123456789012", "12345678901234567890123456789012")
if err != nil {
return err
}
return nil
}