forked from usefathom/fathom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
83 lines (65 loc) · 1.73 KB
/
auth.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package api
import (
"context"
"encoding/json"
"net/http"
"os"
"github.com/dannyvankooten/ana/datastore"
"github.com/gorilla/sessions"
"golang.org/x/crypto/bcrypt"
)
type key int
const (
userKey key = 0
)
type login struct {
Email string `json:"email"`
Password string `json:"password"`
}
var store = sessions.NewCookieStore([]byte(os.Getenv("ANA_SECRET_KEY")))
// URL: POST /api/session
var LoginHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check login creds
var l login
json.NewDecoder(r.Body).Decode(&l)
u, err := datastore.GetUserByEmail(l.Email)
// compare pwd
if err != nil || bcrypt.CompareHashAndPassword([]byte(u.HashedPassword), []byte(l.Password)) != nil {
w.WriteHeader(http.StatusUnauthorized)
respond(w, envelope{Error: "invalid_credentials"})
return
}
session, _ := store.Get(r, "auth")
session.Values["user_id"] = u.ID
err = session.Save(r, w)
checkError(err)
respond(w, envelope{Data: true})
})
// URL: DELETE /api/session
var LogoutHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "auth")
if !session.IsNew {
session.Options.MaxAge = -1
session.Save(r, w)
}
respond(w, envelope{Data: true})
})
/* middleware */
func Authorize(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "auth")
userID, ok := session.Values["user_id"]
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
// find user
u, err := datastore.GetUser(userID.(int64))
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), userKey, u)
next.ServeHTTP(w, r.WithContext(ctx))
})
}