Skip to content

Commit b950411

Browse files
committed
logged in status
1 parent 0b35219 commit b950411

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

cmd/web/helpers.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package main
2+
3+
import "net/http"
4+
5+
func (app *App) LoggedIn(r *http.Request) (bool, error) {
6+
session := app.sessions.Load(r)
7+
loggedIn, err := session.Exists("currentUserId")
8+
if err != nil {
9+
return false, err
10+
}
11+
return loggedIn, nil
12+
}

cmd/web/views.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ type HtmlData struct {
1414
Form interface{}
1515
Path string
1616
Flash string
17+
LoggedIn bool
1718
Snippet *models.Snippet
1819
Snippets []*models.Snippet
1920
}
@@ -29,6 +30,13 @@ func (app *App) RenderHtml(w http.ResponseWriter, r *http.Request, page string,
2930

3031
data.Path = r.URL.Path
3132

33+
var err error
34+
data.LoggedIn, err = app.LoggedIn(r)
35+
if err != nil {
36+
app.ServerError(w, err)
37+
return
38+
}
39+
3240
files := []string{
3341
filepath.Join(app.htmlDir, "base.html"),
3442
filepath.Join(app.htmlDir, page),

ui/html/base.html

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,21 @@ <h1><a href="/">Snippetbox</a></h1>
1515
<a href="/" {{if eq .Path "/"}}class="live"{{end}}>
1616
Home
1717
</a>
18+
{{if .LoggedIn}}
1819
<a href="/snippet/new" {{if eq .Path "/snippet/new"}}class="live"{{end}}>
1920
New Snippet
2021
</a>
22+
<form action="/user/logout" method="POST">
23+
<button>Logout</button>
24+
</form>
25+
{{else}}
26+
<a href="/user/login" {{if eq .Path "/user/login"}}class="live"{{end}}>
27+
Login
28+
</a>
29+
<a href="/user/signup" {{if eq .Path "/user/signup"}}class="live"{{end}}>
30+
Signup
31+
</a>
32+
{{end}}
2133
</nav>
2234
<section>
2335
{{- template "page-body" .}}

0 commit comments

Comments
 (0)