-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
73 lines (62 loc) · 1.72 KB
/
auth.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package handler
import (
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/rudeigerc/broker-gateway/service"
"github.com/satori/go.uuid"
"github.com/spf13/viper"
)
type authRequest struct {
FirmName string `json:"firm_name" binding:"required"`
ExpiresAt time.Time `json:"expires_at" binding:"required" time_format:"2006-01-02 15:04:05"`
}
type authResponse struct {
FirmID int `json:"firm_id"`
FirmName string `json:"firm_name"`
Credit int `json:"credit"`
Token string `json:"token"`
}
func AuthHandler(c *gin.Context) {
var req authRequest
if err := c.ShouldBindJSON(&req); err == nil {
firm := service.Auth{}.Sign(req.FirmName)
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
Audience: req.FirmName,
ExpiresAt: req.ExpiresAt.Unix(),
Id: uuid.NewV1().String(),
IssuedAt: time.Now().Unix(),
Subject: strconv.Itoa(firm.FirmID),
})
tokenString, _ := token.SignedString([]byte(viper.GetString("auth.secret")))
res := authResponse{
FirmID: firm.FirmID,
FirmName: firm.FirmName,
Credit: firm.Credit,
Token: tokenString,
}
c.JSON(http.StatusOK, gin.H{"data": res})
} else {
ErrorHandler(c, http.StatusBadRequest, "Invalid request message framing.")
}
}
func ValidationHandler(c *gin.Context) {
tokenString := c.Request.Header.Get("Authorization")
firm, err := validate(c)
if err != nil {
log.Print(err)
ErrorHandler(c, http.StatusUnauthorized, "Invalid token.")
return
}
res := authResponse{
FirmID: firm.FirmID,
FirmName: firm.FirmName,
Credit: firm.Credit,
Token: strings.Split(tokenString, " ")[1],
}
c.JSON(http.StatusOK, gin.H{"data": res})
}