Add refresh

This commit is contained in:
Amarpreet Minhas 2019-04-14 12:44:02 -04:00
parent 4f0834c3a0
commit a9b09ce4da
2 changed files with 31 additions and 9 deletions

View file

@ -40,7 +40,7 @@ type Claims struct {
jwt.StandardClaims jwt.StandardClaims
} }
type ReturnToken struct { type JWT struct {
JWT string `json:"jwt"` JWT string `json:"jwt"`
} }
@ -49,13 +49,18 @@ func Init() {
} }
func Routes() *chi.Mux { func Routes() *chi.Mux {
router := chi.NewRouter() r := chi.NewRouter()
router.Post("/signin", signin) r.Post("/signin", signin)
router.Post("/signup", signup) r.Post("/register", register)
return router r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(TokenAuth))
r.Use(jwtauth.Authenticator)
r.Post("/refresh", refresh)
})
return r
} }
func signup(w http.ResponseWriter, r *http.Request) { func register(w http.ResponseWriter, r *http.Request) {
returnError := RegistrationError{} returnError := RegistrationError{}
creds := &SignUpCredentials{} creds := &SignUpCredentials{}
err := json.NewDecoder(r.Body).Decode(creds) err := json.NewDecoder(r.Body).Decode(creds)
@ -108,7 +113,7 @@ func signup(w http.ResponseWriter, r *http.Request) {
}, },
} }
_, tokenString, _ := TokenAuth.Encode(claims) _, tokenString, _ := TokenAuth.Encode(claims)
token := ReturnToken{ token := JWT{
JWT: tokenString, JWT: tokenString,
} }
render.JSON(w, r, token) render.JSON(w, r, token)
@ -148,7 +153,24 @@ func signin(w http.ResponseWriter, r *http.Request) {
}, },
} }
_, tokenString, _ := TokenAuth.Encode(claims) _, tokenString, _ := TokenAuth.Encode(claims)
token := ReturnToken{ token := JWT{
JWT: tokenString,
}
render.JSON(w, r, token)
}
func refresh(w http.ResponseWriter, r *http.Request) {
_, claims, _ := jwtauth.FromContext(r.Context())
w.WriteHeader(http.StatusOK)
expirationTime := time.Now().Add(5 * time.Hour)
newClaims := &Claims{
Username: claims["username"].(string),
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
_, tokenString, _ := TokenAuth.Encode(newClaims)
token := JWT{
JWT: tokenString, JWT: tokenString,
} }
render.JSON(w, r, token) render.JSON(w, r, token)

View file

@ -58,7 +58,7 @@ func getUser(w http.ResponseWriter, r *http.Request) {
func updateUser(w http.ResponseWriter, r *http.Request) { func updateUser(w http.ResponseWriter, r *http.Request) {
_, claims, _ := jwtauth.FromContext(r.Context()) _, claims, _ := jwtauth.FromContext(r.Context())
username := claims["username"] username := claims["username"].(string)
searchname := chi.URLParam(r, "username") searchname := chi.URLParam(r, "username")
if username != searchname { if username != searchname {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)