-
Notifications
You must be signed in to change notification settings - Fork 0
/
authhandler.go
47 lines (38 loc) · 1.14 KB
/
authhandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package handlers
import (
"fmt"
"net/http"
"time"
"github.com/dgrijalva/jwt-go"
)
//mySigningKey can be sent from secure place as env variable this has to match the variable sent by the client
var mySigningKey = []byte("ultimateStarAjith")
//AuthHandler handles all the operations related to the JWT Tokens
type AuthHandler struct {
}
//NewMiddlewareHandler returns a new instance of the middleware Handler
func NewMiddlewareHandler() *AuthHandler {
return &AuthHandler{}
}
//GenerateToken generates a new JWT Token
func (handler *AuthHandler) GenerateToken(w http.ResponseWriter, r *http.Request) {
tokenString, err := GenerateJWT()
if err != nil {
fmt.Println("error occured while generating the token string")
}
fmt.Fprintf(w, tokenString)
}
//GenerateJWT generates JWT Token
func GenerateJWT() (string, error) {
token := jwt.New(jwt.SigningMethodHS256)
claims := token.Claims.(jwt.MapClaims)
claims["authorized"] = true
claims["user"] = "Niroop"
claims["exp"] = time.Now().Add(time.Minute * 30).Unix()
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
fmt.Println(err)
return "", err
}
return tokenString, nil
}