Skip to content
Permalink
Browse files

06-User-Login add middleware auth

  • Loading branch information...
bonfy committed Sep 12, 2018
1 parent 6f54950 commit 4ce33f3dbdd4ebb828edcb553caa4e32e9bf0318
Showing with 46 additions and 9 deletions.
  1. +4 −3 controller/home.go
  2. +26 −0 controller/middle.go
  3. +4 −0 templates/_base.html
  4. +1 −1 templates/content/index.html
  5. +7 −1 vm/g.go
  6. +4 −4 vm/index.go
@@ -9,15 +9,16 @@ import (
type home struct{}

func (h home) registerRoutes() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/", middleAuth(indexHandler))
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/logout", logoutHandler)
http.HandleFunc("/logout", middleAuth(logoutHandler))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
tpName := "index.html"
vop := vm.IndexViewModelOp{}
v := vop.GetVM()
username, _ := getSessionUser(r)
v := vop.GetVM(username)
templates[tpName].Execute(w, &v)
}

@@ -0,0 +1,26 @@
package controller

import (
"log"
"net/http"
)

func middleAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
username, err := getSessionUser(r)
log.Println("middle:", username)
if err != nil {
log.Println("middle get session err and redirect to login")
http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
} else {
next.ServeHTTP(w, r)
}
}
}

func middleLogging(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("Logged connection from %s", r.RemoteAddr)
next.ServeHTTP(w, r)
}
}
@@ -10,7 +10,11 @@
<div>
Blog:
<a href="/">Home</a>
{{if .CurrentUser}}
<a href="/logout">Logout</a>
{{else}}
<a href="/login">Login</a>
{{end}}
</div>

{{template "content" .}}
@@ -1,5 +1,5 @@
{{define "content"}}
<h1>Hello, {{.User.Username}}!</h1>
<h1>Hello, {{.CurrentUser}}!</h1>

{{range .Posts}}
<div><p>{{ .User.Username }} says: <b>{{ .Body }}</b></p></div>
@@ -2,10 +2,16 @@ package vm

// BaseViewModel struct
type BaseViewModel struct {
Title string
Title string
CurrentUser string
}

// SetTitle func
func (v *BaseViewModel) SetTitle(title string) {
v.Title = title
}

// SetCurrentUser func
func (v *BaseViewModel) SetCurrentUser(username string) {
v.CurrentUser = username
}
@@ -5,17 +5,17 @@ import "github.com/bonfy/go-mega-code/model"
// IndexViewModel struct
type IndexViewModel struct {
BaseViewModel
model.User
Posts []model.Post
}

// IndexViewModelOp struct
type IndexViewModelOp struct{}

// GetVM func
func (IndexViewModelOp) GetVM() IndexViewModel {
u1, _ := model.GetUserByUsername("rene")
func (IndexViewModelOp) GetVM(username string) IndexViewModel {
u1, _ := model.GetUserByUsername(username)
posts, _ := model.GetPostsByUserID(u1.ID)
v := IndexViewModel{BaseViewModel{Title: "Homepage"}, *u1, *posts}
v := IndexViewModel{BaseViewModel{Title: "Homepage"}, *posts}
v.SetCurrentUser(username)
return v
}

0 comments on commit 4ce33f3

Please sign in to comment.
You can’t perform that action at this time.