-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth_controller.go
136 lines (125 loc) · 4.56 KB
/
auth_controller.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
124
125
126
127
128
129
130
131
132
133
134
135
136
package http
import (
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/jinzhu/gorm"
"github.com/labstack/echo"
"go-echo-api/auth"
"go-echo-api/infrastructure/response"
"go-echo-api/middleware"
"go-echo-api/utils"
"gopkg.in/go-playground/validator.v9"
"os"
)
type authController struct {
authRepository auth.Repository
authMapper *auth.Mapper
}
func NewAuthController(s auth.Repository) *authController {
return &authController{authRepository: s,
authMapper: auth.NewAuthMapper(),
}
}
func (c *authController) Login(ctx echo.Context) error {
var dto auth.LoginDto
if err := ctx.Bind(&dto); err != nil {
return response.InternalServerError(ctx, utils.InternalServerError, nil, err.Error())
}
if err := ctx.Validate(dto); err != nil {
errorData := make(echo.Map)
for _, v := range err.(validator.ValidationErrors) {
errorData[v.Field()] = v.Tag()
}
return response.ValidationError(ctx, utils.ValidationError, nil, err.Error())
}
result, err := c.authRepository.Login(dto.Email)
if err != nil {
return response.InternalServerError(ctx, utils.InternalServerError, nil, err.Error())
}
if !utils.CheckPasswordHash(dto.Password, result.Password) {
return response.BadRequest(ctx, utils.BadRequest, nil, "Wrong username or password")
}
tokens, refreshToken, expire, err := middleware.GenerateTokenPair(result)
if err != nil {
return response.InternalServerError(ctx, utils.InternalServerError, nil, err.Error())
}
return response.SingleData(ctx, utils.OK, echo.Map{"access_token": tokens, "refresh_token": refreshToken, "expire": expire},
nil)
}
func (c *authController) Register(ctx echo.Context) error {
var dto auth.RegisterDto
if err := ctx.Bind(&dto); err != nil {
return response.InternalServerError(ctx, utils.InternalServerError, nil, err.Error())
}
if err := ctx.Validate(dto); err != nil {
errorData := make(echo.Map)
for _, v := range err.(validator.ValidationErrors) {
errorData[v.Field()] = v.Tag()
}
return response.ValidationError(ctx, utils.ValidationError, nil, err.Error())
}
result, err := c.authRepository.Register(dto)
if err != nil {
return response.InternalServerError(ctx, utils.InternalServerError, nil, err.Error())
}
return response.SingleData(ctx, utils.OK, c.authMapper.Map(result), nil)
}
func (c *authController) RefreshToken(ctx echo.Context) error {
type tokenReqBody struct {
RefreshToken string `json:"refresh_token"`
}
tokenReq := tokenReqBody{}
if err := ctx.Bind(&tokenReq); err != nil {
errors := make([]echo.Map, 1)
if he, ok := err.(*echo.HTTPError); ok {
if ute, ok := he.Internal.(*json.UnmarshalTypeError); ok {
errors[0] = echo.Map{
"field": ute.Field,
"message": ute.Error(),
}
return response.InternalServerError(ctx, utils.InternalServerError, errors, err.Error())
}
if se, ok := he.Internal.(*json.SyntaxError); ok {
errors[0] = echo.Map{
"error_type": "SyntaxError",
"message": se.Error(),
}
return response.InternalServerError(ctx, utils.InternalServerError, errors, err.Error())
}
}
return response.InternalServerError(ctx, utils.InternalServerError, nil, err.Error())
}
// Parse takes the token string and a function for looking up the key.
// The latter is especially useful if you use multiple keys for your application.
// The standard is to use 'kid' in the head of the token to identify
// which key to use, but the parsed token (head and claims) is provided
// to the callback, providing flexibility.
token, err := jwt.Parse(tokenReq.RefreshToken, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(os.Getenv("JWT_SECRET_KEY")), nil
})
if err != nil {
return response.Unauthorized(ctx, utils.Unauthorized, nil, "Token not valid or expired")
}
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
// Get the user record from database or
// run through your business logic to verify if the user can log in
email := claims["email"]
result, err := c.authRepository.Login(email.(string))
if gorm.IsRecordNotFoundError(err) {
return response.Unauthorized(ctx, utils.Unauthorized, nil, err.Error())
}
newTokenPair, newRefreshToken, newExpire, err := middleware.GenerateTokenPair(result)
if err != nil {
return err
}
return response.SingleData(ctx, utils.OK, echo.Map{
"access_token": newTokenPair, "refresh_token": newRefreshToken, "expire": newExpire,
}, nil)
}
return err
}