github.com/iron-io/functions@v0.0.0-20180820112432-d59d7d1c40b2/examples/blog/routes/server.go (about) 1 package route 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "os" 7 "strings" 8 "time" 9 10 "github.com/dgrijalva/jwt-go" 11 "github.com/iron-io/functions/examples/blog/database" 12 "github.com/iron-io/functions/examples/blog/models" 13 "golang.org/x/crypto/bcrypt" 14 ) 15 16 var jwtSignKey = []byte("mysecretblog") 17 18 type Response map[string]interface{} 19 20 func SendResponse(resp Response) { 21 data, _ := json.Marshal(resp) 22 fmt.Println(string(data)) 23 } 24 25 func SendError(err interface{}) { 26 SendResponse(Response{ 27 "error": err, 28 }) 29 } 30 31 func HandleToken(db *database.Database) { 32 var login *models.User 33 34 if err := json.NewDecoder(os.Stdin).Decode(&login); err != nil { 35 fmt.Printf("Couldn't decode login JSON: %v\n", err) 36 return 37 } 38 39 user, err := db.GetUser(login.Username) 40 if err != nil { 41 SendError("Couldn't create a token") 42 return 43 } 44 45 if err := bcrypt.CompareHashAndPassword(user.Password, []byte(login.NewPassword)); err != nil { 46 SendError("Couldn't create a token") 47 return 48 } 49 50 token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ 51 "user": login.Username, 52 "exp": time.Now().Add(1 * time.Hour), 53 }) 54 55 // Sign and get the complete encoded token as a string using the secret 56 tokenString, err := token.SignedString(jwtSignKey) 57 if err != nil { 58 SendError("Couldn't create a token") 59 return 60 } 61 62 SendResponse(Response{"token": tokenString}) 63 } 64 65 func Authentication() (map[string]interface{}, bool) { 66 authorization := os.Getenv("HEADER_AUTHORIZATION") 67 68 p := strings.Split(authorization, " ") 69 if len(p) <= 1 { 70 return nil, false 71 } 72 73 token, err := jwt.Parse(p[1], func(token *jwt.Token) (interface{}, error) { 74 if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { 75 return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) 76 } 77 return jwtSignKey, nil 78 }) 79 80 if err != nil { 81 return nil, false 82 } 83 84 if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { 85 return claims, true 86 } 87 88 return nil, false 89 }