gosora/common/user.go

869 lines
22 KiB
Go
Raw Normal View History

/*
*
* Gosora User File
* Copyright Azareal 2017 - 2020
*
*/
package common
import (
"database/sql"
"errors"
"strconv"
"strings"
"time"
//"log"
qgen "github.com/Azareal/Gosora/query_gen"
"github.com/go-sql-driver/mysql"
)
2016-12-02 07:38:54 +00:00
// TODO: Replace any literals with this
var BanGroup = 4
UNSTABLE: Began work on the Nox Theme. Removed the Tempra Cursive Theme. You can now do bulk moderation actions with Shadow. Added: Argon2 as a dependency. The EmailStore. The ReportStore. The Copy method to *Setting. The AddColumn method to the query builder and adapters. The textarea setting type. More logging to better debug issues. The GetOffset method to the UserStore. Removed: Sortable from Code Climate's Analysis. MemberCheck and memberCheck as they're obsolete now. The obsolete url_tags setting. The BcryptGeneratePasswordNoSalt function. Some redundant fields from some of the page structs. Revamped: The Control Panel Setting List and Editor. Refactored: The password hashing logic to make it more amenable to multiple hashing algorithms. The email portion of the Account Manager. The Control Panel User List. The report system. simplePanelUserCheck and simpleUserCheck to remove the duplicated logic as the two do the exact same thing. Fixed: Missing slugs in the profile links in the User Manager. A few template initialisers potentially reducing the number of odd template edge cases. Some problems with the footer. Custom selection colour not applying to images on Shadow. The avatars of the bottom row of the topic list on Conflux leaking out. Other: Moved the startTime variable into package common and exported it. Moved the password hashing logic from user.go to auth.go Split common/themes.go into common/theme.go and common/theme_list.go Replaced the SettingLabels phrase category with the more generic SettingPhrases category. Moved a load of routes, including panel ones into the routes and panel packages. Hid the notifications link from the Account Menu. Moved more inline CSS into the CSS files and made things a little more flexible here and there. Continued work on PgSQL, still a ways away. Guests now have a default avatar like everyone else. Tweaked some of the font sizes on Cosora to make the text look a little nicer. Partially implemented the theme dock override logic. Partially implemented a "symlink" like feature for theme directories. ... And a bunch of other things I might have missed. You will need to run this update script / patcher for this commit. Warning: This is an "unstable commit", therefore some things may be a little less stable than I'd like. For instance, the Shadow Theme is a little broken in this commit.
2018-05-27 09:36:35 +00:00
// TODO: Use something else as the guest avatar, maybe a question mark of some sort?
// GuestUser is an instance of user which holds guest data to avoid having to initialise a guest every time
var GuestUser = User{ID: 0, Name: "Guest", Link: "#", Group: 6, Perms: GuestPerms, CreatedAt: StartTime} // BuildAvatar is done in site.go to make sure it's done after init
var ErrNoTempGroup = errors.New("We couldn't find a temporary group for this user")
type User struct {
ID int
Link string
Name string
Email string
Group int
Active bool
IsMod bool
IsSuperMod bool
IsAdmin bool
IsSuperAdmin bool
IsBanned bool
Perms Perms
PluginPerms map[string]bool
Session string
//AuthToken string
Loggedin bool
RawAvatar string
Avatar string
MicroAvatar string
Message string
// TODO: Implement something like this for profiles?
//URLPrefix string // Move this to another table? Create a user lite?
//URLName string
Tag string
Level int
Score int
Posts int
Liked int
CreatedAt time.Time
LastIP string // ! This part of the UserCache data might fall out of date
LastAgent int // ! Temporary hack for http push, don't use
TempGroup int
ParseSettings *ParseSettings
Privacy UserPrivacy
}
type UserPrivacy struct {
ShowComments int // 0 = default, 1 = public, 2 = registered, 3 = friends, 4 = self, 5 = disabled / unused
AllowMessage int // 0 = default, 1 = registered, 2 = friends, 3 = mods, 4 = disabled / unused
2016-12-02 07:38:54 +00:00
}
2019-08-31 22:59:00 +00:00
func (u *User) WebSockets() *WsJSONUser {
groupID := u.Group
if u.TempGroup != 0 {
groupID = u.TempGroup
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
}
// TODO: Do we want to leak the user's permissions? Users will probably be able to see their status from the group tags, but still
2019-08-31 22:59:00 +00:00
return &WsJSONUser{u.ID, u.Link, u.Name, groupID, u.IsMod, u.Avatar, u.MicroAvatar, u.Level, u.Score, u.Liked}
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
}
// Use struct tags to avoid having to define this? It really depends on the circumstances, sometimes we want the whole thing, sometimes... not.
type WsJSONUser struct {
The Search and Filter Widget is now partly implemented. Just Search to go in the basic implementation. Added AJAX Pagination for the Topic List and Forum Page. A new log file pair is now created every-time Gosora starts up. Added proper per-theme template overrides. Added EasyJSON to make JSON serialisation faster. Moved a bit of boilerplate into paginator.html Improved paginator.html with a richer template with first, last and symbols instead of text. Phased out direct access to Templates.ExecuteTemplate across the software. Fixed the Live Topic List so it should work again. Added MicroAvatar to WsJSONUser for topic list JSON requests. An instance of the plugin is now passed to plugin handlers rather than having the plugins manipulate the globals directly. Added the pre_render_panel_forum_edit and pre_render_panel_forum_edit_perms hooks to replace pre_render_panel_edit_forum. Renamed the pre_render_panel_edit_user hook to pre_render_panel_user_edit Reduced the amount of noise from fsnotify. Added RawPrepare() to qgen.Accumulator. Added a temporary phrase whitelist to the phrase endpoint. Moved the location of the zone data assignments in the topic list to reduce the chances of security issues in the future. Changed the signature of routes/panel/renderTemplate() requiring some changes across the panel routes. Removed bits of boilerplate in some of the panel routes with renderTemplate() Added a BenchmarkTopicsGuestJSRouteParallelWithRouter benchmark. Removed a fair bit of boilerplate for each page struct by generating a couple of interface casts for each template file instead. Added the profile_comments_row_alt template. Added the topics_quick_topic template to reuse part of the quick topic logic for both the topic list and forum page. Tweaked the CSS for the Online Users Widget. Tweaked the CSS for Widgets in every theme with a sidebar. Refactored the template initialisers to hopefully reduce the amount of boilerplate and make things easier to maintain and follow. Add genIntTmpl in the template initialiser file to reduce the amount of boilerplate needed for the fallback template bindings. Removed the topics_head phrase. Moved the paginator_ phrases into the paginator. namespace and renamed them accordingly. Added the paginator.first_page phrase. Added the paginator.first_page_aria phrase. Added the paginator.last_page phrase. Added the paginator.last_page_aria phrase. Added the panel_forum_delete_are_you_sure phrase. Fixed a data race in LogWarning()
2019-02-10 05:52:26 +00:00
ID int
Link string
Name string
Group int // Be sure to mask with TempGroup
IsMod bool
Avatar string
MicroAvatar string
Level int
Score int
Liked int
Almost finished live topic lists, you can find them at /topics/. You can disable them via config.json The topic list cache can handle more groups now, but don't go too crazy with groups (e.g. thousands of them). Make the suspicious request logs more descriptive. Added the phrases API endpoint. Split the template phrases up by prefix, more work on this coming up. Removed #dash_saved and part of #dash_username. Removed some temporary artifacts from trying to implement FA5 in Nox. Removed some commented CSS. Fixed template artifact deletion on Windows. Tweaked HTTPSRedirect to make it more compact. Fixed NullUserCache not complying with the expectations for BulkGet. Swapped out a few RunVhook calls for more appropriate RunVhookNoreturn calls. Removed a few redundant IsAdmin checks when IsMod would suffice. Commented out a few pushers. Desktop notification permission requests are no longer served to guests. Split topics.html into topics.html and topics_topic.html RunThemeTemplate should now fallback to interpreted templates properly when the transpiled variants aren't avaialb.e Changed TopicsRow.CreatedAt from a string to a time.Time Added SkipTmplPtrMap to CTemplateConfig. Added SetBuildTags to CTemplateSet. A bit more data is dumped when something goes wrong while transpiling templates now. topics_topic, topic_posts, and topic_alt_posts are now transpiled for the client, although not all of them are ready to be served to the client yet. Client rendered templates now support phrases. Client rendered templates now support loops. Fixed loadAlerts in global.js Refactored some of the template initialisation code to make it less repetitive. Split topic.html into topic.html and topic_posts.html Split topic_alt.html into topic_alt.html and topic_alt_posts.html Added comments for PollCache. Fixed a data race in the MemoryPollCache. The writer is now closed properly in WsHubImpl.broadcastMessage. Fixed a potential deadlock in WsHubImpl.broadcastMessage. Removed some old commented code in websockets.go Added the DisableLiveTopicList config setting.
2018-06-24 13:49:29 +00:00
}
2019-08-31 22:59:00 +00:00
func (u *User) Me() *MeUser {
groupID := u.Group
if u.TempGroup != 0 {
groupID = u.TempGroup
}
2019-08-31 22:59:00 +00:00
return &MeUser{u.ID, u.Link, u.Name, groupID, u.Active, u.IsMod, u.IsSuperMod, u.IsAdmin, u.IsBanned, u.Session, u.Avatar, u.MicroAvatar, u.Tag, u.Level, u.Score, u.Liked}
}
// For when users need to see their own data, I've omitted some redundancies and less useful items, so we don't wind up sending them on every request
type MeUser struct {
ID int
Link string
Name string
Group int
Active bool
IsMod bool
IsSuperMod bool
IsAdmin bool
IsBanned bool
// TODO: Implement these as copies (might already be the case for Perms, but we'll want to look at it's definition anyway)
//Perms Perms
//PluginPerms map[string]bool
S string // Session
Avatar string
MicroAvatar string
Tag string
Level int
Score int
Liked int
}
type UserStmts struct {
activate *sql.Stmt
changeGroup *sql.Stmt
delete *sql.Stmt
setAvatar *sql.Stmt
setName *sql.Stmt
update *sql.Stmt
// TODO: Split these into a sub-struct
incScore *sql.Stmt
incPosts *sql.Stmt
incBigposts *sql.Stmt
incMegaposts *sql.Stmt
incPostStats *sql.Stmt
incBigpostStats *sql.Stmt
incMegapostStats *sql.Stmt
incLiked *sql.Stmt
incTopics *sql.Stmt
updateLevel *sql.Stmt
resetStats *sql.Stmt
setStats *sql.Stmt
decLiked *sql.Stmt
updateLastIP *sql.Stmt
updatePrivacy *sql.Stmt
setPassword *sql.Stmt
scheduleAvatarResize *sql.Stmt
deletePosts *sql.Stmt
deleteProfilePosts *sql.Stmt
deleteReplyPosts *sql.Stmt
getLikedRepliesOfTopic *sql.Stmt
getAttachmentsOfTopic *sql.Stmt
getAttachmentsOfTopic2 *sql.Stmt
getRepliesOfTopic *sql.Stmt
}
var userStmts UserStmts
func init() {
DbInits.Add(func(acc *qgen.Accumulator) error {
u := "users"
w := "uid=?"
userStmts = UserStmts{
activate: acc.SimpleUpdate(u, "active=1", w),
changeGroup: acc.SimpleUpdate(u, "group=?", w), // TODO: Implement user_count for users_groups here
delete: acc.Delete(u).Where(w).Prepare(),
setAvatar: acc.Update(u).Set("avatar=?").Where(w).Prepare(),
setName: acc.Update(u).Set("name=?").Where(w).Prepare(),
update: acc.Update(u).Set("name=?,email=?,group=?").Where(w).Prepare(), // TODO: Implement user_count for users_groups on things which use this
// Stat Statements
// TODO: Do +0 to avoid having as many statements?
incScore: acc.Update(u).Set("score=score+?").Where(w).Prepare(),
incPosts: acc.Update(u).Set("posts=posts+?").Where(w).Prepare(),
incBigposts: acc.Update(u).Set("posts=posts+?,bigposts=bigposts+?").Where(w).Prepare(),
incMegaposts: acc.Update(u).Set("posts=posts+?,bigposts=bigposts+?,megaposts=megaposts+?").Where(w).Prepare(),
incPostStats: acc.Update(u).Set("posts=posts+?,score=score+?,level=?").Where(w).Prepare(),
incBigpostStats: acc.Update(u).Set("posts=posts+?,bigposts=bigposts+?,score=score+?,level=?").Where(w).Prepare(),
incMegapostStats: acc.Update(u).Set("posts=posts+?,bigposts=bigposts+?,megaposts=megaposts+?,score=score+?,level=?").Where(w).Prepare(),
incTopics: acc.SimpleUpdate(u, "topics=topics+?", w),
updateLevel: acc.SimpleUpdate(u, "level=?", w),
resetStats: acc.Update(u).Set("score=0,posts=0,bigposts=0,megaposts=0,topics=0,level=0").Where(w).Prepare(),
setStats: acc.Update(u).Set("score=?,posts=?,bigposts=?,megaposts=?,topics=?,level=?").Where(w).Prepare(),
incLiked: acc.Update(u).Set("liked=liked+?,lastLiked=UTC_TIMESTAMP()").Where(w).Prepare(),
decLiked: acc.Update(u).Set("liked=liked-?").Where(w).Prepare(),
Fixed a bug where it would use the wrong templates for Tempra Simple, Tempra Cursive, and Shadow Likes are now done over AJAX. Posts you have liked are now visually differentiated from those which you have not. Added support for OR to the where parser. || and && now get translated to OR and AND in the where parser. Added support for ( and ) in the where parser. Added an adapter and builder method for getting the database version. Multiple wheres can now be chained with the micro and accumulator builders. Added the In method to the accumulator select builder. Added the GetConn method to the builder. /uploads/ files should now get cached properly. Added more tooltips for topic titles and usernames. Fixed a bug in the runners where old stale templates would be served. Fixed a bug where liking topics didn't work. Began moving the database initialisation logic out of {adapter}.go and into querygen. Tweaked the alert direction to show the newest alerts rather than the oldest. Tweaked the WS JS to have it handle messages more efficiently. Partially fixed an issue where inline edited posts would lack newlines until the page is refreshed. Used arrow functions in a few places in global.js to save a few characters. Schema: Added the liked, oldestItemLikedCreatedAt and lastLiked columns to the users table. Added the createdAt column to the likes table. MySQL Update Queries: ALTER TABLE `users` ADD COLUMN `liked` INT NOT NULL DEFAULT '0' AFTER `topics`; ALTER TABLE `users` ADD COLUMN `oldestItemLikedCreatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `liked`; ALTER TABLE `users` ADD COLUMN `lastLiked` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `oldestItemLikedCreatedAt`; ALTER TABLE `likes` ADD COLUMN `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP AFTER `sentBy`; delete from `likes`; delete from `activity_stream` where `event` = 'like'; delete from `activity_stream_matches` where `asid` not in(select `asid` from `activity_stream`); update `topics` set `likeCount` = 0; update `replies` set `likeCount` = 0;
2018-03-31 05:25:27 +00:00
//recalcLastLiked: acc...
updateLastIP: acc.SimpleUpdate(u, "last_ip=?", w),
updatePrivacy: acc.Update(u).Set("profile_comments=?,enable_embeds=?").Where(w).Prepare(),
setPassword: acc.Update(u).Set("password=?,salt=?").Where(w).Prepare(),
scheduleAvatarResize: acc.Insert("users_avatar_queue").Columns("uid").Fields("?").Prepare(),
// Delete All Posts Statements
deletePosts: acc.Select("topics").Columns("tid,parentID,postCount,poll").Where("createdBy=?").Prepare(),
deleteProfilePosts: acc.Select("users_replies").Columns("rid,uid").Where("createdBy=?").Prepare(),
deleteReplyPosts: acc.Select("replies").Columns("rid,tid").Where("createdBy=?").Prepare(),
getLikedRepliesOfTopic: acc.Select("replies").Columns("rid").Where("tid=? AND likeCount>0").Prepare(),
getAttachmentsOfTopic: acc.Select("attachments").Columns("attachID").Where("originID=? AND originTable='topics'").Prepare(),
getAttachmentsOfTopic2: acc.Select("attachments").Columns("attachID").Where("extra=? AND originTable='replies'").Prepare(),
getRepliesOfTopic: acc.Select("replies").Columns("words").Where("createdBy!=? AND tid=?").Prepare(),
}
return acc.FirstError()
})
}
2019-08-31 22:59:00 +00:00
func (u *User) Init() {
// TODO: Let admins configure the minimum default?
if u.Privacy.ShowComments < 1 {
u.Privacy.ShowComments = 1
}
2019-08-31 22:59:00 +00:00
u.Avatar, u.MicroAvatar = BuildAvatar(u.ID, u.RawAvatar)
u.Link = BuildProfileURL(NameToSlug(u.Name), u.ID)
u.Tag = Groups.DirtyGet(u.Group).Tag
u.InitPerms()
}
Added the AboutSegment feature, you can see this in use on Cosora, it's a little raw right now, but I'm planning to polish it in the next commit. Refactored the code to use switches instead of if blocks in some places. Refactored the Dashboard to make it easier to add icons to it like I did with Cosora. You can now use maps in transpiled templates. Made progress on Cosora's footer. Swapped out the ThemeName property in the HeaderVars struct for a more general and flexible Theme property. Added the colstack CSS class to make it easier to style the layouts for the Control Panel and profile. Renamed the FStore variable to Forums. Renamed the Fpstore variable to FPStore. Renamed the Gstore variable to Groups. Split the MemoryTopicStore into DefaultTopicStore and MemoryTopicCache. Split the MemoryUserStore into DefaultUserStore and MemoryUserCache. Removed the NullUserStore, SQLUserStore, and SQLTopicStore. Added the NullTopicCache and NullUserCache. Moved the Reload method out of the TopicCache interface and into the TopicStore one. Moved the Reload method out of the UserCache interface and into the UserStore one. Added the SetCache and GetCache methods to the TopicStore and UserStore. Added the BypassGetAll method to the WordFilterMap type. Renamed routePanelSetting to routePanelSettingEdit. Renamed routePanelSettingEdit to routePanelSettingEditSubmit. Moved the page titles into the english language pack. Split main() into main and afterDBInit to avoid code duplication in general_test.go Added the ReqIsJson method so that we don't have to sniff the headers every time. Added the LogStore interface. Added the SQLModLogStore and the SQLAdminLogStore. Refactored the phrase system to use getPhrasePlaceholder instead of hard-coding the string to return in a bunch of functions. Removed a redundant rank check. Added the GuildStore to plugin_guilds. Added the about_segment_title and about_segment_body settings. Refactored the setting system to use predefined errors to make it easier for an upstream caller to filter out sensitive error messages as opposed to safe errors. Added the BypassGetAll method to the SettingMap type. Added the Update method to the SettingMap type. BulkGet is now exposed via the MemoryUserCache. Refactored more logs in the template transpiler to reduce the amount of indentation. Refactored the tests to take up fewer lines. Further improved the Cosora theme's colours, padding, and profiles. Added styling for the Control Panel Dashboard to the Cosora Theme. Reduced the amount of code duplication in the installer query generator and opened the door to certain types of auto-migrations. Refactored the Control Panel Dashboard to reduce the amount of code duplication. Refactored the modlog route to reduce the amount of code duplication and string concatenation.
2017-11-23 05:37:08 +00:00
// TODO: Refactor this idiom into something shorter, maybe with a NullUserCache when one isn't set?
2019-08-31 22:59:00 +00:00
func (u *User) CacheRemove() {
if uc := Users.GetCache(); uc != nil {
uc.Remove(u.ID)
}
TopicListThaw.Thaw()
}
2020-11-09 06:12:08 +00:00
func (u *User) Ban(dur time.Duration, issuedBy int) error {
return u.ScheduleGroupUpdate(BanGroup, issuedBy, dur)
}
2019-08-31 22:59:00 +00:00
func (u *User) Unban() error {
return u.RevertGroupUpdate()
}
2019-08-31 22:59:00 +00:00
func (u *User) deleteScheduleGroupTx(tx *sql.Tx) error {
2020-11-09 06:12:08 +00:00
deleteScheduleGroupStmt, e := qgen.Builder.SimpleDeleteTx(tx, "users_groups_scheduler", "uid=?")
if e != nil {
return e
}
2020-11-09 06:12:08 +00:00
_, e = deleteScheduleGroupStmt.Exec(u.ID)
return e
}
2019-08-31 22:59:00 +00:00
func (u *User) setTempGroupTx(tx *sql.Tx, tempGroup int) error {
2020-11-09 06:12:08 +00:00
setTempGroupStmt, e := qgen.Builder.SimpleUpdateTx(tx, "users", "temp_group=?", "uid=?")
if e != nil {
return e
}
2020-11-09 06:12:08 +00:00
_, e = setTempGroupStmt.Exec(tempGroup, u.ID)
return e
}
// Make this more stateless?
2020-11-09 06:12:08 +00:00
func (u *User) ScheduleGroupUpdate(gid, issuedBy int, dur time.Duration) error {
2019-08-31 22:59:00 +00:00
var temp bool
2020-11-09 06:12:08 +00:00
if dur.Nanoseconds() != 0 {
2019-08-31 22:59:00 +00:00
temp = true
}
2020-11-09 06:12:08 +00:00
revertAt := time.Now().Add(dur)
tx, err := qgen.Builder.Begin()
if err != nil {
return err
}
defer tx.Rollback()
2019-08-31 22:59:00 +00:00
err = u.deleteScheduleGroupTx(tx)
if err != nil {
return err
}
2019-08-31 22:59:00 +00:00
createScheduleGroupTx, err := qgen.Builder.SimpleInsertTx(tx, "users_groups_scheduler", "uid,set_group,issued_by,issued_at,revert_at,temporary", "?,?,?,UTC_TIMESTAMP(),?,?")
if err != nil {
return err
}
2019-08-31 22:59:00 +00:00
_, err = createScheduleGroupTx.Exec(u.ID, gid, issuedBy, revertAt, temp)
if err != nil {
return err
}
2019-08-31 22:59:00 +00:00
err = u.setTempGroupTx(tx, gid)
if err != nil {
return err
}
err = tx.Commit()
2019-08-31 22:59:00 +00:00
u.CacheRemove()
return err
}
2019-08-31 22:59:00 +00:00
func (u *User) RevertGroupUpdate() error {
2020-11-09 06:12:08 +00:00
tx, e := qgen.Builder.Begin()
if e != nil {
return e
}
defer tx.Rollback()
2020-11-09 06:12:08 +00:00
e = u.deleteScheduleGroupTx(tx)
if e != nil {
return e
}
2020-11-09 06:12:08 +00:00
e = u.setTempGroupTx(tx, 0)
if e != nil {
return e
}
2020-11-09 06:12:08 +00:00
e = tx.Commit()
2019-08-31 22:59:00 +00:00
u.CacheRemove()
2020-11-09 06:12:08 +00:00
return e
2017-07-12 11:05:18 +00:00
}
// TODO: Use a transaction here
// ? - Add a Deactivate method? Not really needed, if someone's been bad you could do a ban, I guess it might be useful, if someone says that email x isn't actually owned by the user in question?
2020-11-09 06:12:08 +00:00
func (u *User) Activate() (e error) {
_, e = userStmts.activate.Exec(u.ID)
if e != nil {
return e
2016-12-02 07:38:54 +00:00
}
2020-11-09 06:12:08 +00:00
_, e = userStmts.changeGroup.Exec(Config.DefaultGroup, u.ID)
2019-08-31 22:59:00 +00:00
u.CacheRemove()
2020-11-09 06:12:08 +00:00
return e
}
// TODO: Write tests for this
// TODO: Delete this user's content too?
// TODO: Expose this to the admin?
2019-08-31 22:59:00 +00:00
func (u *User) Delete() error {
2020-11-09 06:12:08 +00:00
_, e := userStmts.delete.Exec(u.ID)
if e != nil {
return e
}
2019-08-31 22:59:00 +00:00
u.CacheRemove()
return nil
}
// TODO: dismiss-event
func (u *User) DeletePosts() error {
rows, err := userStmts.deletePosts.Query(u.ID)
if err != nil {
return err
}
defer rows.Close()
defer TopicListThaw.Thaw()
defer u.CacheRemove()
updatedForums := make(map[int]int) // forum[count]
tc := Topics.GetCache()
umap := make(map[int]struct{})
for rows.Next() {
var tid, parentID, postCount, poll int
err := rows.Scan(&tid, &parentID, &postCount, &poll)
if err != nil {
return err
}
// TODO: Clear reply cache too
_, err = topicStmts.delete.Exec(tid)
if tc != nil {
tc.Remove(tid)
}
if err != nil {
return err
}
updatedForums[parentID] = updatedForums[parentID] + 1
_, err = topicStmts.deleteLikesForTopic.Exec(tid)
if err != nil {
return err
}
err = handleTopicAttachments(tid)
if err != nil {
return err
}
if postCount > 1 {
err = handleLikedTopicReplies(tid)
if err != nil {
return err
}
err = handleTopicReplies(umap, u.ID, tid)
if err != nil {
return err
}
_, err = topicStmts.deleteReplies.Exec(tid)
if err != nil {
return err
}
}
err = Subscriptions.DeleteResource(tid, "topic")
if err != nil {
return err
}
_, err = topicStmts.deleteActivity.Exec(tid)
if err != nil {
return err
}
if poll > 0 {
err = (&Poll{ID: poll}).Delete()
if err != nil {
return err
}
}
}
if err = rows.Err(); err != nil {
return err
}
err = u.ResetPostStats()
if err != nil {
return err
}
for uid, _ := range umap {
err = (&User{ID: uid}).RecalcPostStats()
if err != nil {
return err
}
}
for fid, count := range updatedForums {
err := Forums.RemoveTopics(fid, count)
if err != nil && err != ErrNoRows {
return err
}
}
rows, err = userStmts.deleteProfilePosts.Query(u.ID)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var rid, uid int
err := rows.Scan(&rid, &uid)
if err != nil {
return err
}
_, err = profileReplyStmts.delete.Exec(rid)
if err != nil {
return err
}
// TODO: Optimise this
// TODO: dismiss-event
err = Activity.DeleteByParamsExtra("reply", uid, "user", strconv.Itoa(rid))
if err != nil {
return err
}
}
if err = rows.Err(); err != nil {
return err
}
rows, err = userStmts.deleteReplyPosts.Query(u.ID)
if err != nil {
return err
}
defer rows.Close()
rc := Rstore.GetCache()
for rows.Next() {
var rid, tid int
err := rows.Scan(&rid, &tid)
if err != nil {
return err
}
_, err = replyStmts.delete.Exec(rid)
if err != nil {
return err
}
// TODO: Move this bit to *Topic
_, err = replyStmts.removeRepliesFromTopic.Exec(1, tid)
if err != nil {
return err
}
_, err = replyStmts.updateTopicReplies.Exec(tid)
if err != nil {
return err
}
_, err = replyStmts.updateTopicReplies2.Exec(tid)
if tc != nil {
tc.Remove(tid)
}
_ = rc.Remove(rid)
if err != nil {
return err
}
_, err = replyStmts.deleteLikesForReply.Exec(rid)
if err != nil {
return err
}
err = Activity.DeleteByParamsExtra("reply", tid, "topic", strconv.Itoa(rid))
if err != nil {
return err
}
_, err = replyStmts.deleteActivitySubs.Exec(rid)
if err != nil {
return err
}
_, err = replyStmts.deleteActivity.Exec(rid)
if err != nil {
return err
}
// TODO: Restructure alerts so we can delete the "x replied to topic" ones too.
}
return rows.Err()
}
2020-11-09 06:12:08 +00:00
func (u *User) bindStmt(stmt *sql.Stmt, params ...interface{}) (e error) {
2019-08-31 22:59:00 +00:00
params = append(params, u.ID)
2020-11-09 06:12:08 +00:00
_, e = stmt.Exec(params...)
2019-08-31 22:59:00 +00:00
u.CacheRemove()
2020-11-09 06:12:08 +00:00
return e
}
2020-11-09 06:12:08 +00:00
func (u *User) ChangeName(name string) error {
return u.bindStmt(userStmts.setName, name)
}
2020-11-09 06:12:08 +00:00
func (u *User) ChangeAvatar(avatar string) error {
2019-08-31 22:59:00 +00:00
return u.bindStmt(userStmts.setAvatar, avatar)
}
// TODO: Abstract this with an interface so we can scale this with an actual dedicated queue in a real cluster
2019-08-31 22:59:00 +00:00
func (u *User) ScheduleAvatarResize() (err error) {
_, err = userStmts.scheduleAvatarResize.Exec(u.ID)
if err != nil {
// TODO: Do a more generic check so that we're not as tied to MySQL
me, ok := err.(*mysql.MySQLError)
if !ok {
return err
}
// If it's just telling us that the item already exists in the database, then we can ignore it, as it doesn't matter if it's this call or another which schedules the item in the queue
if me.Number != 1062 {
return err
}
}
return nil
}
2020-11-09 06:12:08 +00:00
func (u *User) ChangeGroup(group int) error {
2019-08-31 22:59:00 +00:00
return u.bindStmt(userStmts.changeGroup, group)
}
func (u *User) GetIP() string {
spl := strings.Split(u.LastIP, "-")
return spl[len(spl)-1]
}
// ! Only updates the database not the *User for safety reasons
func (u *User) UpdateIP(ip string) error {
_, err := userStmts.updateLastIP.Exec(ip, u.ID)
if uc := Users.GetCache(); uc != nil {
uc.Remove(u.ID)
}
return err
}
//var ErrMalformedInteger = errors.New("malformed integer")
var ErrProfileCommentsOutOfBounds = errors.New("profile_comments must be an integer between -1 and 4")
var ErrEnableEmbedsOutOfBounds = errors.New("enable_embeds must be -1, 0 or 1")
/*func (u *User) UpdatePrivacyS(sProfileComments, sEnableEmbeds string) error {
return u.UpdatePrivacy(profileComments, enableEmbeds)
}*/
func (u *User) UpdatePrivacy(profileComments, enableEmbeds int) error {
if profileComments < -1 || profileComments > 4 {
return ErrProfileCommentsOutOfBounds
}
if enableEmbeds < -1 || enableEmbeds > 1 {
return ErrEnableEmbedsOutOfBounds
}
_, e := userStmts.updatePrivacy.Exec(profileComments, enableEmbeds, u.ID)
if uc := Users.GetCache(); uc != nil {
uc.Remove(u.ID)
}
return e
}
func (u *User) Update(name, email string, group int) (err error) {
return u.bindStmt(userStmts.update, name, email, group)
Added support for two-factor authentication. Added the Account Dashboard and merged a few account views into it. BREAKING CHANGE: We now use config/config.json instead of config/config.go, be sure to setup one of these files, you can config_default.json as an example of what a config.json should look like. If you don't have an existing installation, you can just rely on the installer to do this for you. CSS Changes (does not include Nox Theme): Sidebar should no longer show up in the account manager in some odd situations or themes. Made a few CSS rules more generic. Forms have a new look in Cosora now. Config Changes: Removed the DefaultRoute config field. Added the DefaultPath config field. Added the MaxRequestSizeStr config field to make it easier for users to input custom max request sizes without having to use a calculator or figure out how many bytes there are in a megabyte. Removed the CacheTopicUser config field. Added the UserCache config field. Added the TopicCache config field Phrases: Removed ten english phrases. Added 21 english phrases. Changed eleven english phrases. Removed some duplicate indices in the english phrase pack. Removed some old benchmark code. Tweaked some things to make the linter happy. Added comments for all the MemoryUserCache and MemoryTopicCache methods. Added a comment for the null caches, consult the other caches for further information on the methods. Added a client-side check to make sure the user doesn't upload too much data in a single post. The server already did this, but it might be a while before feedback arrives from it. Simplified a lot of the control panel route code with the buildBasePage function. Renamed /user/edit/critical/ to /user/edit/password/ Renamed /user/edit/critical/submit/ to /user/edit/password/submit/ Made some small improvements to SEO with a couple of meta tags. Renamed some of the control panel templates so that they use _ instead of -. Fixed a bug where notices were being moved to the wrong place in some areas in Cosora. Added the writeJsonError function to help abstract writing json errors. Moved routePanelUsers to panel.Users Moved routePanelUsersEdit to panel.UsersEdit Moved routePanelUsersEditSubmit to panel.UsersEditSubmit Renamed routes.AccountEditCritical to routes.AccountEditPassword Renamed routes.AccountEditCriticalSubmit to routes.AccountEditPasswordSubmit Removed the routes.AccountEditAvatar and routes.AccountEditUsername routes. Fixed a data race in MemoryTopicCache.Add which could lead to the capacity limit being bypassed. Tweaked MemoryTopicCache.AddUnsafe under the assumption that it's not going to be safe anyway, but we might as-well try in case this call is properly synchronised. Fixed a data race in MemoryTopicCache.Remove which could lead to the length counter being decremented twice. Tweaked the behaviour of MemoryTopicCache.RemoveUnsafe to mirror that of Remove. Fixed a data race in MemoryUserCache.Add which could lead to the capacity limit being bypassed. User can no longer change their usernames to blank. Made a lot of progress on the Nox theme. Added modified FA5 SVGs as a dependency for Nox. Be sure to run the patcher or update script and don't forget to create a customised config/config.json file.
2018-06-17 07:28:18 +00:00
}
2019-08-31 22:59:00 +00:00
func (u *User) IncreasePostStats(wcount int, topic bool) (err error) {
baseScore := 1
if topic {
_, err = userStmts.incTopics.Exec(1, u.ID)
if err != nil {
return err
}
baseScore = 2
}
settings := SettingBox.Load().(SettingMap)
var mod, level int
if wcount >= settings["megapost_min_words"].(int) {
mod = 4
level = GetLevel(u.Score + baseScore + mod)
_, err = userStmts.incMegapostStats.Exec(1, 1, 1, baseScore+mod, level, u.ID)
} else if wcount >= settings["bigpost_min_words"].(int) {
mod = 1
level = GetLevel(u.Score + baseScore + mod)
_, err = userStmts.incBigpostStats.Exec(1, 1, baseScore+mod, level, u.ID)
} else {
level = GetLevel(u.Score + baseScore + mod)
_, err = userStmts.incPostStats.Exec(1, baseScore+mod, level, u.ID)
}
if err != nil {
return err
}
err = GroupPromotions.PromoteIfEligible(u, level, u.Posts+1, u.CreatedAt)
u.CacheRemove()
return err
}
func (u *User) countf(stmt *sql.Stmt) (count int) {
2020-11-09 06:12:08 +00:00
e := stmt.QueryRow().Scan(&count)
if e != nil {
LogError(e)
}
return count
}
func (u *User) RecalcPostStats() error {
var score int
tcount := Topics.CountUser(u.ID)
rcount := Rstore.CountUser(u.ID)
//log.Print("tcount:", tcount)
//log.Print("rcount:", rcount)
score += tcount * 2
score += rcount
var tmega, tbig, rmega, rbig int
if tcount > 0 {
tmega = Topics.CountMegaUser(u.ID)
score += tmega * 3
tbig := Topics.CountBigUser(u.ID)
score += tbig
}
if rcount > 0 {
rmega = Rstore.CountMegaUser(u.ID)
score += rmega * 3
rbig = Rstore.CountBigUser(u.ID)
score += rbig
}
_, err := userStmts.setStats.Exec(score, tcount+rcount, tbig+rbig, tmega+rmega, tcount, GetLevel(score), u.ID)
u.CacheRemove()
return err
}
2019-08-31 22:59:00 +00:00
func (u *User) DecreasePostStats(wcount int, topic bool) (err error) {
baseScore := -1
if topic {
_, err = userStmts.incTopics.Exec(-1, u.ID)
if err != nil {
return err
}
baseScore = -2
}
// TODO: Use a transaction to prevent level desyncs?
var mod int
settings := SettingBox.Load().(SettingMap)
if wcount >= settings["megapost_min_words"].(int) {
mod = 4
_, err = userStmts.incMegapostStats.Exec(-1, -1, -1, baseScore-mod, GetLevel(u.Score-baseScore-mod), u.ID)
} else if wcount >= settings["bigpost_min_words"].(int) {
mod = 1
_, err = userStmts.incBigpostStats.Exec(-1, -1, baseScore-mod, GetLevel(u.Score-baseScore-mod), u.ID)
} else {
_, err = userStmts.incPostStats.Exec(-1, baseScore-mod, GetLevel(u.Score-baseScore-mod), u.ID)
}
u.CacheRemove()
return err
}
2020-11-09 06:12:08 +00:00
func (u *User) ResetPostStats() error {
_, err := userStmts.resetStats.Exec(u.ID)
u.CacheRemove()
return err
}
// Copy gives you a non-pointer concurrency safe copy of the user
2019-08-31 22:59:00 +00:00
func (u *User) Copy() User {
return *u
}
// TODO: Write unit tests for this
2019-08-31 22:59:00 +00:00
func (u *User) InitPerms() {
if u.TempGroup != 0 {
u.Group = u.TempGroup
}
2019-08-31 22:59:00 +00:00
group := Groups.DirtyGet(u.Group)
if u.IsSuperAdmin {
u.Perms = AllPerms
u.PluginPerms = AllPluginPerms
Added support for HTTP/2 Push. The themes are still going to be a little broken for a while, but here's the progress I've made. Renamed the topics_trow_assign hook to topics_topic_row_assign. Added more debug code to the generated router. Added a robots.txt file. Gosora now responds to favicon.ico requests with a 404 rather than the topic list. Fixed the tests and some of the benchmarks. Changed the default UserCacheCapacity from 100 to 120. Changed the default TopicCacheCapacity from 100 to 200. Added the last replyer to the topics list and the forum pages. Added the BulkCascadeGetMap method to the UserStore. Refactored the topics list and forum page to load the users with a call to the UserStore rather than via a join. WebSockets now work on SSL. Fixed a race condition when the user permissions are initialised at the start of a request. Fixed a race condition when the user permissions for the OP of a topic are initialised. The rows.Close() calls are deferred once more, so that we can catch problems with recover() Improved support for struct pointers in the template compiler. Added a pin emoji to pinned topics to make them stand-out on the Shadow theme, we have some other ideas in mind for this, but I'd like to get Shadow fully functional for this commit. Fixed a bug an issue with Chrome not detecting XHTML style closes on <form>s. Fixed a visual issue with `color` not being set for textarea elements for the Shadow theme. Fixed a function which wasn't getting renamed for PGSQL. Added seven new UserStore tests.
2017-08-06 15:22:18 +00:00
} else {
2019-08-31 22:59:00 +00:00
u.Perms = group.Perms
u.PluginPerms = group.PluginPerms
}
/*if len(group.CanSee) == 0 {
panic("should not be zero")
}*/
2019-08-31 22:59:00 +00:00
u.IsAdmin = u.IsSuperAdmin || group.IsAdmin
u.IsSuperMod = u.IsAdmin || group.IsMod
u.IsMod = u.IsSuperMod
u.IsBanned = group.IsBanned
if u.IsBanned && u.IsSuperMod {
u.IsBanned = false
}
}
// TODO: Write tests
// TODO: Implement and use this
// TODO: Implement friends
func PrivacyAllowMessage(pu, u *User) (canMsg bool) {
switch pu.Privacy.AllowMessage {
case 4: // Unused
canMsg = false
case 3: // mods
canMsg = u.IsSuperMod
//case 2: // friends
case 1: // registered
canMsg = true
default: // 0
canMsg = true
}
return canMsg
}
// TODO: Implement friend system
func PrivacyCommentsShow(pu, u *User) (showComments bool) {
switch pu.Privacy.ShowComments {
case 5: // Unused
showComments = false
case 4: // Self
showComments = u.ID == pu.ID
case 3: // friends
showComments = u.ID == pu.ID
case 2: // registered
showComments = u.Loggedin
case 1: // public
showComments = true
default: // 0
showComments = true
}
return showComments
}
var guestAvatar GuestAvatar
type GuestAvatar struct {
Normal string
Micro string
}
func buildNoavatar(uid, width int) string {
if !Config.DisableNoavatarRange {
// TODO: Find a faster algorithm
if uid > 50000 {
uid -= 50000
}
if uid > 5000 {
uid -= 5000
}
if uid > 500 {
uid -= 500
}
for uid > 50 {
uid -= 50
}
}
2020-11-09 06:18:03 +00:00
if !Config.DisableDefaultNoavatar && uid < 11 {
if width == 200 {
return noavatarCache200[uid]
} else if width == 48 {
return noavatarCache48[uid]
}
return StaticFiles.Prefix + "n" + strconv.Itoa(uid) + "-" + strconv.Itoa(width) + ".png?i=0"
}
// ? - Add a prefix setting to make this faster?
return strings.Replace(strings.Replace(Config.Noavatar, "{id}", strconv.Itoa(uid), 1), "{width}", strconv.Itoa(width), 1)
}
// ? - Make this part of *User?
// TODO: Write tests for this
func BuildAvatar(uid int, avatar string) (normalAvatar, microAvatar string) {
if avatar == "" {
if uid == 0 {
return guestAvatar.Normal, guestAvatar.Micro
}
return buildNoavatar(uid, 200), buildNoavatar(uid, 48)
}
if avatar[0] == '.' {
if avatar[1] == '.' {
2020-11-09 06:12:08 +00:00
normalAvatar = Config.AvatarResBase + "avatar_" + strconv.Itoa(uid) + "_tmp" + avatar[1:]
return normalAvatar, normalAvatar
}
2020-11-09 06:12:08 +00:00
normalAvatar = Config.AvatarResBase + "avatar_" + strconv.Itoa(uid) + avatar
return normalAvatar, normalAvatar
}
return avatar, avatar
}
// TODO: Move this to *User
func SetPassword(uid int, password string) error {
hashedPassword, salt, err := GeneratePassword(password)
if err != nil {
return err
}
_, err = userStmts.setPassword.Exec(hashedPassword, salt, uid)
return err
}
// TODO: Write units tests for this
func wordsToScore(wcount int, topic bool) (score int) {
if topic {
score = 2
} else {
score = 1
}
settings := SettingBox.Load().(SettingMap)
if wcount >= settings["megapost_min_words"].(int) {
score += 4
} else if wcount >= settings["bigpost_min_words"].(int) {
score++
}
return score
}
// For use in tests and to help generate dummy users for forums which don't have last posters
func BlankUser() *User {
return new(User)
}
// TODO: Write unit tests for this
func BuildProfileURL(slug string, uid int) string {
if slug == "" || !Config.BuildSlugs {
return "/user/" + strconv.Itoa(uid)
}
return "/user/" + slug + "." + strconv.Itoa(uid)
}
func BuildProfileURLSb(sb *strings.Builder, slug string, uid int) {
if slug == "" || !Config.BuildSlugs {
sb.Grow(6 + 1)
sb.WriteString("/user/")
sb.WriteString(strconv.Itoa(uid))
return
}
sb.Grow(7 + 1 + len(slug))
sb.WriteString("/user/")
sb.WriteString(slug)
sb.WriteRune('.')
sb.WriteString(strconv.Itoa(uid))
}