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

94 lines
2.5 KiB
Go
Raw Normal View History

2020-08-01 15:31:08 +00:00
package main
import (
"encoding/json"
"io/ioutil"
"os"
"strings"
"time"
"github.com/fsnotify/fsnotify"
2020-08-01 15:31:08 +00:00
)
func (app *appContext) StartPWR() {
app.info.Println("Starting password reset daemon")
path := app.config.Section("password_resets").Key("watch_directory").String()
2020-08-01 15:31:08 +00:00
if _, err := os.Stat(path); os.IsNotExist(err) {
app.err.Printf("Failed to start password reset daemon: Directory \"%s\" doesn't exist", path)
2020-08-01 15:31:08 +00:00
return
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
app.err.Printf("Couldn't initialise password reset daemon")
2020-08-01 15:31:08 +00:00
return
}
defer watcher.Close()
done := make(chan bool)
go pwrMonitor(app, watcher)
2020-08-01 15:31:08 +00:00
err = watcher.Add(path)
if err != nil {
app.err.Printf("Failed to start password reset daemon: %s", err)
2020-08-01 15:31:08 +00:00
}
<-done
}
type Pwr struct {
Pin string `json:"Pin"`
Username string `json:"UserName"`
Expiry time.Time `json:"ExpirationDate"`
}
func pwrMonitor(app *appContext, watcher *fsnotify.Watcher) {
2020-08-01 15:31:08 +00:00
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write && strings.Contains(event.Name, "passwordreset") {
var pwr Pwr
data, err := ioutil.ReadFile(event.Name)
if err != nil {
return
}
err = json.Unmarshal(data, &pwr)
if len(pwr.Pin) == 0 || err != nil {
return
}
app.info.Printf("New password reset for user \"%s\"", pwr.Username)
2020-08-01 15:31:08 +00:00
if ct := time.Now(); pwr.Expiry.After(ct) {
user, status, err := app.jf.userByName(pwr.Username, false)
2020-08-01 15:31:08 +00:00
if !(status == 200 || status == 204) || err != nil {
app.err.Printf("Failed to get users from Jellyfin: Code %d", status)
app.debug.Printf("Error: %s", err)
2020-08-01 15:31:08 +00:00
return
}
app.storage.loadEmails()
address, ok := app.storage.emails[user["Id"].(string)].(string)
2020-08-01 15:31:08 +00:00
if !ok {
app.err.Printf("Couldn't find email for user \"%s\". Make sure it's set", pwr.Username)
2020-08-01 15:31:08 +00:00
return
}
if app.email.constructReset(pwr, app) != nil {
app.err.Printf("Failed to construct password reset email for %s", pwr.Username)
} else if app.email.send(address, app) != nil {
app.err.Printf("Failed to send password reset email to \"%s\"", address)
2020-08-01 15:31:08 +00:00
} else {
app.info.Printf("Sent password reset email to \"%s\"", address)
2020-08-01 15:31:08 +00:00
}
} else {
app.err.Printf("Password reset for user \"%s\" has already expired (%s). Check your time settings.", pwr.Username, pwr.Expiry)
2020-08-01 15:31:08 +00:00
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
app.err.Printf("Password reset daemon: %s", err)
2020-08-01 15:31:08 +00:00
}
}
}