-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
58 lines (53 loc) · 1.35 KB
/
common.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
package test
import (
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
m "github.com/saeedafshari8/authenticator/middleware"
"net/http"
"time"
)
func GetRouter() *gin.Engine {
r := gin.Default()
authInfo := &m.AuthInfo{
IdentityKey: "testIdentity",
Realm: "test Realm",
Secret: "secret",
TokenTimeout: time.Hour,
MaxRefresh: time.Hour,
Authenticator: MockAuthentication,
Authorizator: MockAuthorization,
}
r.Use(m.JwtAuthentication(authInfo, r).MiddlewareFunc())
{
r.POST("/v1/echo", func(c *gin.Context) {
var login m.Login
if err := c.ShouldBindJSON(&login); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, login)
})
}
return r
}
func MockAuthentication(login *m.Login) (*m.Account, error) {
if (login.Username == "admin" && login.Password == "admin") ||
(login.Username == "test" && login.Password == "test") {
return &m.Account{
Email: login.Username,
UserName: login.Username,
LastName: "Afshari",
FirstName: "Saeed",
}, nil
}
return nil, jwt.ErrFailedAuthentication
}
func MockAuthorization(account *m.Account, request *http.Request) (bool, error) {
if account.UserName == "admin" && request != nil {
return true, nil
}
return false, jwt.ErrForbidden
}
func init() {
gin.SetMode(gin.ReleaseMode)
}