website/pkg/controller/chat/chat.go

211 lines
5.7 KiB
Go
Raw Normal View History

2023-02-06 04:26:36 +00:00
package chat
import (
"bytes"
"encoding/json"
2023-02-06 04:26:36 +00:00
"fmt"
"io"
2023-02-06 04:26:36 +00:00
"net/http"
"strings"
"time"
"code.nonshy.com/nonshy/website/pkg/config"
"code.nonshy.com/nonshy/website/pkg/geoip"
"code.nonshy.com/nonshy/website/pkg/log"
"code.nonshy.com/nonshy/website/pkg/middleware"
"code.nonshy.com/nonshy/website/pkg/models"
2023-02-06 04:26:36 +00:00
"code.nonshy.com/nonshy/website/pkg/photo"
"code.nonshy.com/nonshy/website/pkg/session"
"code.nonshy.com/nonshy/website/pkg/templates"
"code.nonshy.com/nonshy/website/pkg/worker"
2023-02-06 04:26:36 +00:00
"github.com/golang-jwt/jwt/v4"
)
// JWT claims.
type Claims struct {
// Custom claims.
IsAdmin bool `json:"op,omitempty"`
Avatar string `json:"img,omitempty"`
ProfileURL string `json:"url,omitempty"`
Nickname string `json:"nick,omitempty"`
Emoji string `json:"emoji,omitempty"`
Gender string `json:"gender,omitempty"`
2023-02-06 04:26:36 +00:00
// Standard claims. Notes:
// subject = username
jwt.RegisteredClaims
}
// Gender returns the BareRTC gender string for the user's gender selection.
func Gender(u *models.User) string {
switch u.GetProfileField("gender") {
case "Man", "Trans (FTM)":
return "m"
case "Woman", "Trans (MTF)":
return "f"
case "Non-binary", "Trans", "Other":
return "o"
default:
return ""
}
}
2023-02-06 04:26:36 +00:00
// Landing page for chat rooms.
func Landing() http.HandlerFunc {
tmpl := templates.Must("chat.html")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the current user.
currentUser, err := session.CurrentUser(r)
if err != nil {
session.FlashError(w, r, "Couldn't get current user: %s", err)
templates.Redirect(w, "/")
return
}
// Are they logging into the chat room?
var (
intent = r.FormValue("intent")
isShy = currentUser.IsShy()
)
2023-02-06 04:26:36 +00:00
if intent == "join" {
// Maintenance mode?
if middleware.ChatMaintenance(currentUser, w, r) {
return
}
// If we are shy, block chat for now.
if isShy {
session.FlashError(w, r,
"You have a Shy Account and are not allowed in the chat room at this time where our non-shy members may "+
"be on camera.",
)
templates.Redirect(w, "/chat")
return
}
2023-02-06 04:26:36 +00:00
// Get our Chat JWT secret.
var (
secret = []byte(config.Current.BareRTC.JWTSecret)
chatURL = config.Current.BareRTC.URL
)
if len(secret) == 0 || chatURL == "" {
session.FlashError(w, r, "Couldn't sign you into the chat: JWT secret key or chat URL not configured!")
templates.Redirect(w, r.URL.Path)
return
}
// Avatar URL - masked if non-public.
avatar := photo.URLPath(currentUser.ProfilePhoto.CroppedFilename)
switch currentUser.ProfilePhoto.Visibility {
case models.PhotoPrivate:
avatar = "/static/img/shy-private.png"
case models.PhotoFriends:
avatar = "/static/img/shy-friends.png"
}
// Country flag emoji.
2023-08-16 03:56:22 +00:00
emoji, err := geoip.GetChatFlagEmoji(r)
if err != nil {
emoji, err = geoip.CountryFlagEmojiWithCode("US")
if err != nil {
emoji = "🏴‍☠️"
}
}
2023-02-06 04:26:36 +00:00
// Create the JWT claims.
claims := Claims{
Admin Groups & Permissions Add a permission system for admin users so you can lock down specific admins to a narrower set of features instead of them all having omnipotent powers. * New page: Admin Dashboard -> Admin Permissions Management * Permissions are handled in the form of 'scopes' relevant to each feature or action on the site. Scopes are assigned to Groups, and in turn, admin user accounts are placed in those Groups. * The Superusers group (scope '*') has wildcard permission to all scopes. The permissions dashboard has a create-once action to initialize the Superusers for the first admin who clicks on it, and places that admin in the group. The following are the exhaustive list of permission changes on the site: * Moderator scopes: * Chat room (enter the room with Operator permission) * Forums (can edit or delete user posts on the forum) * Photo Gallery (can see all private/friends-only photos on the site gallery or user profile pages) * Certification photos (with nuanced sub-action permissions) * Approve: has access to the Pending tab to act on incoming pictures * List: can paginate thru past approved/rejected photos * View: can bring up specific user cert photo from their profile * The minimum requirement is Approve or else no cert photo page will load for your admin user. * User Actions (each action individually scoped) * Impersonate * Ban * Delete * Promote to admin * Inner circle whitelist: no longer are admins automatically part of the inner circle unless they have a specialized scope attached. The AdminRequired decorator may also apply scopes on an entire admin route. The following routes have scopes to limit them: * Forum Admin (manage forums and their settings) * Remove from inner circle
2023-08-02 03:39:48 +00:00
IsAdmin: currentUser.HasAdminScope(config.ScopeChatModerator),
Avatar: avatar,
2023-02-06 04:26:36 +00:00
ProfileURL: "/u/" + currentUser.Username,
2023-04-19 05:19:08 +00:00
Nickname: currentUser.NameOrUsername(),
Emoji: emoji,
Gender: Gender(currentUser),
2023-02-06 04:26:36 +00:00
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(5 * time.Minute)),
2023-02-06 04:26:36 +00:00
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: config.Title,
Subject: currentUser.Username,
ID: fmt.Sprintf("%d", currentUser.ID),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString(secret)
if err != nil {
session.FlashError(w, r, "Couldn't sign you into the chat: %s", err)
templates.Redirect(w, r.URL.Path)
return
}
// Send over their blocklist to the chat server.
if err := SendBlocklist(currentUser); err != nil {
log.Error("SendBlocklist: %s", err)
}
2023-02-06 04:26:36 +00:00
// Redirect them to the chat room.
templates.Redirect(w, strings.TrimSuffix(chatURL, "/")+"/?jwt="+ss)
return
}
2023-02-10 07:07:07 +00:00
var vars = map[string]interface{}{
"ChatAPI": strings.TrimSuffix(config.Current.BareRTC.URL, "/") + "/api/statistics",
"IsShyUser": isShy,
// Pre-populate the "who's online" widget from backend cache data
"ChatStatistics": worker.GetChatStatistics(),
2023-02-10 07:07:07 +00:00
}
2023-02-06 04:26:36 +00:00
if err := tmpl.Execute(w, r, vars); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
}
// SendBlocklist syncs the user blocklist to the chat server prior to sending them over.
func SendBlocklist(user *models.User) error {
// Get the user's blocklist.
blockedUsernames := models.BlockedUsernames(user.ID)
log.Info("SendBlocklist(%s) to BareRTC: %d blocked usernames", user.Username, len(blockedUsernames))
// API request struct for BareRTC /api/blocklist endpoint.
var request = struct {
APIKey string
Username string
Blocklist []string
}{
config.Current.CronAPIKey,
user.Username,
blockedUsernames,
}
// JSON request body.
jsonStr, err := json.Marshal(request)
if err != nil {
return err
}
// Make the API request to BareRTC.
2023-07-30 17:56:14 +00:00
var url = strings.TrimSuffix(config.Current.BareRTC.URL, "/") + "/api/blocklist"
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
log.Error("SendBlocklist: error syncing blocklist to BareRTC: status %d body %s", resp.StatusCode, body)
}
return nil
}