/
auth.go
96 lines (78 loc) 路 2.5 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
84
85
86
87
88
89
90
91
92
93
94
95
96
package restapi
import (
"context"
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/go-chi/jwtauth"
"github.com/go-chi/render"
"github.com/mitchellh/mapstructure"
"github.com/uwblueprint/shoe-project/config"
"github.com/uwblueprint/shoe-project/internal/database/models"
"github.com/uwblueprint/shoe-project/restapi/rest"
"google.golang.org/api/idtoken"
)
type GoogleClaims struct {
Email string `mapstructure:"email"`
Hd string `mapstructure:"hd"`
}
func (api api) Login(w http.ResponseWriter, r *http.Request) render.Renderer {
payload, err := idtoken.Validate(context.TODO(), r.Header.Get("Authorization"), config.GetGoogleClientId())
if err != nil {
return rest.ErrInvalidRequest(api.logger, "Invalid token in header", err)
}
googleClaims := GoogleClaims{}
err = mapstructure.Decode(payload.Claims, &googleClaims)
if err != nil {
return rest.ErrInvalidRequest(api.logger, "Could not decode google response", err)
}
user := models.User{
Email: googleClaims.Email,
Hd: googleClaims.Hd,
}
// create user in database if valid
err = api.database.FirstOrCreate(&user, models.User{Email: user.Email}).Error
if err != nil {
return rest.ErrInvalidRequest(api.logger, "User does not have a valid email address", err)
}
// if valid set jwt token in cookie
err = generateJWTToken(user.Email, w)
if err != nil {
return rest.ErrInvalidRequest(api.logger, "Could not generate JWT token", err)
}
return rest.JSONStatusOK("Authenticated Successfully")
}
func generateJWTToken(email string, w http.ResponseWriter) error {
claim := &models.Claims{
Email: email,
StandardClaims: jwt.StandardClaims{
ExpiresAt: 0,
Issuer: config.GetTokenIssuer(),
},
}
token := config.GetJWTKey()
_, signedToken, err := token.Encode(claim)
if err != nil {
return err
}
// TODO: change this back when we start using https
// secure := (config.GetMode() == config.MODE_PROD)
secure := false
cookie := http.Cookie{Name: "jwt", Value: signedToken, HttpOnly: true, Secure: secure, Path: "/api"}
http.SetCookie(w, &cookie)
return nil
}
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, _, err := jwtauth.FromContext(r.Context())
if err != nil {
http.Error(w, "Could not find JWT token", http.StatusBadRequest)
return
}
if token == nil || !token.Valid {
http.Error(w, "Invalid JWT token", http.StatusBadRequest)
return
}
// Token is authenticated, pass it through
next.ServeHTTP(w, r)
})
}