-
Notifications
You must be signed in to change notification settings - Fork 98
/
main.go
173 lines (144 loc) · 4.05 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// PLEASE REFER THE SOURCE AT https://github.com/shijuvar/go-web/blob/master/taskmanager/common/auth.go
// in which I have updated the source for latest API changes of go-jwt package.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
)
// using asymmetric crypto/RSA keys
// location of the files used for signing and verification
const (
privKeyPath = "keys/app.rsa" // openssl genrsa -out app.rsa keysize
pubKeyPath = "keys/app.rsa.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub
)
// verify key and sign key
var (
verifyKey, signKey []byte
)
//struct User for parsing login credentials
type User struct {
UserName string `json:"username"`
Password string `json:"password"`
}
// read the key files before starting http handlers
func init() {
var err error
signKey, err = ioutil.ReadFile(privKeyPath)
if err != nil {
log.Fatal("Error reading private key")
return
}
verifyKey, err = ioutil.ReadFile(pubKeyPath)
if err != nil {
log.Fatal("Error reading public key")
return
}
}
// reads the login credentials, checks them and creates the JWT token
func loginHandler(w http.ResponseWriter, r *http.Request) {
var user User
//decode into User struct
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Error in request body")
return
}
// validate user credentials
if user.UserName != "shijuvar" && user.Password != "pass" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintln(w, "Wrong info")
return
}
// create a signer for rsa 256
t := jwt.New(jwt.GetSigningMethod("RS256"))
// set our claims
t.Claims["iss"] = "admin"
t.Claims["CustomUserInfo"] = struct {
Name string
Role string
}{user.UserName, "Member"}
// set the expire time
t.Claims["exp"] = time.Now().Add(time.Minute * 20).Unix()
tokenString, err := t.SignedString(signKey)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Sorry, error while Signing Token!")
log.Printf("Token Signing error: %v\n", err)
return
}
response := Token{tokenString}
jsonResponse(response, w)
}
// only accessible with a valid token
func authHandler(w http.ResponseWriter, r *http.Request) {
// validate the token
token, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
// since we only use one private key to sign the tokens,
// we also only use its public counter part to verify
return verifyKey, nil
})
if err != nil {
switch err.(type) {
case *jwt.ValidationError: // something was wrong during the validation
vErr := err.(*jwt.ValidationError)
switch vErr.Errors {
case jwt.ValidationErrorExpired:
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintln(w, "Token Expired, get a new one.")
return
default:
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Error while Parsing Token!")
log.Printf("ValidationError error: %+v\n", vErr.Errors)
return
}
default: // something else went wrong
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(w, "Error while Parsing Token!")
log.Printf("Token parse error: %v\n", err)
return
}
}
if token.Valid {
response := Response{"Authorized to the system"}
jsonResponse(response, w)
} else {
response := Response{"Invalid token"}
jsonResponse(response, w)
}
}
type Response struct {
Text string `json:"text"`
}
type Token struct {
Token string `json:"token"`
}
func jsonResponse(response interface{}, w http.ResponseWriter) {
json, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write(json)
}
//Entry point of the program
func main() {
r := mux.NewRouter()
r.HandleFunc("/login", loginHandler).Methods("POST")
r.HandleFunc("/auth", authHandler).Methods("POST")
server := &http.Server{
Addr: ":8080",
Handler: r,
}
log.Println("Listening...")
server.ListenAndServe()
}