Skip to content

Instantly share code, notes, and snippets.

@luisnquin
Last active December 31, 2021 01:22
Show Gist options
  • Save luisnquin/4764e8027c340636602f67d1263e5b91 to your computer and use it in GitHub Desktop.
Save luisnquin/4764e8027c340636602f67d1263e5b91 to your computer and use it in GitHub Desktop.
package auth
import (
"crypto/rsa"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
"playground/models"
)
var (
privateKey *rsa.PrivateKey
publicKey *rsa.PublicKey
)
func init() {
privateBytes, err := ioutil.ReadFile("./private.rsa")
if err != nil {
panic(err)
}
publicBytes, err := ioutil.ReadFile("./public.rsa.pub")
if err != nil {
panic(err)
}
privateKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateBytes)
if err != nil {
panic(err)
}
publicKey, err = jwt.ParseRSAPublicKeyFromPEM(publicBytes)
if err != nil {
panic(err)
}
}
func GenerateToken(client models.Client) (string, error) {
claims := models.Claim{
Client: client,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
Issuer: "User authenticated",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
result, err := token.SignedString(privateKey)
if err != nil {
return "", err
}
return result, nil
}
func Login(w http.ResponseWriter, r *http.Request) {
var client models.Client
err := json.NewDecoder(r.Body).Decode(&client)
if err != nil {
log.Println(err)
}
if client.Username == "alexys" && client.Password == "alexys" {
client.Password = ""
client.Email = "[email protected]"
token, err := GenerateToken(client)
if err != nil {
log.Fatal(err)
}
result := models.ResponseToken{Token: token}
jsonResult, err := json.Marshal(&result)
if err != nil {
log.Println(err)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(jsonResult)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
func ValidateToken(w http.ResponseWriter, r *http.Request) {
token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &models.Claim{}, func(token *jwt.Token) (interface{}, error) {
return publicKey, nil
})
if err != nil {
switch err.(type) {
case *jwt.ValidationError:
vErr := err.(jwt.ValidationError)
switch vErr.Errors {
case jwt.ValidationErrorExpired:
log.Println("Token expired")
return
case jwt.ValidationErrorSignatureInvalid:
log.Println("Token expired")
return
default:
log.Println("Invalid token")
return
}
}
}
if token.Valid {
w.WriteHeader(http.StatusAccepted)
log.Println("Welcome!")
} else {
w.WriteHeader(http.StatusForbidden)
log.Println("Ups")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment