2019-01-10 18:57:21 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
jwt "github.com/dgrijalva/jwt-go"
|
|
|
|
)
|
|
|
|
|
|
|
|
var mySigningKey = []byte("DoTokenowDlaUszytkownikow")
|
|
|
|
|
|
|
|
func GenerateJWT(_login string) (string, error) {
|
2019-01-12 20:42:29 +01:00
|
|
|
//generowanie tokena jwt
|
2019-01-10 18:57:21 +01:00
|
|
|
token := jwt.New(jwt.SigningMethodHS256)
|
|
|
|
claims := token.Claims.(jwt.MapClaims)
|
|
|
|
|
|
|
|
claims["authorized"] = true
|
|
|
|
claims["user"] = _login
|
|
|
|
claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
|
|
|
|
|
|
|
|
tokenString, err := token.SignedString(mySigningKey)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println("[generateJWT][Error] Nie mozna wygenerować")
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return tokenString, nil
|
|
|
|
}
|
|
|
|
|
2019-01-12 20:42:29 +01:00
|
|
|
func isTokenValid(tokenString string) (bool, error) {
|
2019-01-10 18:57:21 +01:00
|
|
|
//sprawdza czy podany token jest pawidlowy
|
2019-01-12 20:42:29 +01:00
|
|
|
if tokenString != "" { //JWT Parse przyjmuje stroinga, bo header norlanie jest lista, a ja mu tu wyluskane stringa dam
|
|
|
|
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { //sprawdzanie tokena
|
2019-01-10 18:57:21 +01:00
|
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
|
|
return nil, fmt.Errorf("There was an error ")
|
|
|
|
}
|
|
|
|
//jesli token jest ok
|
|
|
|
return mySigningKey, nil //zwraca token, do zmiennej 'token'
|
|
|
|
}) //koniec dunkcji zwracajacej token
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err.Error())
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if token.Valid {
|
|
|
|
//jesli token prawidlowy, to zwraca true
|
2019-01-12 20:42:29 +01:00
|
|
|
return true, nil
|
|
|
|
} else {
|
2019-01-10 18:57:21 +01:00
|
|
|
fmt.Println("[isTokenValid] Nieprawidłowy token")
|
2019-01-12 20:42:29 +01:00
|
|
|
return false, nil
|
2019-01-10 18:57:21 +01:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2019-01-12 20:42:29 +01:00
|
|
|
return false, nil
|
2019-01-10 18:57:21 +01:00
|
|
|
|
|
|
|
}
|