@@ -2,7 +2,11 @@ package handlers
2
2
3
3
import (
4
4
"crypto/rand"
5
+ "errors"
6
+ "fmt"
7
+ "strings"
5
8
9
+ jwt "github.com/dgrijalva/jwt-go"
6
10
scheduler "github.com/gaia-pipeline/gaia/scheduler"
7
11
"github.com/gaia-pipeline/gaia/store"
8
12
"github.com/kataras/iris"
@@ -12,6 +16,10 @@ const (
12
16
apiVersion = "v1"
13
17
)
14
18
19
+ var (
20
+ errNotAuthorized = errors .New ("no or invalid jwt token provided. You are not authorized" )
21
+ )
22
+
15
23
// storeService is an instance of store.
16
24
// Use this to talk to the store.
17
25
var storeService * store.Store
@@ -53,5 +61,54 @@ func InitHandlers(i *iris.Application, store *store.Store, scheduler *scheduler.
53
61
i .Get (p + "pipelines/start/{id:string}" , PipelineStart )
54
62
i .Get (p + "pipelines/runs/{pipelineid:string}" , PipelineGetAllRuns )
55
63
64
+ // Authentication Barrier
65
+ i .UseGlobal (authBarrier )
66
+
56
67
return nil
57
68
}
69
+
70
+ // authBarrier is the middleware which prevents user exploits.
71
+ // It makes sure that the request contains a valid jwt token.
72
+ // TODO: Role based access
73
+ func authBarrier (ctx iris.Context ) {
74
+ // Login resource is open
75
+ if strings .Contains (ctx .Path (), "users/login" ) {
76
+ ctx .Next ()
77
+ return
78
+ }
79
+
80
+ // Get JWT token
81
+ jwtRaw := ctx .GetHeader ("Authorization" )
82
+ split := strings .Split (jwtRaw , " " )
83
+ if len (split ) != 2 {
84
+ ctx .StatusCode (iris .StatusForbidden )
85
+ ctx .WriteString (errNotAuthorized .Error ())
86
+ return
87
+ }
88
+ jwtString := split [1 ]
89
+
90
+ // Parse token
91
+ token , err := jwt .Parse (jwtString , func (token * jwt.Token ) (interface {}, error ) {
92
+ // Validate signing method
93
+ if _ , ok := token .Method .(* jwt.SigningMethodHMAC ); ! ok {
94
+ return nil , fmt .Errorf ("unexpected signing method: %v" , token .Header ["alg" ])
95
+ }
96
+
97
+ // return secret
98
+ return jwtKey , nil
99
+ })
100
+ if err != nil {
101
+ ctx .StatusCode (iris .StatusForbidden )
102
+ ctx .WriteString (err .Error ())
103
+ return
104
+ }
105
+
106
+ // Validate token
107
+ if _ , ok := token .Claims .(jwt.MapClaims ); ok && token .Valid {
108
+ // All ok, continue
109
+ ctx .Next ()
110
+ } else {
111
+ ctx .StatusCode (iris .StatusForbidden )
112
+ ctx .WriteString (errNotAuthorized .Error ())
113
+ }
114
+ }
0 commit comments