-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
86 lines (73 loc) · 1.87 KB
/
handler.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
package user
import (
"github.com/dgrijalva/jwt-go"
"github.com/labstack/echo"
"github.com/labstack/gommon/log"
"go-boilerplate/config"
"go-boilerplate/models"
"golang.org/x/oauth2"
"net/http"
"strconv"
"time"
)
var (
googleOauthConfig *oauth2.Config
/*
Set some random string for each request
*/
oauthStateString = "random"
)
type UHandler struct {
userUseCase *UserUseCase
}
func NewUserHandler(u *UserUseCase) *UHandler {
googleOauthConfig = getGOAuthConfig()
return &UHandler {
userUseCase: u,
}
}
func (userHandler* UHandler) LoginHandler(c echo.Context) error {
url := googleOauthConfig.AuthCodeURL(oauthStateString)
return c.Redirect(http.StatusTemporaryRedirect, url)
}
func (userHandler* UHandler) LoginCallbackHandler(c echo.Context) error {
/*
Get OAuth config from here
*/
user := new(models.User)
tkn, e := getJWToken(user)
if e != nil {
log.Warn("Trouble converting json", e)
}
c.SetCookie(getCookie(tkn))
return c.String(http.StatusOK, tkn)
}
func getJWToken(u *models.User) (string, error) {
expTime, _ := strconv.Atoi(config.GetConfig("JWT_TOKEN_EXP_TIME_HOURS"))
claims := &models.JWTClaims {
Name: u.Name,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Duration(expTime) * time.Hour).Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(config.GetConfig("JWT_SECRET")))
if err != nil {
return "", err
}
return tokenString, nil
}
func getGOAuthConfig() *oauth2.Config {
return &oauth2.Config{
}
}
func getCookie(token string) *http.Cookie {
cookie := new(http.Cookie)
cookie.Name = config.GetConfig("JWT_COOKIE_NAME")
cookie.Value = token
cookie.HttpOnly = true
cookie.Secure = true
expTime, _ := strconv.Atoi(config.GetConfig("JWT_COOKIE_EXP_TIME_HOURS"))
cookie.Expires = time.Now().Add(time.Duration(expTime) * time.Hour)
return cookie
}