page.auth.actions.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
 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/json"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func (config *Config) IsAdmin(r *http.Request) (bool, string) {
	if cookie, err := r.Cookie("tap-auth"); err == nil {
		config.sessionMapLock.Lock()
		defer config.sessionMapLock.Unlock()

		if _, exists := config.sessions[cookie.Value]; exists {
			return true, cookie.Value
		}
	}
	return false, ""
}

func (config *Config) likeHandler(w http.ResponseWriter, r *http.Request) {
	if isAdmin, session := config.IsAdmin(r); isAdmin {
		if r.Method == http.MethodPost {
			target := r.FormValue("target")
			activeUser := config.ActiveAccount(session)
			if targetJson, err := os.ReadFile(target); err == nil {
				if strings.HasPrefix(target, "notes") {
					targetNote := &NoteMeta{}
					if err := json.Unmarshal(targetJson, targetNote); err == nil {
						if actor, err := activeUser.fetchActorInfo(targetNote.AttributedTo, false); err == nil {
							activeUser.SendLike(targetNote.ID, actor.Inbox)
						}
					}
				} else {
					targetNote := &PostMeta{}
					if err := json.Unmarshal(targetJson, targetNote); err == nil {
						if actor, err := activeUser.fetchActorInfo(targetNote.Actor, false); err == nil {
							activeUser.SendLike(targetNote.Object.ID, actor.Inbox)
						}
					}
				}
			}
		}
	} else {
		fmt.Printf("[access] could not find session for [like]\n")
	}
	http.Redirect(w, r, r.Referer(), http.StatusTemporaryRedirect)
}

func LinkHandle(link string, handle string) string {
	return fmt.Sprintf("<a href=\"%s\" class=\"u-url mention\">%s</a>", link, handle)
}

func (config *Config) switchHandler(w http.ResponseWriter, r *http.Request) {

	if isAdmin, session := config.IsAdmin(r); isAdmin {
		if r.Method == http.MethodPost {

			err := r.ParseForm()
			if err != nil {
				http.Error(w, "Error parsing form data", http.StatusBadRequest)
				return
			}

			account := r.FormValue("account")
			config.ChangeActiveAccount(session, account)
			http.Redirect(w, r, "https://"+config.Host+"/"+account, http.StatusFound)
			return
		}
	}
	http.Error(w, "Error parsing form data", http.StatusBadRequest)
}

func (config *Config) newHandler(w http.ResponseWriter, r *http.Request) {

	if isAdmin, session := config.IsAdmin(r); isAdmin {
		if r.Method != http.MethodPost {

			parentRef := r.URL.Query().Get("parent")
			replyContent := ""
			activeUser := config.ActiveAccount(session)
			if parentRef != "" {
				if note := activeUser.NoteFromRef(parentRef); note != nil {
					if from, err := activeUser.fetchActorInfo(note.actor, false); err == nil {
						fmt.Printf("[sending] checking reply: %s %s %s\n", note.actor, from.ID, activeUser.ID)
						if from.ID != activeUser.ID {
							replyContent += LinkHandle(from.ID, from.Handle()) + " "
						}
						for _, mention := range note.Tag {
							if mention.Name != from.Handle() && mention.Href != activeUser.ID {
								replyContent += LinkHandle(mention.Href, mention.Name) + " "
							}
						}
					}
				}
			}

			page := config.DefaultPage(r)
			page.Accounts = config.Users
			page.ReplyToRef = parentRef
			page.ReplyContents = template.HTML(config.UGCPolicy.Sanitize(replyContent))
			config.Templates.ExecuteTemplate(w, "new.tpl.html", page)
			return
		} else {

			err := r.ParseForm()
			if err != nil {
				http.Error(w, "Error parsing form data", http.StatusBadRequest)
				return
			}

			account := r.FormValue("account")
			post := r.FormValue("post")
			replyTo := r.FormValue("replyto")
			if account == "" || post == "" {
				page := config.DefaultPage(r)
				page.Accounts = config.Users
				config.Templates.ExecuteTemplate(w, "new.tpl.html", page)
				return
			} else {
				for _, user := range config.Users {
					if user.UserNamePlain == account {

						created := time.Now()

						note := NoteMeta{}

						note.Type = "Note"
						note.To = []string{"https://www.w3.org/ns/activitystreams#Public"}
						note.CC = []string{user.ID + "/followers"}

						if replyTo != "" {
							if replyNote := user.NoteFromRef(replyTo); replyNote != nil {
								note.InReplyTo = replyNote.ID
								note.CC = append(note.CC, replyNote.actor)
							}
						}

						note.Tag = ExtractMentions(post)

						for _, tag := range note.Tag {
							if tag.Type == "Mention" {
								note.CC = append(note.CC, tag.Href)
							}
						}

						note.Content = post
						note.ContentMap = map[string]string{}
						note.ContentMap["en"] = post
						note.Published = created.Format("2006-01-02T15:04:05Z")
						note.ID = user.ID + "/posts/" + strconv.Itoa(int(created.Unix()))
						note.URL = note.ID
						note.Sensitive = false
						note.AttributedTo = user.ID

						note.created = created

						note.Conversation = fmt.Sprintf("tag:%s,%s:objectID=%d:objectType=Conversation", config.Host, time.Now().Format("2006-01-02"), int(created.Unix()))

						note.Likes = CollectionMeta{
							ID:         note.ID + "/likes",
							Type:       "Collection",
							TotalItems: 0,
						}

						note.Shares = CollectionMeta{
							ID:         note.ID + "/shares",
							Type:       "Collection",
							TotalItems: 0,
						}

						note.Replies = CollectionMeta{
							ID:         note.ID + "/replies",
							Type:       "Collection",
							TotalItems: 0,
						}

						data, _ := json.Marshal(note)
						CacheData(user, "notes", "", note.ID, data)

						user.PostMessage(note)
					}
				}

				http.Redirect(w, r, "https://"+config.Host+"/"+account, http.StatusFound)
			}

			return
		}
	} else {
		fmt.Printf("[access] could not find session\n")
	}

	http.Redirect(w, r, "https://"+config.Host+"/login", http.StatusTemporaryRedirect)
}

func (config *Config) loginHandler(w http.ResponseWriter, r *http.Request) {
	// Check if the request method is POST
	if r.Method != http.MethodPost {
		config.Templates.ExecuteTemplate(w, "login.tpl.html", config.DefaultPage(r))
		return
	}

	err := r.ParseForm()
	if err != nil {
		http.Error(w, "Error parsing form data", http.StatusBadRequest)
		return
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	// TODO: Replace this with argon2 or something...
	adminPasswordHash, _ := os.ReadFile("adminpass")
	hash := sha256.Sum256([]byte(password))
	if username == "admin" && subtle.ConstantTimeCompare(adminPasswordHash, hash[:]) == 1 {

		sessionID := rand.Text()
		config.sessionMapLock.Lock()
		config.sessions[sessionID] = config.Users[0]
		config.sessionMapLock.Unlock()

		http.SetCookie(w, &http.Cookie{
			Name:     "tap-auth",
			Value:    sessionID,
			Expires:  time.Now().Add(time.Hour * 24),
			Secure:   true,
			HttpOnly: true,
			Path:     "/",
			SameSite: http.SameSiteLaxMode,
		})

		http.Redirect(w, r, "https://"+config.Host+"/admin", http.StatusTemporaryRedirect)

	} else {
		config.Templates.ExecuteTemplate(w, "login.tpl.html", config.DefaultPage(r))
	}
}