1
1
package main
2
2
3
3
import (
4
- jwt_lib "github.com/dgrijalva/jwt-go"
5
- "github.com/gin-gonic/contrib/jwt"
4
+ _"fmt"
5
+ "github.com/dgrijalva/jwt-go"
6
+ "github.com/fatih/structs"
6
7
"github.com/gin-gonic/gin"
7
8
"github.com/gophergala2016/golin/login"
8
9
"github.com/gophergala2016/golin/tokens"
@@ -22,29 +23,41 @@ type Token struct {
22
23
Token string
23
24
}
24
25
26
+ type Claim struct {
27
+ Id string
28
+ exp int64
29
+ }
30
+
25
31
func (u User ) Login (user , password string ) (string , string ) {
26
32
if password == "qwerty" {
27
33
28
34
}
29
35
return "No" , "NO"
30
36
}
31
37
32
- func (t Token ) GenerateToken (SignatureStr string ) string {
33
- var tokenStr string
38
+ func (t Token ) GenerateToken (SignatureStr string ) (string , error ) {
39
+ var claim Claim
40
+
41
+ claim .Id = SignatureStr
42
+ claim .exp = time .Now ().Add (time .Hour * 1 ).Unix ()
34
43
35
- token := jwt_lib .New (jwt_lib .GetSigningMethod ("HS256" ))
36
- token .Claims ["ID" ] = SignatureStr
37
- token .Claims ["exp" ] = time .Now ().Add (time .Hour * 1 ).Unix ()
38
- tokenStr , _ = token .SignedString ([]byte (secret ))
44
+ alg := jwt .GetSigningMethod ("HS256" )
45
+ token := jwt .New (alg )
46
+ token .Claims = structs .Map (claim )
39
47
40
- return tokenStr
48
+ if tokenStr , err := token .SignedString ([]byte (secret )); err == nil {
49
+ return tokenStr , nil
50
+ } else {
51
+ return "" , err
52
+ }
53
+ //TODO Storage
41
54
}
42
55
43
56
func main () {
44
57
r := gin .Default ()
45
58
publics := r .Group ("api/v1/public" )
46
59
privates := r .Group ("api/v1/private" )
47
- privates .Use (jwt .Auth (secret ))
60
+ // privates.Use(jwt.Auth(secret)) //TODO Change by verify method
48
61
privates .GET ("/users/:id" , GetUser )
49
62
publics .POST ("/users" , LoginUser )
50
63
r .Run (":8080" )
@@ -53,6 +66,7 @@ func main() {
53
66
func LoginUser (c * gin.Context ) {
54
67
var user User
55
68
var loginer login.Loginer
69
+ var tokenStr string
56
70
57
71
var token Token
58
72
var tokener tokens.Tokener
@@ -63,8 +77,13 @@ func LoginUser(c *gin.Context) {
63
77
tokener = token
64
78
65
79
SignatureStr , email := loginer .Login (user .Username , user .Password )
66
- //token := tokens.GenerateToken(SignatureStr)
67
- c .JSON (201 , gin.H {"token" : tokener .GenerateToken (SignatureStr ), "email" : email })
80
+ tokenStr , err := tokener .GenerateToken (SignatureStr )
81
+
82
+ if err != nil {
83
+ c .JSON (404 , gin.H {"error" : err })
84
+ } else {
85
+ c .JSON (201 , gin.H {"token" : tokenStr , "email" : email })
86
+ }
68
87
69
88
}
70
89
0 commit comments