gosora/common/user.go

405 lines
10 KiB
Go
Raw Normal View History

/*
*
* Gosora User File
* Copyright Azareal 2017 - 2019
*
*/
package common
import (
"database/sql"
"errors"
"strconv"
"strings"
"time"
"../query_gen/lib"
)
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
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
var GuestUser = User{ID: 0, Name: "Guest", Link: "#", Group: 6, Perms: GuestPerms} // 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
Avatar string
Message string
URLPrefix string // Move this to another table? Create a user lite?
URLName string
Tag string
Level int
Score int
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
Liked int
LastIP string // ! This part of the UserCache data might fall out of date
TempGroup int
2016-12-02 07:38:54 +00:00
}
type UserStmts struct {
activate *sql.Stmt
changeGroup *sql.Stmt
delete *sql.Stmt
setAvatar *sql.Stmt
setUsername *sql.Stmt
incrementTopics *sql.Stmt
updateLevel *sql.Stmt
// TODO: Split these into a sub-struct
incrementScore *sql.Stmt
incrementPosts *sql.Stmt
incrementBigposts *sql.Stmt
incrementMegaposts *sql.Stmt
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
incrementLiked *sql.Stmt
decrementLiked *sql.Stmt
updateLastIP *sql.Stmt
setPassword *sql.Stmt
}
var userStmts UserStmts
func init() {
DbInits.Add(func(acc *qgen.Accumulator) error {
var where = "uid = ?"
userStmts = UserStmts{
activate: acc.SimpleUpdate("users", "active = 1", where),
changeGroup: acc.SimpleUpdate("users", "group = ?", where), // TODO: Implement user_count for users_groups here
delete: acc.SimpleDelete("users", where),
setAvatar: acc.Update("users").Set("avatar = ?").Where(where).Prepare(),
setUsername: acc.Update("users").Set("name = ?").Where(where).Prepare(),
incrementTopics: acc.SimpleUpdate("users", "topics = topics + ?", where),
updateLevel: acc.SimpleUpdate("users", "level = ?", where),
incrementScore: acc.SimpleUpdate("users", "score = score + ?", where),
incrementPosts: acc.SimpleUpdate("users", "posts = posts + ?", where),
incrementBigposts: acc.SimpleUpdate("users", "posts = posts + ?, bigposts = bigposts + ?", where),
incrementMegaposts: acc.SimpleUpdate("users", "posts = posts + ?, bigposts = bigposts + ?, megaposts = megaposts + ?", where),
incrementLiked: acc.SimpleUpdate("users", "liked = liked + ?, lastLiked = UTC_TIMESTAMP()", where),
decrementLiked: acc.SimpleUpdate("users", "liked = liked - ?", where),
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("users", "last_ip = ?", where),
setPassword: acc.Update("users").Set("password = ?, salt = ?").Where(where).Prepare(),
}
return acc.FirstError()
})
}
func (user *User) Init() {
user.Avatar = BuildAvatar(user.ID, user.Avatar)
user.Link = BuildProfileURL(NameToSlug(user.Name), user.ID)
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
user.Tag = Groups.DirtyGet(user.Group).Tag
user.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?
func (user *User) CacheRemove() {
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
ucache := Users.GetCache()
if ucache != nil {
ucache.Remove(user.ID)
}
}
func (user *User) Ban(duration time.Duration, issuedBy int) error {
return user.ScheduleGroupUpdate(BanGroup, issuedBy, duration)
}
func (user *User) Unban() error {
return user.RevertGroupUpdate()
}
func (user *User) deleteScheduleGroupTx(tx *sql.Tx) error {
deleteScheduleGroupStmt, err := qgen.Builder.SimpleDeleteTx(tx, "users_groups_scheduler", "uid = ?")
if err != nil {
return err
}
_, err = deleteScheduleGroupStmt.Exec(user.ID)
return err
}
func (user *User) setTempGroupTx(tx *sql.Tx, tempGroup int) error {
setTempGroupStmt, err := qgen.Builder.SimpleUpdateTx(tx, "users", "temp_group = ?", "uid = ?")
if err != nil {
return err
}
_, err = setTempGroupStmt.Exec(tempGroup, user.ID)
return err
}
// Make this more stateless?
func (user *User) ScheduleGroupUpdate(gid int, issuedBy int, duration time.Duration) error {
var temporary bool
if duration.Nanoseconds() != 0 {
temporary = true
}
revertAt := time.Now().Add(duration)
tx, err := qgen.Builder.Begin()
if err != nil {
return err
}
defer tx.Rollback()
err = user.deleteScheduleGroupTx(tx)
if err != nil {
return err
}
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
}
_, err = createScheduleGroupTx.Exec(user.ID, gid, issuedBy, revertAt, temporary)
if err != nil {
return err
}
err = user.setTempGroupTx(tx, gid)
if err != nil {
return err
}
err = tx.Commit()
user.CacheRemove()
return err
}
func (user *User) RevertGroupUpdate() error {
tx, err := qgen.Builder.Begin()
if err != nil {
return err
}
defer tx.Rollback()
err = user.deleteScheduleGroupTx(tx)
if err != nil {
return err
}
err = user.setTempGroupTx(tx, 0)
if err != nil {
return err
}
err = tx.Commit()
user.CacheRemove()
return err
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?
func (user *User) Activate() (err error) {
_, err = userStmts.activate.Exec(user.ID)
2016-12-02 07:38:54 +00:00
if err != nil {
return err
}
_, err = userStmts.changeGroup.Exec(Config.DefaultGroup, user.ID)
user.CacheRemove()
return err
}
// TODO: Write tests for this
// TODO: Delete this user's content too?
// TODO: Expose this to the admin?
func (user *User) Delete() error {
_, err := userStmts.delete.Exec(user.ID)
if err != nil {
return err
}
user.CacheRemove()
return err
}
func (user *User) bindStmt(stmt *sql.Stmt, params ...interface{}) (err error) {
params = append(params, user.ID)
_, err = stmt.Exec(params...)
user.CacheRemove()
return err
}
func (user *User) ChangeName(username string) (err error) {
return user.bindStmt(userStmts.setUsername, username)
}
func (user *User) ChangeAvatar(avatar string) (err error) {
return user.bindStmt(userStmts.setAvatar, avatar)
}
func (user *User) ChangeGroup(group int) (err error) {
return user.bindStmt(userStmts.changeGroup, group)
}
// ! Only updates the database not the *User for safety reasons
func (user *User) UpdateIP(host string) error {
_, err := userStmts.updateLastIP.Exec(host, user.ID)
return err
}
func (user *User) IncreasePostStats(wcount int, topic bool) (err error) {
var mod int
baseScore := 1
if topic {
_, err = userStmts.incrementTopics.Exec(1, user.ID)
if err != nil {
return err
}
baseScore = 2
}
settings := SettingBox.Load().(SettingMap)
if wcount >= settings["megapost_min_words"].(int) {
_, err = userStmts.incrementMegaposts.Exec(1, 1, 1, user.ID)
mod = 4
} else if wcount >= settings["bigpost_min_words"].(int) {
_, err = userStmts.incrementBigposts.Exec(1, 1, user.ID)
mod = 1
} else {
_, err = userStmts.incrementPosts.Exec(1, user.ID)
}
if err != nil {
return err
}
_, err = userStmts.incrementScore.Exec(baseScore+mod, user.ID)
if err != nil {
return err
}
//log.Print(user.Score + base_score + mod)
//log.Print(getLevel(user.Score + base_score + mod))
// TODO: Use a transaction to prevent level desyncs?
_, err = userStmts.updateLevel.Exec(GetLevel(user.Score+baseScore+mod), user.ID)
return err
}
func (user *User) DecreasePostStats(wcount int, topic bool) (err error) {
var mod int
baseScore := -1
if topic {
_, err = userStmts.incrementTopics.Exec(-1, user.ID)
if err != nil {
return err
}
baseScore = -2
}
settings := SettingBox.Load().(SettingMap)
if wcount >= settings["megapost_min_words"].(int) {
_, err = userStmts.incrementMegaposts.Exec(-1, -1, -1, user.ID)
mod = 4
} else if wcount >= settings["bigpost_min_words"].(int) {
_, err = userStmts.incrementBigposts.Exec(-1, -1, user.ID)
mod = 1
} else {
_, err = userStmts.incrementPosts.Exec(-1, user.ID)
}
if err != nil {
return err
}
_, err = userStmts.incrementScore.Exec(baseScore-mod, user.ID)
if err != nil {
return err
}
// TODO: Use a transaction to prevent level desyncs?
_, err = userStmts.updateLevel.Exec(GetLevel(user.Score-baseScore-mod), user.ID)
return err
}
// Copy gives you a non-pointer concurrency safe copy of the user
func (user *User) Copy() User {
return *user
}
// TODO: Write unit tests for this
func (user *User) InitPerms() {
if user.TempGroup != 0 {
user.Group = user.TempGroup
}
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
group := Groups.DirtyGet(user.Group)
if user.IsSuperAdmin {
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
user.Perms = AllPerms
user.PluginPerms = AllPluginPerms
} else {
user.Perms = group.Perms
user.PluginPerms = group.PluginPerms
}
user.IsAdmin = user.IsSuperAdmin || group.IsAdmin
user.IsSuperMod = user.IsAdmin || group.IsMod
user.IsMod = user.IsSuperMod
user.IsBanned = group.IsBanned
if user.IsBanned && user.IsSuperMod {
user.IsBanned = false
}
}
// ? Make this part of *User?
func BuildAvatar(uid int, avatar string) string {
if avatar != "" {
if avatar[0] == '.' {
return "/uploads/avatar_" + strconv.Itoa(uid) + avatar
}
return avatar
}
return strings.Replace(Config.Noavatar, "{id}", strconv.Itoa(uid), 1)
}
// 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 &User{ID: 0, Name: ""}
}
// 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)
}