Implement split tokens that work with curl

This commit is contained in:
Amarpreet Minhas 2019-10-05 20:21:48 -04:00
parent ada62e95e2
commit 8a897dc16f

View file

@ -12,6 +12,7 @@ import (
"github.com/go-chi/render"
"golang.org/x/crypto/bcrypt"
"net/http"
"strings"
"time"
)
@ -42,7 +43,6 @@ type Claims struct {
type JWT struct {
JWT string `json:"jwt"`
Username string `json:"username"`
}
func Init() {
@ -114,9 +114,8 @@ func register(w http.ResponseWriter, r *http.Request) {
},
}
_, tokenString, _ := TokenAuth.Encode(claims)
token := JWT{
JWT: tokenString,
}
token := setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, token)
}
@ -141,7 +140,6 @@ func signin(w http.ResponseWriter, r *http.Request) {
if err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password)); err != nil {
w.WriteHeader(http.StatusUnauthorized)
}
w.WriteHeader(http.StatusOK)
expirationTime := time.Now().Add(5 * time.Hour)
claims := &Claims{
Username: creds.Username,
@ -150,10 +148,8 @@ func signin(w http.ResponseWriter, r *http.Request) {
},
}
_, tokenString, _ := TokenAuth.Encode(claims)
token := JWT{
JWT: tokenString,
Username: creds.Username,
}
token := setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, token)
}
@ -168,8 +164,16 @@ func refresh(w http.ResponseWriter, r *http.Request) {
},
}
_, tokenString, _ := TokenAuth.Encode(newClaims)
token := JWT{
JWT: tokenString,
}
token := setCookies(w, tokenString, expirationTime)
w.WriteHeader(http.StatusOK)
render.JSON(w, r, token)
}
func setCookies(w http.ResponseWriter, jwt string, expiration time.Time) string {
splitToken := strings.Split(jwt, ".")
dataCookie := http.Cookie{Name: "DataCookie", Value: strings.Join(splitToken[:2], "."), Expires: expiration, HttpOnly: false, Path: "/"}
http.SetCookie(w, &dataCookie)
signatureCookie := http.Cookie{Name: "SignatureCookie", Value: splitToken[2], Expires: expiration, HttpOnly: true, Path: "/"}
http.SetCookie(w, &signatureCookie)
return strings.Join(splitToken[:2], ".")
}