1
0
mirror of https://github.com/hrfee/jfa-go.git synced 2024-11-09 20:00:12 +00:00

Compare commits

..

No commits in common. "8113f794ab46e9899a386fd907623e282b4d590e" and "ebacfd43be5e292248a5e175afc56aac7e08c17c" have entirely different histories.

7 changed files with 97 additions and 133 deletions

View File

@ -16,7 +16,7 @@ func (app *appContext) checkInvites() {
currentTime := time.Now()
app.storage.loadInvites()
changed := false
for code, data := range app.storage.GetInvites() {
for code, data := range app.storage.invites {
expiry := data.ValidTill
if !currentTime.After(expiry) {
continue
@ -54,7 +54,7 @@ func (app *appContext) checkInvites() {
wait.Wait()
}
changed = true
app.storage.DeleteInvitesKey(code)
delete(app.storage.invites, code)
}
if changed {
app.storage.storeInvites()
@ -65,7 +65,7 @@ func (app *appContext) checkInvite(code string, used bool, username string) bool
currentTime := time.Now()
app.storage.loadInvites()
changed := false
inv, match := app.storage.GetInvitesKey(code)
inv, match := app.storage.invites[code]
if !match {
return false
}
@ -105,21 +105,21 @@ func (app *appContext) checkInvite(code string, used bool, username string) bool
}
changed = true
match = false
app.storage.DeleteInvitesKey(code)
delete(app.storage.invites, code)
} else if used {
changed = true
del := false
newInv := inv
if newInv.RemainingUses == 1 {
del = true
app.storage.DeleteInvitesKey(code)
delete(app.storage.invites, code)
} else if newInv.RemainingUses != 0 {
// 0 means infinite i guess?
newInv.RemainingUses--
}
newInv.UsedBy = append(newInv.UsedBy, []string{username, strconv.FormatInt(currentTime.Unix(), 10)})
if !del {
app.storage.SetInvitesKey(code, newInv)
app.storage.invites[code] = newInv
}
}
if changed {
@ -219,7 +219,7 @@ func (app *appContext) GenerateInvite(gc *gin.Context) {
invite.Profile = "Default"
}
}
app.storage.SetInvitesKey(inviteCode, invite)
app.storage.invites[inviteCode] = invite
app.storage.storeInvites()
respondBool(200, true, gc)
}
@ -236,7 +236,7 @@ func (app *appContext) GetInvites(gc *gin.Context) {
app.storage.loadInvites()
app.checkInvites()
var invites []inviteDTO
for code, inv := range app.storage.GetInvites() {
for code, inv := range app.storage.invites {
_, months, days, hours, minutes, _ := timeDiff(inv.ValidTill, currentTime)
invite := inviteDTO{
Code: code,
@ -335,9 +335,9 @@ func (app *appContext) SetProfile(gc *gin.Context) {
respond(500, "Profile not found", gc)
return
}
inv, _ := app.storage.GetInvitesKey(req.Invite)
inv := app.storage.invites[req.Invite]
inv.Profile = req.Profile
app.storage.SetInvitesKey(req.Invite, inv)
app.storage.invites[req.Invite] = inv
app.storage.storeInvites()
respondBool(200, true, gc)
}
@ -359,7 +359,7 @@ func (app *appContext) SetNotify(gc *gin.Context) {
app.debug.Printf("%s: Notification settings change requested", code)
app.storage.loadInvites()
app.storage.loadEmails()
invite, ok := app.storage.GetInvitesKey(code)
invite, ok := app.storage.invites[code]
if !ok {
app.err.Printf("%s Notification setting change failed: Invalid code", code)
respond(400, "Invalid invite code", gc)
@ -398,7 +398,7 @@ func (app *appContext) SetNotify(gc *gin.Context) {
changed = true
}
if changed {
app.storage.SetInvitesKey(code, invite)
app.storage.invites[code] = invite
}
}
if changed {
@ -419,9 +419,9 @@ func (app *appContext) DeleteInvite(gc *gin.Context) {
gc.BindJSON(&req)
app.debug.Printf("%s: Deletion requested", req.Code)
var ok bool
_, ok = app.storage.GetInvitesKey(req.Code)
_, ok = app.storage.invites[req.Code]
if ok {
app.storage.DeleteInvitesKey(req.Code)
delete(app.storage.invites, req.Code)
app.storage.storeInvites()
app.info.Printf("%s: Invite deleted", req.Code)
respondBool(200, true, gc)

View File

@ -460,7 +460,7 @@ func (app *appContext) TelegramVerified(gc *gin.Context) {
// @tags Other
func (app *appContext) TelegramVerifiedInvite(gc *gin.Context) {
code := gc.Param("invCode")
if _, ok := app.storage.GetInvitesKey(code); !ok {
if _, ok := app.storage.invites[code]; !ok {
respondBool(401, false, gc)
return
}
@ -484,7 +484,7 @@ func (app *appContext) TelegramVerifiedInvite(gc *gin.Context) {
// @tags Other
func (app *appContext) DiscordVerifiedInvite(gc *gin.Context) {
code := gc.Param("invCode")
if _, ok := app.storage.GetInvitesKey(code); !ok {
if _, ok := app.storage.invites[code]; !ok {
respondBool(401, false, gc)
return
}
@ -513,7 +513,7 @@ func (app *appContext) DiscordServerInvite(gc *gin.Context) {
return
}
code := gc.Param("invCode")
if _, ok := app.storage.GetInvitesKey(code); !ok {
if _, ok := app.storage.invites[code]; !ok {
respondBool(401, false, gc)
return
}
@ -537,7 +537,7 @@ func (app *appContext) DiscordServerInvite(gc *gin.Context) {
// @tags Other
func (app *appContext) MatrixSendPIN(gc *gin.Context) {
code := gc.Param("invCode")
if _, ok := app.storage.GetInvitesKey(code); !ok {
if _, ok := app.storage.invites[code]; !ok {
respondBool(401, false, gc)
return
}
@ -575,7 +575,7 @@ func (app *appContext) MatrixSendPIN(gc *gin.Context) {
// @tags Other
func (app *appContext) MatrixCheckPIN(gc *gin.Context) {
code := gc.Param("invCode")
if _, ok := app.storage.GetInvitesKey(code); !ok {
if _, ok := app.storage.invites[code]; !ok {
app.debug.Println("Matrix: Invite code was invalid")
respondBool(401, false, gc)
return

View File

@ -227,10 +227,14 @@ func (app *appContext) newUser(req newUserDTO, confirmed bool) (f errorFunc, suc
}
if emailEnabled && app.config.Section("email_confirmation").Key("enabled").MustBool(false) && !confirmed {
claims := jwt.MapClaims{
"valid": true,
"invite": req.Code,
"exp": time.Now().Add(30 * time.Minute).Unix(),
"type": "confirmation",
"valid": true,
"invite": req.Code,
"email": req.Email,
"username": req.Username,
"password": req.Password,
"telegramPIN": req.TelegramPIN,
"exp": time.Now().Add(time.Hour * 12).Unix(),
"type": "confirmation",
}
tk := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
key, err := tk.SignedString([]byte(os.Getenv("JFA_SECRET")))
@ -242,17 +246,10 @@ func (app *appContext) newUser(req newUserDTO, confirmed bool) (f errorFunc, suc
success = false
return
}
if app.ConfirmationKeys == nil {
app.ConfirmationKeys = map[string]map[string]newUserDTO{}
}
cKeys, ok := app.ConfirmationKeys[req.Code]
if !ok {
cKeys = map[string]newUserDTO{}
}
cKeys[key] = req
app.confirmationKeysLock.Lock()
app.ConfirmationKeys[req.Code] = cKeys
app.confirmationKeysLock.Unlock()
inv := app.storage.invites[req.Code]
inv.Keys = append(inv.Keys, key)
app.storage.invites[req.Code] = inv
app.storage.storeInvites()
f = func(gc *gin.Context) {
app.debug.Printf("%s: Email confirmation required", req.Code)
respond(401, "confirmEmail", gc)
@ -279,7 +276,7 @@ func (app *appContext) newUser(req newUserDTO, confirmed bool) (f errorFunc, suc
return
}
app.storage.loadProfiles()
invite, _ := app.storage.GetInvitesKey(req.Code)
invite := app.storage.invites[req.Code]
app.checkInvite(req.Code, true, req.Username)
if emailEnabled && app.config.Section("notifications").Key("enabled").MustBool(false) {
for address, settings := range invite.Notify {

View File

@ -1,7 +1,7 @@
<!DOCTYPE html>
<html lang="en" class="{{ .cssClass }}">
<head>
<link rel="stylesheet" type="text/css" href="{{ .urlBase }}/css/{{ .cssVersion }}bundle.css">
<link rel="stylesheet" type="text/css" href="css/{{ .cssVersion }}bundle.css">
{{ template "header.html" . }}
<title>Invalid Code - jfa-go</title>
</head>

45
main.go
View File

@ -17,7 +17,6 @@ import (
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
@ -91,29 +90,27 @@ type appContext struct {
adminUsers []User
invalidTokens []string
// Keeping jf name because I can't think of a better one
jf *mediabrowser.MediaBrowser
authJf *mediabrowser.MediaBrowser
ombi *ombi.Ombi
datePattern string
timePattern string
storage Storage
validator Validator
email *Emailer
telegram *TelegramDaemon
discord *DiscordDaemon
matrix *MatrixDaemon
info, debug, err *logger.Logger
host string
port int
version string
URLBase string
updater *Updater
newUpdate bool // Whether whatever's in update is new.
tag Tag
update Update
internalPWRs map[string]InternalPWR
ConfirmationKeys map[string]map[string]newUserDTO // Map of invite code to jwt to request
confirmationKeysLock sync.Mutex
jf *mediabrowser.MediaBrowser
authJf *mediabrowser.MediaBrowser
ombi *ombi.Ombi
datePattern string
timePattern string
storage Storage
validator Validator
email *Emailer
telegram *TelegramDaemon
discord *DiscordDaemon
matrix *MatrixDaemon
info, debug, err *logger.Logger
host string
port int
version string
URLBase string
updater *Updater
newUpdate bool // Whether whatever's in update is new.
tag Tag
update Update
internalPWRs map[string]InternalPWR
}
func generateSecret(length int) (string, error) {

View File

@ -167,39 +167,6 @@ func (st *Storage) DeleteMatrixKey(k string) {
st.matrixLock.Unlock()
}
// GetInvites returns a copy of the store.
func (st *Storage) GetInvites() Invites {
if st.invites == nil {
st.invites = Invites{}
}
return st.invites
}
// GetInvitesKey returns the value stored in the store's key.
func (st *Storage) GetInvitesKey(k string) (Invite, bool) {
v, ok := st.invites[k]
return v, ok
}
// SetInvitesKey stores value v in key k.
func (st *Storage) SetInvitesKey(k string, v Invite) {
st.invitesLock.Lock()
if st.invites == nil {
st.invites = Invites{}
}
st.invites[k] = v
st.storeInvites()
st.invitesLock.Unlock()
}
// DeleteInvitesKey deletes value at key k.
func (st *Storage) DeleteInvitesKey(k string) {
st.invitesLock.Lock()
delete(st.invites, k)
st.storeInvites()
st.invitesLock.Unlock()
}
type TelegramUser struct {
ChatID int64
Username string
@ -278,6 +245,7 @@ type Invite struct {
Notify map[string]map[string]bool `json:"notify"`
Profile string `json:"profile"`
Label string `json:"label,omitempty"`
Keys []string `json:"keys,omitempty"`
Captchas map[string]*captcha.Data // Map of Captcha IDs to answers
}
@ -964,10 +932,14 @@ func (st *Storage) loadLangTelegram(filesystems ...fs.FS) error {
type Invites map[string]Invite
func (st *Storage) loadInvites() error {
st.invitesLock.Lock()
defer st.invitesLock.Unlock()
return loadJSON(st.invite_path, &st.invites)
}
func (st *Storage) storeInvites() error {
st.invitesLock.Lock()
defer st.invitesLock.Unlock()
return storeJSON(st.invite_path, st.invites)
}

View File

@ -342,10 +342,9 @@ func (app *appContext) ResetPassword(gc *gin.Context) {
func (app *appContext) GetCaptcha(gc *gin.Context) {
code := gc.Param("invCode")
captchaID := gc.Param("captchaID")
inv, ok := app.storage.GetInvitesKey(code)
inv, ok := app.storage.invites[code]
if !ok {
gcHTML(gc, 404, "invalidCode.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
@ -377,10 +376,9 @@ func (app *appContext) GetCaptcha(gc *gin.Context) {
// @tags Users
func (app *appContext) GenCaptcha(gc *gin.Context) {
code := gc.Param("invCode")
inv, ok := app.storage.GetInvitesKey(code)
inv, ok := app.storage.invites[code]
if !ok {
gcHTML(gc, 404, "invalidCode.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
@ -397,7 +395,8 @@ func (app *appContext) GenCaptcha(gc *gin.Context) {
}
captchaID := genAuthToken()
inv.Captchas[captchaID] = capt
app.storage.SetInvitesKey(code, inv)
app.storage.invites[code] = inv
app.storage.storeInvites()
gc.JSON(200, genCaptchaDTO{captchaID})
return
}
@ -406,7 +405,7 @@ func (app *appContext) verifyCaptcha(code, id, text string) bool {
reCAPTCHA := app.config.Section("captcha").Key("recaptcha").MustBool(false)
if !reCAPTCHA {
// internal CAPTCHA
inv, ok := app.storage.GetInvitesKey(code)
inv, ok := app.storage.invites[code]
if !ok || inv.Captchas == nil {
app.debug.Printf("Couldn't find invite \"%s\"", code)
return false
@ -473,10 +472,9 @@ func (app *appContext) VerifyCaptcha(gc *gin.Context) {
code := gc.Param("invCode")
captchaID := gc.Param("captchaID")
text := gc.Param("text")
inv, ok := app.storage.GetInvitesKey(code)
inv, ok := app.storage.invites[code]
if !ok {
gcHTML(gc, 404, "invalidCode.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
@ -505,10 +503,9 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
lang := app.getLang(gc, FormPage, app.storage.lang.chosenUserLang)
/* Don't actually check if the invite is valid, just if it exists, just so the page loads quicker. Invite is actually checked on submit anyway. */
// if app.checkInvite(code, false, "") {
inv, ok := app.storage.GetInvitesKey(code)
inv, ok := app.storage.invites[code]
if !ok {
gcHTML(gc, 404, "invalidCode.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
@ -516,27 +513,23 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
return
}
if key := gc.Query("key"); key != "" && app.config.Section("email_confirmation").Key("enabled").MustBool(false) {
validKey := false
keyIndex := -1
for i, k := range inv.Keys {
if k == key {
validKey = true
keyIndex = i
break
}
}
fail := func() {
gcHTML(gc, 404, "404.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
})
}
var req newUserDTO
if app.ConfirmationKeys == nil {
fail()
return
}
invKeys, ok := app.ConfirmationKeys[code]
if !ok {
fail()
return
}
req, ok = invKeys[key]
if !ok {
if !validKey {
fail()
return
}
@ -547,17 +540,26 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
return
}
claims, ok := token.Claims.(jwt.MapClaims)
expiry := time.Unix(int64(claims["exp"].(float64)), 0)
expiryUnix := int64(claims["exp"].(float64))
if err != nil {
fail()
app.err.Printf("Failed to parse key expiry: %s", err)
return
}
expiry := time.Unix(expiryUnix, 0)
if !(ok && token.Valid && claims["invite"].(string) == code && claims["type"].(string) == "confirmation" && expiry.After(time.Now())) {
fail()
app.debug.Printf("Invalid key")
return
}
f, success := app.newUser(req, true)
req := newUserDTO{
Email: claims["email"].(string),
Username: claims["username"].(string),
Password: claims["password"].(string),
Code: claims["invite"].(string),
}
_, success := app.newUser(req, true)
if !success {
app.err.Printf("Failed to create new user")
// Not meant for us. Calling this will be a mess, but at least it might give us some information.
f(gc)
fail()
return
}
@ -566,25 +568,22 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
gc.Redirect(301, jfLink)
} else {
gcHTML(gc, http.StatusOK, "create-success.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"strings": app.storage.lang.User[lang].Strings,
"successMessage": app.config.Section("ui").Key("success_message").String(),
"contactMessage": app.config.Section("ui").Key("contact_message").String(),
"jfLink": jfLink,
})
}
delete(invKeys, key)
app.confirmationKeysLock.Lock()
app.ConfirmationKeys[code] = invKeys
app.confirmationKeysLock.Unlock()
inv, ok := app.storage.invites[code]
if ok {
l := len(inv.Keys)
inv.Keys[l-1], inv.Keys[keyIndex] = inv.Keys[keyIndex], inv.Keys[l-1]
app.storage.invites[code] = inv
}
return
}
email := ""
if invite, ok := app.storage.GetInvitesKey(code); ok {
email = invite.SendTo
}
email := app.storage.invites[code].SendTo
if strings.Contains(email, "Failed") || !strings.Contains(email, "@") {
email = ""
}
@ -658,7 +657,6 @@ func (app *appContext) InviteProxy(gc *gin.Context) {
func (app *appContext) NoRouteHandler(gc *gin.Context) {
app.pushResources(gc, OtherPage)
gcHTML(gc, 404, "404.html", gin.H{
"urlBase": app.getURLBase(gc),
"cssClass": app.cssClass,
"cssVersion": cssVersion,
"contactMessage": app.config.Section("ui").Key("contact_message").String(),