Last active
February 14, 2017 08:19
-
-
Save FredrikAugust/fb94f7d209adc885c0d4dd7465cbb9d0 to your computer and use it in GitHub Desktop.
jwtgoauth.go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"github.com/dgrijalva/jwt-go" | |
"github.com/gorilla/mux" | |
) | |
// User model | |
type User struct { | |
ID int | |
Name string | |
Age int | |
} | |
// UserClaims is the payload used in the jwt token | |
type UserClaims struct { | |
// Payload | |
UserID int `json:"userid"` | |
// Extend the default struct | |
jwt.StandardClaims | |
} | |
// Tells it to map string to a reference to the user (I think..) | |
var users = map[string]*User{ | |
"1": &User{ID: 1, Name: "John", Age: 12}, | |
"2": &User{ID: 2, Name: "Tom", Age: 22}, | |
} | |
func createToken(res http.ResponseWriter, req *http.Request) { | |
// Extract the user params from the request | |
vars := mux.Vars(req) | |
user, ok := users[vars["user"]] | |
// Does that user exist | |
if !ok { | |
res.WriteHeader(http.StatusNotFound) | |
fmt.Fprint(res, "User not found") | |
return | |
} | |
claims := UserClaims{ | |
user.ID, | |
jwt.StandardClaims{ | |
// Pretty long time from now | |
ExpiresAt: 1500000000000, | |
Issuer: "GOJSON", | |
}, | |
} | |
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | |
tokenString, err := token.SignedString([]byte("supahsecret")) | |
if err != nil { | |
res.WriteHeader(http.StatusInternalServerError) | |
fmt.Fprint(res, "Could not create token") | |
fmt.Printf(err.Error()) | |
return | |
} | |
res.WriteHeader(http.StatusOK) | |
fmt.Fprint(res, tokenString) | |
} | |
func validateToken(res http.ResponseWriter, req *http.Request) { | |
vars := mux.Vars(req) | |
token, err := jwt.ParseWithClaims(vars["token"], &UserClaims{}, func(token *jwt.Token) (interface{}, error) { | |
return []byte("supahsecret"), nil | |
}) | |
if claims, ok := token.Claims.(*UserClaims); ok && token.Valid { | |
res.WriteHeader(http.StatusOK) | |
fmt.Fprint(res, "Authenticated for user: ", claims.UserID) | |
} else { | |
res.WriteHeader(http.StatusUnauthorized) | |
fmt.Fprint(res, "Error encountered while parsing token: ", err) | |
} | |
} | |
func upload(res http.ResponseWriter, req *http.Request) { | |
// 32 MB I believe | |
req.ParseMultipartForm(32 << 20) | |
file, handler, err := req.FormFile("uploadfile") | |
if err != nil { | |
fmt.Println("Error encountered while parsing uploadfile: ", err) | |
return | |
} | |
defer file.Close() | |
f, err := os.OpenFile("./public/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) | |
if err != nil { | |
fmt.Println("Error encountered while opening uploadfile: ", err) | |
return | |
} | |
defer f.Close() | |
io.Copy(f, file) | |
res.WriteHeader(http.StatusOK) | |
} | |
func main() { | |
router := mux.NewRouter().StrictSlash(true) | |
// Register routes | |
router.HandleFunc("/api/create_token/{user}", createToken).Methods("GET") | |
router.HandleFunc("/api/validate_token/{token}", validateToken).Methods("GET") | |
router.HandleFunc("/api/upload", upload).Methods("POST") | |
log.Fatal(http.ListenAndServe(":8080", router)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta http-equiv="content-type" content="text/html; charset=utf-8"> | |
<title>Upload file</title> | |
</head> | |
<body> | |
<form action="http://localhost:8080/api/upload" method="POST" | |
enctype="multipart/form-data"> | |
<input type="file" name="uploadfile"> | |
<input type="submit" value="upload"> | |
</form> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment