-
Notifications
You must be signed in to change notification settings - Fork 341
/
main.go
123 lines (100 loc) · 3.28 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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
gommonlog "github.com/labstack/gommon/log"
)
var (
// ErrHttpGenericMessage that is returned in general case, details should be logged in such case
ErrHttpGenericMessage = echo.NewHTTPError(http.StatusInternalServerError, "something went wrong, please try again later")
// ErrWrongCredentials indicates that login attempt failed because of incorrect login or password
ErrWrongCredentials = echo.NewHTTPError(http.StatusUnauthorized, "username or password is invalid")
jwtSecret = "myfancysecret"
)
func main() {
hostport := ":" + os.Getenv("AUTH_API_PORT")
userAPIAddress := os.Getenv("USERS_API_ADDRESS")
envJwtSecret := os.Getenv("JWT_SECRET")
if len(envJwtSecret) != 0 {
jwtSecret = envJwtSecret
}
userService := UserService{
Client: http.DefaultClient,
UserAPIAddress: userAPIAddress,
AllowedUserHashes: map[string]interface{}{
"admin_admin": nil,
"johnd_foo": nil,
"janed_ddd": nil,
},
}
e := echo.New()
e.Logger.SetLevel(gommonlog.INFO)
if zipkinURL := os.Getenv("ZIPKIN_URL"); len(zipkinURL) != 0 {
e.Logger.Infof("init tracing to Zipkit at %s", zipkinURL)
if tracedMiddleware, tracedClient, err := initTracing(zipkinURL); err == nil {
e.Use(echo.WrapMiddleware(tracedMiddleware))
userService.Client = tracedClient
} else {
e.Logger.Infof("Zipkin tracer init failed: %s", err.Error())
}
} else {
e.Logger.Infof("Zipkin URL was not provided, tracing is not initialised")
}
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Use(middleware.CORS())
// Route => handler
e.GET("/version", func(c echo.Context) error {
return c.String(http.StatusOK, "Auth API, written in Go\n")
})
e.POST("/login", getLoginHandler(userService))
// Start server
e.Logger.Fatal(e.Start(hostport))
}
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
func getLoginHandler(userService UserService) echo.HandlerFunc {
f := func(c echo.Context) error {
requestData := LoginRequest{}
decoder := json.NewDecoder(c.Request().Body)
if err := decoder.Decode(&requestData); err != nil {
log.Printf("could not read credentials from POST body: %s", err.Error())
return ErrHttpGenericMessage
}
ctx := c.Request().Context()
user, err := userService.Login(ctx, requestData.Username, requestData.Password)
if err != nil {
if err != ErrWrongCredentials {
log.Printf("could not authorize user '%s': %s", requestData.Username, err.Error())
return ErrHttpGenericMessage
}
return ErrWrongCredentials
}
token := jwt.New(jwt.SigningMethodHS256)
// Set claims
claims := token.Claims.(jwt.MapClaims)
claims["username"] = user.Username
claims["firstname"] = user.FirstName
claims["lastname"] = user.LastName
claims["role"] = user.Role
claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(jwtSecret))
if err != nil {
log.Printf("could not generate a JWT token: %s", err.Error())
return ErrHttpGenericMessage
}
return c.JSON(http.StatusOK, map[string]string{
"accessToken": t,
})
}
return echo.HandlerFunc(f)
}