Skip to content

Commit

Permalink
Refactoring.
Browse files Browse the repository at this point in the history
  • Loading branch information
haruyama committed Jul 13, 2014
1 parent 9914321 commit 74fadda
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 38 deletions.
10 changes: 5 additions & 5 deletions controllers/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (controller *MainController) SignInPost(c web.C, r *http.Request) (string,
email, password := r.FormValue("email"), r.FormValue("password")

session := controller.GetSession(c)
dbMap := models.GetDbMap()
dbMap := controller.GetDbMap(c)

user, err := helpers.Login(dbMap, email, password)

Expand All @@ -63,7 +63,7 @@ func (controller *MainController) SignInPost(c web.C, r *http.Request) (string,
return controller.SignIn(c, r)
}

session.Values["User"] = user.Id
session.Values["UserId"] = user.Id

return "/", http.StatusSeeOther
}
Expand Down Expand Up @@ -91,7 +91,7 @@ func (controller *MainController) SignUpPost(c web.C, r *http.Request) (string,
email, password := r.FormValue("email"), r.FormValue("password")

session := controller.GetSession(c)
dbMap := models.GetDbMap()
dbMap := controller.GetDbMap(c)

user := models.GetUserByEmail(dbMap, email)

Expand All @@ -112,7 +112,7 @@ func (controller *MainController) SignUpPost(c web.C, r *http.Request) (string,
return controller.SignUp(c, r)
}

session.Values["User"] = user.Id
session.Values["UserId"] = user.Id

return "/", http.StatusSeeOther
}
Expand All @@ -121,7 +121,7 @@ func (controller *MainController) SignUpPost(c web.C, r *http.Request) (string,
func (controller *MainController) Logout(c web.C, r *http.Request) (string, int) {
session := controller.GetSession(c)

session.Values["User"] = nil
session.Values["UserId"] = nil

return "/", http.StatusSeeOther
}
2 changes: 1 addition & 1 deletion helpers/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

func Login(dbMap *gorp.DbMap, email string, password string) (*models.User, error) {
var user models.User
err := dbMap.SelectOne(&user, "SELECT * FROM users WHERE Email = ?", email)
err := dbMap.SelectOne(&user, "SELECT * FROM Users WHERE Email = ?", email)
if err != nil {
return nil, err
}
Expand Down
20 changes: 11 additions & 9 deletions models/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,17 @@ package models

import (
"database/sql"
"fmt"
"log"

"code.google.com/p/go.crypto/bcrypt"
"github.com/coopernurse/gorp"
_ "github.com/go-sql-driver/mysql"
"github.com/golang/glog"
)

type User struct {
Id int64 `db:"user_id"`
Id int64 `db:"UserId"`
Email string
Username string
Password []byte
Expand All @@ -26,7 +28,7 @@ func (user *User) HashPassword(password string) {
}

func GetUserByEmail(dbMap *gorp.DbMap, email string) (user *User) {
err := dbMap.SelectOne(&user, "SELECT * FROM users where email = ?", email)
err := dbMap.SelectOne(&user, "SELECT * FROM Users where Email = ?", email)

if err != nil {
glog.Warningf("Can't get user by email: %v", err)
Expand All @@ -35,29 +37,29 @@ func GetUserByEmail(dbMap *gorp.DbMap, email string) (user *User) {
}

func InsertUser(dbMap *gorp.DbMap, user *User) error {
return dbMap.Insert(&user)
return dbMap.Insert(user)
}

func GetDbMap() *gorp.DbMap {
func GetDbMap(user, password, hostname, database string) *gorp.DbMap {
// connect to db using standard Go database/sql API
// use whatever database/sql driver you wish
//TODO: Get user, password and database from config.
db, err := sql.Open("mysql", "root:password@/goji")
db, err := sql.Open("mysql", fmt.Sprint(user, ":", password, "@", hostname, "/", database))
checkErr(err, "sql.Open failed")

// construct a gorp DbMap
dbmap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8MB4"}}
dbMap := &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8MB4"}}

// add a table, setting the table name to 'posts' and
// specifying that the Id property is an auto incrementing PK
dbmap.AddTableWithName(User{}, "users").SetKeys(true, "Id")
dbMap.AddTableWithName(User{}, "Users").SetKeys(true, "Id")

// create the table. in a production system you'd generally
// use a migration tool, or create the tables via scripts
err = dbmap.CreateTablesIfNotExists()
err = dbMap.CreateTablesIfNotExists()
checkErr(err, "Create tables failed")

return dbmap
return dbMap
}

func checkErr(err error, msg string) {
Expand Down
1 change: 1 addition & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func main() {
// Apply middleware
goji.Use(application.ApplyTemplates)
goji.Use(application.ApplySessions)
goji.Use(application.ApplyDbMap)
goji.Use(application.ApplyAuth)

controller := &controllers.MainController{}
Expand Down
10 changes: 6 additions & 4 deletions system/configuration.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package system

type ConfigurationDatabase struct {
Hosts string `json:"hosts"`
User string `json:"user"`
Password string `json:"password"`
Hostname string `json:"hostname"`
Database string `json:"database"`
}

type Configuration struct {
Secret string `json:"secret"`
PublicPath string `json:"public_path"`
Secret string `json:"secret"`
PublicPath string `json:"public_path"`
TemplatePath string `json:"template_path"`
Database ConfigurationDatabase
Database ConfigurationDatabase
}
6 changes: 5 additions & 1 deletion system/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"bytes"
"html/template"

_ "github.com/go-sql-driver/mysql"
"github.com/coopernurse/gorp"
"github.com/gorilla/sessions"
"github.com/zenazn/goji/web"
)
Expand All @@ -20,6 +20,10 @@ func (controller *Controller) GetTemplate(c web.C) *template.Template {
return c.Env["Template"].(*template.Template)
}

func (controller *Controller) GetDbMap(c web.C) *gorp.DbMap {
return c.Env["DbMap"].(*gorp.DbMap)
}

func (controller *Controller) Parse(t *template.Template, name string, data interface{}) string {
var doc bytes.Buffer
t.ExecuteTemplate(&doc, name, data)
Expand Down
26 changes: 11 additions & 15 deletions system/core.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,31 @@
package system

import (
"encoding/gob"
"encoding/json"
"net/http"

"github.com/golang/glog"
"labix.org/v2/mgo/bson"

"reflect"

"github.com/zenazn/goji/web"

"github.com/gorilla/sessions"

"html/template"

"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"

"github.com/coopernurse/gorp"
"github.com/golang/glog"
"github.com/gorilla/sessions"
"github.com/haruyama/golang-goji-sample/models"
"github.com/zenazn/goji/web"
)

type Application struct {
Configuration *Configuration
Template *template.Template
Store *sessions.CookieStore
DbMap *gorp.DbMap
}

func (application *Application) Init(filename *string) {
gob.Register(bson.ObjectId(""))

data, err := ioutil.ReadFile(*filename)

if err != nil {
Expand All @@ -49,6 +43,8 @@ func (application *Application) Init(filename *string) {
}

application.Store = sessions.NewCookieStore([]byte(application.Configuration.Secret))
dbConfig := application.Configuration.Database
application.DbMap = models.GetDbMap(dbConfig.User, dbConfig.Password, dbConfig.Hostname, dbConfig.Database)
}

func (application *Application) LoadTemplates() error {
Expand Down
14 changes: 11 additions & 3 deletions system/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package system
import (
"net/http"

"github.com/coopernurse/gorp"
"github.com/golang/glog"
"github.com/gorilla/sessions"
"github.com/haruyama/golang-goji-sample/models"
"github.com/zenazn/goji/web"
"labix.org/v2/mgo/bson"
)

// Makes sure templates are stored in the context
Expand All @@ -29,11 +29,19 @@ func (application *Application) ApplySessions(c *web.C, h http.Handler) http.Han
return http.HandlerFunc(fn)
}

func (application *Application) ApplyDbMap(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
c.Env["DbMap"] = application.DbMap
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}

func (application *Application) ApplyAuth(c *web.C, h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
session := c.Env["Session"].(*sessions.Session)
if userId, ok := session.Values["User"].(bson.ObjectId); ok {
dbMap := models.GetDbMap()
if userId, ok := session.Values["UserId"]; ok {
dbMap := c.Env["DbMap"].(*gorp.DbMap)

user, err := dbMap.Get(models.User{}, userId)
if err != nil {
Expand Down

0 comments on commit 74fadda

Please sign in to comment.