-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.go
90 lines (69 loc) · 1.84 KB
/
server.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
package main
import (
"net/http"
"time"
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/binding"
"github.com/codegangsta/martini-contrib/render"
"github.com/dgrijalva/jwt-go"
)
// User model
type User struct {
UserId string `form:"userid" json:"userid" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
// Field validator
func (u *User) Validate(errors *binding.Errors, req *http.Request) {
if len(u.UserId) < 4 {
errors.Fields["userid"] = "Too short; minimum 4 characters"
}
}
const (
ValidUser = "John"
ValidPass = "Doe"
SecretKey = "WOW,MuchShibe,ToDogge"
)
func main() {
m := martini.Classic()
m.Use(martini.Static("static"))
m.Use(render.Renderer())
m.Get("/", func(r render.Render) {
r.HTML(201, "index", nil)
})
// Authenticate user
m.Post("/auth", binding.Bind(User{}), func(user User, r render.Render) {
if user.UserId == ValidUser && user.Password == ValidPass {
// Create JWT token
token := jwt.New(jwt.GetSigningMethod("HS256"))
token.Claims["userid"] = user.UserId
// Expire in 5 mins
token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix()
tokenString, err := token.SignedString([]byte(SecretKey))
if err != nil {
r.HTML(201, "error", nil)
return
}
data := map[string]string{
"token": tokenString,
}
r.HTML(201, "success", data)
} else {
r.HTML(201, "error", nil)
}
})
// Check Key is ok
m.Get("/debug/:token", func(params martini.Params, r render.Render) string {
token, err := jwt.Parse(params["token"], func(token *jwt.Token) ([]byte, error) {
return []byte(SecretKey), nil
})
if err == nil && token.Valid {
return "User id: " + token.Claims["userid"].(string)
} else {
return "Invalid"
}
})
// Only accesible if authenticated
m.Post("/secret", func() {
})
m.Run()
}