2014-01-09 23:18:49 +00:00
package db
import (
"database/sql"
"fmt"
"os"
2014-01-30 21:08:14 +00:00
"github.com/coopernurse/gorp"
2014-01-09 23:18:49 +00:00
"github.com/jordan-wright/gophish/config"
2014-01-30 21:08:14 +00:00
"github.com/jordan-wright/gophish/models"
2014-01-09 23:18:49 +00:00
_ "github.com/mattn/go-sqlite3"
)
2014-01-30 21:08:14 +00:00
var Conn * gorp . DbMap
var DB * sql . DB
var err error
2014-01-09 23:18:49 +00:00
// Setup initializes the Conn object
// It also populates the Gophish Config object
2014-01-30 21:08:14 +00:00
func Setup ( ) error {
DB , err := sql . Open ( "sqlite3" , config . Conf . DBPath )
Conn = & gorp . DbMap { Db : DB , Dialect : gorp . SqliteDialect { } }
2014-01-09 23:18:49 +00:00
//If the file already exists, delete it and recreate it
2014-01-30 21:08:14 +00:00
_ , err = os . Stat ( config . Conf . DBPath )
Conn . AddTableWithName ( models . User { } , "users" ) . SetKeys ( true , "Id" )
Conn . AddTableWithName ( models . Campaign { } , "campaigns" ) . SetKeys ( true , "Id" )
2014-01-09 23:18:49 +00:00
if err != nil {
2014-01-30 21:08:14 +00:00
fmt . Println ( "Database not found, recreating..." )
2014-01-13 04:39:40 +00:00
createTablesSQL := [ ] string {
//Create tables
` CREATE TABLE Users (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, hash VARCHAR(60) NOT NULL, apikey VARCHAR(32)); ` ,
2014-01-30 21:08:14 +00:00
` CREATE TABLE Campaigns (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, created_date TEXT NOT NULL, completed_date TEXT, template TEXT, status TEXT NOT NULL, uid INTEGER, FOREIGN KEY (uid) REFERENCES Users(id)); ` ,
2014-01-13 04:39:40 +00:00
}
fmt . Println ( "Creating db at " + config . Conf . DBPath )
//Create the tables needed
for _ , stmt := range createTablesSQL {
2014-01-30 21:08:14 +00:00
_ , err = DB . Exec ( stmt )
2014-01-13 04:39:40 +00:00
if err != nil {
return err
}
}
//Create the default user
2014-01-30 21:08:14 +00:00
init_user := models . User {
Username : "jordan" ,
Hash : "$2a$10$d4OtT.RkEOQn.iruVWIQ5u8CeV/85ZYF41y8wKeUwsAPqPNFvTccW" ,
APIKey : "12345678901234567890123456789012" ,
2014-01-13 04:39:40 +00:00
}
2014-01-30 21:08:14 +00:00
Conn . Insert ( & init_user )
2014-01-13 03:46:51 +00:00
if err != nil {
2014-01-30 21:08:14 +00:00
fmt . Println ( err )
2014-01-13 03:46:51 +00:00
}
2014-01-09 23:18:49 +00:00
}
return nil
}