-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
67 lines (53 loc) · 1.49 KB
/
helpers.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
package helpers
import (
"errors"
"math/rand"
"net/http"
"time"
"github.com/mraron/njudge/internal/njudge/db/models"
"github.com/mraron/njudge/internal/web/helpers/config"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
)
func GenerateActivationKey(length int) string {
var (
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678901234567890123456789"
ans = make([]byte, length)
)
src := rand.NewSource(time.Now().UnixNano())
for i := 0; i < length; i++ {
ans[i] = alphabet[(int(src.Int63()))%len(alphabet)]
}
return string(ans)
}
func CensorUserPassword(user *models.User) {
user.Password = "***CENSORED***"
}
func LoginRequired(c echo.Context) error {
SetFlash(c, "LoginMessage", "A kért oldal megtekintéséhez belépés szükséges!")
to := ""
if c.Request().Method == "GET" {
to = "?next=" + c.Request().URL.Path
}
return c.Redirect(http.StatusFound, "/user/login"+to)
}
func UnauthorizedError(c echo.Context) error {
return echo.NewHTTPError(http.StatusUnauthorized, errors.New("unauthorized"))
}
func GetJWT(cfg config.Keys) (string, error) {
if cfg.PrivateKey == nil {
return "", nil
}
claims := &jwt.StandardClaims{
ExpiresAt: time.Now().Add(10 * time.Minute).Unix(),
NotBefore: time.Now().Unix(),
Issuer: "njudge web",
IssuedAt: time.Now().Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodRS512, claims)
jwt, err := token.SignedString(cfg.PrivateKey)
if err != nil {
return "", err
}
return jwt, nil
}