From 580dec5b89215310ce34341e11ff17fe38bdb63a Mon Sep 17 00:00:00 2001
From: FChannel <>
Date: Sun, 8 May 2022 14:57:40 -0700
Subject: more cleanup, logging and error logging everywhere things are mostly
in place can work on "features" and polish
---
db/cache.go | 72 -------
db/database.go | 584 +++++++++++++----------------------------------------
db/follow.go | 306 ----------------------------
db/pem.go | 95 ---------
db/report.go | 112 ++++------
db/verification.go | 514 ----------------------------------------------
6 files changed, 178 insertions(+), 1505 deletions(-)
delete mode 100644 db/cache.go
delete mode 100644 db/follow.go
delete mode 100644 db/pem.go
delete mode 100644 db/verification.go
(limited to 'db')
diff --git a/db/cache.go b/db/cache.go
deleted file mode 100644
index d1c1fe7..0000000
--- a/db/cache.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package db
-
-import (
- "github.com/FChannel0/FChannel-Server/activitypub"
- "github.com/FChannel0/FChannel-Server/config"
- "github.com/FChannel0/FChannel-Server/webfinger"
- _ "github.com/lib/pq"
-)
-
-func WriteObjectReplyToCache(obj activitypub.ObjectBase) error {
- for i, e := range obj.InReplyTo {
- res, err := IsReplyInThread(obj.InReplyTo[0].Id, e.Id)
- if err != nil {
- return err
- }
-
- if i == 0 || res {
- query := `select id from replies where id=$1`
-
- rows, err := config.DB.Query(query, obj.Id)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- var id string
- rows.Next()
- err = rows.Scan(&id)
- if err != nil {
- return err
- } else if id != "" {
- return nil // TODO: error?
- }
-
- query = `insert into cachereplies (id, inreplyto) values ($1, $2)`
-
- _, err = config.DB.Exec(query, obj.Id, e.Id)
- if err != nil {
- return err
- }
- }
- }
-
- if len(obj.InReplyTo) < 1 {
- query := `insert into cachereplies (id, inreplyto) values ($1, $2)`
-
- _, err := config.DB.Exec(query, obj.Id, "")
- return err
- }
-
- return nil
-}
-
-func WriteActorToCache(actorID string) error {
- actor, err := webfinger.FingerActor(actorID)
- if err != nil {
- return err
- }
-
- collection, err := webfinger.GetActorCollection(actor.Outbox)
- if err != nil {
- return err
- }
-
- for _, e := range collection.OrderedItems {
- if err := e.WriteCache(); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/db/database.go b/db/database.go
index 5d53f46..c6c2fc7 100644
--- a/db/database.go
+++ b/db/database.go
@@ -2,11 +2,9 @@ package db
import (
"database/sql"
- "encoding/json"
"fmt"
"html/template"
"io/ioutil"
- "net/http"
"os"
"regexp"
"strings"
@@ -15,7 +13,6 @@ import (
"github.com/FChannel0/FChannel-Server/activitypub"
"github.com/FChannel0/FChannel-Server/config"
"github.com/FChannel0/FChannel-Server/util"
- "github.com/FChannel0/FChannel-Server/webfinger"
_ "github.com/lib/pq"
)
@@ -25,8 +22,7 @@ type NewsItem struct {
Time int
}
-// ConnectDB connects to the PostgreSQL database configured.
-func ConnectDB() error {
+func Connect() error {
host := config.DBHost
port := config.DBPort
user := config.DBUser
@@ -37,89 +33,98 @@ func ConnectDB() error {
"dbname=%s sslmode=disable", host, port, user, password, dbname)
_db, err := sql.Open("postgres", psqlInfo)
+
if err != nil {
- return err
+ return util.MakeError(err, "Connect")
}
if err := _db.Ping(); err != nil {
- return err
+ return util.MakeError(err, "Connect")
}
- fmt.Println("Successfully connected DB")
+ config.Log.Println("Successfully connected DB")
config.DB = _db
+
return nil
}
-// Close closes the database connection.
func Close() error {
- return config.DB.Close()
+ err := config.DB.Close()
+
+ return util.MakeError(err, "Close")
}
func RunDatabaseSchema() error {
query, err := ioutil.ReadFile("databaseschema.psql")
if err != nil {
- return err
+ return util.MakeError(err, "RunDatabaseSchema")
}
_, err = config.DB.Exec(string(query))
- return err
+ return util.MakeError(err, "RunDatabaseSchema")
}
-func CreateNewBoardDB(actor activitypub.Actor) (activitypub.Actor, error) {
- query := `insert into actor (type, id, name, preferedusername, inbox, outbox, following, followers, summary, restricted) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`
+func CreateNewBoard(actor activitypub.Actor) (activitypub.Actor, error) {
+ if _, err := activitypub.GetActorFromDB(actor.Id); err == nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ } else {
+ query := `insert into actor (type, id, name, preferedusername, inbox, outbox, following, followers, summary, restricted) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`
+ _, err := config.DB.Exec(query, actor.Type, actor.Id, actor.Name, actor.PreferredUsername, actor.Inbox, actor.Outbox, actor.Following, actor.Followers, actor.Summary, actor.Restricted)
- _, err := config.DB.Exec(query, actor.Type, actor.Id, actor.Name, actor.PreferredUsername, actor.Inbox, actor.Outbox, actor.Following, actor.Followers, actor.Summary, actor.Restricted)
+ if err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
- if err != nil {
- // TODO: board exists error
- return activitypub.Actor{}, err
- } else {
- fmt.Println("board added")
+ config.Log.Println("board added")
for _, e := range actor.AuthRequirement {
query = `insert into actorauth (type, board) values ($1, $2)`
-
if _, err := config.DB.Exec(query, e, actor.Name); err != nil {
- return activitypub.Actor{}, err
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
}
}
- var verify Verify
+ var verify util.Verify
- verify.Identifier = actor.Id
- verify.Code = util.CreateKey(50)
verify.Type = "admin"
-
- CreateVerification(verify)
-
verify.Identifier = actor.Id
- verify.Code = util.CreateKey(50)
- verify.Type = "janitor"
- CreateVerification(verify)
+ if verify.Code, err = util.CreateKey(50); err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
+
+ if err := verify.Create(); err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
+ verify.Type = "janitor"
verify.Identifier = actor.Id
- verify.Code = util.CreateKey(50)
- verify.Type = "post"
- CreateVerification(verify)
+ if verify.Code, err = util.CreateKey(50); err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
+
+ if err := verify.Create(); err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
- var nverify Verify
+ var nverify util.Verify
nverify.Board = actor.Id
nverify.Identifier = "admin"
nverify.Type = "admin"
- CreateBoardMod(nverify)
+
+ if err := nverify.CreateBoardMod(); err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
nverify.Board = actor.Id
nverify.Identifier = "janitor"
nverify.Type = "janitor"
- CreateBoardMod(nverify)
- nverify.Board = actor.Id
- nverify.Identifier = "post"
- nverify.Type = "post"
- CreateBoardMod(nverify)
+ if err := nverify.CreateBoardMod(); err != nil {
+ return activitypub.Actor{}, util.MakeError(err, "CreateNewBoardDB")
+ }
activitypub.CreatePem(actor)
@@ -128,165 +133,90 @@ func CreateNewBoardDB(actor activitypub.Actor) (activitypub.Actor, error) {
var nActivity activitypub.Activity
nActor, err := activitypub.GetActorFromDB(config.Domain)
+
if err != nil {
- return actor, err
+ return actor, util.MakeError(err, "CreateNewBoardDB")
}
nActivity.AtContext.Context = "https://www.w3.org/ns/activitystreams"
nActivity.Type = "Follow"
nActivity.Actor = &nActor
nActivity.Object = &nObject
-
mActor, err := activitypub.GetActorFromDB(actor.Id)
+
if err != nil {
- return actor, err
+ return actor, util.MakeError(err, "CreateNewBoardDB")
}
nActivity.Object.Actor = mActor.Id
nActivity.To = append(nActivity.To, actor.Id)
- response := AcceptFollow(nActivity)
- if _, err := SetActorFollowingDB(response); err != nil {
- return actor, err
+ activityRequest := nActivity.AcceptFollow()
+
+ if _, err := activityRequest.SetActorFollowing(); err != nil {
+ return actor, util.MakeError(err, "CreateNewBoardDB")
}
- if err := MakeActivityRequest(nActivity); err != nil {
- return actor, err
+
+ if err := activityRequest.MakeRequestInbox(); err != nil {
+ return actor, util.MakeError(err, "CreateNewBoardDB")
}
}
-
}
return actor, nil
}
func RemovePreviewFromFile(id string) error {
+ var href string
+
query := `select href from activitystream where id in (select preview from activitystream where id=$1)`
- rows, err := config.DB.Query(query, id)
- if err != nil {
- return err
+ if err := config.DB.QueryRow(query, id).Scan(&href); err != nil {
+ return nil
}
- defer rows.Close()
- for rows.Next() {
- var href string
+ href = strings.Replace(href, config.Domain+"/", "", 1)
- if err := rows.Scan(&href); err != nil {
- return err
+ if href != "static/notfound.png" {
+ if _, err := os.Stat(href); err != nil {
+ return util.MakeError(err, "RemovePreviewFromFile")
}
- href = strings.Replace(href, config.Domain+"/", "", 1)
-
- if href != "static/notfound.png" {
- _, err = os.Stat(href)
- if err == nil {
- return os.Remove(href)
- }
- return err
- }
+ err := os.Remove(href)
+ return util.MakeError(err, "RemovePreviewFromFile")
}
obj := activitypub.ObjectBase{Id: id}
- return obj.DeletePreview()
-}
-
-func GetRandomCaptcha() (string, error) {
- var verify string
-
- query := `select identifier from verification where type='captcha' order by random() limit 1`
-
- rows, err := config.DB.Query(query)
- if err != nil {
- return verify, err
- }
- defer rows.Close()
-
- rows.Next()
- if err := rows.Scan(&verify); err != nil {
- return verify, err
- }
-
- return verify, nil
-}
-
-func GetCaptchaTotal() (int, error) {
- query := `select count(*) from verification where type='captcha'`
-
- rows, err := config.DB.Query(query)
- if err != nil {
- return 0, err
- }
-
- defer rows.Close()
-
- var count int
- for rows.Next() {
- if err := rows.Scan(&count); err != nil {
- return count, err
- }
- }
-
- return count, nil
-}
-
-func GetCaptchaCodeDB(verify string) (string, error) {
- query := `select code from verification where identifier=$1 limit 1`
-
- rows, err := config.DB.Query(query, verify)
- if err != nil {
- return "", err
- }
- defer rows.Close()
-
- var code string
-
- rows.Next()
- if err := rows.Scan(&code); err != nil {
- fmt.Println("Could not get verification captcha")
- }
-
- return code, nil
-}
-
-func DeleteCaptchaCodeDB(verify string) error {
- query := `delete from verification where identifier=$1`
-
- _, err := config.DB.Exec(query, verify)
- if err != nil {
- return err
- }
-
- return os.Remove("./" + verify)
+ err := obj.DeletePreview()
+ return util.MakeError(err, "RemovePreviewFromFile")
}
//if limit less than 1 return all news items
-func GetNewsFromDB(limit int) ([]NewsItem, error) {
+func GetNews(limit int) ([]NewsItem, error) {
var news []NewsItem
-
var query string
- if limit > 0 {
- query = `select title, content, time from newsItem order by time desc limit $1`
- } else {
- query = `select title, content, time from newsItem order by time desc`
- }
var rows *sql.Rows
var err error
+
if limit > 0 {
+ query = `select title, content, time from newsItem order by time desc limit $1`
rows, err = config.DB.Query(query, limit)
} else {
+ query = `select title, content, time from newsItem order by time desc`
rows, err = config.DB.Query(query)
}
if err != nil {
- return news, nil
+ return news, util.MakeError(err, "GetNews")
}
defer rows.Close()
for rows.Next() {
- n := NewsItem{}
var content string
+ n := NewsItem{}
+
if err := rows.Scan(&n.Title, &content, &n.Time); err != nil {
- return news, err
+ return news, util.MakeError(err, "GetNews")
}
content = strings.ReplaceAll(content, "\n", "
")
@@ -298,21 +228,13 @@ func GetNewsFromDB(limit int) ([]NewsItem, error) {
return news, nil
}
-func GetNewsItemFromDB(timestamp int) (NewsItem, error) {
+func GetNewsItem(timestamp int) (NewsItem, error) {
var news NewsItem
var content string
- query := `select title, content, time from newsItem where time=$1 limit 1`
-
- rows, err := config.DB.Query(query, timestamp)
- if err != nil {
- return news, err
- }
-
- defer rows.Close()
- rows.Next()
- if err := rows.Scan(&news.Title, &content, &news.Time); err != nil {
- return news, err
+ query := `select title, content, time from newsItem where time=$1 limit 1`
+ if err := config.DB.QueryRow(query, timestamp).Scan(&news.Title, &content, &news.Time); err != nil {
+ return news, util.MakeError(err, "GetNewsItem")
}
content = strings.ReplaceAll(content, "\n", "
")
@@ -321,65 +243,54 @@ func GetNewsItemFromDB(timestamp int) (NewsItem, error) {
return news, nil
}
-func deleteNewsItemFromDB(timestamp int) error {
+func DeleteNewsItem(timestamp int) error {
query := `delete from newsItem where time=$1`
_, err := config.DB.Exec(query, timestamp)
- return err
+
+ return util.MakeError(err, "DeleteNewsItem")
}
-func WriteNewsToDB(news NewsItem) error {
+func WriteNews(news NewsItem) error {
query := `insert into newsItem (title, content, time) values ($1, $2, $3)`
-
_, err := config.DB.Exec(query, news.Title, news.Content, time.Now().Unix())
- return err
-}
-
-func AddInstanceToInactiveDB(instance string) error {
- query := `select timestamp from inactive where instance=$1`
- rows, err := config.DB.Query(query, instance)
- if err != nil {
- return err
- }
+ return util.MakeError(err, "WriteNews")
+}
+func AddInstanceToInactive(instance string) error {
var timeStamp string
- defer rows.Close()
- rows.Next()
- rows.Scan(&timeStamp)
- if timeStamp == "" {
+ query := `select timestamp from inactive where instance=$1`
+ if err := config.DB.QueryRow(query, instance).Scan(&timeStamp); err != nil {
query := `insert into inactive (instance, timestamp) values ($1, $2)`
-
_, err := config.DB.Exec(query, instance, time.Now().UTC().Format(time.RFC3339))
- return err
+
+ return util.MakeError(err, "AddInstanceToInactive")
}
if !IsInactiveTimestamp(timeStamp) {
return nil
}
- query = `delete from following where following like $1`
- if _, err := config.DB.Exec(query, "%"+instance+"%"); err != nil {
- return err
- }
-
query = `delete from follower where follower like $1`
- if _, err = config.DB.Exec(query, "%"+instance+"%"); err != nil {
- return err
+ if _, err := config.DB.Exec(query, "%"+instance+"%"); err != nil {
+ return util.MakeError(err, "AddInstanceToInactive")
}
- return DeleteInstanceFromInactiveDB(instance)
+ err := DeleteInstanceFromInactive(instance)
+ return util.MakeError(err, "AddInstanceToInactive")
}
-func DeleteInstanceFromInactiveDB(instance string) error {
+func DeleteInstanceFromInactive(instance string) error {
query := `delete from inactive where instance=$1`
-
_, err := config.DB.Exec(query, instance)
- return err
+
+ return util.MakeError(err, "DeleteInstanceFromInactive")
}
func IsInactiveTimestamp(timeStamp string) bool {
stamp, _ := time.Parse(time.RFC3339, timeStamp)
+
if time.Now().UTC().Sub(stamp).Hours() > 48 {
return true
}
@@ -387,45 +298,9 @@ func IsInactiveTimestamp(timeStamp string) bool {
return false
}
-func ArchivePosts(actor activitypub.Actor) error {
- if actor.Id != "" && actor.Id != config.Domain {
- col, err := actor.GetAllArchive(165)
- if err != nil {
- return err
- }
-
- for _, e := range col.OrderedItems {
- for _, k := range e.Replies.OrderedItems {
- if err := k.UpdateType("Archive"); err != nil {
- return err
- }
- }
-
- if err := e.UpdateType("Archive"); err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-func IsReplyInThread(inReplyTo string, id string) (bool, error) {
- obj, _, err := webfinger.CheckValidActivity(inReplyTo)
- if err != nil {
- return false, err
- }
-
- for _, e := range obj.OrderedItems[0].Replies.OrderedItems {
- if e.Id == id {
- return true, nil
- }
- }
-
- return false, nil
-}
-
func IsReplyToOP(op string, link string) (string, bool, error) {
+ var id string
+
if op == link {
return link, true, nil
}
@@ -440,52 +315,22 @@ func IsReplyToOP(op string, link string) (string, bool, error) {
}
query := `select id from replies where id like $1 and inreplyto=$2`
-
- rows, err := config.DB.Query(query, link, op)
- if err != nil {
- return op, false, err
- }
-
- defer rows.Close()
-
- var id string
- rows.Next()
- if err := rows.Scan(&id); err != nil {
- return id, false, err
+ if err := config.DB.QueryRow(query, link, op).Scan(&id); err != nil {
+ return op, false, nil
}
return id, id != "", nil
}
func GetReplyOP(link string) (string, error) {
- query := `select id from replies where id in (select inreplyto from replies where id=$1) and inreplyto=''`
-
- rows, err := config.DB.Query(query, link)
- if err != nil {
- return "", err
- }
- defer rows.Close()
-
var id string
- rows.Next()
- err = rows.Scan(&id)
- return id, err
-}
-
-func StartupArchive() error {
- for _, e := range webfinger.FollowingBoards {
- actor, err := activitypub.GetActorFromDB(e.Id)
- if err != nil {
- return err
- }
-
- if err := ArchivePosts(actor); err != nil {
- return err
- }
+ query := `select id from replies where id in (select inreplyto from replies where id=$1) and inreplyto=''`
+ if err := config.DB.QueryRow(query, link).Scan(&id); err != nil {
+ return "", nil
}
- return nil
+ return id, nil
}
func CheckInactive() {
@@ -496,54 +341,59 @@ func CheckInactive() {
}
func CheckInactiveInstances() (map[string]string, error) {
+ var rows *sql.Rows
+ var err error
+
instances := make(map[string]string)
- query := `select following from following`
- rows, err := config.DB.Query(query)
- if err != nil {
- return instances, err
+ query := `select following from following`
+ if rows, err = config.DB.Query(query); err != nil {
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
- defer rows.Close()
+ defer rows.Close()
for rows.Next() {
var instance string
+
if err := rows.Scan(&instance); err != nil {
- return instances, err
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
instances[instance] = instance
}
query = `select follower from follower`
- rows, err = config.DB.Query(query)
- if err != nil {
- return instances, err
+ if rows, err = config.DB.Query(query); err != nil {
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
- defer rows.Close()
+ defer rows.Close()
for rows.Next() {
var instance string
+
if err := rows.Scan(&instance); err != nil {
- return instances, err
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
instances[instance] = instance
}
re := regexp.MustCompile(config.Domain + `(.+)?`)
+
for _, e := range instances {
- actor, err := webfinger.GetActor(e)
+ actor, err := activitypub.GetActor(e)
+
if err != nil {
- return instances, err
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
if actor.Id == "" && !re.MatchString(e) {
- if err := AddInstanceToInactiveDB(e); err != nil {
- return instances, err
+ if err := AddInstanceToInactive(e); err != nil {
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
} else {
- if err := DeleteInstanceFromInactiveDB(e); err != nil {
- return instances, err
+ if err := DeleteInstanceFromInactive(e); err != nil {
+ return instances, util.MakeError(err, "CheckInactiveInstances")
}
}
}
@@ -552,12 +402,12 @@ func CheckInactiveInstances() (map[string]string, error) {
}
func GetAdminAuth() (string, string, error) {
- query := fmt.Sprintf("select identifier, code from boardaccess where board='%s' and type='admin'", config.Domain)
-
var code string
var identifier string
- if err := config.DB.QueryRow(query).Scan(&identifier, &code); err != nil {
- return "", "", err
+
+ query := `select identifier, code from boardaccess where board=$1 and type='admin'`
+ if err := config.DB.QueryRow(query, config.Domain).Scan(&identifier, &code); err != nil {
+ return "", "", nil
}
return code, identifier, nil
@@ -567,175 +417,27 @@ func IsHashBanned(hash string) (bool, error) {
var h string
query := `select hash from bannedmedia where hash=$1`
-
_ = config.DB.QueryRow(query, hash).Scan(&h)
return h == hash, nil
}
-func MakeCaptchas(total int) error {
- dbtotal, err := GetCaptchaTotal()
- if err != nil {
- return err
- }
-
- difference := total - dbtotal
-
- for i := 0; i < difference; i++ {
- if err := CreateNewCaptcha(); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func GetActorReported(w http.ResponseWriter, r *http.Request, id string) error {
- auth := r.Header.Get("Authorization")
- verification := strings.Split(auth, " ")
-
- if len(verification) < 2 {
- w.WriteHeader(http.StatusBadRequest)
- _, err := w.Write([]byte(""))
- return err
- }
-
- if res, err := HasAuth(verification[1], id); err == nil && !res {
- w.WriteHeader(http.StatusBadRequest)
- _, err = w.Write([]byte(""))
- return err
- } else if err != nil {
- return err
- }
-
- actor, _ := activitypub.GetActorFromDB(id)
-
- var following activitypub.Collection
- var err error
-
- following.AtContext.Context = "https://www.w3.org/ns/activitystreams"
- following.Type = "Collection"
- following.TotalItems, err = actor.GetReportedTotal()
- if err != nil {
- return err
- }
-
- following.Items, err = actor.GetReported()
- if err != nil {
- return err
- }
-
- enc, err := json.MarshalIndent(following, "", "\t")
- if err != nil {
- return err
- }
-
- w.Header().Set("Content-Type", config.ActivityStreams)
-
- _, err = w.Write(enc)
- return err
-}
-
func PrintAdminAuth() error {
- identifier, code, err := GetAdminAuth()
- if err != nil {
- return err
- }
-
- fmt.Println("Mod key: " + config.Key)
- fmt.Println("Admin Login: " + identifier + ", Code: " + code)
- return nil
-}
-
-func DeleteObjectRequest(id string) error {
- var nObj activitypub.ObjectBase
- var nActor activitypub.Actor
- nObj.Id = id
- nObj.Actor = nActor.Id
-
- activity, err := webfinger.CreateActivity("Delete", nObj)
- if err != nil {
- return err
- }
-
- obj, err := nObj.GetFromPath()
- if err != nil {
- return err
- }
+ code, identifier, err := GetAdminAuth()
- actor, err := webfinger.FingerActor(obj.Actor)
if err != nil {
- return err
- }
- activity.Actor = &actor
- objActor, _ := webfinger.GetActor(obj.Actor)
- followers, err := objActor.GetFollow()
- if err != nil {
- return err
- }
-
- for _, e := range followers {
- activity.To = append(activity.To, e.Id)
- }
-
- following, err := objActor.GetFollowing()
- if err != nil {
- return err
- }
- for _, e := range following {
- activity.To = append(activity.To, e.Id)
+ return util.MakeError(err, "PrintAdminAuth")
}
- return MakeActivityRequest(activity)
-}
-
-func DeleteObjectAndRepliesRequest(id string) error {
- var nObj activitypub.ObjectBase
- var nActor activitypub.Actor
- nObj.Id = id
- nObj.Actor = nActor.Id
-
- activity, err := webfinger.CreateActivity("Delete", nObj)
- if err != nil {
- return err
- }
-
- obj, err := nObj.GetCollectionFromPath()
- if err != nil {
- return err
- }
-
- activity.Actor.Id = obj.OrderedItems[0].Actor
-
- activity.Object = &obj.OrderedItems[0]
-
- objActor, _ := webfinger.GetActor(obj.OrderedItems[0].Actor)
- followers, err := objActor.GetFollow()
- if err != nil {
- return err
- }
- for _, e := range followers {
- activity.To = append(activity.To, e.Id)
- }
-
- following, err := objActor.GetFollowing()
- if err != nil {
- return err
- }
-
- for _, e := range following {
- activity.To = append(activity.To, e.Id)
- }
-
- return MakeActivityRequest(activity)
+ config.Log.Println("Mod key: " + config.Key)
+ config.Log.Println("Admin Login: " + identifier + ", Code: " + code)
+ return nil
}
-// root actor is used to follow remote feeds that are not local
-//name, prefname, summary, auth requirements, restricted
-func InitInstance() {
+func InitInstance() error {
if config.InstanceName != "" {
- if _, err := CreateNewBoardDB(*activitypub.CreateNewActor("", config.InstanceName, config.InstanceSummary, config.AuthReq, false)); err != nil {
- //panic(err)
+ if _, err := CreateNewBoard(*activitypub.CreateNewActor("", config.InstanceName, config.InstanceSummary, config.AuthReq, false)); err != nil {
+ return util.MakeError(err, "InitInstance")
}
if config.PublicIndexing == "true" {
@@ -743,4 +445,6 @@ func InitInstance() {
//AddInstanceToIndex(config.Domain)
}
}
+
+ return nil
}
diff --git a/db/follow.go b/db/follow.go
deleted file mode 100644
index 3932ea1..0000000
--- a/db/follow.go
+++ /dev/null
@@ -1,306 +0,0 @@
-package db
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "regexp"
- "strings"
- "time"
-
- "github.com/FChannel0/FChannel-Server/activitypub"
- "github.com/FChannel0/FChannel-Server/config"
- "github.com/FChannel0/FChannel-Server/util"
- "github.com/FChannel0/FChannel-Server/webfinger"
- _ "github.com/lib/pq"
-)
-
-func AcceptFollow(activity activitypub.Activity) activitypub.Activity {
- var accept activitypub.Activity
- accept.AtContext.Context = activity.AtContext.Context
- accept.Type = "Accept"
- var nActor activitypub.Actor
- accept.Actor = &nActor
- accept.Actor.Id = activity.Object.Actor
- var nObj activitypub.ObjectBase
- accept.Object = &nObj
- accept.Object.Actor = activity.Actor.Id
- var nNested activitypub.NestedObjectBase
- accept.Object.Object = &nNested
- accept.Object.Object.Actor = activity.Object.Actor
- accept.Object.Object.Type = "Follow"
- accept.To = append(accept.To, activity.Object.Actor)
-
- return accept
-}
-
-func SetActorFollowingDB(activity activitypub.Activity) (activitypub.Activity, error) {
- var query string
- alreadyFollowing := false
- alreadyFollower := false
- objActor, _ := webfinger.GetActor(activity.Object.Actor)
- following, err := objActor.GetFollowing()
- if err != nil {
- return activity, err
- }
-
- actor, err := webfinger.FingerActor(activity.Actor.Id)
- if err != nil {
- return activity, err
- }
-
- remoteActorFollowerCol, err := webfinger.GetCollectionFromReq(actor.Followers)
- if err != nil {
- return activity, err
- }
-
- for _, e := range following {
- if e.Id == activity.Actor.Id {
- alreadyFollowing = true
- }
- }
-
- for _, e := range remoteActorFollowerCol.Items {
- if e.Id == activity.Object.Actor {
- alreadyFollower = true
- }
- }
-
- activity.Type = "Reject"
-
- if activity.Actor.Id == activity.Object.Actor {
- return activity, nil
- }
-
- if alreadyFollowing && alreadyFollower {
- query = `delete from following where id=$1 and following=$2`
- activity.Summary = activity.Object.Actor + " Unfollowing " + activity.Actor.Id
- if res, err := activity.Actor.IsLocal(); err == nil && !res {
- go activity.Actor.DeleteCache()
- } else {
- return activity, err
- }
-
- if _, err := config.DB.Exec(query, activity.Object.Actor, activity.Actor.Id); err != nil {
- return activity, err
- }
-
- activity.Type = "Accept"
- return activity, nil
- }
-
- if !alreadyFollowing && !alreadyFollower {
-
- query = `insert into following (id, following) values ($1, $2)`
- activity.Summary = activity.Object.Actor + " Following " + activity.Actor.Id
- if res, err := activity.Actor.IsLocal(); err == nil && !res {
- go WriteActorToCache(activity.Actor.Id)
- }
- if _, err := config.DB.Exec(query, activity.Object.Actor, activity.Actor.Id); err != nil {
- return activity, err
- }
-
- activity.Type = "Accept"
- return activity, nil
- }
-
- return activity, nil
-}
-
-func AutoFollow(actorID string) error {
- actor, _ := webfinger.GetActor(actorID)
- following, err := actor.GetFollowing()
- if err != nil {
- return err
- }
-
- follower, err := actor.GetFollow()
- if err != nil {
- return err
- }
-
- isFollowing := false
-
- for _, e := range follower {
- for _, k := range following {
- if e.Id == k.Id {
- isFollowing = true
- }
- }
-
- if !isFollowing && e.Id != config.Domain && e.Id != actor.Id {
- followActivity, err := MakeFollowActivity(actor.Id, e.Id)
- if err != nil {
- return err
- }
-
- nActor, err := webfinger.FingerActor(e.Id)
- if err != nil {
- return err
- }
-
- if nActor.Id != "" {
- MakeActivityRequestOutbox(followActivity)
- }
- }
- }
-
- return nil
-}
-
-func MakeFollowActivity(actor string, follow string) (activitypub.Activity, error) {
- var followActivity activitypub.Activity
- var err error
-
- followActivity.AtContext.Context = "https://www.w3.org/ns/activitystreams"
- followActivity.Type = "Follow"
-
- var obj activitypub.ObjectBase
- var nactor activitypub.Actor
- if actor == config.Domain {
- nactor, err = activitypub.GetActorFromDB(actor)
- } else {
- nactor, err = webfinger.FingerActor(actor)
- }
-
- if err != nil {
- return followActivity, err
- }
-
- followActivity.Actor = &nactor
- followActivity.Object = &obj
-
- followActivity.Object.Actor = follow
- followActivity.To = append(followActivity.To, follow)
-
- return followActivity, nil
-}
-
-func MakeActivityRequestOutbox(activity activitypub.Activity) error {
- j, _ := json.Marshal(activity)
-
- if activity.Actor.Outbox == "" {
- // TODO: good enough?
- return errors.New("invalid outbox")
- }
-
- req, err := http.NewRequest("POST", activity.Actor.Outbox, bytes.NewBuffer(j))
- if err != nil {
- return err
- }
-
- re := regexp.MustCompile("https?://(www.)?")
-
- var instance string
- if activity.Actor.Id == config.Domain {
- instance = re.ReplaceAllString(config.Domain, "")
- } else {
- _, instance = activitypub.GetActorAndInstance(activity.Actor.Id)
- }
-
- date := time.Now().UTC().Format(time.RFC1123)
- path := strings.Replace(activity.Actor.Outbox, instance, "", 1)
-
- path = re.ReplaceAllString(path, "")
-
- sig := fmt.Sprintf("(request-target): %s %s\nhost: %s\ndate: %s", "post", path, instance, date)
- encSig, err := activity.Actor.ActivitySign(sig)
- if err != nil {
- return err
- }
-
- signature := fmt.Sprintf("keyId=\"%s\",headers=\"(request-target) host date\",signature=\"%s\"", activity.Actor.PublicKey.Id, encSig)
-
- req.Header.Set("Content-Type", config.ActivityStreams)
- req.Header.Set("Date", date)
- req.Header.Set("Signature", signature)
- req.Host = instance
-
- _, err = util.RouteProxy(req)
- return err
-}
-
-func MakeActivityRequest(activity activitypub.Activity) error {
- j, _ := json.MarshalIndent(activity, "", "\t")
-
- for _, e := range activity.To {
- if e != activity.Actor.Id {
- actor, err := webfinger.FingerActor(e)
- if err != nil {
- return err
- }
-
- if actor.Id != "" {
- _, instance := activitypub.GetActorAndInstance(actor.Id)
-
- if actor.Inbox != "" {
- req, err := http.NewRequest("POST", actor.Inbox, bytes.NewBuffer(j))
- if err != nil {
- return err
- }
-
- date := time.Now().UTC().Format(time.RFC1123)
- path := strings.Replace(actor.Inbox, instance, "", 1)
-
- re := regexp.MustCompile("https?://(www.)?")
- path = re.ReplaceAllString(path, "")
-
- sig := fmt.Sprintf("(request-target): %s %s\nhost: %s\ndate: %s", "post", path, instance, date)
- encSig, err := activity.Actor.ActivitySign(sig)
- if err != nil {
- return err
- }
-
- signature := fmt.Sprintf("keyId=\"%s\",headers=\"(request-target) host date\",signature=\"%s\"", activity.Actor.PublicKey.Id, encSig)
-
- req.Header.Set("Content-Type", config.ActivityStreams)
- req.Header.Set("Date", date)
- req.Header.Set("Signature", signature)
- req.Host = instance
-
- _, err = util.RouteProxy(req)
- if err != nil {
- fmt.Println("error with sending activity resp to actor " + instance)
- return err // TODO: needs further testing
- }
- }
- }
- }
- }
-
- return nil
-}
-
-func SendToFollowers(actorID string, activity activitypub.Activity) error {
- nActor, err := activitypub.GetActorFromDB(actorID)
- if err != nil {
- return err
- }
-
- activity.Actor = &nActor
-
- followers, err := nActor.GetFollow()
- if err != nil {
- return err
- }
-
- var to []string
-
- for _, e := range followers {
- for _, k := range activity.To {
- if e.Id != k {
- to = append(to, e.Id)
- }
- }
- }
-
- activity.To = to
-
- if len(activity.Object.InReplyTo) > 0 {
- err = MakeActivityRequest(activity)
- }
-
- return err
-}
diff --git a/db/pem.go b/db/pem.go
deleted file mode 100644
index 66bf25a..0000000
--- a/db/pem.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package db
-
-import (
- "crypto"
- "crypto/rsa"
- "crypto/sha256"
- "crypto/x509"
- "encoding/base64"
- "encoding/pem"
- "strings"
- "time"
-
- "github.com/FChannel0/FChannel-Server/activitypub"
- "github.com/FChannel0/FChannel-Server/webfinger"
- "github.com/gofiber/fiber/v2"
-)
-
-func VerifyHeaderSignature(ctx *fiber.Ctx, actor activitypub.Actor) bool {
- s := activitypub.ParseHeaderSignature(ctx.Get("Signature"))
-
- var method string
- var path string
- var host string
- var date string
- var digest string
- var contentLength string
-
- var sig string
- for i, e := range s.Headers {
- var nl string
- if i < len(s.Headers)-1 {
- nl = "\n"
- }
-
- switch e {
- case "(request-target)":
- method = strings.ToLower(ctx.Method())
- path = ctx.Path()
- sig += "(request-target): " + method + " " + path + "" + nl
- break
- case "host":
- host = ctx.Hostname()
- sig += "host: " + host + "" + nl
- break
- case "date":
- date = ctx.Get("date")
- sig += "date: " + date + "" + nl
- break
- case "digest":
- digest = ctx.Get("digest")
- sig += "digest: " + digest + "" + nl
- break
- case "content-length":
- contentLength = ctx.Get("content-length")
- sig += "content-length: " + contentLength + "" + nl
- break
- }
- }
-
- if s.KeyId != actor.PublicKey.Id {
- return false
- }
-
- t, _ := time.Parse(time.RFC1123, date)
-
- if time.Now().UTC().Sub(t).Seconds() > 75 {
- return false
- }
-
- if ActivityVerify(actor, s.Signature, sig) != nil {
- return false
- }
-
- return true
-}
-
-func ActivityVerify(actor activitypub.Actor, signature string, verify string) error {
- sig, _ := base64.StdEncoding.DecodeString(signature)
-
- if actor.PublicKey.PublicKeyPem == "" {
- _actor, err := webfinger.FingerActor(actor.Id)
- if err != nil {
- return err
- }
- actor = _actor
- }
-
- block, _ := pem.Decode([]byte(actor.PublicKey.PublicKeyPem))
- pub, _ := x509.ParsePKIXPublicKey(block.Bytes)
-
- hashed := sha256.New()
- hashed.Write([]byte(verify))
-
- return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.SHA256, hashed.Sum(nil), sig)
-}
diff --git a/db/report.go b/db/report.go
index 4120d9a..958b619 100644
--- a/db/report.go
+++ b/db/report.go
@@ -1,6 +1,9 @@
package db
-import "github.com/FChannel0/FChannel-Server/config"
+import (
+ "github.com/FChannel0/FChannel-Server/config"
+ "github.com/FChannel0/FChannel-Server/util"
+)
type Report struct {
ID string
@@ -14,57 +17,53 @@ type Removed struct {
Board string
}
-func CreateLocalDeleteDB(id string, _type string) error {
- query := `select id from removed where id=$1`
-
- rows, err := config.DB.Query(query, id)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- if rows.Next() {
- var i string
+func CloseLocalReport(id string, board string) error {
+ query := `delete from reported where id=$1 and board=$2`
+ _, err := config.DB.Exec(query, id, board)
- if err := rows.Scan(&i); err != nil {
- return err
- }
+ return util.MakeError(err, "CloseLocalReportDB")
+}
- if i != "" {
- query := `update removed set type=$1 where id=$2`
+func CreateLocalDelete(id string, _type string) error {
+ var i string
- if _, err := config.DB.Exec(query, _type, id); err != nil {
- return err
- }
- }
- } else {
+ query := `select id from removed where id=$1`
+ if err := config.DB.QueryRow(query, id).Scan(&i); err != nil {
query := `insert into removed (id, type) values ($1, $2)`
-
if _, err := config.DB.Exec(query, id, _type); err != nil {
- return err
+ return util.MakeError(err, "CreateLocalDeleteDB")
}
}
- return nil
+ query = `update removed set type=$1 where id=$2`
+ _, err := config.DB.Exec(query, _type, id)
+
+ return util.MakeError(err, "CreateLocalDeleteDB")
+}
+
+func CreateLocalReport(id string, board string, reason string) error {
+ query := `insert into reported (id, count, board, reason) values ($1, $2, $3, $4)`
+ _, err := config.DB.Exec(query, id, 1, board, reason)
+
+ return util.MakeError(err, "CreateLocalReportDB")
}
-func GetLocalDeleteDB() ([]Removed, error) {
+func GetLocalDelete() ([]Removed, error) {
var deleted []Removed
query := `select id, type from removed`
-
rows, err := config.DB.Query(query)
+
if err != nil {
- return deleted, err
+ return deleted, util.MakeError(err, "GetLocalDeleteDB")
}
defer rows.Close()
-
for rows.Next() {
var r Removed
if err := rows.Scan(&r.ID, &r.Type); err != nil {
- return deleted, err
+ return deleted, util.MakeError(err, "GetLocalDeleteDB")
}
deleted = append(deleted, r)
@@ -73,58 +72,22 @@ func GetLocalDeleteDB() ([]Removed, error) {
return deleted, nil
}
-func CreateLocalReportDB(id string, board string, reason string) error {
- query := `select id, count from reported where id=$1 and board=$2`
-
- rows, err := config.DB.Query(query, id, board)
- if err != nil {
- return err
- }
- defer rows.Close()
-
- if rows.Next() {
- var i string
- var count int
-
- if err := rows.Scan(&i, &count); err != nil {
- return err
- }
-
- if i != "" {
- count = count + 1
- query := `update reported set count=$1 where id=$2`
-
- if _, err := config.DB.Exec(query, count, id); err != nil {
- return err
- }
- }
- } else {
- query := `insert into reported (id, count, board, reason) values ($1, $2, $3, $4)`
-
- if _, err := config.DB.Exec(query, id, 1, board, reason); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func GetLocalReportDB(board string) ([]Report, error) {
+func GetLocalReport(board string) ([]Report, error) {
var reported []Report
query := `select id, count, reason from reported where board=$1`
-
rows, err := config.DB.Query(query, board)
+
if err != nil {
- return reported, err
+ return reported, util.MakeError(err, "GetLocalReportDB")
}
- defer rows.Close()
+ defer rows.Close()
for rows.Next() {
var r Report
if err := rows.Scan(&r.ID, &r.Count, &r.Reason); err != nil {
- return reported, err
+ return reported, util.MakeError(err, "GetLocalReportDB")
}
reported = append(reported, r)
@@ -132,10 +95,3 @@ func GetLocalReportDB(board string) ([]Report, error) {
return reported, nil
}
-
-func CloseLocalReportDB(id string, board string) error {
- query := `delete from reported where id=$1 and board=$2`
-
- _, err := config.DB.Exec(query, id, board)
- return err
-}
diff --git a/db/verification.go b/db/verification.go
deleted file mode 100644
index eea22ea..0000000
--- a/db/verification.go
+++ /dev/null
@@ -1,514 +0,0 @@
-package db
-
-import (
- "fmt"
- "math/rand"
- "net/smtp"
- "os"
- "os/exec"
- "strings"
- "time"
-
- "github.com/FChannel0/FChannel-Server/activitypub"
- "github.com/FChannel0/FChannel-Server/config"
- "github.com/FChannel0/FChannel-Server/util"
- "github.com/gofiber/fiber/v2"
- _ "github.com/lib/pq"
-)
-
-type Verify struct {
- Type string
- Identifier string
- Code string
- Created string
- Board string
-}
-
-type VerifyCooldown struct {
- Identifier string
- Code string
- Time int
-}
-
-type Signature struct {
- KeyId string
- Headers []string
- Signature string
- Algorithm string
-}
-
-func DeleteBoardMod(verify Verify) error {
- query := `select code from boardaccess where identifier=$1 and board=$1`
-
- rows, err := config.DB.Query(query, verify.Identifier, verify.Board)
- if err != nil {
- return err
- }
-
- defer rows.Close()
-
- var code string
- rows.Next()
- rows.Scan(&code)
-
- if code != "" {
- query := `delete from crossverification where code=$1`
-
- if _, err := config.DB.Exec(query, code); err != nil {
- return err
- }
-
- query = `delete from boardaccess where identifier=$1 and board=$2`
-
- if _, err := config.DB.Exec(query, verify.Identifier, verify.Board); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func GetBoardMod(identifier string) (Verify, error) {
- var nVerify Verify
-
- query := `select code, board, type, identifier from boardaccess where identifier=$1`
-
- rows, err := config.DB.Query(query, identifier)
-
- if err != nil {
- return nVerify, err
- }
-
- defer rows.Close()
-
- rows.Next()
- rows.Scan(&nVerify.Code, &nVerify.Board, &nVerify.Type, &nVerify.Identifier)
-
- return nVerify, nil
-}
-
-func CreateBoardMod(verify Verify) error {
- pass := util.CreateKey(50)
-
- query := `select code from verification where identifier=$1 and type=$2`
-
- rows, err := config.DB.Query(query, verify.Board, verify.Type)
- if err != nil {
- return err
- }
-
- defer rows.Close()
-
- var code string
-
- rows.Next()
- rows.Scan(&code)
-
- if code != "" {
-
- query := `select identifier from boardaccess where identifier=$1 and board=$2`
-
- rows, err := config.DB.Query(query, verify.Identifier, verify.Board)
- if err != nil {
- return err
- }
-
- defer rows.Close()
-
- var ident string
- rows.Next()
- rows.Scan(&ident)
-
- if ident != verify.Identifier {
-
- query := `insert into crossverification (verificationcode, code) values ($1, $2)`
-
- if _, err := config.DB.Exec(query, code, pass); err != nil {
- return err
- }
-
- query = `insert into boardaccess (identifier, code, board, type) values ($1, $2, $3, $4)`
-
- if _, err = config.DB.Exec(query, verify.Identifier, pass, verify.Board, verify.Type); err != nil {
- return err
- }
-
- fmt.Printf("Board access - Board: %s, Identifier: %s, Code: %s\n", verify.Board, verify.Identifier, pass)
- }
- }
-
- return nil
-}
-
-func CreateVerification(verify Verify) error {
- query := `insert into verification (type, identifier, code, created) values ($1, $2, $3, $4)`
-
- _, err := config.DB.Exec(query, verify.Type, verify.Identifier, verify.Code, time.Now().UTC().Format(time.RFC3339))
- return err
-}
-
-func GetVerificationByEmail(email string) (Verify, error) {
- // TODO: this only needs to select one row.
-
- var verify Verify
-
- query := `select type, identifier, code, board from boardaccess where identifier=$1`
-
- rows, err := config.DB.Query(query, email)
- if err != nil {
- return verify, err
- }
-
- defer rows.Close()
-
- for rows.Next() {
- if err := rows.Scan(&verify.Type, &verify.Identifier, &verify.Code, &verify.Board); err != nil {
- return verify, err
- }
- }
-
- return verify, nil
-}
-
-func GetVerificationByCode(code string) (Verify, error) {
- // TODO: this only needs to select one row.
-
- var verify Verify
-
- query := `select type, identifier, code, board from boardaccess where code=$1`
-
- rows, err := config.DB.Query(query, code)
- if err != nil {
- return verify, err
- }
-
- defer rows.Close()
-
- for rows.Next() {
- if err := rows.Scan(&verify.Type, &verify.Identifier, &verify.Code, &verify.Board); err != nil {
- return verify, err
- }
- }
-
- return verify, nil
-}
-
-func GetVerificationCode(verify Verify) (Verify, error) {
- var nVerify Verify
-
- query := `select type, identifier, code, board from boardaccess where identifier=$1 and board=$2`
-
- rows, err := config.DB.Query(query, verify.Identifier, verify.Board)
- if err != nil {
- return verify, err
- }
-
- defer rows.Close()
-
- for rows.Next() {
- if err := rows.Scan(&nVerify.Type, &nVerify.Identifier, &nVerify.Code, &nVerify.Board); err != nil {
- return nVerify, err
- }
-
- }
-
- return nVerify, nil
-}
-
-func VerifyCooldownCurrent(auth string) (VerifyCooldown, error) {
- var current VerifyCooldown
-
- query := `select identifier, code, time from verificationcooldown where code=$1`
-
- rows, err := config.DB.Query(query, auth)
- if err != nil {
- query := `select identifier, code, time from verificationcooldown where identifier=$1`
-
- rows, err := config.DB.Query(query, auth)
-
- if err != nil {
- return current, err
- }
-
- defer rows.Close()
-
- for rows.Next() {
- if err := rows.Scan(¤t.Identifier, ¤t.Code, ¤t.Time); err != nil {
- return current, err
- }
- }
- } else {
- defer rows.Close()
- }
-
- for rows.Next() {
- if err := rows.Scan(¤t.Identifier, ¤t.Code, ¤t.Time); err != nil {
- return current, err
- }
- }
-
- return current, nil
-}
-
-func VerifyCooldownAdd(verify Verify) error {
- query := `insert into verficationcooldown (identifier, code) values ($1, $2)`
-
- _, err := config.DB.Exec(query, verify.Identifier, verify.Code)
- return err
-}
-
-func VerficationCooldown() error {
- query := `select identifier, code, time from verificationcooldown`
-
- rows, err := config.DB.Query(query)
- if err != nil {
- return err
- }
-
- defer rows.Close()
-
- for rows.Next() {
- var verify VerifyCooldown
-
- if err := rows.Scan(&verify.Identifier, &verify.Code, &verify.Time); err != nil {
- return err
- }
-
- nTime := verify.Time - 1
-
- query = `update set time=$1 where identifier=$2`
-
- if _, err := config.DB.Exec(query, nTime, verify.Identifier); err != nil {
- return err
- }
-
- VerficationCooldownRemove()
- }
-
- return nil
-}
-
-func VerficationCooldownRemove() error {
- query := `delete from verificationcooldown where time < 1`
-
- _, err := config.DB.Exec(query)
- return err
-}
-
-func SendVerification(verify Verify) error {
- fmt.Println("sending email")
-
- from := config.SiteEmail
- pass := config.SiteEmailPassword
- to := verify.Identifier
- body := fmt.Sprintf("You can use either\r\nEmail: %s \r\n Verfication Code: %s\r\n for the board %s", verify.Identifier, verify.Code, verify.Board)
-
- msg := "From: " + from + "\n" +
- "To: " + to + "\n" +
- "Subject: Image Board Verification\n\n" +
- body
-
- return smtp.SendMail(config.SiteEmailServer+":"+config.SiteEmailPort,
- smtp.PlainAuth("", from, pass, config.SiteEmailServer),
- from, []string{to}, []byte(msg))
-}
-
-func IsEmailSetup() bool {
- return config.SiteEmail != "" || config.SiteEmailPassword != "" || config.SiteEmailServer != "" || config.SiteEmailPort != ""
-}
-
-func HasAuth(code string, board string) (bool, error) {
- verify, err := GetVerificationByCode(code)
- if err != nil {
- return false, err
- }
-
- if res, err := HasBoardAccess(verify); err != nil && (verify.Board == config.Domain || (res && verify.Board == board)) {
- return true, nil
- } else {
- return false, err
- }
-
- return false, nil
-}
-
-func HasAuthCooldown(auth string) (bool, error) {
- current, err := VerifyCooldownCurrent(auth)
- if err != nil {
- return false, err
- }
-
- if current.Time > 0 {
- return true, nil
- }
-
- // fmt.Println("has auth is false")
- return false, nil
-}
-
-func GetVerify(access string) (Verify, error) {
- verify, err := GetVerificationByCode(access)
- if err != nil {
- return verify, err
- }
-
- if verify.Identifier == "" {
- verify, err = GetVerificationByEmail(access)
- }
-
- return verify, err
-}
-
-func CreateNewCaptcha() error {
- id := util.RandomID(8)
- file := "public/" + id + ".png"
-
- for true {
- if _, err := os.Stat("./" + file); err == nil {
- id = util.RandomID(8)
- file = "public/" + id + ".png"
- } else {
- break
- }
- }
-
- captcha := Captcha()
-
- var pattern string
- rnd := fmt.Sprintf("%d", rand.Intn(3))
-
- srnd := string(rnd)
-
- switch srnd {
- case "0":
- pattern = "pattern:verticalbricks"
- break
-
- case "1":
- pattern = "pattern:verticalsaw"
- break
-
- case "2":
- pattern = "pattern:hs_cross"
- break
-
- }
-
- cmd := exec.Command("convert", "-size", "200x98", pattern, "-transparent", "white", file)
- cmd.Stderr = os.Stderr
-
- if err := cmd.Run(); err != nil {
- return err
- }
-
- cmd = exec.Command("convert", file, "-fill", "blue", "-pointsize", "62", "-annotate", "+0+70", captcha, "-tile", "pattern:left30", "-gravity", "center", "-transparent", "white", file)
- cmd.Stderr = os.Stderr
-
- if err := cmd.Run(); err != nil {
- return err
- }
-
- rnd = fmt.Sprintf("%d", rand.Intn(24)-12)
-
- cmd = exec.Command("convert", file, "-rotate", rnd, "-wave", "5x35", "-distort", "Arc", "20", "-wave", "2x35", "-transparent", "white", file)
- cmd.Stderr = os.Stderr
-
- if err := cmd.Run(); err != nil {
- return err
- }
-
- var verification Verify
- verification.Type = "captcha"
- verification.Code = captcha
- verification.Identifier = file
-
- return CreateVerification(verification)
-}
-
-func CreateBoardAccess(verify Verify) error {
- hasAccess, err := HasBoardAccess(verify)
- if err != nil {
- return err
- }
-
- if !hasAccess {
- query := `insert into boardaccess (identifier, board) values($1, $2)`
-
- _, err := config.DB.Exec(query, verify.Identifier, verify.Board)
- return err
- }
-
- return nil
-}
-
-func HasBoardAccess(verify Verify) (bool, error) {
- query := `select count(*) from boardaccess where identifier=$1 and board=$2`
-
- rows, err := config.DB.Query(query, verify.Identifier, verify.Board)
- if err != nil {
- return false, err
- }
-
- defer rows.Close()
-
- var count int
-
- rows.Next()
- rows.Scan(&count)
-
- if count > 0 {
- return true, nil
- } else {
- return false, nil
- }
-}
-
-func BoardHasAuthType(board string, auth string) (bool, error) {
- authTypes, err := util.GetBoardAuth(board)
- if err != nil {
- return false, err
- }
-
- for _, e := range authTypes {
- if e == auth {
- return true, nil
- }
- }
-
- return false, nil
-}
-
-func Captcha() string {
- rand.Seed(time.Now().UTC().UnixNano())
- domain := "ABEFHKMNPQRSUVWXYZ#$&"
- rng := 4
- newID := ""
- for i := 0; i < rng; i++ {
- newID += string(domain[rand.Intn(len(domain))])
- }
-
- return newID
-}
-
-func HasValidation(ctx *fiber.Ctx, actor activitypub.Actor) bool {
- id, _ := GetPasswordFromSession(ctx)
-
- if id == "" || (id != actor.Id && id != config.Domain) {
- //http.Redirect(w, r, "/", http.StatusSeeOther)
- return false
- }
-
- return true
-}
-
-func GetPasswordFromSession(r *fiber.Ctx) (string, string) {
- cookie := r.Cookies("session_token")
-
- parts := strings.Split(cookie, "|")
-
- if len(parts) > 1 {
- return parts[0], parts[1]
- }
-
- return "", ""
-}
--
cgit v1.2.3