-
Notifications
You must be signed in to change notification settings - Fork 3
/
auth_services.go
70 lines (59 loc) · 1.46 KB
/
auth_services.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
package services
import (
"encoding/json"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/nathandao/vantaa/core/auth"
"github.com/nathandao/vantaa/services/models/user"
)
type TokenAuthentication struct {
Token string `json:"token" form:"token"`
}
func Login(requestUser *user.User) (int, []byte) {
authBackend, err := auth.InitJwtAuthBackend()
if err != nil {
return http.StatusInternalServerError, []byte("")
}
if authBackend.Authenticate(requestUser) {
token, err := authBackend.GenerateToken(requestUser)
if err != nil {
return http.StatusInternalServerError, []byte("")
} else {
response, _ := json.Marshal(TokenAuthentication{token})
return http.StatusOK, response
}
}
return http.StatusUnauthorized, []byte("")
}
func RefreshToken(requestUser *user.User) []byte {
authBackend, err := auth.InitJwtAuthBackend()
if err != nil {
panic(err)
}
token, err := authBackend.GenerateToken(requestUser)
if err != nil {
panic(err)
}
response, err := json.Marshal(TokenAuthentication{token})
if err != nil {
panic(err)
}
return response
}
func Logout(req *http.Request) error {
authBackend, err := auth.InitJwtAuthBackend()
if err != nil {
return err
}
token, err := jwt.ParseFromRequest(
req,
func(token *jwt.Token) (interface{}, error) {
return authBackend.PublicKey, nil
},
)
if err != nil {
return err
}
tokenString := req.Header.Get("Authorization")
return authBackend.TerminateToken(tokenString, token)
}