-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
126 lines (98 loc) · 3.95 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"Permission-Based-Two-Factor/apis/userAPI"
"Permission-Based-Two-Factor/entities"
"Permission-Based-Two-Factor/models"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"github.com/urfave/negroni"
)
func main() {
r := mux.NewRouter()
//Declaring all APIs endpoints and methods they accetp
r.HandleFunc("/api/user/authenticate", userAPI.CreateToken).Methods("POST")
r.HandleFunc("/api/user/register", userAPI.RegisterUser).Methods("POST")
r.HandleFunc("/api/user/forgot_password", userAPI.ForgotPassword).Methods("GET")
r.HandleFunc("/api/user/forgot_password", userAPI.ForgotPassword).Methods("POST")
r.HandleFunc("/api/user/security_questions", ValidateEmailConfirmation(userAPI.SecurityQuestions)).Methods("GET")
r.HandleFunc("/api/user/security_questions", ValidateEmailConfirmation(userAPI.SecurityQuestions)).Methods("POST")
r.HandleFunc("/api/user/change_password", ValidateEmailConfirmation(userAPI.ChangePassword)).Methods("GET")
r.HandleFunc("/api/user/change_password", ValidateEmailConfirmation(userAPI.ChangePassword)).Methods("POST")
r.HandleFunc("/api/user/add_device", ValidateMiddleware(userAPI.AddDevice)).Methods("POST")
r.HandleFunc("/api/user/login", userAPI.WebLogin).Methods("GET")
r.HandleFunc("/api/user/login", userAPI.WebLogin).Methods("POST")
r.HandleFunc("/api/user/post_login", userAPI.PostLogin).Methods("GET")
r.HandleFunc("/api/user/verify_device", ValidateMiddleware(userAPI.VerifyDevice)).Methods("POST")
r.HandleFunc("/api/user/all_devices", ValidateMiddleware(userAPI.GetAllDevices)).Methods("GET")
n := negroni.Classic()
n.UseHandler(r)
n.Run(":5000")
}
//Function wrapper that protects endpoints that require the user to have a JWT token in authorization header
func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
authorizationHeader := req.Header.Get("authorization")
if authorizationHeader != "" {
bearerToken := strings.Split(authorizationHeader, " ")
if len(bearerToken) == 2 {
token, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("There was an error")
}
return []byte("secret"), nil
})
if error != nil {
json.NewEncoder(w).Encode(models.Exception{Message: error.Error()})
return
}
if token.Valid {
context.Set(req, "decoded", token.Claims)
next(w, req)
} else {
json.NewEncoder(w).Encode(models.Exception{Message: "Invalid authorization token"})
}
}
} else {
json.NewEncoder(w).Encode(models.Exception{Message: "An authorization header is required"})
}
})
}
//Wrapper function used to verify forgot password url sent in email to user
//Decodes base64 encoded JWT token for validation
func ValidateEmailConfirmation(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
keys, err := req.URL.Query()["token"]
if !err || len(keys[0]) == 0 {
json.NewEncoder(w).Encode(entities.Message{Message: "Error, no token provided"})
} else {
decodedToken, tokErr := base64.StdEncoding.DecodeString(keys[0])
if tokErr != nil {
fmt.Println("Error decoding")
} else {
token, error := jwt.Parse(string(decodedToken), func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Error occurred")
} else {
return []byte("secret"), nil
}
})
if error != nil {
json.NewEncoder(w).Encode(models.Exception{Message: error.Error()})
return
}
if token.Valid {
context.Set(req, "decoded", token.Claims)
next(w, req)
} else {
json.NewEncoder(w).Encode(models.Exception{Message: "Invalid authorization token"})
}
}
}
})
}