-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
178 lines (141 loc) · 4.35 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package api
import (
"crypto/rsa"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/momocomics/backend/pkg/config"
"github.com/momocomics/backend/pkg/entity"
)
const (
JwtTtl = 1 * time.Minute
Issuer = "momocomic-backend"
CookieTokenEntry = "token"
JwtExpiry = 30 * time.Second
)
//TODO: use real db
var users = map[string]string{
"user1": "password1",
"user2": "password2",
}
func SigninFn(cfg *config.ServerConfig) func(*gin.Context) {
return func(c *gin.Context) {
var account entity.Account
err := json.NewDecoder(c.Request.Body).Decode(&account)
if err != nil {
c.Writer.WriteHeader(http.StatusBadRequest)
c.Writer.WriteString("User account info not in JSON format")
return
}
//TODO:read from db
pwd, ok := users[account.Username]
if !ok || pwd != account.Password {
c.Writer.WriteHeader(http.StatusUnauthorized)
return
}
tokenString, err := signToken(c.Request, account, cfg.PrivateKey())
if err != nil {
c.Writer.WriteHeader(http.StatusInternalServerError)
c.Writer.WriteString("error while signing token")
log.Printf("Token signing error: %v\n", err)
return
}
/*
// true means no scripts, http requests only. This has
// nothing to do with https vs http
HttpOnly: true,
// Defaults to host-only, which means exact subdomain
// matching. Only change this to enable subdomains if you
// need to! The below code would work on any subdomain for
// yoursite.com
Domain: "yoursite.com",
// Defaults to any path on your app, but you can use this
// to limit to a specific subdirectory. Eg:
Path: "/app/",
*/
c.SetCookie(CookieTokenEntry, tokenString, int(JwtTtl.Seconds()), "/", cfg.Domain(), true, true)
//c.Header("Content-Type", "application/jwt")
//c.Writer.WriteHeader(http.StatusOK)
if cfg.IsDebug() {
c.JSON(http.StatusOK, fmt.Sprintf("Token: %s", tokenString))
}
}
}
func signToken(r *http.Request, account entity.Account, key *rsa.PrivateKey) (string, error) {
c := &entity.Claims{
Username: account.Username,
UserAgent: r.UserAgent(),
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(JwtTtl).Unix(),
Id: uuid.New().String(),
IssuedAt: time.Now().Unix(),
Issuer: Issuer,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
return token.SignedString(key)
}
func VerifyToken(token string, key *rsa.PublicKey) (*entity.Claims, error) {
claims := &entity.Claims{}
t, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (i interface{}, e error) {
return key, nil
})
if err != nil {
return nil, fmt.Errorf("couldn't parse token: %v", err)
}
if !t.Valid {
return nil, fmt.Errorf("token is invalid")
}
return claims, nil
}
func RefreshTokenFn(cfg *config.ServerConfig) func(*gin.Context) {
return func(c *gin.Context) {
token, err := c.Cookie(CookieTokenEntry)
if err != nil {
c.Writer.WriteHeader(http.StatusBadRequest)
c.Writer.WriteString("Token not in cookie")
return
}
_, err = VerifyToken(token, cfg.PublicKey())
if err != nil {
c.Writer.WriteHeader(http.StatusUnauthorized)
c.Writer.WriteString(err.Error())
return
}
tokenString, err := refreshToken(token, cfg.PublicKey(), cfg.PrivateKey())
if err != nil {
c.Writer.WriteHeader(http.StatusInternalServerError)
c.Writer.WriteString("error while signing token")
log.Printf("Token refreshing error: %v\n", err)
return
}
c.SetCookie(CookieTokenEntry, tokenString, int(JwtTtl.Seconds()), "/", cfg.Domain(), true, true)
if cfg.IsDebug() {
c.JSON(http.StatusOK, fmt.Sprintf("Token: %s", tokenString))
}
}
}
func refreshToken(token string, pubKey *rsa.PublicKey, privKey *rsa.PrivateKey) (string, error) {
claims, err := VerifyToken(token, pubKey)
if err != nil {
return "", err
}
if time.Unix(claims.ExpiresAt, 0).Sub(time.Now()) > JwtExpiry {
return "", fmt.Errorf("token expired more than %v seconds", JwtExpiry.Seconds())
}
claims.ExpiresAt = time.Now().Add(JwtTtl).Unix()
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return t.SignedString(privKey)
}
func IsExpired(token string, key *rsa.PublicKey) (bool, error) {
claims, err := VerifyToken(token, key)
if err != nil {
return false, err
}
return claims.ExpiresAt > time.Now().Unix(), nil
}