-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.go
75 lines (58 loc) · 1.66 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
package handlers
import (
"context"
"fmt"
"log"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/markbates/goth/gothic"
"github.com/scottmckendry/mnemstart/views"
)
func (h *Handler) HandleLogin(w http.ResponseWriter, r *http.Request) {
views.Login().Render(r.Context(), w)
}
func (h *Handler) HandleProviderLogin(w http.ResponseWriter, r *http.Request) {
provider := chi.URLParam(r, "provider")
r = r.WithContext(context.WithValue(r.Context(), "provider", provider))
// try to get the user without re-authenticating
if u, err := gothic.CompleteUserAuth(w, r); err == nil {
log.Printf("User already authenticated! %v", u)
views.Login().Render(r.Context(), w)
} else {
gothic.BeginAuthHandler(w, r)
}
}
func (h *Handler) HandleAuthCallbackFunction(w http.ResponseWriter, r *http.Request) {
provider := chi.URLParam(r, "provider")
r = r.WithContext(context.WithValue(r.Context(), "provider", provider))
user, err := gothic.CompleteUserAuth(w, r)
if err != nil {
fmt.Fprintln(w, err)
return
}
err = h.auth.StoreUserSession(w, r, user)
if err != nil {
log.Println(err)
return
}
err = h.store.CreateOrUpdateUser(user)
if err != nil {
log.Println(err)
return
}
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusTemporaryRedirect)
}
func (h *Handler) HandleLogout(w http.ResponseWriter, r *http.Request) {
provider := chi.URLParam(r, "provider")
r = r.WithContext(context.WithValue(r.Context(), "provider", provider))
log.Println("Logging out...")
err := gothic.Logout(w, r)
if err != nil {
log.Println(err)
return
}
h.auth.RemoveUserSession(w, r)
w.Header().Set("Location", "/")
w.WriteHeader(http.StatusTemporaryRedirect)
}