-
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
// SPDX-FileCopyrightText: 2025 Shota FUJI <pockawoooh@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-only
package core
import (
"fmt"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
workspace "pocka.jp/x/yamori/proto/go/backend/projections/workspace/v1"
"pocka.jp/x/yamori/backend/core/projection"
)
const cookieName = "yamori-login-token"
type token string
func (core *Core) LoadTokenFromCookie(header *http.Header) (*token, error) {
for _, header := range header.Values("Cookie") {
cookies, err := http.ParseCookie(header)
if err != nil {
return nil, err
}
for _, cookie := range cookies {
if cookie.Name == cookieName {
token := token(cookie.Value)
return &token, nil
}
}
}
return nil, nil
}
func DeleteTokenFromCookie(header *http.Header) {
cookie := http.Cookie{
Name: cookieName,
Value: "",
Expires: time.Now(),
SameSite: http.SameSiteStrictMode,
Secure: true,
HttpOnly: true,
}
header.Add("Set-Cookie", cookie.String())
}
func (core *Core) IssueToken(secret *projection.LoginJwtSecret, user *workspace.Users_User) (*token, error) {
t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"sub": user.GetId(),
})
signed, err := t.SignedString(secret.Projection)
if err != nil {
return nil, err
}
token := token(signed)
return &token, nil
}
func (t *token) SaveToCookie(header *http.Header) {
cookie := http.Cookie{
Name: cookieName,
Value: string(*t),
SameSite: http.SameSiteStrictMode,
Secure: true,
HttpOnly: true,
}
header.Add("Set-Cookie", cookie.String())
}
func (t *token) Validate(secret *projection.LoginJwtSecret) error {
_, err := jwt.Parse(string(*t), func(token *jwt.Token) (any, error) {
return secret.Projection, nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
return err
}
func (t *token) FindUser(
secret *projection.LoginJwtSecret,
users *projection.Users,
) (*workspace.Users_User, error) {
parsed, err := jwt.Parse(string(*t), func(token *jwt.Token) (any, error) {
return secret.Projection, nil
}, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil {
return nil, err
}
sub, err := parsed.Claims.GetSubject()
if err != nil {
return nil, err
}
for _, u := range users.Projection.Users {
if u.GetId() == sub {
return u, nil
}
}
return nil, fmt.Errorf("No user found for sub=%s", sub)
}