-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
65 lines (51 loc) · 1.36 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
package auth
import (
"encoding/json"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
)
var jwtSecret = "98wly4tgop98w4UTYOWG9A8W3U4TL9lksdjrogphge4oys4e0GUWYO8OGFSushgals48la"
func GetSecret() string {
return jwtSecret
}
type Claims struct {
UserID int64 `json:"user_id"`
UserName string `json:"user_name"`
jwt.RegisteredClaims
}
func createToken(authenticated Authenticated) (string, error) {
expirationTime := time.Now().Add(30 * time.Minute)
claims := &Claims{
UserID: authenticated.GetID(),
UserName: authenticated.GetName(),
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expirationTime),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(jwtSecret))
}
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (h *handler) auth(rw http.ResponseWriter, r *http.Request) {
var creds Credentials
err := json.NewDecoder(r.Body).Decode(&creds)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
u, err := h.authenticate(creds.Username, creds.Password)
if err != nil {
http.Error(rw, err.Error(), http.StatusUnauthorized)
return
}
token, err := createToken(u)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Write([]byte(token))
}