-
Notifications
You must be signed in to change notification settings - Fork 1
/
auth.go
67 lines (52 loc) · 1.53 KB
/
auth.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package controllers
import (
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/ernestio/api-gateway/helpers"
h "github.com/ernestio/api-gateway/helpers"
"github.com/ernestio/api-gateway/models"
"github.com/labstack/echo"
)
// Secret : TODO
var Secret string
// AuthenticatedUser : Get the authenticated user from the JWT Token
func AuthenticatedUser(c echo.Context) models.User {
var u models.User
user := c.Get("user").(*jwt.Token)
claims, ok := user.Claims.(jwt.MapClaims)
if ok {
u.Username = claims["username"].(string)
u.Admin = helpers.Bool(claims["admin"].(bool))
}
return u
}
// AuthenticateHandler manages user authentication
func AuthenticateHandler(c echo.Context) error {
var u models.User
err := c.Bind(&u)
if err != nil {
return echo.NewHTTPError(400, err.Error())
}
err = u.Validate()
if err != nil {
h.L.Error(err.Error())
return echo.NewHTTPError(400, err.Error())
}
res, err := u.Authenticate()
if err != nil {
h.L.Error(err.Error())
return echo.NewHTTPError(400, err.Error())
}
if !res.OK {
h.L.Error(res.Message + " (" + u.Username + ")")
return echo.NewHTTPError(403, res.Message)
}
if err := h.ValidCliVersion(c.Request()); err != nil {
h.L.Error(err.Error())
return echo.NewHTTPError(403, err.Error())
}
return c.JSON(http.StatusOK, map[string]string{"token": res.Token})
}